LCOV - code coverage report
Current view: top level - gcc - tree-vect-loop.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 89.1 % 5154 4594
Test Date: 2026-09-19 16:22:48 Functions: 94.9 % 99 94
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Loop Vectorization
       2              :    Copyright (C) 2003-2026 Free Software Foundation, Inc.
       3              :    Contributed by Dorit Naishlos <dorit@il.ibm.com> and
       4              :    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              : #define INCLUDE_ALGORITHM
      23              : #include "config.h"
      24              : #include "system.h"
      25              : #include "coretypes.h"
      26              : #include "backend.h"
      27              : #include "target.h"
      28              : #include "rtl.h"
      29              : #include "tree.h"
      30              : #include "gimple.h"
      31              : #include "cfghooks.h"
      32              : #include "tree-pass.h"
      33              : #include "ssa.h"
      34              : #include "optabs-tree.h"
      35              : #include "memmodel.h"
      36              : #include "optabs.h"
      37              : #include "diagnostic-core.h"
      38              : #include "fold-const.h"
      39              : #include "stor-layout.h"
      40              : #include "cfganal.h"
      41              : #include "gimplify.h"
      42              : #include "gimple-iterator.h"
      43              : #include "gimplify-me.h"
      44              : #include "tree-ssa-loop-ivopts.h"
      45              : #include "tree-ssa-loop-manip.h"
      46              : #include "tree-ssa-loop-niter.h"
      47              : #include "tree-ssa-loop.h"
      48              : #include "cfgloop.h"
      49              : #include "tree-scalar-evolution.h"
      50              : #include "tree-vectorizer.h"
      51              : #include "gimple-fold.h"
      52              : #include "cgraph.h"
      53              : #include "tree-cfg.h"
      54              : #include "tree-if-conv.h"
      55              : #include "internal-fn.h"
      56              : #include "tree-vector-builder.h"
      57              : #include "vec-perm-indices.h"
      58              : #include "tree-eh.h"
      59              : #include "case-cfn-macros.h"
      60              : #include "langhooks.h"
      61              : #include "opts.h"
      62              : #include "hierarchical_discriminator.h"
      63              : 
      64              : /* Loop Vectorization Pass.
      65              : 
      66              :    This pass tries to vectorize loops.
      67              : 
      68              :    For example, the vectorizer transforms the following simple loop:
      69              : 
      70              :         short a[N]; short b[N]; short c[N]; int i;
      71              : 
      72              :         for (i=0; i<N; i++){
      73              :           a[i] = b[i] + c[i];
      74              :         }
      75              : 
      76              :    as if it was manually vectorized by rewriting the source code into:
      77              : 
      78              :         typedef int __attribute__((mode(V8HI))) v8hi;
      79              :         short a[N];  short b[N]; short c[N];   int i;
      80              :         v8hi *pa = (v8hi*)a, *pb = (v8hi*)b, *pc = (v8hi*)c;
      81              :         v8hi va, vb, vc;
      82              : 
      83              :         for (i=0; i<N/8; i++){
      84              :           vb = pb[i];
      85              :           vc = pc[i];
      86              :           va = vb + vc;
      87              :           pa[i] = va;
      88              :         }
      89              : 
      90              :         The main entry to this pass is vectorize_loops(), in which
      91              :    the vectorizer applies a set of analyses on a given set of loops,
      92              :    followed by the actual vectorization transformation for the loops that
      93              :    had successfully passed the analysis phase.
      94              :         Throughout this pass we make a distinction between two types of
      95              :    data: scalars (which are represented by SSA_NAMES), and memory references
      96              :    ("data-refs").  These two types of data require different handling both
      97              :    during analysis and transformation. The types of data-refs that the
      98              :    vectorizer currently supports are ARRAY_REFS which base is an array DECL
      99              :    (not a pointer), and INDIRECT_REFS through pointers; both array and pointer
     100              :    accesses are required to have a simple (consecutive) access pattern.
     101              : 
     102              :    Analysis phase:
     103              :    ===============
     104              :         The driver for the analysis phase is vect_analyze_loop().
     105              :    It applies a set of analyses, some of which rely on the scalar evolution
     106              :    analyzer (scev) developed by Sebastian Pop.
     107              : 
     108              :         During the analysis phase the vectorizer records some information
     109              :    per stmt in a "stmt_vec_info" struct which is attached to each stmt in the
     110              :    loop, as well as general information about the loop as a whole, which is
     111              :    recorded in a "loop_vec_info" struct attached to each loop.
     112              : 
     113              :    Transformation phase:
     114              :    =====================
     115              :         The loop transformation phase scans all the stmts in the loop, and
     116              :    creates a vector stmt (or a sequence of stmts) for each scalar stmt S in
     117              :    the loop that needs to be vectorized.  It inserts the vector code sequence
     118              :    just before the scalar stmt S, and records a pointer to the vector code
     119              :    in STMT_VINFO_VEC_STMT (stmt_info) (stmt_info is the stmt_vec_info struct
     120              :    attached to S).  This pointer will be used for the vectorization of following
     121              :    stmts which use the def of stmt S. Stmt S is removed if it writes to memory;
     122              :    otherwise, we rely on dead code elimination for removing it.
     123              : 
     124              :         For example, say stmt S1 was vectorized into stmt VS1:
     125              : 
     126              :    VS1: vb = px[i];
     127              :    S1:  b = x[i];    STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
     128              :    S2:  a = b;
     129              : 
     130              :    To vectorize stmt S2, the vectorizer first finds the stmt that defines
     131              :    the operand 'b' (S1), and gets the relevant vector def 'vb' from the
     132              :    vector stmt VS1 pointed to by STMT_VINFO_VEC_STMT (stmt_info (S1)).  The
     133              :    resulting sequence would be:
     134              : 
     135              :    VS1: vb = px[i];
     136              :    S1:  b = x[i];       STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
     137              :    VS2: va = vb;
     138              :    S2:  a = b;          STMT_VINFO_VEC_STMT (stmt_info (S2)) = VS2
     139              : 
     140              :         Operands that are not SSA_NAMEs, are data-refs that appear in
     141              :    load/store operations (like 'x[i]' in S1), and are handled differently.
     142              : 
     143              :    Target modeling:
     144              :    =================
     145              :         Currently the only target specific information that is used is the
     146              :    size of the vector (in bytes) - "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD".
     147              :    Targets that can support different sizes of vectors, for now will need
     148              :    to specify one value for "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD".  More
     149              :    flexibility will be added in the future.
     150              : 
     151              :         Since we only vectorize operations which vector form can be
     152              :    expressed using existing tree codes, to verify that an operation is
     153              :    supported, the vectorizer checks the relevant optab at the relevant
     154              :    machine_mode (e.g, optab_handler (add_optab, V8HImode)).  If
     155              :    the value found is CODE_FOR_nothing, then there's no target support, and
     156              :    we can't vectorize the stmt.
     157              : 
     158              :    For additional information on this project see:
     159              :    http://gcc.gnu.org/projects/tree-ssa/vectorization.html
     160              : */
     161              : 
     162              : static void vect_estimate_min_profitable_iters (loop_vec_info, int *, int *,
     163              :                                                 unsigned *);
     164              : static stmt_vec_info vect_is_simple_reduction (loop_vec_info, stmt_vec_info,
     165              :                                                gphi **);
     166              : 
     167              : 
     168              : /* Function vect_is_simple_iv_evolution.
     169              : 
     170              :    FORNOW: A simple evolution of an induction variables in the loop is
     171              :    considered a polynomial evolution.  */
     172              : 
     173              : static bool
     174       938111 : vect_is_simple_iv_evolution (unsigned loop_nb, tree access_fn,
     175              :                              stmt_vec_info stmt_info)
     176              : {
     177       938111 :   tree init_expr;
     178       938111 :   tree step_expr;
     179       938111 :   tree evolution_part = evolution_part_in_loop_num (access_fn, loop_nb);
     180       938111 :   basic_block bb;
     181              : 
     182              :   /* When there is no evolution in this loop, the evolution function
     183              :      is not "simple".  */
     184       938111 :   if (evolution_part == NULL_TREE)
     185              :     return false;
     186              : 
     187              :   /* When the evolution is a polynomial of degree >= 2
     188              :      the evolution function is not "simple".  */
     189       824035 :   if (tree_is_chrec (evolution_part))
     190              :     return false;
     191              : 
     192       824035 :   step_expr = evolution_part;
     193       824035 :   init_expr = unshare_expr (initial_condition_in_loop_num (access_fn, loop_nb));
     194              : 
     195       824035 :   if (dump_enabled_p ())
     196        40355 :     dump_printf_loc (MSG_NOTE, vect_location, "step: %T,  init: %T\n",
     197              :                      step_expr, init_expr);
     198              : 
     199       824035 :   STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_info) = init_expr;
     200       824035 :   STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info) = step_expr;
     201              : 
     202       824035 :   if (TREE_CODE (step_expr) != INTEGER_CST
     203        72416 :       && (TREE_CODE (step_expr) != SSA_NAME
     204        60569 :           || ((bb = gimple_bb (SSA_NAME_DEF_STMT (step_expr)))
     205        60310 :               && flow_bb_inside_loop_p (get_loop (cfun, loop_nb), bb))
     206         7782 :           || (!INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
     207          133 :               && (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr))
     208          133 :                   || !flag_associative_math)))
     209       888766 :       && (TREE_CODE (step_expr) != REAL_CST
     210          416 :           || !flag_associative_math))
     211              :     {
     212        64641 :       if (dump_enabled_p ())
     213         3162 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     214              :                          "step unknown.\n");
     215              :       return false;
     216              :     }
     217              : 
     218              :   return true;
     219              : }
     220              : 
     221              : /* Function vect_is_nonlinear_iv_evolution
     222              : 
     223              :    Only support nonlinear induction for integer type
     224              :    1. neg
     225              :    2. mul by constant
     226              :    3. lshift/rshift by constant.
     227              : 
     228              :    For neg induction, return a fake step as integer -1.  */
     229              : static bool
     230       176271 : vect_is_nonlinear_iv_evolution (class loop* loop, stmt_vec_info stmt_info,
     231              :                                 gphi* loop_phi_node)
     232              : {
     233       176271 :   tree init_expr, ev_expr, result, op1, op2;
     234       176271 :   gimple* def;
     235              : 
     236       176271 :   if (gimple_phi_num_args (loop_phi_node) != 2)
     237              :     return false;
     238              : 
     239       176271 :   init_expr = PHI_ARG_DEF_FROM_EDGE (loop_phi_node, loop_preheader_edge (loop));
     240       176271 :   ev_expr = PHI_ARG_DEF_FROM_EDGE (loop_phi_node, loop_latch_edge (loop));
     241              : 
     242              :   /* Support nonlinear induction only for integer type.  */
     243       176271 :   if (!INTEGRAL_TYPE_P (TREE_TYPE (init_expr)))
     244              :     return false;
     245              : 
     246       110022 :   result = PHI_RESULT (loop_phi_node);
     247              : 
     248       110022 :   if (TREE_CODE (ev_expr) != SSA_NAME
     249       107694 :       || ((def = SSA_NAME_DEF_STMT (ev_expr)), false)
     250       110022 :       || !is_gimple_assign (def))
     251              :     return false;
     252              : 
     253        99143 :   enum tree_code t_code = gimple_assign_rhs_code (def);
     254        99143 :   tree step;
     255        99143 :   switch (t_code)
     256              :     {
     257         3540 :     case NEGATE_EXPR:
     258         3540 :       if (gimple_assign_rhs1 (def) != result)
     259              :         return false;
     260         3540 :       step = build_int_cst (TREE_TYPE (init_expr), -1);
     261         3540 :       STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_neg;
     262         3540 :       break;
     263              : 
     264        11843 :     case RSHIFT_EXPR:
     265        11843 :     case LSHIFT_EXPR:
     266        11843 :     case MULT_EXPR:
     267        11843 :       op1 = gimple_assign_rhs1 (def);
     268        11843 :       op2 = gimple_assign_rhs2 (def);
     269        11843 :       if (TREE_CODE (op2) != INTEGER_CST
     270         7946 :           || op1 != result)
     271              :         return false;
     272         7549 :       step = op2;
     273         7549 :       if (t_code == LSHIFT_EXPR)
     274          487 :         STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_shl;
     275         7062 :       else if (t_code == RSHIFT_EXPR)
     276         6082 :         STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_shr;
     277              :       /* NEGATE_EXPR and MULT_EXPR are both vect_step_op_mul.  */
     278              :       else
     279          980 :         STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_mul;
     280              :       break;
     281              : 
     282              :     default:
     283              :       return false;
     284              :     }
     285              : 
     286        11089 :   STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_info) = init_expr;
     287        11089 :   STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info) = step;
     288              : 
     289        11089 :   return true;
     290              : }
     291              : 
     292              : /* Returns true if Phi is a first-order recurrence. A first-order
     293              :    recurrence is a non-reduction recurrence relation in which the value of
     294              :    the recurrence in the current loop iteration equals a value defined in
     295              :    the previous iteration.  */
     296              : 
     297              : static bool
     298        66170 : vect_phi_first_order_recurrence_p (loop_vec_info loop_vinfo, class loop *loop,
     299              :                                    gphi *phi)
     300              : {
     301              :   /* A nested cycle isn't vectorizable as first order recurrence.  */
     302        66170 :   if (LOOP_VINFO_LOOP (loop_vinfo) != loop)
     303              :     return false;
     304              : 
     305              :   /* Ensure the loop latch definition is from within the loop.  */
     306        66031 :   edge latch = loop_latch_edge (loop);
     307        66031 :   tree ldef = PHI_ARG_DEF_FROM_EDGE (phi, latch);
     308        66031 :   if (TREE_CODE (ldef) != SSA_NAME
     309        63360 :       || SSA_NAME_IS_DEFAULT_DEF (ldef)
     310        63294 :       || is_a <gphi *> (SSA_NAME_DEF_STMT (ldef))
     311       123036 :       || !flow_bb_inside_loop_p (loop, gimple_bb (SSA_NAME_DEF_STMT (ldef))))
     312              :     return false;
     313              : 
     314        56338 :   tree def = gimple_phi_result (phi);
     315              : 
     316              :   /* Ensure every use_stmt of the phi node is dominated by the latch
     317              :      definition.  */
     318        56338 :   imm_use_iterator imm_iter;
     319        56338 :   use_operand_p use_p;
     320        72121 :   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, def)
     321        71530 :     if (!is_gimple_debug (USE_STMT (use_p))
     322       136309 :         && (SSA_NAME_DEF_STMT (ldef) == USE_STMT (use_p)
     323        43869 :             || !vect_stmt_dominates_stmt_p (SSA_NAME_DEF_STMT (ldef),
     324              :                                             USE_STMT (use_p))))
     325        55747 :       return false;
     326              : 
     327              :   /* First-order recurrence autovectorization needs shuffle vector.  */
     328          591 :   tree scalar_type = TREE_TYPE (def);
     329          591 :   tree vectype = get_vectype_for_scalar_type (loop_vinfo, scalar_type);
     330          591 :   if (!vectype)
     331            6 :     return false;
     332              : 
     333              :   return true;
     334              : }
     335              : 
     336              : /* Function vect_analyze_scalar_cycles_1.
     337              : 
     338              :    Examine the cross iteration def-use cycles of scalar variables
     339              :    in LOOP.  LOOP_VINFO represents the loop that is now being
     340              :    considered for vectorization (can be LOOP, or an outer-loop
     341              :    enclosing LOOP).  SLP indicates there will be some subsequent
     342              :    slp analyses or not.  */
     343              : 
     344              : static void
     345       459263 : vect_analyze_scalar_cycles_1 (loop_vec_info loop_vinfo, class loop *loop)
     346              : {
     347       459263 :   basic_block bb = loop->header;
     348       459263 :   auto_vec<stmt_vec_info, 64> worklist;
     349       459263 :   gphi_iterator gsi;
     350              : 
     351       459263 :   DUMP_VECT_SCOPE ("vect_analyze_scalar_cycles");
     352              : 
     353              :   /* First - identify all inductions.  Reduction detection assumes that all the
     354              :      inductions have been identified, therefore, this order must not be
     355              :      changed.  */
     356      1643242 :   for (gsi = gsi_start_phis  (bb); !gsi_end_p (gsi); gsi_next (&gsi))
     357              :     {
     358      1183979 :       gphi *phi = gsi.phi ();
     359      1183979 :       tree access_fn = NULL;
     360      1183979 :       tree def = PHI_RESULT (phi);
     361      1183979 :       stmt_vec_info stmt_vinfo = loop_vinfo->lookup_stmt (phi);
     362              : 
     363              :       /* Skip virtual phi's.  The data dependences that are associated with
     364              :          virtual defs/uses (i.e., memory accesses) are analyzed elsewhere.  */
     365      2367958 :       if (virtual_operand_p (def))
     366       413502 :         continue;
     367              : 
     368              :       /* Skip already analyzed inner loop PHIs of double reductions.  */
     369       939128 :       if (VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_vinfo)))
     370         1017 :         continue;
     371              : 
     372       938111 :       if (dump_enabled_p ())
     373        42474 :         dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: %G",
     374              :                          (gimple *) phi);
     375              : 
     376       938111 :       STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_unknown_def_type;
     377              : 
     378              :       /* Analyze the evolution function.  */
     379       938111 :       access_fn = analyze_scalar_evolution (loop, def);
     380       938111 :       if (dump_enabled_p ())
     381        42474 :         dump_printf_loc (MSG_NOTE, vect_location,
     382              :                          "Access function of PHI: %T\n", access_fn);
     383       938111 :       if (access_fn)
     384       938111 :         STRIP_NOPS (access_fn);
     385              : 
     386      1105745 :       if ((!access_fn
     387       938111 :            || !vect_is_simple_iv_evolution (loop->num, access_fn, stmt_vinfo)
     388       759394 :            || (LOOP_VINFO_LOOP (loop_vinfo) != loop
     389        11436 :                && (TREE_CODE (STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo))
     390              :                    != INTEGER_CST)))
     391              :           /* Only handle nonlinear iv for same loop.  */
     392      1116834 :           && (LOOP_VINFO_LOOP (loop_vinfo) != loop
     393       176271 :               || !vect_is_nonlinear_iv_evolution (loop, stmt_vinfo, phi)))
     394              :         {
     395       167634 :           worklist.safe_push (stmt_vinfo);
     396       167634 :           continue;
     397              :         }
     398              : 
     399       770477 :       gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
     400              :                   != NULL_TREE);
     401       770477 :       gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo) != NULL_TREE);
     402              : 
     403       770477 :       if (dump_enabled_p ())
     404        37302 :         dump_printf_loc (MSG_NOTE, vect_location, "Detected induction.\n");
     405       770477 :       STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_induction_def;
     406              : 
     407              :       /* Mark if we have a non-linear IV.  */
     408       770477 :       LOOP_VINFO_NON_LINEAR_IV (loop_vinfo)
     409       770477 :         = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_vinfo) != vect_step_op_add;
     410              :     }
     411              : 
     412              : 
     413              :   /* Second - identify all reductions and nested cycles.  */
     414       626897 :   while (worklist.length () > 0)
     415              :     {
     416       167634 :       stmt_vec_info stmt_vinfo = worklist.pop ();
     417       167634 :       gphi *phi = as_a <gphi *> (stmt_vinfo->stmt);
     418       167634 :       tree def = PHI_RESULT (phi);
     419              : 
     420       167634 :       if (dump_enabled_p ())
     421         5172 :         dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: %G",
     422              :                          (gimple *) phi);
     423              : 
     424       335268 :       gcc_assert (!virtual_operand_p (def)
     425              :                   && STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_unknown_def_type);
     426              : 
     427       167634 :       gphi *double_reduc;
     428       167634 :       stmt_vec_info reduc_stmt_info
     429       167634 :         = vect_is_simple_reduction (loop_vinfo, stmt_vinfo, &double_reduc);
     430       167634 :       if (reduc_stmt_info && double_reduc)
     431              :         {
     432         1119 :           stmt_vec_info inner_phi_info
     433         1119 :               = loop_vinfo->lookup_stmt (double_reduc);
     434              :           /* ???  Pass down flag we're the inner loop of a double reduc.  */
     435         1119 :           stmt_vec_info inner_reduc_info
     436         1119 :             = vect_is_simple_reduction (loop_vinfo, inner_phi_info, NULL);
     437         1119 :           if (inner_reduc_info)
     438              :             {
     439         1017 :               STMT_VINFO_REDUC_DEF (stmt_vinfo) = reduc_stmt_info;
     440         1017 :               STMT_VINFO_REDUC_DEF (reduc_stmt_info) = stmt_vinfo;
     441         1017 :               STMT_VINFO_REDUC_DEF (inner_phi_info) = inner_reduc_info;
     442         1017 :               STMT_VINFO_REDUC_DEF (inner_reduc_info) = inner_phi_info;
     443         1017 :               if (dump_enabled_p ())
     444          130 :                 dump_printf_loc (MSG_NOTE, vect_location,
     445              :                                  "Detected double reduction.\n");
     446              : 
     447         1017 :               STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_double_reduction_def;
     448         1017 :               STMT_VINFO_DEF_TYPE (reduc_stmt_info) = vect_double_reduction_def;
     449         1017 :               STMT_VINFO_DEF_TYPE (inner_phi_info) = vect_nested_cycle;
     450              :               /* Make it accessible for SLP vectorization.  */
     451         1017 :               LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push (reduc_stmt_info);
     452              :             }
     453          102 :           else if (dump_enabled_p ())
     454           14 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     455              :                              "Unknown def-use cycle pattern.\n");
     456              :         }
     457       166515 :       else if (reduc_stmt_info)
     458              :         {
     459       100345 :           if (loop != LOOP_VINFO_LOOP (loop_vinfo))
     460              :             {
     461         2313 :               if (dump_enabled_p ())
     462          434 :                 dump_printf_loc (MSG_NOTE, vect_location,
     463              :                                  "Detected vectorizable nested cycle.\n");
     464              : 
     465         2313 :               STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_nested_cycle;
     466              :             }
     467              :           else
     468              :             {
     469        98032 :               STMT_VINFO_REDUC_DEF (stmt_vinfo) = reduc_stmt_info;
     470        98032 :               STMT_VINFO_REDUC_DEF (reduc_stmt_info) = stmt_vinfo;
     471        98032 :               if (dump_enabled_p ())
     472         4030 :                 dump_printf_loc (MSG_NOTE, vect_location,
     473              :                                  "Detected reduction.\n");
     474              : 
     475        98032 :               STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_reduction_def;
     476        98032 :               STMT_VINFO_DEF_TYPE (reduc_stmt_info) = vect_reduction_def;
     477        98032 :               LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push (reduc_stmt_info);
     478              :             }
     479              :         }
     480        66170 :       else if (vect_phi_first_order_recurrence_p (loop_vinfo, loop, phi))
     481          585 :         STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_first_order_recurrence;
     482              :       else
     483        65585 :         if (dump_enabled_p ())
     484          487 :           dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     485              :                            "Unknown def-use cycle pattern.\n");
     486              :     }
     487       459263 : }
     488              : 
     489              : 
     490              : /* Function vect_analyze_scalar_cycles.
     491              : 
     492              :    Examine the cross iteration def-use cycles of scalar variables, by
     493              :    analyzing the loop-header PHIs of scalar variables.  Classify each
     494              :    cycle as one of the following: invariant, induction, reduction, unknown.
     495              :    We do that for the loop represented by LOOP_VINFO, and also to its
     496              :    inner-loop, if exists.
     497              :    Examples for scalar cycles:
     498              : 
     499              :    Example1: reduction:
     500              : 
     501              :               loop1:
     502              :               for (i=0; i<N; i++)
     503              :                  sum += a[i];
     504              : 
     505              :    Example2: induction:
     506              : 
     507              :               loop2:
     508              :               for (i=0; i<N; i++)
     509              :                  a[i] = i;  */
     510              : 
     511              : static void
     512       453447 : vect_analyze_scalar_cycles (loop_vec_info loop_vinfo)
     513              : {
     514       453447 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
     515              : 
     516       453447 :   vect_analyze_scalar_cycles_1 (loop_vinfo, loop);
     517              : 
     518              :   /* When vectorizing an outer-loop, the inner-loop is executed sequentially.
     519              :      Reductions in such inner-loop therefore have different properties than
     520              :      the reductions in the nest that gets vectorized:
     521              :      1. When vectorized, they are executed in the same order as in the original
     522              :         scalar loop, so we can't change the order of computation when
     523              :         vectorizing them.
     524              :      2. FIXME: Inner-loop reductions can be used in the inner-loop, so the
     525              :         current checks are too strict.  */
     526              : 
     527       453447 :   if (loop->inner)
     528         5816 :     vect_analyze_scalar_cycles_1 (loop_vinfo, loop->inner);
     529       453447 : }
     530              : 
     531              : /* Function vect_get_loop_niters.
     532              : 
     533              :    Determine how many iterations the loop is executed and place it
     534              :    in NUMBER_OF_ITERATIONS.  Place the number of latch iterations
     535              :    in NUMBER_OF_ITERATIONSM1.  Place the condition under which the
     536              :    niter information holds in ASSUMPTIONS.
     537              : 
     538              :    Return the loop exit conditions.  */
     539              : 
     540              : 
     541              : static vec<gcond *>
     542       285664 : vect_get_loop_niters (class loop *loop, const_edge main_exit, tree *assumptions,
     543              :                       tree *number_of_iterations, tree *number_of_iterationsm1)
     544              : {
     545       285664 :   auto_vec<edge> exits = get_loop_exit_edges (loop);
     546       285664 :   vec<gcond *> conds;
     547       571328 :   conds.create (exits.length ());
     548       285664 :   class tree_niter_desc niter_desc;
     549       285664 :   tree niter_assumptions, niter, may_be_zero;
     550              : 
     551       285664 :   *assumptions = boolean_true_node;
     552       285664 :   *number_of_iterationsm1 = chrec_dont_know;
     553       285664 :   *number_of_iterations = chrec_dont_know;
     554              : 
     555       285664 :   DUMP_VECT_SCOPE ("get_loop_niters");
     556              : 
     557       285664 :   if (exits.is_empty ())
     558            0 :     return conds;
     559              : 
     560       285664 :   if (dump_enabled_p ())
     561        14782 :     dump_printf_loc (MSG_NOTE, vect_location, "Loop has %d exits.\n",
     562              :                      exits.length ());
     563              : 
     564       285664 :   edge exit;
     565       285664 :   unsigned int i;
     566       697796 :   FOR_EACH_VEC_ELT (exits, i, exit)
     567              :     {
     568       412132 :       gcond *cond = get_loop_exit_condition (exit);
     569       412132 :       if (cond)
     570       412098 :         conds.safe_push (cond);
     571              : 
     572       412132 :       if (dump_enabled_p ())
     573        15951 :         dump_printf_loc (MSG_NOTE, vect_location, "Analyzing exit %d...\n", i);
     574              : 
     575       412132 :       if (exit != main_exit)
     576       186604 :         continue;
     577              : 
     578       285664 :       may_be_zero = NULL_TREE;
     579       285664 :       if (!number_of_iterations_exit_assumptions (loop, exit, &niter_desc, NULL)
     580       285664 :           || chrec_contains_undetermined (niter_desc.niter))
     581        60136 :         continue;
     582              : 
     583       225528 :       niter_assumptions = niter_desc.assumptions;
     584       225528 :       may_be_zero = niter_desc.may_be_zero;
     585       225528 :       niter = niter_desc.niter;
     586              : 
     587       225528 :       if (may_be_zero && integer_zerop (may_be_zero))
     588              :         may_be_zero = NULL_TREE;
     589              : 
     590         9452 :       if (may_be_zero)
     591              :         {
     592         9452 :           if (COMPARISON_CLASS_P (may_be_zero))
     593              :             {
     594              :               /* Try to combine may_be_zero with assumptions, this can simplify
     595              :                  computation of niter expression.  */
     596         9452 :               if (niter_assumptions && !integer_nonzerop (niter_assumptions))
     597          971 :                 niter_assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
     598              :                                                  niter_assumptions,
     599              :                                                  fold_build1 (TRUTH_NOT_EXPR,
     600              :                                                               boolean_type_node,
     601              :                                                               may_be_zero));
     602              :               else
     603         8481 :                 niter = fold_build3 (COND_EXPR, TREE_TYPE (niter), may_be_zero,
     604              :                                      build_int_cst (TREE_TYPE (niter), 0),
     605              :                                      rewrite_to_non_trapping_overflow (niter));
     606              : 
     607       225528 :               may_be_zero = NULL_TREE;
     608              :             }
     609            0 :           else if (integer_nonzerop (may_be_zero))
     610              :             {
     611            0 :               *number_of_iterationsm1 = build_int_cst (TREE_TYPE (niter), 0);
     612            0 :               *number_of_iterations = build_int_cst (TREE_TYPE (niter), 1);
     613            0 :               continue;
     614              :             }
     615              :           else
     616            0 :             continue;
     617              :        }
     618              : 
     619              :       /* Loop assumptions are based off the normal exit.  */
     620       225528 :       *assumptions = niter_assumptions;
     621       225528 :       *number_of_iterationsm1 = niter;
     622              : 
     623              :       /* We want the number of loop header executions which is the number
     624              :          of latch executions plus one.
     625              :          ???  For UINT_MAX latch executions this number overflows to zero
     626              :          for loops like do { n++; } while (n != 0);  */
     627       225528 :       if (niter && !chrec_contains_undetermined (niter))
     628              :         {
     629       225528 :           niter = fold_build2 (PLUS_EXPR, TREE_TYPE (niter),
     630              :                                unshare_expr (niter),
     631              :                                build_int_cst (TREE_TYPE (niter), 1));
     632       225528 :           if (TREE_CODE (niter) == INTEGER_CST
     633       124613 :               && TREE_CODE (*number_of_iterationsm1) != INTEGER_CST)
     634              :             {
     635              :               /* If we manage to fold niter + 1 into INTEGER_CST even when
     636              :                  niter is some complex expression, ensure back
     637              :                  *number_of_iterationsm1 is an INTEGER_CST as well.  See
     638              :                  PR113210.  */
     639            0 :               *number_of_iterationsm1
     640            0 :                 = fold_build2 (PLUS_EXPR, TREE_TYPE (niter), niter,
     641              :                                build_minus_one_cst (TREE_TYPE (niter)));
     642              :             }
     643              :         }
     644       225528 :       *number_of_iterations = niter;
     645              :     }
     646              : 
     647       285664 :   if (dump_enabled_p ())
     648        14782 :     dump_printf_loc (MSG_NOTE, vect_location, "All loop exits successfully analyzed.\n");
     649              : 
     650       285664 :   return conds;
     651       285664 : }
     652              : 
     653              : /*  Determine the main loop exit for the vectorizer.  */
     654              : 
     655              : edge
     656       497046 : vec_init_loop_exit_info (class loop *loop)
     657              : {
     658              :   /* Before we begin we must first determine which exit is the main one and
     659              :      which are auxiliary exits.  */
     660       497046 :   auto_vec<edge> exits = get_loop_exit_edges (loop);
     661       989001 :   if (exits.length () == 0)
     662              :     return NULL;
     663       491955 :   if (exits.length () == 1)
     664       320243 :     return exits[0];
     665              : 
     666              :   /* If we have multiple exits, look for counting IV exit.
     667              :      Analyze all exits and return the last one we can analyze.  */
     668       171712 :   class tree_niter_desc niter_desc;
     669       171712 :   edge candidate = NULL;
     670       638771 :   for (edge exit : exits)
     671              :     {
     672       488317 :       if (!get_loop_exit_condition (exit))
     673              :         {
     674        21258 :           if (dump_enabled_p ())
     675           14 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     676              :                              "Unhandled loop exit detected.\n");
     677              :           return NULL;
     678              :         }
     679              : 
     680       467059 :       if (number_of_iterations_exit_assumptions (loop, exit, &niter_desc, NULL)
     681       467059 :           && !chrec_contains_undetermined (niter_desc.niter))
     682              :         {
     683       137197 :           tree may_be_zero = niter_desc.may_be_zero;
     684       137197 :           if ((integer_zerop (may_be_zero)
     685              :                /* As we are handling may_be_zero that's not false by
     686              :                   rewriting niter to may_be_zero ? 0 : niter we require
     687              :                   an empty latch.  */
     688       477594 :                || (single_pred_p (loop->latch)
     689        10316 :                    && exit->src == single_pred (loop->latch)
     690         2743 :                    && (integer_nonzerop (may_be_zero)
     691         2743 :                        || COMPARISON_CLASS_P (may_be_zero))))
     692       139940 :               && (!candidate
     693         5829 :                   || dominated_by_p (CDI_DOMINATORS, exit->src,
     694         5829 :                                      candidate->src)))
     695              :             candidate = exit;
     696              :         }
     697              :     }
     698              : 
     699              :   /* If no exit is analyzable by scalar evolution, we return the last exit
     700              :      under the assummption we are dealing with an uncounted loop.  */
     701       207823 :   if (!candidate && single_pred_p (loop->latch))
     702        36111 :     candidate = loop_exits_from_bb_p (loop, single_pred (loop->latch));
     703              : 
     704              :   return candidate;
     705       171712 : }
     706              : 
     707              : /* Function bb_in_loop_p
     708              : 
     709              :    Used as predicate for dfs order traversal of the loop bbs.  */
     710              : 
     711              : static bool
     712      1735227 : bb_in_loop_p (const_basic_block bb, const void *data)
     713              : {
     714      1735227 :   const class loop *const loop = (const class loop *)data;
     715      1735227 :   if (flow_bb_inside_loop_p (loop, bb))
     716              :     return true;
     717              :   return false;
     718              : }
     719              : 
     720              : 
     721              : /* Create and initialize a new loop_vec_info struct for LOOP_IN, as well as
     722              :    stmt_vec_info structs for all the stmts in LOOP_IN.  */
     723              : 
     724       591676 : _loop_vec_info::_loop_vec_info (class loop *loop_in, vec_info_shared *shared)
     725              :   : vec_info (vec_info::loop, shared),
     726       591676 :     loop (loop_in),
     727       591676 :     num_itersm1 (NULL_TREE),
     728       591676 :     num_iters (NULL_TREE),
     729       591676 :     num_iters_unchanged (NULL_TREE),
     730       591676 :     num_iters_assumptions (NULL_TREE),
     731       591676 :     vector_costs (nullptr),
     732       591676 :     scalar_costs (nullptr),
     733       591676 :     th (0),
     734       591676 :     versioning_threshold (0),
     735       591676 :     vectorization_factor (0),
     736       591676 :     main_loop_edge (nullptr),
     737       591676 :     skip_main_loop_edge (nullptr),
     738       591676 :     skip_this_loop_edge (nullptr),
     739       591676 :     reusable_accumulators (),
     740       591676 :     suggested_unroll_factor (1),
     741       591676 :     max_vectorization_factor (0),
     742       591676 :     mask_skip_niters (NULL_TREE),
     743       591676 :     mask_skip_niters_pfa_offset (NULL_TREE),
     744       591676 :     rgroup_compare_type (NULL_TREE),
     745       591676 :     simd_if_cond (NULL_TREE),
     746       591676 :     partial_vector_style (vect_partial_vectors_none),
     747       591676 :     unaligned_dr (NULL),
     748       591676 :     peeling_for_alignment (0),
     749       591676 :     ptr_mask (0),
     750       591676 :     max_spec_read_amount (0),
     751       591676 :     nonlinear_iv (false),
     752       591676 :     ivexpr_map (NULL),
     753       591676 :     scan_map (NULL),
     754       591676 :     inner_loop_cost_factor (param_vect_inner_loop_cost_factor),
     755       591676 :     vectorizable (false),
     756       591676 :     can_use_partial_vectors_p (true),
     757       591676 :     must_use_partial_vectors_p (false),
     758       591676 :     using_partial_vectors_p (false),
     759       591676 :     using_decrementing_iv_p (false),
     760       591676 :     using_select_vl_p (false),
     761       591676 :     allow_mutual_alignment (false),
     762       591676 :     partial_load_store_bias (0),
     763       591676 :     peeling_for_gaps (false),
     764       591676 :     peeling_for_niter (false),
     765       591676 :     early_breaks (false),
     766       591676 :     loop_iv_cond (NULL),
     767       591676 :     user_unroll (false),
     768       591676 :     no_data_dependencies (false),
     769       591676 :     has_mask_store (false),
     770       591676 :     scalar_loop_scaling (profile_probability::uninitialized ()),
     771       591676 :     scalar_loop (NULL),
     772       591676 :     main_loop_info (NULL),
     773       591676 :     orig_loop_info (NULL),
     774       591676 :     epilogue_vinfo (NULL),
     775       591676 :     drs_advanced_by (NULL_TREE),
     776       591676 :     vec_loop_main_exit (NULL),
     777       591676 :     vec_epilogue_loop_main_exit (NULL),
     778       591676 :     scalar_loop_main_exit (NULL),
     779       591676 :     early_break_needs_epilogue (false),
     780       591676 :     early_break_niters_var (NULL)
     781              : {
     782              :   /* CHECKME: We want to visit all BBs before their successors (except for
     783              :      latch blocks, for which this assertion wouldn't hold).  In the simple
     784              :      case of the loop forms we allow, a dfs order of the BBs would the same
     785              :      as reversed postorder traversal, so we are safe.  */
     786              : 
     787       591676 :   bbs = XCNEWVEC (basic_block, loop->num_nodes);
     788      1183352 :   nbbs = dfs_enumerate_from (loop->header, 0, bb_in_loop_p, bbs,
     789       591676 :                              loop->num_nodes, loop);
     790       591676 :   gcc_assert (nbbs == loop->num_nodes);
     791              : 
     792      2064632 :   for (unsigned int i = 0; i < nbbs; i++)
     793              :     {
     794      1472956 :       basic_block bb = bbs[i];
     795      1472956 :       gimple_stmt_iterator si;
     796              : 
     797      3038994 :       for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
     798              :         {
     799      1566038 :           gimple *phi = gsi_stmt (si);
     800      1566038 :           gimple_set_uid (phi, 0);
     801      1566038 :           add_stmt (phi);
     802              :         }
     803              : 
     804     13812112 :       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
     805              :         {
     806     10866200 :           gimple *stmt = gsi_stmt (si);
     807     10866200 :           gimple_set_uid (stmt, 0);
     808     10866200 :           if (is_gimple_debug (stmt) || is_a <glabel *> (stmt))
     809      4757935 :             continue;
     810      6108265 :           add_stmt (stmt);
     811              :           /* If .GOMP_SIMD_LANE call for the current loop has 3 arguments, the
     812              :              third argument is the #pragma omp simd if (x) condition, when 0,
     813              :              loop shouldn't be vectorized, when non-zero constant, it should
     814              :              be vectorized normally, otherwise versioned with vectorized loop
     815              :              done if the condition is non-zero at runtime.  */
     816      6108265 :           if (loop_in->simduid
     817        43430 :               && is_gimple_call (stmt)
     818         4265 :               && gimple_call_internal_p (stmt)
     819         4138 :               && gimple_call_internal_fn (stmt) == IFN_GOMP_SIMD_LANE
     820         4134 :               && gimple_call_num_args (stmt) >= 3
     821          103 :               && TREE_CODE (gimple_call_arg (stmt, 0)) == SSA_NAME
     822      6108368 :               && (loop_in->simduid
     823          103 :                   == SSA_NAME_VAR (gimple_call_arg (stmt, 0))))
     824              :             {
     825          103 :               tree arg = gimple_call_arg (stmt, 2);
     826          103 :               if (integer_zerop (arg) || TREE_CODE (arg) == SSA_NAME)
     827          103 :                 simd_if_cond = arg;
     828              :               else
     829            0 :                 gcc_assert (integer_nonzerop (arg));
     830              :             }
     831              :         }
     832              :     }
     833       591676 : }
     834              : 
     835              : /* Free all levels of rgroup CONTROLS.  */
     836              : 
     837              : void
     838      1479607 : release_vec_loop_controls (vec<rgroup_controls> *controls)
     839              : {
     840      1479607 :   rgroup_controls *rgc;
     841      1479607 :   unsigned int i;
     842      1504248 :   FOR_EACH_VEC_ELT (*controls, i, rgc)
     843        24641 :     rgc->controls.release ();
     844      1479607 :   controls->release ();
     845      1479607 : }
     846              : 
     847              : /* Free all memory used by the _loop_vec_info, as well as all the
     848              :    stmt_vec_info structs of all the stmts in the loop.  */
     849              : 
     850       591676 : _loop_vec_info::~_loop_vec_info ()
     851              : {
     852       591676 :   free (bbs);
     853              : 
     854       591676 :   release_vec_loop_controls (&masks.rgc_vec);
     855       591676 :   release_vec_loop_controls (&lens);
     856       595598 :   delete ivexpr_map;
     857       591998 :   delete scan_map;
     858       591676 :   delete scalar_costs;
     859       591676 :   delete vector_costs;
     860       808676 :   for (auto reduc_info : reduc_infos)
     861       208104 :     delete reduc_info;
     862              : 
     863              :   /* When we release an epiloge vinfo that we do not intend to use
     864              :      avoid clearing AUX of the main loop which should continue to
     865              :      point to the main loop vinfo since otherwise we'll leak that.  */
     866       591676 :   if (loop->aux == this)
     867        62304 :     loop->aux = NULL;
     868      1183352 : }
     869              : 
     870              : /* Return an invariant or register for EXPR and emit necessary
     871              :    computations in the LOOP_VINFO loop preheader.  */
     872              : 
     873              : tree
     874        20550 : cse_and_gimplify_to_preheader (loop_vec_info loop_vinfo, tree expr)
     875              : {
     876        20550 :   if (is_gimple_reg (expr)
     877        20550 :       || is_gimple_min_invariant (expr))
     878              :     return expr;
     879              : 
     880        13547 :   if (! loop_vinfo->ivexpr_map)
     881         3922 :     loop_vinfo->ivexpr_map = new hash_map<tree_operand_hash, tree>;
     882        13547 :   tree &cached = loop_vinfo->ivexpr_map->get_or_insert (expr);
     883        13547 :   if (! cached)
     884              :     {
     885         8696 :       gimple_seq stmts = NULL;
     886         8696 :       cached = force_gimple_operand (unshare_expr (expr),
     887              :                                      &stmts, true, NULL_TREE);
     888         8696 :       if (stmts)
     889              :         {
     890         8546 :           edge e = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
     891         8546 :           gsi_insert_seq_on_edge_immediate (e, stmts);
     892              :         }
     893              :     }
     894        13547 :   return cached;
     895              : }
     896              : 
     897              : /* Return true if we can use CMP_TYPE as the comparison type to produce
     898              :    all masks required to mask LOOP_VINFO.  */
     899              : 
     900              : static bool
     901       110349 : can_produce_all_loop_masks_p (loop_vec_info loop_vinfo, tree cmp_type)
     902              : {
     903       110349 :   rgroup_controls *rgm;
     904       110349 :   unsigned int i;
     905       126054 :   FOR_EACH_VEC_ELT (LOOP_VINFO_MASKS (loop_vinfo).rgc_vec, i, rgm)
     906       126054 :     if (rgm->type != NULL_TREE
     907       126054 :         && !direct_internal_fn_supported_p (IFN_WHILE_ULT,
     908              :                                             cmp_type, rgm->type,
     909              :                                             OPTIMIZE_FOR_SPEED))
     910              :       return false;
     911              :   return true;
     912              : }
     913              : 
     914              : /* Calculate the maximum number of scalars per iteration for every
     915              :    rgroup in LOOP_VINFO.  */
     916              : 
     917              : static unsigned int
     918        23524 : vect_get_max_nscalars_per_iter (loop_vec_info loop_vinfo)
     919              : {
     920        23524 :   unsigned int res = 1;
     921        23524 :   unsigned int i;
     922        23524 :   rgroup_controls *rgm;
     923        56352 :   FOR_EACH_VEC_ELT (LOOP_VINFO_MASKS (loop_vinfo).rgc_vec, i, rgm)
     924        32828 :     res = MAX (res, rgm->max_nscalars_per_iter);
     925        23524 :   return res;
     926              : }
     927              : 
     928              : /* Calculate the minimum precision necessary to represent:
     929              : 
     930              :       MAX_NITERS * FACTOR
     931              : 
     932              :    as an unsigned integer, where MAX_NITERS is the maximum number of
     933              :    loop header iterations for the original scalar form of LOOP_VINFO.  */
     934              : 
     935              : unsigned
     936        25971 : vect_min_prec_for_max_niters (loop_vec_info loop_vinfo, unsigned int factor)
     937              : {
     938        25971 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
     939              : 
     940              :   /* Get the maximum number of iterations that is representable
     941              :      in the counter type.  */
     942        25971 :   tree ni_type;
     943        25971 :   if (!LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo))
     944        25971 :     ni_type = TREE_TYPE (LOOP_VINFO_NITERSM1 (loop_vinfo));
     945              :   else
     946            0 :     ni_type = sizetype;
     947        25971 :   widest_int max_ni = wi::to_widest (TYPE_MAX_VALUE (ni_type)) + 1;
     948              : 
     949              :   /* Get a more refined estimate for the number of iterations.  */
     950        25971 :   widest_int max_back_edges;
     951        25971 :   if (max_loop_iterations (loop, &max_back_edges))
     952        25971 :     max_ni = wi::smin (max_ni, max_back_edges + 1);
     953              : 
     954              :   /* Work out how many bits we need to represent the limit.  */
     955        25971 :   return wi::min_precision (max_ni * factor, UNSIGNED);
     956        25971 : }
     957              : 
     958              : /* True if the loop needs peeling or partial vectors when vectorized.  */
     959              : 
     960              : static bool
     961       156840 : vect_need_peeling_or_partial_vectors_p (loop_vec_info loop_vinfo)
     962              : {
     963       156840 :   unsigned HOST_WIDE_INT const_vf;
     964              : 
     965       156840 :   if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
     966              :     return true;
     967              : 
     968        13422 :   loop_vec_info main_loop_vinfo
     969       155525 :     = (LOOP_VINFO_EPILOGUE_P (loop_vinfo)
     970       155525 :        ? LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo) : loop_vinfo);
     971       155525 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
     972        79949 :       && LOOP_VINFO_PEELING_FOR_ALIGNMENT (main_loop_vinfo) >= 0)
     973              :     {
     974              :       /* Work out the (constant) number of iterations that need to be
     975              :          peeled for reasons other than niters.  */
     976        79899 :       unsigned int peel_niter
     977              :         = LOOP_VINFO_PEELING_FOR_ALIGNMENT (main_loop_vinfo);
     978        79899 :       return !multiple_p (LOOP_VINFO_INT_NITERS (loop_vinfo) - peel_niter,
     979        79899 :                           LOOP_VINFO_VECT_FACTOR (loop_vinfo));
     980              :     }
     981              : 
     982        75626 :   if (!LOOP_VINFO_PEELING_FOR_ALIGNMENT (main_loop_vinfo)
     983        75626 :       && LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant (&const_vf))
     984              :     {
     985              :       /* When the number of iterations is a multiple of the vectorization
     986              :          factor and we are not doing prologue or forced epilogue peeling
     987              :          the epilogue isn't necessary.  */
     988        75212 :       if (tree_ctz (LOOP_VINFO_NITERS (loop_vinfo))
     989       150424 :           >= (unsigned) exact_log2 (const_vf))
     990         1785 :         return false;
     991              :     }
     992              : 
     993              :   return true;
     994              : }
     995              : 
     996              : /* Each statement in LOOP_VINFO can be masked where necessary.  Check
     997              :    whether we can actually generate the masks required.  Return true if so,
     998              :    storing the type of the scalar IV in LOOP_VINFO_RGROUP_COMPARE_TYPE.  */
     999              : 
    1000              : static bool
    1001        23524 : vect_verify_full_masking (loop_vec_info loop_vinfo)
    1002              : {
    1003        23524 :   unsigned int min_ni_width;
    1004              : 
    1005              :   /* Use a normal loop if there are no statements that need masking.
    1006              :      This only happens in rare degenerate cases: it means that the loop
    1007              :      has no loads, no stores, and no live-out values.  */
    1008        23524 :   if (LOOP_VINFO_MASKS (loop_vinfo).is_empty ())
    1009              :     return false;
    1010              : 
    1011              :   /* Produce the rgroup controls.  */
    1012        58127 :   for (auto mask : LOOP_VINFO_MASKS (loop_vinfo).mask_set)
    1013              :     {
    1014        34603 :       vec_loop_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
    1015        34603 :       tree vectype = mask.first;
    1016        34603 :       unsigned nvectors = mask.second;
    1017              : 
    1018        45682 :       if (masks->rgc_vec.length () < nvectors)
    1019        25647 :         masks->rgc_vec.safe_grow_cleared (nvectors, true);
    1020        34603 :       rgroup_controls *rgm = &(*masks).rgc_vec[nvectors - 1];
    1021              :       /* The number of scalars per iteration and the number of vectors are
    1022              :          both compile-time constants.  */
    1023        34603 :       unsigned int nscalars_per_iter
    1024        34603 :           = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
    1025        34603 :                        LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
    1026              : 
    1027        34603 :       if (rgm->max_nscalars_per_iter < nscalars_per_iter)
    1028              :         {
    1029        27550 :           rgm->max_nscalars_per_iter = nscalars_per_iter;
    1030        27550 :           rgm->type = truth_type_for (vectype);
    1031        27550 :           rgm->factor = 1;
    1032              :         }
    1033              :     }
    1034              : 
    1035        23524 :   unsigned int max_nscalars_per_iter
    1036        23524 :     = vect_get_max_nscalars_per_iter (loop_vinfo);
    1037              : 
    1038              :   /* Work out how many bits we need to represent the limit.  */
    1039        23524 :   min_ni_width
    1040        23524 :     = vect_min_prec_for_max_niters (loop_vinfo, max_nscalars_per_iter);
    1041              : 
    1042              :   /* Find a scalar mode for which WHILE_ULT is supported.  */
    1043        23524 :   opt_scalar_int_mode cmp_mode_iter;
    1044        23524 :   tree cmp_type = NULL_TREE;
    1045        23524 :   tree iv_type = NULL_TREE;
    1046        23524 :   widest_int iv_limit = vect_iv_limit_for_partial_vectors (loop_vinfo);
    1047        23524 :   unsigned int iv_precision = UINT_MAX;
    1048              : 
    1049        23524 :   if (iv_limit != -1)
    1050        23524 :     iv_precision = wi::min_precision (iv_limit * max_nscalars_per_iter,
    1051              :                                       UNSIGNED);
    1052              : 
    1053       188192 :   FOR_EACH_MODE_IN_CLASS (cmp_mode_iter, MODE_INT)
    1054              :     {
    1055       164668 :       unsigned int cmp_bits = GET_MODE_BITSIZE (cmp_mode_iter.require ());
    1056       164668 :       if (cmp_bits >= min_ni_width
    1057       164668 :           && targetm.scalar_mode_supported_p (cmp_mode_iter.require ()))
    1058              :         {
    1059       110349 :           tree this_type = build_nonstandard_integer_type (cmp_bits, true);
    1060       110349 :           if (this_type
    1061       110349 :               && can_produce_all_loop_masks_p (loop_vinfo, this_type))
    1062              :             {
    1063              :               /* Although we could stop as soon as we find a valid mode,
    1064              :                  there are at least two reasons why that's not always the
    1065              :                  best choice:
    1066              : 
    1067              :                  - An IV that's Pmode or wider is more likely to be reusable
    1068              :                    in address calculations than an IV that's narrower than
    1069              :                    Pmode.
    1070              : 
    1071              :                  - Doing the comparison in IV_PRECISION or wider allows
    1072              :                    a natural 0-based IV, whereas using a narrower comparison
    1073              :                    type requires mitigations against wrap-around.
    1074              : 
    1075              :                  Conversely, if the IV limit is variable, doing the comparison
    1076              :                  in a wider type than the original type can introduce
    1077              :                  unnecessary extensions, so picking the widest valid mode
    1078              :                  is not always a good choice either.
    1079              : 
    1080              :                  Here we prefer the first IV type that's Pmode or wider,
    1081              :                  and the first comparison type that's IV_PRECISION or wider.
    1082              :                  (The comparison type must be no wider than the IV type,
    1083              :                  to avoid extensions in the vector loop.)
    1084              : 
    1085              :                  ??? We might want to try continuing beyond Pmode for ILP32
    1086              :                  targets if CMP_BITS < IV_PRECISION.  */
    1087            0 :               iv_type = this_type;
    1088            0 :               if (!cmp_type || iv_precision > TYPE_PRECISION (cmp_type))
    1089              :                 cmp_type = this_type;
    1090            0 :               if (cmp_bits >= GET_MODE_BITSIZE (Pmode))
    1091              :                 break;
    1092              :             }
    1093              :         }
    1094              :     }
    1095              : 
    1096        23524 :   if (!cmp_type)
    1097              :     {
    1098        23524 :       LOOP_VINFO_MASKS (loop_vinfo).rgc_vec.release ();
    1099        23524 :       return false;
    1100              :     }
    1101              : 
    1102            0 :   LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo) = cmp_type;
    1103            0 :   LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo) = iv_type;
    1104            0 :   LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) = vect_partial_vectors_while_ult;
    1105            0 :   return true;
    1106        23524 : }
    1107              : 
    1108              : /* Each statement in LOOP_VINFO can be masked where necessary.  Check
    1109              :    whether we can actually generate AVX512 style masks.  Return true if so,
    1110              :    storing the type of the scalar IV in LOOP_VINFO_RGROUP_IV_TYPE.  */
    1111              : 
    1112              : static bool
    1113        23524 : vect_verify_full_masking_avx512 (loop_vec_info loop_vinfo)
    1114              : {
    1115              :   /* Produce differently organized rgc_vec and differently check
    1116              :      we can produce masks.  */
    1117              : 
    1118              :   /* Use a normal loop if there are no statements that need masking.
    1119              :      This only happens in rare degenerate cases: it means that the loop
    1120              :      has no loads, no stores, and no live-out values.  */
    1121        23524 :   if (LOOP_VINFO_MASKS (loop_vinfo).is_empty ())
    1122              :     return false;
    1123              : 
    1124              :   /* For the decrementing IV we need to represent all values in
    1125              :      [0, niter + niter_skip] where niter_skip is the elements we
    1126              :      skip in the first iteration for prologue peeling.  */
    1127        23524 :   tree iv_type = NULL_TREE;
    1128        23524 :   widest_int iv_limit = vect_iv_limit_for_partial_vectors (loop_vinfo);
    1129        23524 :   unsigned int iv_precision = UINT_MAX;
    1130        23524 :   if (iv_limit != -1)
    1131        23524 :     iv_precision = wi::min_precision (iv_limit, UNSIGNED);
    1132              : 
    1133              :   /* First compute the type for the IV we use to track the remaining
    1134              :      scalar iterations.  */
    1135        23524 :   opt_scalar_int_mode cmp_mode_iter;
    1136        30773 :   FOR_EACH_MODE_IN_CLASS (cmp_mode_iter, MODE_INT)
    1137              :     {
    1138        30773 :       unsigned int cmp_bits = GET_MODE_BITSIZE (cmp_mode_iter.require ());
    1139        30773 :       if (cmp_bits >= iv_precision
    1140        30773 :           && targetm.scalar_mode_supported_p (cmp_mode_iter.require ()))
    1141              :         {
    1142        23524 :           iv_type = build_nonstandard_integer_type (cmp_bits, true);
    1143        23524 :           if (iv_type)
    1144              :             break;
    1145              :         }
    1146              :     }
    1147        23524 :   if (!iv_type)
    1148              :     return false;
    1149              : 
    1150              :   /* Produce the rgroup controls.  */
    1151        58127 :   for (auto const &mask : LOOP_VINFO_MASKS (loop_vinfo).mask_set)
    1152              :     {
    1153        34603 :       vec_loop_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
    1154        34603 :       tree vectype = mask.first;
    1155        34603 :       unsigned nvectors = mask.second;
    1156              : 
    1157              :       /* The number of scalars per iteration and the number of vectors are
    1158              :          both compile-time constants.  */
    1159        34603 :       unsigned int nscalars_per_iter
    1160        34603 :         = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
    1161        34603 :                      LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
    1162              : 
    1163              :       /* We index the rgroup_controls vector with nscalars_per_iter
    1164              :          which we keep constant and instead have a varying nvectors,
    1165              :          remembering the vector mask with the fewest nV.  */
    1166        45682 :       if (masks->rgc_vec.length () < nscalars_per_iter)
    1167        23564 :         masks->rgc_vec.safe_grow_cleared (nscalars_per_iter, true);
    1168        34603 :       rgroup_controls *rgm = &(*masks).rgc_vec[nscalars_per_iter - 1];
    1169              : 
    1170        34603 :       if (!rgm->type || rgm->factor > nvectors)
    1171              :         {
    1172        25463 :           rgm->type = truth_type_for (vectype);
    1173        25463 :           rgm->compare_type = NULL_TREE;
    1174        25463 :           rgm->max_nscalars_per_iter = nscalars_per_iter;
    1175        25463 :           rgm->factor = nvectors;
    1176        25463 :           rgm->bias_adjusted_ctrl = NULL_TREE;
    1177              :         }
    1178              :     }
    1179              : 
    1180              :   /* There is no fixed compare type we are going to use but we have to
    1181              :      be able to get at one for each mask group.  */
    1182        23524 :   unsigned int min_ni_width
    1183        23524 :     = wi::min_precision (vect_max_vf (loop_vinfo), UNSIGNED);
    1184              : 
    1185        23524 :   bool ok = true;
    1186        89060 :   for (auto &rgc : LOOP_VINFO_MASKS (loop_vinfo).rgc_vec)
    1187              :     {
    1188        24593 :       tree mask_type = rgc.type;
    1189        24593 :       if (!mask_type)
    1190          990 :         continue;
    1191              : 
    1192              :       /* For now vect_get_loop_mask only supports integer mode masks
    1193              :          when we need to split it.  */
    1194        23603 :       if (GET_MODE_CLASS (TYPE_MODE (mask_type)) != MODE_INT
    1195        23603 :           || TYPE_PRECISION (TREE_TYPE (mask_type)) != 1)
    1196              :         {
    1197              :           ok = false;
    1198              :           break;
    1199              :         }
    1200              : 
    1201              :       /* If iv_type is usable as compare type use that - we can elide the
    1202              :          saturation in that case.   */
    1203        17502 :       if (TYPE_PRECISION (iv_type) >= min_ni_width)
    1204              :         {
    1205        17502 :           tree cmp_vectype
    1206        17502 :             = build_vector_type (iv_type, TYPE_VECTOR_SUBPARTS (mask_type));
    1207        17502 :           if (expand_vec_cmp_expr_p (cmp_vectype, mask_type, LT_EXPR))
    1208         5953 :             rgc.compare_type = cmp_vectype;
    1209              :         }
    1210        17502 :       if (!rgc.compare_type)
    1211        33222 :         FOR_EACH_MODE_IN_CLASS (cmp_mode_iter, MODE_INT)
    1212              :           {
    1213        33218 :             unsigned int cmp_bits = GET_MODE_BITSIZE (cmp_mode_iter.require ());
    1214        33218 :             if (cmp_bits >= min_ni_width
    1215        33218 :                 && targetm.scalar_mode_supported_p (cmp_mode_iter.require ()))
    1216              :               {
    1217        33206 :                 tree cmp_type = build_nonstandard_integer_type (cmp_bits, true);
    1218        33206 :                 if (!cmp_type)
    1219            0 :                   continue;
    1220              : 
    1221              :                 /* Check whether we can produce the mask with cmp_type.  */
    1222        33206 :                 tree cmp_vectype
    1223        33206 :                   = build_vector_type (cmp_type, TYPE_VECTOR_SUBPARTS (mask_type));
    1224        33206 :                 if (expand_vec_cmp_expr_p (cmp_vectype, mask_type, LT_EXPR))
    1225              :                   {
    1226        11545 :                     rgc.compare_type = cmp_vectype;
    1227        11545 :                     break;
    1228              :                   }
    1229              :               }
    1230              :         }
    1231        17502 :       if (!rgc.compare_type)
    1232              :         {
    1233              :           ok = false;
    1234              :           break;
    1235              :         }
    1236              :     }
    1237        23524 :   if (!ok)
    1238              :     {
    1239         6105 :       release_vec_loop_controls (&LOOP_VINFO_MASKS (loop_vinfo).rgc_vec);
    1240         6105 :       return false;
    1241              :     }
    1242              : 
    1243        17419 :   LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo) = error_mark_node;
    1244        17419 :   LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo) = iv_type;
    1245        17419 :   LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) = vect_partial_vectors_avx512;
    1246        17419 :   return true;
    1247        23524 : }
    1248              : 
    1249              : /* Check whether we can use vector access with length based on precision
    1250              :    comparison.  So far, to keep it simple, we only allow the case that the
    1251              :    precision of the target supported length is larger than the precision
    1252              :    required by loop niters.  */
    1253              : 
    1254              : static bool
    1255            6 : vect_verify_loop_lens (loop_vec_info loop_vinfo)
    1256              : {
    1257            6 :   if (LOOP_VINFO_LENS (loop_vinfo).is_empty ())
    1258              :     return false;
    1259              : 
    1260            0 :   if (!VECTOR_MODE_P (loop_vinfo->vector_mode))
    1261              :     return false;
    1262              : 
    1263            0 :   machine_mode len_load_mode, len_store_mode;
    1264            0 :   if (!get_len_load_store_mode (loop_vinfo->vector_mode, true)
    1265            0 :          .exists (&len_load_mode))
    1266            0 :     return false;
    1267            0 :   if (!get_len_load_store_mode (loop_vinfo->vector_mode, false)
    1268            0 :          .exists (&len_store_mode))
    1269            0 :     return false;
    1270              : 
    1271            0 :   signed char partial_load_bias = internal_len_load_store_bias
    1272            0 :     (IFN_LEN_LOAD, len_load_mode);
    1273              : 
    1274            0 :   signed char partial_store_bias = internal_len_load_store_bias
    1275            0 :     (IFN_LEN_STORE, len_store_mode);
    1276              : 
    1277            0 :   gcc_assert (partial_load_bias == partial_store_bias);
    1278              : 
    1279            0 :   if (partial_load_bias == VECT_PARTIAL_BIAS_UNSUPPORTED)
    1280              :     return false;
    1281              : 
    1282              :   /* If the backend requires a bias of -1 for LEN_LOAD, we must not emit
    1283              :      len_loads with a length of zero.  In order to avoid that we prohibit
    1284              :      more than one loop length here.  */
    1285            0 :   if (partial_load_bias == -1
    1286            0 :       && LOOP_VINFO_LENS (loop_vinfo).length () > 1)
    1287              :     return false;
    1288              : 
    1289            0 :   LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo) = partial_load_bias;
    1290              : 
    1291            0 :   unsigned int max_nitems_per_iter = 1;
    1292            0 :   unsigned int i;
    1293            0 :   rgroup_controls *rgl;
    1294              :   /* Find the maximum number of items per iteration for every rgroup.  */
    1295            0 :   FOR_EACH_VEC_ELT (LOOP_VINFO_LENS (loop_vinfo), i, rgl)
    1296              :     {
    1297            0 :       unsigned nitems_per_iter = rgl->max_nscalars_per_iter * rgl->factor;
    1298            0 :       max_nitems_per_iter = MAX (max_nitems_per_iter, nitems_per_iter);
    1299              :     }
    1300              : 
    1301              :   /* Work out how many bits we need to represent the length limit.  */
    1302            0 :   unsigned int min_ni_prec
    1303            0 :     = vect_min_prec_for_max_niters (loop_vinfo, max_nitems_per_iter);
    1304              : 
    1305              :   /* Now use the maximum of below precisions for one suitable IV type:
    1306              :      - the IV's natural precision
    1307              :      - the precision needed to hold: the maximum number of scalar
    1308              :        iterations multiplied by the scale factor (min_ni_prec above)
    1309              :      - the Pmode precision
    1310              : 
    1311              :      If min_ni_prec is less than the precision of the current niters,
    1312              :      we prefer to still use the niters type.  Prefer to use Pmode and
    1313              :      wider IV to avoid narrow conversions.  */
    1314              : 
    1315            0 :   unsigned int ni_prec
    1316            0 :     = TYPE_PRECISION (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)));
    1317            0 :   min_ni_prec = MAX (min_ni_prec, ni_prec);
    1318            0 :   min_ni_prec = MAX (min_ni_prec, GET_MODE_BITSIZE (Pmode));
    1319              : 
    1320            0 :   tree iv_type = NULL_TREE;
    1321            0 :   opt_scalar_int_mode tmode_iter;
    1322            0 :   FOR_EACH_MODE_IN_CLASS (tmode_iter, MODE_INT)
    1323              :     {
    1324            0 :       scalar_mode tmode = tmode_iter.require ();
    1325            0 :       unsigned int tbits = GET_MODE_BITSIZE (tmode);
    1326              : 
    1327              :       /* ??? Do we really want to construct one IV whose precision exceeds
    1328              :          BITS_PER_WORD?  */
    1329            0 :       if (tbits > BITS_PER_WORD)
    1330              :         break;
    1331              : 
    1332              :       /* Find the first available standard integral type.  */
    1333            0 :       if (tbits >= min_ni_prec && targetm.scalar_mode_supported_p (tmode))
    1334              :         {
    1335            0 :           iv_type = build_nonstandard_integer_type (tbits, true);
    1336            0 :           break;
    1337              :         }
    1338              :     }
    1339              : 
    1340            0 :   if (!iv_type)
    1341              :     {
    1342            0 :       if (dump_enabled_p ())
    1343            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1344              :                          "can't vectorize with length-based partial vectors"
    1345              :                          " because there is no suitable iv type.\n");
    1346              :       return false;
    1347              :     }
    1348              : 
    1349            0 :   LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo) = iv_type;
    1350            0 :   LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo) = iv_type;
    1351            0 :   LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) = vect_partial_vectors_len;
    1352              : 
    1353            0 :   return true;
    1354              : }
    1355              : 
    1356              : /* Calculate the cost of one scalar iteration of the loop.  */
    1357              : static void
    1358       374587 : vect_compute_single_scalar_iteration_cost (loop_vec_info loop_vinfo)
    1359              : {
    1360       374587 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    1361       374587 :   basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
    1362       374587 :   int nbbs = loop->num_nodes, factor;
    1363       374587 :   int innerloop_iters, i;
    1364              : 
    1365       374587 :   DUMP_VECT_SCOPE ("vect_compute_single_scalar_iteration_cost");
    1366              : 
    1367              :   /* Gather costs for statements in the scalar loop.  */
    1368              : 
    1369              :   /* FORNOW.  */
    1370       374587 :   innerloop_iters = 1;
    1371       374587 :   if (loop->inner)
    1372         1600 :     innerloop_iters = LOOP_VINFO_INNER_LOOP_COST_FACTOR (loop_vinfo);
    1373              : 
    1374      1290205 :   for (i = 0; i < nbbs; i++)
    1375              :     {
    1376       915618 :       gimple_stmt_iterator si;
    1377       915618 :       basic_block bb = bbs[i];
    1378              : 
    1379       915618 :       if (bb->loop_father == loop->inner)
    1380              :         factor = innerloop_iters;
    1381              :       else
    1382       912418 :         factor = 1;
    1383              : 
    1384      7558712 :       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
    1385              :         {
    1386      5727476 :           gimple *stmt = gsi_stmt (si);
    1387      5727476 :           stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (stmt);
    1388              : 
    1389      5727476 :           if (!is_gimple_assign (stmt)
    1390              :               && !is_gimple_call (stmt)
    1391              :               && !is_a<gcond *> (stmt))
    1392      2105616 :             continue;
    1393              : 
    1394              :           /* Skip stmts that are not vectorized inside the loop.  */
    1395      3621860 :           stmt_vec_info vstmt_info = vect_stmt_to_vectorize (stmt_info);
    1396      3621860 :           if (!STMT_VINFO_RELEVANT_P (vstmt_info)
    1397      1791305 :               && (!STMT_VINFO_LIVE_P (vstmt_info)
    1398           36 :                   || !VECTORIZABLE_CYCLE_DEF
    1399              :                         (STMT_VINFO_DEF_TYPE (vstmt_info))))
    1400      1791305 :             continue;
    1401              : 
    1402      1830555 :           vect_cost_for_stmt kind;
    1403      1830555 :           if (STMT_VINFO_DATA_REF (stmt_info))
    1404              :             {
    1405       883712 :               if (DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)))
    1406              :                kind = scalar_load;
    1407              :              else
    1408       328797 :                kind = scalar_store;
    1409              :             }
    1410       946843 :           else if (vect_nop_conversion_p (stmt_info))
    1411        53766 :             continue;
    1412              :           else
    1413              :             kind = scalar_stmt;
    1414              : 
    1415              :           /* We are using vect_prologue here to avoid scaling twice
    1416              :              by the inner loop factor.  */
    1417      1776789 :           record_stmt_cost (&LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo),
    1418              :                             factor, kind, stmt_info, 0, vect_body);
    1419              :         }
    1420              :     }
    1421              : 
    1422              :   /* Now accumulate cost.  */
    1423       374587 :   loop_vinfo->scalar_costs = init_cost (loop_vinfo, true);
    1424       374587 :   add_stmt_costs (loop_vinfo->scalar_costs,
    1425              :                   &LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo));
    1426       374587 :   loop_vinfo->scalar_costs->finish_cost (nullptr);
    1427       374587 : }
    1428              : 
    1429              : /* Function vect_analyze_loop_form.
    1430              : 
    1431              :    Verify that certain CFG restrictions hold, including:
    1432              :    - the loop has a pre-header
    1433              :    - the loop has a single entry
    1434              :    - nested loops can have only a single exit.
    1435              :    - the loop exit condition is simple enough
    1436              :    - the number of iterations can be analyzed, i.e, a countable loop.  The
    1437              :      niter could be analyzed under some assumptions.  */
    1438              : 
    1439              : opt_result
    1440       465372 : vect_analyze_loop_form (class loop *loop, gimple *loop_vectorized_call,
    1441              :                         vect_loop_form_info *info)
    1442              : {
    1443       465372 :   DUMP_VECT_SCOPE ("vect_analyze_loop_form");
    1444              : 
    1445       465372 :   edge exit_e = vec_init_loop_exit_info (loop);
    1446       465372 :   if (!exit_e)
    1447        30162 :     return opt_result::failure_at (vect_location,
    1448              :                                    "not vectorized:"
    1449              :                                    " Infinite loop detected.\n");
    1450       435210 :   if (loop_vectorized_call)
    1451              :     {
    1452        25009 :       tree arg = gimple_call_arg (loop_vectorized_call, 1);
    1453        25009 :       class loop *scalar_loop = get_loop (cfun, tree_to_shwi (arg));
    1454        25009 :       edge scalar_exit_e = vec_init_loop_exit_info (scalar_loop);
    1455        25009 :       if (!scalar_exit_e)
    1456            0 :         return opt_result::failure_at (vect_location,
    1457              :                                        "not vectorized:"
    1458              :                                        " could not determine main exit from"
    1459              :                                        " loop with multiple exits.\n");
    1460              :     }
    1461              : 
    1462       435210 :   info->loop_exit = exit_e;
    1463       435210 :   if (dump_enabled_p ())
    1464        16191 :       dump_printf_loc (MSG_NOTE, vect_location,
    1465              :                        "using as main loop exit: %d -> %d [AUX: %p]\n",
    1466        16191 :                        exit_e->src->index, exit_e->dest->index, exit_e->aux);
    1467              : 
    1468              :   /* Check if we have any control flow that doesn't leave the loop.  */
    1469       435210 :   basic_block *bbs = get_loop_body (loop);
    1470      1861546 :   for (unsigned i = 0; i < loop->num_nodes; i++)
    1471      1109651 :     if (EDGE_COUNT (bbs[i]->succs) != 1
    1472      1109651 :         && (EDGE_COUNT (bbs[i]->succs) != 2
    1473       664671 :             || !loop_exits_from_bb_p (bbs[i]->loop_father, bbs[i])))
    1474              :       {
    1475       118525 :         free (bbs);
    1476       118525 :         return opt_result::failure_at (vect_location,
    1477              :                                        "not vectorized:"
    1478              :                                        " unsupported control flow in loop.\n");
    1479              :       }
    1480              : 
    1481              :   /* Check if we have any control flow that doesn't leave the loop.  */
    1482       317785 :   bool has_phi = false;
    1483       317785 :   for (unsigned i = 0; i < loop->num_nodes; i++)
    1484       317327 :     if (!gimple_seq_empty_p (phi_nodes (bbs[i])))
    1485              :       {
    1486              :         has_phi = true;
    1487              :         break;
    1488              :       }
    1489       316685 :   if (!has_phi)
    1490          458 :     return opt_result::failure_at (vect_location,
    1491              :                                    "not vectorized:"
    1492              :                                    " no scalar evolution detected in loop.\n");
    1493              : 
    1494       316227 :   free (bbs);
    1495              : 
    1496              :   /* Different restrictions apply when we are considering an inner-most loop,
    1497              :      vs. an outer (nested) loop.
    1498              :      (FORNOW. May want to relax some of these restrictions in the future).  */
    1499              : 
    1500       316227 :   info->inner_loop_cond = NULL;
    1501       316227 :   if (!loop->inner)
    1502              :     {
    1503              :       /* Inner-most loop.  */
    1504              : 
    1505       297430 :       if (empty_block_p (loop->header))
    1506            0 :         return opt_result::failure_at (vect_location,
    1507              :                                        "not vectorized: empty loop.\n");
    1508              :     }
    1509              :   else
    1510              :     {
    1511        18797 :       class loop *innerloop = loop->inner;
    1512        18797 :       edge entryedge;
    1513              : 
    1514              :       /* Nested loop. We currently require that the loop is doubly-nested,
    1515              :          contains a single inner loop with a single exit to the block
    1516              :          with the single exit condition in the outer loop.
    1517              :          Vectorizable outer-loops look like this:
    1518              : 
    1519              :                         (pre-header)
    1520              :                            |
    1521              :                           header <---+
    1522              :                            |         |
    1523              :                           inner-loop |
    1524              :                            |         |
    1525              :                           tail ------+
    1526              :                            |
    1527              :                         (exit-bb)
    1528              : 
    1529              :          The inner-loop also has the properties expected of inner-most loops
    1530              :          as described above.  */
    1531              : 
    1532        18797 :       if ((loop->inner)->inner || (loop->inner)->next)
    1533         3041 :         return opt_result::failure_at (vect_location,
    1534              :                                        "not vectorized:"
    1535              :                                        " multiple nested loops.\n");
    1536              : 
    1537        15756 :       entryedge = loop_preheader_edge (innerloop);
    1538        15756 :       if (entryedge->src != loop->header
    1539        15214 :           || !single_exit (innerloop)
    1540        27277 :           || single_exit (innerloop)->dest != EDGE_PRED (loop->latch, 0)->src)
    1541         4542 :         return opt_result::failure_at (vect_location,
    1542              :                                        "not vectorized:"
    1543              :                                        " unsupported outerloop form.\n");
    1544              : 
    1545              :       /* Analyze the inner-loop.  */
    1546        11214 :       vect_loop_form_info inner;
    1547        11214 :       opt_result res = vect_analyze_loop_form (loop->inner, NULL, &inner);
    1548        11214 :       if (!res)
    1549              :         {
    1550          417 :           if (dump_enabled_p ())
    1551            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1552              :                              "not vectorized: Bad inner loop.\n");
    1553          417 :           return res;
    1554              :         }
    1555              : 
    1556              :       /* Don't support analyzing niter under assumptions for inner
    1557              :          loop.  */
    1558        10797 :       if (!integer_onep (inner.assumptions))
    1559          263 :         return opt_result::failure_at (vect_location,
    1560              :                                        "not vectorized: Bad inner loop.\n");
    1561              : 
    1562        10534 :       if (inner.number_of_iterations ==  chrec_dont_know
    1563        10534 :           || !expr_invariant_in_loop_p (loop, inner.number_of_iterations))
    1564         1846 :         return opt_result::failure_at (vect_location,
    1565              :                                        "not vectorized: inner-loop count not"
    1566              :                                        " invariant.\n");
    1567              : 
    1568         8688 :       if (dump_enabled_p ())
    1569         1050 :         dump_printf_loc (MSG_NOTE, vect_location,
    1570              :                          "Considering outer-loop vectorization.\n");
    1571         8688 :       info->inner_loop_cond = inner.conds[0];
    1572        11214 :     }
    1573              : 
    1574       306118 :   if (EDGE_COUNT (loop->header->preds) != 2)
    1575            0 :     return opt_result::failure_at (vect_location,
    1576              :                                    "not vectorized:"
    1577              :                                    " too many incoming edges.\n");
    1578              : 
    1579              :   /* We assume that the latch is empty.  */
    1580       306118 :   basic_block latch = loop->latch;
    1581       306118 :   do
    1582              :     {
    1583       306118 :       if (!empty_block_p (latch)
    1584       306118 :           || !gimple_seq_empty_p (phi_nodes (latch)))
    1585        20421 :         return opt_result::failure_at (vect_location,
    1586              :                                        "not vectorized: latch block not "
    1587              :                                        "empty.\n");
    1588       285697 :       latch = single_pred (latch);
    1589              :     }
    1590       571394 :   while (single_succ_p (latch));
    1591              : 
    1592              :   /* Make sure there is no abnormal exit.  */
    1593       285697 :   auto_vec<edge> exits = get_loop_exit_edges (loop);
    1594       983526 :   for (edge e : exits)
    1595              :     {
    1596       412165 :       if (e->flags & EDGE_ABNORMAL)
    1597           33 :         return opt_result::failure_at (vect_location,
    1598              :                                        "not vectorized:"
    1599              :                                        " abnormal loop exit edge.\n");
    1600              :     }
    1601              : 
    1602       285664 :   info->conds
    1603       285664 :     = vect_get_loop_niters (loop, exit_e, &info->assumptions,
    1604              :                             &info->number_of_iterations,
    1605       285664 :                             &info->number_of_iterationsm1);
    1606       285664 :   if (info->conds.is_empty ())
    1607           34 :     return opt_result::failure_at
    1608           34 :       (vect_location,
    1609              :        "not vectorized: complicated exit condition.\n");
    1610              : 
    1611              :   /* Determine what the primary and alternate exit conds are.  */
    1612       697728 :   for (unsigned i = 0; i < info->conds.length (); i++)
    1613              :     {
    1614       412098 :       gcond *cond = info->conds[i];
    1615       412098 :       if (exit_e->src == gimple_bb (cond))
    1616       285630 :         std::swap (info->conds[0], info->conds[i]);
    1617              :     }
    1618              : 
    1619       285630 :   if (chrec_contains_undetermined (info->number_of_iterations))
    1620              :     {
    1621        60102 :       if (dump_enabled_p ())
    1622          257 :         dump_printf_loc (MSG_NOTE, vect_location,
    1623              :                          "Loop being analyzed as uncounted.\n");
    1624        60102 :       if (loop->inner)
    1625          563 :         return opt_result::failure_at
    1626          563 :           (vect_location,
    1627              :            "not vectorized: outer loop vectorization of uncounted loops"
    1628              :            " is unsupported.\n");
    1629        59539 :       return opt_result::success ();
    1630              :     }
    1631              : 
    1632       225528 :   if (integer_zerop (info->assumptions))
    1633            4 :     return opt_result::failure_at
    1634            4 :       (info->conds[0],
    1635              :        "not vectorized: number of iterations cannot be computed.\n");
    1636              : 
    1637       225524 :   if (integer_zerop (info->number_of_iterations))
    1638           12 :     return opt_result::failure_at
    1639           12 :       (info->conds[0],
    1640              :        "not vectorized: number of iterations = 0.\n");
    1641              : 
    1642       225512 :   if (!(tree_fits_shwi_p (info->number_of_iterations)
    1643       124591 :         && tree_to_shwi (info->number_of_iterations) > 0))
    1644              :     {
    1645       100921 :       if (dump_enabled_p ())
    1646              :         {
    1647         2550 :           dump_printf_loc (MSG_NOTE, vect_location,
    1648              :                            "Symbolic number of iterations is ");
    1649         2550 :           dump_generic_expr (MSG_NOTE, TDF_DETAILS, info->number_of_iterations);
    1650         2550 :           dump_printf (MSG_NOTE, "\n");
    1651              :         }
    1652              :     }
    1653              : 
    1654       225512 :   if (!integer_onep (info->assumptions))
    1655              :     {
    1656         8764 :       if (dump_enabled_p ())
    1657              :         {
    1658           75 :           dump_printf_loc (MSG_NOTE, vect_location,
    1659              :                            "Loop to be versioned with niter assumption ");
    1660           75 :           dump_generic_expr (MSG_NOTE, TDF_SLIM, info->assumptions);
    1661           75 :           dump_printf (MSG_NOTE, "\n");
    1662              :         }
    1663              :     }
    1664              : 
    1665       225512 :   return opt_result::success ();
    1666       285697 : }
    1667              : 
    1668              : /* Create a loop_vec_info for LOOP with SHARED and the
    1669              :    vect_analyze_loop_form result.  */
    1670              : 
    1671              : loop_vec_info
    1672       591676 : vect_create_loop_vinfo (class loop *loop, vec_info_shared *shared,
    1673              :                         const vect_loop_form_info *info,
    1674              :                         loop_vec_info orig_loop_info)
    1675              : {
    1676       591676 :   loop_vec_info loop_vinfo = new _loop_vec_info (loop, shared);
    1677       591676 :   LOOP_VINFO_NITERSM1 (loop_vinfo) = info->number_of_iterationsm1;
    1678       591676 :   LOOP_VINFO_NITERS (loop_vinfo) = info->number_of_iterations;
    1679       591676 :   LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = info->number_of_iterations;
    1680       591676 :   LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo) = orig_loop_info;
    1681       591676 :   if (orig_loop_info && LOOP_VINFO_EPILOGUE_P (orig_loop_info))
    1682          340 :     LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo)
    1683          340 :       = LOOP_VINFO_MAIN_LOOP_INFO (orig_loop_info);
    1684              :   else
    1685       591336 :     LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo) = orig_loop_info;
    1686              :   /* Also record the assumptions for versioning.  */
    1687       591676 :   if (!integer_onep (info->assumptions) && !orig_loop_info)
    1688        19769 :     LOOP_VINFO_NITERS_ASSUMPTIONS (loop_vinfo) = info->assumptions;
    1689              : 
    1690      2628975 :   for (gcond *cond : info->conds)
    1691              :     {
    1692       853947 :       stmt_vec_info loop_cond_info = loop_vinfo->lookup_stmt (cond);
    1693              :       /* Mark the statement as a condition.  */
    1694       853947 :       STMT_VINFO_DEF_TYPE (loop_cond_info) = vect_condition_def;
    1695              :     }
    1696              : 
    1697       591676 :   unsigned cond_id = 0;
    1698       591676 :   if (!LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo))
    1699       504352 :     LOOP_VINFO_LOOP_IV_COND (loop_vinfo) = info->conds[cond_id++];
    1700              : 
    1701       941271 :   for (; cond_id < info->conds.length (); cond_id ++)
    1702       349595 :     LOOP_VINFO_LOOP_CONDS (loop_vinfo).safe_push (info->conds[cond_id]);
    1703              : 
    1704       591676 :   LOOP_VINFO_MAIN_EXIT (loop_vinfo) = info->loop_exit;
    1705              : 
    1706              :   /* Check to see if we're vectorizing multiple exits.  */
    1707       591676 :   LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
    1708       591676 :     = !LOOP_VINFO_LOOP_CONDS (loop_vinfo).is_empty ();
    1709              : 
    1710              :   /* At the moment we can't support no epilogs for multiple exits, result of
    1711              :      the first compare should be masked by that of the second.  We can only
    1712              :      allow it if the early exits have the same live values.  for differing
    1713              :      values we have to calculate a third mask to disambiguate. */
    1714       591676 :   LOOP_VINFO_EARLY_BRK_NEEDS_EPILOG (loop_vinfo)
    1715       591676 :     = LOOP_VINFO_LOOP_CONDS (loop_vinfo).length () > 1;
    1716              : 
    1717       591676 :   if (info->inner_loop_cond)
    1718              :     {
    1719              :       /* If we have an estimate on the number of iterations of the inner
    1720              :          loop use that to limit the scale for costing, otherwise use
    1721              :          --param vect-inner-loop-cost-factor literally.  */
    1722         9103 :       widest_int nit;
    1723         9103 :       if (estimated_stmt_executions (loop->inner, &nit))
    1724         7788 :         LOOP_VINFO_INNER_LOOP_COST_FACTOR (loop_vinfo)
    1725         7788 :           = wi::smin (nit, param_vect_inner_loop_cost_factor).to_uhwi ();
    1726         9103 :     }
    1727              : 
    1728       591676 :   return loop_vinfo;
    1729              : }
    1730              : 
    1731              : 
    1732              : 
    1733              : /* Return true if we know that the iteration count is smaller than the
    1734              :    vectorization factor.  Return false if it isn't, or if we can't be sure
    1735              :    either way.  */
    1736              : 
    1737              : static bool
    1738       155911 : vect_known_niters_smaller_than_vf (loop_vec_info loop_vinfo)
    1739              : {
    1740       155911 :   unsigned int assumed_vf = vect_vf_for_cost (loop_vinfo);
    1741              : 
    1742       155911 :   HOST_WIDE_INT max_niter;
    1743       155911 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
    1744        80183 :     max_niter = LOOP_VINFO_INT_NITERS (loop_vinfo);
    1745              :   else
    1746        75728 :     max_niter = max_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
    1747              : 
    1748       155911 :   if (max_niter != -1 && (unsigned HOST_WIDE_INT) max_niter < assumed_vf)
    1749        11056 :     return true;
    1750              : 
    1751              :   return false;
    1752              : }
    1753              : 
    1754              : /* Analyze the cost of the loop described by LOOP_VINFO.  Decide if it
    1755              :    is worthwhile to vectorize.  Return 1 if definitely yes, 0 if
    1756              :    definitely no, or -1 if it's worth retrying.  */
    1757              : 
    1758              : static int
    1759       155924 : vect_analyze_loop_costing (loop_vec_info loop_vinfo,
    1760              :                            unsigned *suggested_unroll_factor)
    1761              : {
    1762       155924 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    1763       155924 :   unsigned int assumed_vf = vect_vf_for_cost (loop_vinfo);
    1764              : 
    1765              :   /* Only loops that can handle partially-populated vectors can have iteration
    1766              :      counts less than the vectorization factor.  */
    1767       155924 :   if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    1768       155924 :       && vect_known_niters_smaller_than_vf (loop_vinfo))
    1769              :     {
    1770        11046 :       if (dump_enabled_p ())
    1771          242 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1772              :                          "not vectorized: iteration count smaller than "
    1773              :                          "vectorization factor.\n");
    1774              :       return 0;
    1775              :     }
    1776              : 
    1777              :   /* If we know the number of iterations we can do better, for the
    1778              :      epilogue we can also decide whether the main loop leaves us
    1779              :      with enough iterations, preferring a smaller vector epilog then
    1780              :      also possibly used for the case we skip the vector loop.  */
    1781       144878 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
    1782              :     {
    1783        70418 :       widest_int scalar_niters
    1784        70418 :         = wi::to_widest (LOOP_VINFO_NITERSM1 (loop_vinfo)) + 1;
    1785        70418 :       if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
    1786              :         {
    1787         2644 :           loop_vec_info orig_loop_vinfo
    1788              :             = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
    1789         2644 :           loop_vec_info main_loop_vinfo
    1790              :             = LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo);
    1791         2644 :           unsigned lowest_vf
    1792         2644 :             = constant_lower_bound (LOOP_VINFO_VECT_FACTOR (orig_loop_vinfo));
    1793         2644 :           int prolog_peeling = 0;
    1794         2644 :           if (!vect_use_loop_mask_for_alignment_p (main_loop_vinfo))
    1795         2644 :             prolog_peeling = LOOP_VINFO_PEELING_FOR_ALIGNMENT (main_loop_vinfo);
    1796         2644 :           if (prolog_peeling >= 0
    1797         2644 :               && known_eq (LOOP_VINFO_VECT_FACTOR (orig_loop_vinfo),
    1798              :                            lowest_vf))
    1799              :             {
    1800         5278 :               unsigned gap
    1801         2639 :                 = LOOP_VINFO_PEELING_FOR_GAPS (main_loop_vinfo) ? 1 : 0;
    1802         5278 :               scalar_niters = ((scalar_niters - gap - prolog_peeling)
    1803         5278 :                                % lowest_vf + gap);
    1804              :             }
    1805              :         }
    1806              :       /* Reject vectorizing for a single scalar iteration, even if
    1807              :          we could in principle implement that using partial vectors.
    1808              :          But allow such vectorization if VF == 1 in case we do not
    1809              :          need to peel for gaps (if we need, avoid vectorization for
    1810              :          reasons of code footprint).  */
    1811        70418 :       unsigned peeling_gap = LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo);
    1812        70418 :       if (scalar_niters <= peeling_gap + 1
    1813        70418 :           && (assumed_vf > 1 || peeling_gap != 0))
    1814              :         {
    1815          670 :           if (dump_enabled_p ())
    1816          162 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1817              :                              "not vectorized: loop only has a single "
    1818              :                              "scalar iteration.\n");
    1819              :           return 0;
    1820              :         }
    1821              : 
    1822        69748 :       if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    1823              :         {
    1824              :           /* Check that the loop processes at least one full vector.  */
    1825        69735 :           poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    1826        69735 :           if (known_lt (scalar_niters, vf))
    1827              :             {
    1828          350 :               if (dump_enabled_p ())
    1829          296 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1830              :                                  "loop does not have enough iterations "
    1831              :                                  "to support vectorization.\n");
    1832          390 :               return 0;
    1833              :             }
    1834              : 
    1835              :           /* If we need to peel an extra epilogue iteration to handle data
    1836              :              accesses with gaps, check that there are enough scalar iterations
    1837              :              available.
    1838              : 
    1839              :              The check above is redundant with this one when peeling for gaps,
    1840              :              but the distinction is useful for diagnostics.  */
    1841        69385 :           if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
    1842        69706 :               && known_le (scalar_niters, vf))
    1843              :             {
    1844           40 :               if (dump_enabled_p ())
    1845            9 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1846              :                                  "loop does not have enough iterations "
    1847              :                                  "to support peeling for gaps.\n");
    1848              :               return 0;
    1849              :             }
    1850              :         }
    1851        70418 :     }
    1852              : 
    1853              :   /* If using the "very cheap" model. reject cases in which we'd keep
    1854              :      a copy of the scalar code (even if we might be able to vectorize it).  */
    1855       143818 :   if (loop_cost_model (loop) == VECT_COST_MODEL_VERY_CHEAP
    1856       143818 :       && (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
    1857        76247 :           || LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)))
    1858              :     {
    1859          721 :       if (dump_enabled_p ())
    1860            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1861              :                          "some scalar iterations would need to be peeled\n");
    1862              :       return 0;
    1863              :     }
    1864              : 
    1865       143097 :   int min_profitable_iters, min_profitable_estimate;
    1866       143097 :   vect_estimate_min_profitable_iters (loop_vinfo, &min_profitable_iters,
    1867              :                                       &min_profitable_estimate,
    1868              :                                       suggested_unroll_factor);
    1869              : 
    1870       143097 :   if (min_profitable_iters < 0)
    1871              :     {
    1872        24332 :       if (dump_enabled_p ())
    1873           30 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1874              :                          "not vectorized: vectorization not profitable.\n");
    1875        24332 :       if (dump_enabled_p ())
    1876           30 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1877              :                          "not vectorized: vector version will never be "
    1878              :                          "profitable.\n");
    1879              :       return -1;
    1880              :     }
    1881              : 
    1882       118765 :   int min_scalar_loop_bound = (param_min_vect_loop_bound
    1883       118765 :                                * assumed_vf);
    1884              : 
    1885              :   /* Use the cost model only if it is more conservative than user specified
    1886              :      threshold.  */
    1887       118765 :   unsigned int th = (unsigned) MAX (min_scalar_loop_bound,
    1888              :                                     min_profitable_iters);
    1889              : 
    1890       118765 :   LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = th;
    1891              : 
    1892        63980 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    1893       182745 :       && LOOP_VINFO_INT_NITERS (loop_vinfo) < th)
    1894              :     {
    1895          457 :       if (dump_enabled_p ())
    1896            1 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1897              :                          "not vectorized: vectorization not profitable.\n");
    1898          457 :       if (dump_enabled_p ())
    1899            1 :         dump_printf_loc (MSG_NOTE, vect_location,
    1900              :                          "not vectorized: iteration count smaller than user "
    1901              :                          "specified loop bound parameter or minimum profitable "
    1902              :                          "iterations (whichever is more conservative).\n");
    1903              :       return 0;
    1904              :     }
    1905              : 
    1906              :   /* The static profitablity threshold min_profitable_estimate includes
    1907              :      the cost of having to check at runtime whether the scalar loop
    1908              :      should be used instead.  If it turns out that we don't need or want
    1909              :      such a check, the threshold we should use for the static estimate
    1910              :      is simply the point at which the vector loop becomes more profitable
    1911              :      than the scalar loop.  */
    1912       118308 :   if (min_profitable_estimate > min_profitable_iters
    1913        25230 :       && !LOOP_REQUIRES_VERSIONING (loop_vinfo)
    1914        24655 :       && !LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
    1915          642 :       && !LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
    1916       118950 :       && !vect_apply_runtime_profitability_check_p (loop_vinfo))
    1917              :     {
    1918           14 :       if (dump_enabled_p ())
    1919            8 :         dump_printf_loc (MSG_NOTE, vect_location, "no need for a runtime"
    1920              :                          " choice between the scalar and vector loops\n");
    1921           14 :       min_profitable_estimate = min_profitable_iters;
    1922              :     }
    1923              : 
    1924              :   /* If the vector loop needs multiple iterations to be beneficial then
    1925              :      things are probably too close to call, and the conservative thing
    1926              :      would be to stick with the scalar code.  */
    1927       118308 :   if (loop_cost_model (loop) == VECT_COST_MODEL_VERY_CHEAP
    1928       118308 :       && min_profitable_estimate > (int) vect_vf_for_cost (loop_vinfo))
    1929              :     {
    1930        18433 :       if (dump_enabled_p ())
    1931          225 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1932              :                          "one iteration of the vector loop would be"
    1933              :                          " more expensive than the equivalent number of"
    1934              :                          " iterations of the scalar loop\n");
    1935              :       return 0;
    1936              :     }
    1937              : 
    1938        99875 :   HOST_WIDE_INT estimated_niter;
    1939              : 
    1940              :   /* If we are vectorizing an epilogue then we know the maximum number of
    1941              :      scalar iterations it will cover is at least one lower than the
    1942              :      vectorization factor of the main loop.  */
    1943        99875 :   if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
    1944        12084 :     estimated_niter
    1945        12084 :       = vect_vf_for_cost (LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo)) - 1;
    1946              :   else
    1947              :     {
    1948        87791 :       estimated_niter = estimated_stmt_executions_int (loop);
    1949        87791 :       if (estimated_niter == -1)
    1950        31870 :         estimated_niter = likely_max_stmt_executions_int (loop);
    1951              :     }
    1952        43954 :   if (estimated_niter != -1
    1953        96937 :       && ((unsigned HOST_WIDE_INT) estimated_niter
    1954        96937 :           < MAX (th, (unsigned) min_profitable_estimate)))
    1955              :     {
    1956         4293 :       if (dump_enabled_p ())
    1957           34 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1958              :                          "not vectorized: estimated iteration count too "
    1959              :                          "small.\n");
    1960         4293 :       if (dump_enabled_p ())
    1961           34 :         dump_printf_loc (MSG_NOTE, vect_location,
    1962              :                          "not vectorized: estimated iteration count smaller "
    1963              :                          "than specified loop bound parameter or minimum "
    1964              :                          "profitable iterations (whichever is more "
    1965              :                          "conservative).\n");
    1966              :       return -1;
    1967              :     }
    1968              : 
    1969              :   /* As we cannot use a runtime check to gate profitability for uncounted
    1970              :      loops require either an estimate or if none, at least a profitable
    1971              :      vectorization within the first vector iteration (that condition
    1972              :      will practically never be true due to the required epilog and
    1973              :      likely alignment prologue).   */
    1974        95582 :   if (LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo)
    1975          163 :       && estimated_niter == -1
    1976        95718 :       && min_profitable_estimate > (int) vect_vf_for_cost (loop_vinfo))
    1977              :     {
    1978          120 :       if (dump_enabled_p ())
    1979            2 :         dump_printf_loc (MSG_NOTE, vect_location,
    1980              :                          "not vectorized: no loop iteration estimate on the "
    1981              :                          "uncounted loop and not trivially profitable.\n");
    1982              :       return -1;
    1983              :     }
    1984              : 
    1985              :   return 1;
    1986              : }
    1987              : 
    1988              : /* Gather data references in LOOP with body BBS and store them into
    1989              :    *DATAREFS.  */
    1990              : 
    1991              : static opt_result
    1992       283285 : vect_get_datarefs_in_loop (loop_p loop, basic_block *bbs,
    1993              :                            vec<data_reference_p> *datarefs)
    1994              : {
    1995       848498 :   for (unsigned i = 0; i < loop->num_nodes; i++)
    1996      1257156 :     for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
    1997      5471736 :          !gsi_end_p (gsi); gsi_next (&gsi))
    1998              :       {
    1999      4906523 :         gimple *stmt = gsi_stmt (gsi);
    2000      4906523 :         if (is_gimple_debug (stmt))
    2001      2357232 :           continue;
    2002      2549421 :         opt_result res = vect_find_stmt_data_reference (loop, stmt, datarefs,
    2003              :                                                         NULL, 0);
    2004      2549421 :         if (!res)
    2005              :           {
    2006        63495 :             if (is_gimple_call (stmt) && loop->safelen)
    2007              :               {
    2008          406 :                 tree fndecl = gimple_call_fndecl (stmt), op;
    2009          406 :                 if (fndecl == NULL_TREE
    2010          406 :                     && gimple_call_internal_p (stmt, IFN_MASK_CALL))
    2011              :                   {
    2012            0 :                     fndecl = gimple_call_arg (stmt, 0);
    2013            0 :                     gcc_checking_assert (TREE_CODE (fndecl) == ADDR_EXPR);
    2014            0 :                     fndecl = TREE_OPERAND (fndecl, 0);
    2015            0 :                     gcc_checking_assert (TREE_CODE (fndecl) == FUNCTION_DECL);
    2016              :                   }
    2017          406 :                 if (fndecl != NULL_TREE)
    2018              :                   {
    2019          369 :                     cgraph_node *node = cgraph_node::get (fndecl);
    2020          369 :                     if (node != NULL && node->simd_clones != NULL)
    2021              :                       {
    2022          131 :                         unsigned int j, n = gimple_call_num_args (stmt);
    2023          545 :                         for (j = 0; j < n; j++)
    2024              :                           {
    2025          284 :                             op = gimple_call_arg (stmt, j);
    2026          284 :                             if (DECL_P (op)
    2027          284 :                                 || (REFERENCE_CLASS_P (op)
    2028            0 :                                     && get_base_address (op)))
    2029              :                               break;
    2030              :                           }
    2031          131 :                         op = gimple_call_lhs (stmt);
    2032              :                         /* Ignore #pragma omp declare simd functions
    2033              :                            if they don't have data references in the
    2034              :                            call stmt itself.  */
    2035          261 :                         if (j == n
    2036          131 :                             && !(op
    2037          120 :                                  && (DECL_P (op)
    2038          120 :                                      || (REFERENCE_CLASS_P (op)
    2039            0 :                                          && get_base_address (op)))))
    2040          130 :                           continue;
    2041              :                       }
    2042              :                   }
    2043              :               }
    2044        63365 :             return res;
    2045              :           }
    2046              :         /* If dependence analysis will give up due to the limit on the
    2047              :            number of datarefs stop here and fail fatally.  */
    2048      4357084 :         if (datarefs->length ()
    2049      1871158 :             > (unsigned)param_loop_max_datarefs_for_datadeps)
    2050            0 :           return opt_result::failure_at (stmt, "exceeded param "
    2051              :                                          "loop-max-datarefs-for-datadeps\n");
    2052              :       }
    2053       219920 :   return opt_result::success ();
    2054              : }
    2055              : 
    2056              : /* Determine if operating on full vectors for LOOP_VINFO might leave
    2057              :    some scalar iterations still to do.  If so, decide how we should
    2058              :    handle those scalar iterations.  The possibilities are:
    2059              : 
    2060              :    (1) Make LOOP_VINFO operate on partial vectors instead of full vectors.
    2061              :        In this case:
    2062              : 
    2063              :          LOOP_VINFO_USING_PARTIAL_VECTORS_P == true
    2064              :          LOOP_VINFO_PEELING_FOR_NITER == false
    2065              : 
    2066              :    (2) Make LOOP_VINFO operate on full vectors and use an epilogue loop
    2067              :        to handle the remaining scalar iterations.  In this case:
    2068              : 
    2069              :          LOOP_VINFO_USING_PARTIAL_VECTORS_P == false
    2070              :          LOOP_VINFO_PEELING_FOR_NITER == true
    2071              : 
    2072              :    The MASKED_P argument specifies to what extent
    2073              :    param_vect_partial_vector_usage is to be honored.  For MASKED_P == 0
    2074              :    no partial vectors are to be used, for MASKED_P == -1 it's
    2075              :    param_vect_partial_vector_usage that gets to decide whether we may
    2076              :    consider partial vector usage.  For MASKED_P == 1 partial vectors
    2077              :    may be used if possible.
    2078              : 
    2079              :  */
    2080              : 
    2081              : static opt_result
    2082       156840 : vect_determine_partial_vectors_and_peeling (loop_vec_info loop_vinfo,
    2083              :                                             int masked_p)
    2084              : {
    2085              :   /* Determine whether there would be any scalar iterations left over.  */
    2086       156840 :   bool need_peeling_or_partial_vectors_p
    2087       156840 :     = vect_need_peeling_or_partial_vectors_p (loop_vinfo);
    2088              : 
    2089              :   /* Decide whether to vectorize the loop with partial vectors.  */
    2090       156840 :   LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2091       156840 :   if (masked_p == 0
    2092       156840 :       || (masked_p == -1 && param_vect_partial_vector_usage == 0))
    2093              :     /* If requested explicitly do not use partial vectors.  */
    2094              :     LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2095          211 :   else if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
    2096           69 :            && LOOP_VINFO_MUST_USE_PARTIAL_VECTORS_P (loop_vinfo))
    2097            0 :     LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = true;
    2098          211 :   else if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
    2099           69 :            && need_peeling_or_partial_vectors_p)
    2100              :     {
    2101              :       /* For partial-vector-usage=1, try to push the handling of partial
    2102              :          vectors to the epilogue, with the main loop continuing to operate
    2103              :          on full vectors.
    2104              : 
    2105              :          If we are unrolling we also do not want to use partial vectors. This
    2106              :          is to avoid the overhead of generating multiple masks and also to
    2107              :          avoid having to execute entire iterations of FALSE masked instructions
    2108              :          when dealing with one or less full iterations.
    2109              : 
    2110              :          ??? We could then end up failing to use partial vectors if we
    2111              :          decide to peel iterations into a prologue, and if the main loop
    2112              :          then ends up processing fewer than VF iterations.  */
    2113           47 :       if ((param_vect_partial_vector_usage == 1
    2114           14 :            || loop_vinfo->suggested_unroll_factor > 1)
    2115           33 :           && !LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    2116           69 :           && !vect_known_niters_smaller_than_vf (loop_vinfo))
    2117              :         ;
    2118              :       else
    2119           35 :         LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = true;
    2120              :     }
    2121              : 
    2122       156840 :   if (LOOP_VINFO_MUST_USE_PARTIAL_VECTORS_P (loop_vinfo)
    2123            0 :       && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    2124            0 :     return opt_result::failure_at (vect_location,
    2125              :                                    "not vectorized: loop needs but cannot "
    2126              :                                    "use partial vectors\n");
    2127              : 
    2128       156840 :   if (dump_enabled_p ())
    2129        12693 :     dump_printf_loc (MSG_NOTE, vect_location,
    2130              :                      "operating on %s vectors%s.\n",
    2131        12693 :                      LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    2132              :                      ? "partial" : "full",
    2133        12693 :                      LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    2134              :                      ? " for epilogue loop" : "");
    2135              : 
    2136       156840 :   LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
    2137       313680 :     = (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    2138       156840 :        && need_peeling_or_partial_vectors_p);
    2139              : 
    2140       156840 :   return opt_result::success ();
    2141              : }
    2142              : 
    2143              : /* Function vect_analyze_loop_2.
    2144              : 
    2145              :    Apply a set of analyses on LOOP specified by LOOP_VINFO, the different
    2146              :    analyses will record information in some members of LOOP_VINFO.  FATAL
    2147              :    indicates if some analysis meets fatal error.  If one non-NULL pointer
    2148              :    SUGGESTED_UNROLL_FACTOR is provided, it's intent to be filled with one
    2149              :    worked out suggested unroll factor, while one NULL pointer shows it's
    2150              :    going to apply the suggested unroll factor.
    2151              :    SINGLE_LANE_SLP_DONE_FOR_SUGGESTED_UF is to hold whether single-lane
    2152              :    slp was forced when the suggested unroll factor was worked out.  */
    2153              : static opt_result
    2154       590979 : vect_analyze_loop_2 (loop_vec_info loop_vinfo, int masked_p, bool &fatal,
    2155              :                      unsigned *suggested_unroll_factor,
    2156              :                      bool& single_lane_slp_done_for_suggested_uf)
    2157              : {
    2158       590979 :   opt_result ok = opt_result::success ();
    2159       590979 :   int res;
    2160       590979 :   unsigned int max_vf = MAX_VECTORIZATION_FACTOR;
    2161       590979 :   loop_vec_info orig_loop_vinfo = NULL;
    2162              : 
    2163              :   /* If we are dealing with an epilogue then orig_loop_vinfo points to the
    2164              :      loop_vec_info of the first vectorized loop.  */
    2165       590979 :   if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
    2166        13925 :     orig_loop_vinfo = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
    2167              :   else
    2168              :     orig_loop_vinfo = loop_vinfo;
    2169        13925 :   gcc_assert (orig_loop_vinfo);
    2170              : 
    2171              :   /* We can't mask on niters for uncounted loops due to unknown upper bound.  */
    2172       590979 :   if (LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo))
    2173        87324 :     LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2174              : 
    2175              :   /* The first group of checks is independent of the vector size.  */
    2176       590979 :   fatal = true;
    2177              : 
    2178       590979 :   if (LOOP_VINFO_SIMD_IF_COND (loop_vinfo)
    2179       590979 :       && integer_zerop (LOOP_VINFO_SIMD_IF_COND (loop_vinfo)))
    2180            5 :     return opt_result::failure_at (vect_location,
    2181              :                                    "not vectorized: simd if(0)\n");
    2182              : 
    2183              :   /* Find all data references in the loop (which correspond to vdefs/vuses)
    2184              :      and analyze their evolution in the loop.  */
    2185              : 
    2186       590974 :   loop_p loop = LOOP_VINFO_LOOP (loop_vinfo);
    2187              : 
    2188              :   /* Gather the data references.  */
    2189       590974 :   if (!LOOP_VINFO_DATAREFS (loop_vinfo).exists ())
    2190              :     {
    2191       283285 :       opt_result res
    2192       283285 :         = vect_get_datarefs_in_loop (loop, LOOP_VINFO_BBS (loop_vinfo),
    2193              :                                      &LOOP_VINFO_DATAREFS (loop_vinfo));
    2194       283285 :       if (!res)
    2195              :         {
    2196        63365 :           if (dump_enabled_p ())
    2197         1636 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2198              :                              "not vectorized: loop contains function "
    2199              :                              "calls or data references that cannot "
    2200              :                              "be analyzed\n");
    2201        63365 :           return res;
    2202              :         }
    2203       219920 :       loop_vinfo->shared->save_datarefs ();
    2204              :     }
    2205              :   else
    2206       307689 :     loop_vinfo->shared->check_datarefs ();
    2207              : 
    2208              :   /* Analyze the data references and also adjust the minimal
    2209              :      vectorization factor according to the loads and stores.  */
    2210              : 
    2211       527609 :   ok = vect_analyze_data_refs (loop_vinfo, &fatal);
    2212       527609 :   if (!ok)
    2213              :     {
    2214        74162 :       if (dump_enabled_p ())
    2215         1274 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2216              :                          "bad data references.\n");
    2217        74162 :       return ok;
    2218              :     }
    2219              : 
    2220              :   /* Check if we are applying unroll factor now.  */
    2221       453447 :   bool applying_suggested_uf = loop_vinfo->suggested_unroll_factor > 1;
    2222       453447 :   gcc_assert (!applying_suggested_uf || !suggested_unroll_factor);
    2223              : 
    2224              :   /* When single-lane SLP was forced and we are applying suggested unroll
    2225              :      factor, keep that decision here.  */
    2226       906894 :   bool force_single_lane = (applying_suggested_uf
    2227       453447 :                             && single_lane_slp_done_for_suggested_uf);
    2228              : 
    2229              :   /* Classify all cross-iteration scalar data-flow cycles.
    2230              :      Cross-iteration cycles caused by virtual phis are analyzed separately.  */
    2231       453447 :   vect_analyze_scalar_cycles (loop_vinfo);
    2232              : 
    2233       453447 :   vect_pattern_recog (loop_vinfo);
    2234              : 
    2235              :   /* Analyze the access patterns of the data-refs in the loop (consecutive,
    2236              :      complex, etc.). FORNOW: Only handle consecutive access pattern.  */
    2237              : 
    2238       453447 :   ok = vect_analyze_data_ref_accesses (loop_vinfo, NULL);
    2239       453447 :   if (!ok)
    2240              :     {
    2241         8029 :       if (dump_enabled_p ())
    2242          292 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2243              :                          "bad data access.\n");
    2244         8029 :       return ok;
    2245              :     }
    2246              : 
    2247              :   /* Data-flow analysis to detect stmts that do not need to be vectorized.  */
    2248              : 
    2249       445418 :   ok = vect_mark_stmts_to_be_vectorized (loop_vinfo, &fatal);
    2250       445418 :   if (!ok)
    2251              :     {
    2252        46195 :       if (dump_enabled_p ())
    2253          403 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2254              :                          "unexpected pattern.\n");
    2255        46195 :       return ok;
    2256              :     }
    2257              : 
    2258              :   /* While the rest of the analysis below depends on it in some way.  */
    2259       399223 :   fatal = false;
    2260              : 
    2261              :   /* Analyze data dependences between the data-refs in the loop
    2262              :      and adjust the maximum vectorization factor according to
    2263              :      the dependences.
    2264              :      FORNOW: fail at the first data dependence that we encounter.  */
    2265              : 
    2266       399223 :   ok = vect_analyze_data_ref_dependences (loop_vinfo, &max_vf);
    2267       399223 :   if (!ok)
    2268              :     {
    2269        24636 :       if (dump_enabled_p ())
    2270          560 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2271              :                          "bad data dependence.\n");
    2272        24636 :       return ok;
    2273              :     }
    2274       374587 :   LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo) = max_vf;
    2275              : 
    2276              :   /* Compute the scalar iteration cost.  */
    2277       374587 :   vect_compute_single_scalar_iteration_cost (loop_vinfo);
    2278              : 
    2279       374587 :   bool saved_can_use_partial_vectors_p
    2280              :     = LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo);
    2281              : 
    2282              :   /* This is the point where we can re-start analysis with single-lane
    2283              :      SLP forced.  */
    2284       519662 : start_over:
    2285              : 
    2286              :   /* Check the SLP opportunities in the loop, analyze and build
    2287              :      SLP trees.  */
    2288      1039324 :   ok = vect_analyze_slp (loop_vinfo, loop_vinfo->stmt_vec_infos.length (),
    2289              :                          force_single_lane);
    2290       519662 :   if (!ok)
    2291        18153 :     return ok;
    2292              : 
    2293              :   /* If there are any SLP instances mark them as pure_slp and compute
    2294              :      the overall vectorization factor.  */
    2295       501509 :   if (!vect_make_slp_decision (loop_vinfo))
    2296        66607 :     return opt_result::failure_at (vect_location, "no stmts to vectorize.\n");
    2297              : 
    2298       434902 :   if (dump_enabled_p ())
    2299        19664 :     dump_printf_loc (MSG_NOTE, vect_location, "Loop contains only SLP stmts\n");
    2300              : 
    2301              :   /* Dump the vectorization factor from the SLP decision.  */
    2302       434902 :   if (dump_enabled_p ())
    2303              :     {
    2304        19664 :       dump_printf_loc (MSG_NOTE, vect_location, "vectorization factor = ");
    2305        19664 :       dump_dec (MSG_NOTE, LOOP_VINFO_VECT_FACTOR (loop_vinfo));
    2306        19664 :       dump_printf (MSG_NOTE, "\n");
    2307              :     }
    2308              : 
    2309              :   /* We don't expect to have to roll back to anything other than an empty
    2310              :      set of rgroups.  */
    2311       434902 :   gcc_assert (LOOP_VINFO_MASKS (loop_vinfo).is_empty ());
    2312              : 
    2313              :   /* Apply the suggested unrolling factor, this was determined by the backend
    2314              :      during finish_cost the first time we ran the analysis for this
    2315              :      vector mode.  */
    2316       434902 :   if (applying_suggested_uf)
    2317          459 :     LOOP_VINFO_VECT_FACTOR (loop_vinfo) *= loop_vinfo->suggested_unroll_factor;
    2318              : 
    2319              :   /* Now the vectorization factor is final.  */
    2320       434902 :   poly_uint64 vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    2321       434902 :   gcc_assert (known_ne (vectorization_factor, 0U));
    2322              : 
    2323              :   /* Optimize the SLP graph with the vectorization factor fixed.  */
    2324       434902 :   vect_optimize_slp (loop_vinfo);
    2325              : 
    2326              :   /* Gather the loads reachable from the SLP graph entries.  */
    2327       434902 :   vect_gather_slp_loads (loop_vinfo);
    2328              : 
    2329       434902 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && dump_enabled_p ())
    2330              :     {
    2331        14564 :       dump_printf_loc (MSG_NOTE, vect_location,
    2332              :                        "vectorization_factor = ");
    2333        14564 :       dump_dec (MSG_NOTE, vectorization_factor);
    2334        14564 :       dump_printf (MSG_NOTE, ", niters = %wd\n",
    2335        14564 :                    LOOP_VINFO_INT_NITERS (loop_vinfo));
    2336              :     }
    2337              : 
    2338       434902 :   if (max_vf != MAX_VECTORIZATION_FACTOR
    2339       434902 :       && maybe_lt (max_vf, LOOP_VINFO_VECT_FACTOR (loop_vinfo)))
    2340           41 :     return opt_result::failure_at (vect_location, "bad data dependence.\n");
    2341              : 
    2342       434861 :   loop_vinfo->vector_costs = init_cost (loop_vinfo, false);
    2343              : 
    2344              :   /* Analyze the alignment of the data-refs in the loop.  */
    2345       434861 :   vect_analyze_data_refs_alignment (loop_vinfo);
    2346              : 
    2347              :   /* Prune the list of ddrs to be tested at run-time by versioning for alias.
    2348              :      It is important to call pruning after vect_analyze_data_ref_accesses,
    2349              :      since we use grouping information gathered by interleaving analysis.  */
    2350       434861 :   ok = vect_prune_runtime_alias_test_list (loop_vinfo);
    2351       434861 :   if (!ok)
    2352        17856 :     return ok;
    2353              : 
    2354              :   /* Do not invoke vect_enhance_data_refs_alignment for epilogue
    2355              :      vectorization, since we do not want to add extra peeling or
    2356              :      add versioning for alignment.  */
    2357       417005 :   if (!LOOP_VINFO_EPILOGUE_P (loop_vinfo))
    2358              :     /* This pass will decide on using loop versioning and/or loop peeling in
    2359              :        order to enhance the alignment of data references in the loop.  */
    2360       402227 :     ok = vect_enhance_data_refs_alignment (loop_vinfo);
    2361       417005 :   if (!ok)
    2362            0 :     return ok;
    2363              : 
    2364              :   /* Analyze operations in the SLP instances.  We can't simply
    2365              :      remove unsupported SLP instances as this makes the above
    2366              :      SLP kind detection invalid and might also affect the VF.  */
    2367       417005 :   if (! vect_slp_analyze_operations (loop_vinfo))
    2368              :     {
    2369       260165 :       ok = opt_result::failure_at (vect_location,
    2370              :                                    "unsupported SLP instances\n");
    2371       260165 :       goto again;
    2372              :     }
    2373              : 
    2374              :   /* For now, we don't expect to mix both masking and length approaches for one
    2375              :      loop, disable it if both are recorded.  */
    2376       156840 :   if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
    2377        23530 :       && !LOOP_VINFO_MASKS (loop_vinfo).is_empty ()
    2378       180364 :       && !LOOP_VINFO_LENS (loop_vinfo).is_empty ())
    2379              :     {
    2380            0 :       if (dump_enabled_p ())
    2381            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2382              :                          "can't vectorize a loop with partial vectors"
    2383              :                          " because we don't expect to mix different"
    2384              :                          " approaches with partial vectors for the"
    2385              :                          " same loop.\n");
    2386            0 :       LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2387              :     }
    2388              : 
    2389              :   /* If we still have the option of using partial vectors,
    2390              :      check whether we can generate the necessary loop controls.  */
    2391       156840 :   if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
    2392              :     {
    2393        23530 :       if (!LOOP_VINFO_MASKS (loop_vinfo).is_empty ())
    2394              :         {
    2395        23524 :           if (!vect_verify_full_masking (loop_vinfo)
    2396        23524 :               && !vect_verify_full_masking_avx512 (loop_vinfo))
    2397         6105 :             LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2398              :         }
    2399              :       else /* !LOOP_VINFO_LENS (loop_vinfo).is_empty () */
    2400            6 :         if (!vect_verify_loop_lens (loop_vinfo))
    2401            6 :           LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2402              :     }
    2403              : 
    2404              :   /* Decide whether this loop_vinfo should use partial vectors or peeling,
    2405              :      assuming that the loop will be used as a main loop.  We will redo
    2406              :      this analysis later if we instead decide to use the loop as an
    2407              :      epilogue loop.  */
    2408       156840 :   ok = vect_determine_partial_vectors_and_peeling (loop_vinfo, masked_p);
    2409       156840 :   if (!ok)
    2410            0 :     return ok;
    2411              : 
    2412              :   /* If we're vectorizing a loop that uses length "controls" and
    2413              :      can iterate more than once, we apply decrementing IV approach
    2414              :      in loop control.  */
    2415       156840 :   if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    2416           35 :       && LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) == vect_partial_vectors_len
    2417            0 :       && LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo) == 0
    2418       156840 :       && !(LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    2419            0 :            && known_le (LOOP_VINFO_INT_NITERS (loop_vinfo),
    2420              :                         LOOP_VINFO_VECT_FACTOR (loop_vinfo))))
    2421            0 :     LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo) = true;
    2422              : 
    2423              :   /* If a loop uses length controls and has a decrementing loop control IV,
    2424              :      we will normally pass that IV through a MIN_EXPR to calcaluate the
    2425              :      basis for the length controls.  E.g. in a loop that processes one
    2426              :      element per scalar iteration, the number of elements would be
    2427              :      MIN_EXPR <N, VF>, where N is the number of scalar iterations left.
    2428              : 
    2429              :      This MIN_EXPR approach allows us to use pointer IVs with an invariant
    2430              :      step, since only the final iteration of the vector loop can have
    2431              :      inactive lanes.
    2432              : 
    2433              :      However, some targets have a dedicated instruction for calculating the
    2434              :      preferred length, given the total number of elements that still need to
    2435              :      be processed.  This is encapsulated in the SELECT_VL internal function.
    2436              : 
    2437              :      If the target supports SELECT_VL, we can use it instead of MIN_EXPR
    2438              :      to determine the basis for the length controls.  However, unlike the
    2439              :      MIN_EXPR calculation, the SELECT_VL calculation can decide to make
    2440              :      lanes inactive in any iteration of the vector loop, not just the last
    2441              :      iteration.  This SELECT_VL approach therefore requires us to use pointer
    2442              :      IVs with variable steps.
    2443              : 
    2444              :      Once we've decided how many elements should be processed by one
    2445              :      iteration of the vector loop, we need to populate the rgroup controls.
    2446              :      If a loop has multiple rgroups, we need to make sure that those rgroups
    2447              :      "line up" (that is, they must be consistent about which elements are
    2448              :      active and which aren't).  This is done by vect_adjust_loop_lens_control.
    2449              : 
    2450              :      In principle, it would be possible to use vect_adjust_loop_lens_control
    2451              :      on either the result of a MIN_EXPR or the result of a SELECT_VL.
    2452              :      However:
    2453              : 
    2454              :      (1) In practice, it only makes sense to use SELECT_VL when a vector
    2455              :          operation will be controlled directly by the result.  It is not
    2456              :          worth using SELECT_VL if it would only be the input to other
    2457              :          calculations.
    2458              : 
    2459              :      (2) If we use SELECT_VL for an rgroup that has N controls, each associated
    2460              :          pointer IV will need N updates by a variable amount (N-1 updates
    2461              :          within the iteration and 1 update to move to the next iteration).
    2462              : 
    2463              :      Because of this, we prefer to use the MIN_EXPR approach whenever there
    2464              :      is more than one length control.
    2465              : 
    2466              :      In addition, SELECT_VL always operates to a granularity of 1 unit.
    2467              :      If we wanted to use it to control an SLP operation on N consecutive
    2468              :      elements, we would need to make the SELECT_VL inputs measure scalar
    2469              :      iterations (rather than elements) and then multiply the SELECT_VL
    2470              :      result by N.  But using SELECT_VL this way is inefficient because
    2471              :      of (1) above.
    2472              : 
    2473              :      2. We don't apply SELECT_VL on single-rgroup when both (1) and (2) are
    2474              :         satisfied:
    2475              : 
    2476              :      (1). LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) is true.
    2477              :      (2). LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant () is true.
    2478              : 
    2479              :      Since SELECT_VL (variable step) will make SCEV analysis failed and then
    2480              :      we will fail to gain benefits of following unroll optimizations. We prefer
    2481              :      using the MIN_EXPR approach in this situation.  */
    2482       156840 :   if (LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo))
    2483              :     {
    2484            0 :       tree iv_type = LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo);
    2485            0 :       if (LOOP_VINFO_LENS (loop_vinfo).length () == 1
    2486            0 :           && LOOP_VINFO_LENS (loop_vinfo)[0].factor == 1
    2487            0 :           && (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    2488              :               || !LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant ()))
    2489            0 :         LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = true;
    2490              : 
    2491            0 :       if (LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo))
    2492            0 :         for (auto rgc : LOOP_VINFO_LENS (loop_vinfo))
    2493            0 :           if (rgc.type
    2494            0 :               && !direct_internal_fn_supported_p (IFN_SELECT_VL,
    2495              :                                                   rgc.type, iv_type,
    2496              :                                                   OPTIMIZE_FOR_SPEED))
    2497              :             {
    2498            0 :               LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = false;
    2499            0 :               break;
    2500              :             }
    2501              : 
    2502              :       /* If any of the SLP instances cover more than a single lane
    2503              :          we cannot use .SELECT_VL at the moment, even if the number
    2504              :          of lanes is uniform throughout the SLP graph.  */
    2505            0 :       if (LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo))
    2506            0 :         for (slp_instance inst : LOOP_VINFO_SLP_INSTANCES (loop_vinfo))
    2507            0 :           if (SLP_TREE_LANES (SLP_INSTANCE_TREE (inst)) != 1
    2508            0 :               && !(SLP_INSTANCE_KIND (inst) == slp_inst_kind_store
    2509            0 :                    && SLP_INSTANCE_TREE (inst)->ldst_lanes))
    2510              :             {
    2511            0 :               LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = false;
    2512            0 :               break;
    2513              :             }
    2514              :     }
    2515              : 
    2516              :   /* If we're vectorizing an epilogue loop, the vectorized loop either needs
    2517              :      to be able to handle fewer than VF scalars, or needs to have a lower VF
    2518              :      than the main loop.  */
    2519       156840 :   if (LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    2520        13500 :       && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    2521              :     {
    2522        13484 :       poly_uint64 unscaled_vf
    2523        13484 :         = exact_div (LOOP_VINFO_VECT_FACTOR (orig_loop_vinfo),
    2524              :                      orig_loop_vinfo->suggested_unroll_factor);
    2525        13484 :       if (maybe_ge (LOOP_VINFO_VECT_FACTOR (loop_vinfo), unscaled_vf))
    2526          382 :         return opt_result::failure_at (vect_location,
    2527              :                                        "Vectorization factor too high for"
    2528              :                                        " epilogue loop.\n");
    2529              :     }
    2530              : 
    2531              :   /* If the epilogue needs peeling for gaps but the main loop doesn't give
    2532              :      up on the epilogue.  */
    2533       156458 :   if (LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    2534        13118 :       && LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
    2535           73 :       && (LOOP_VINFO_PEELING_FOR_GAPS (orig_loop_vinfo)
    2536              :           != LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)))
    2537            4 :     return opt_result::failure_at (vect_location,
    2538              :                                    "Epilogue loop requires peeling for gaps "
    2539              :                                    "but main loop does not.\n");
    2540              : 
    2541              :   /* If an epilogue loop is required make sure we can create one.  */
    2542       156454 :   if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
    2543       155148 :       || LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
    2544        57103 :       || LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
    2545              :     {
    2546       100881 :       if (dump_enabled_p ())
    2547         5621 :         dump_printf_loc (MSG_NOTE, vect_location, "epilog loop required\n");
    2548       100881 :       if (!vect_can_advance_ivs_p (loop_vinfo)
    2549       201232 :           || !slpeel_can_duplicate_loop_p (loop,
    2550              :                                            LOOP_VINFO_MAIN_EXIT (loop_vinfo),
    2551       100351 :                                            LOOP_VINFO_MAIN_EXIT (loop_vinfo)))
    2552              :         {
    2553          530 :           ok = opt_result::failure_at (vect_location,
    2554              :                                        "not vectorized: can't create required "
    2555              :                                        "epilog loop\n");
    2556          530 :           goto again;
    2557              :         }
    2558              :     }
    2559              : 
    2560              :   /* Check the costings of the loop make vectorizing worthwhile.  */
    2561       155924 :   res = vect_analyze_loop_costing (loop_vinfo, suggested_unroll_factor);
    2562       155924 :   if (res < 0 && !param_vect_allow_possibly_not_worthwhile_vectorizations)
    2563              :     {
    2564        28745 :       ok = opt_result::failure_at (vect_location,
    2565              :                                    "Loop costings may not be worthwhile.\n");
    2566        28745 :       goto again;
    2567              :     }
    2568       127179 :   if (!res)
    2569        31717 :     return opt_result::failure_at (vect_location,
    2570              :                                    "Loop costings not worthwhile.\n");
    2571              : 
    2572              :   /* During peeling, we need to check if number of loop iterations is
    2573              :      enough for both peeled prolog loop and vector loop.  This check
    2574              :      can be merged along with threshold check of loop versioning, so
    2575              :      increase threshold for this case if necessary.
    2576              : 
    2577              :      If we are analyzing an epilogue we still want to check what its
    2578              :      versioning threshold would be.  If we decide to vectorize the epilogues we
    2579              :      will want to use the lowest versioning threshold of all epilogues and main
    2580              :      loop.  This will enable us to enter a vectorized epilogue even when
    2581              :      versioning the loop.  We can't simply check whether the epilogue requires
    2582              :      versioning though since we may have skipped some versioning checks when
    2583              :      analyzing the epilogue.  For instance, checks for alias versioning will be
    2584              :      skipped when dealing with epilogues as we assume we already checked them
    2585              :      for the main loop.  So instead we always check the 'orig_loop_vinfo'.  */
    2586        95462 :   if (LOOP_REQUIRES_VERSIONING (orig_loop_vinfo))
    2587              :     {
    2588         9076 :       poly_uint64 niters_th = 0;
    2589         9076 :       unsigned int th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
    2590              : 
    2591         9076 :       if (!vect_use_loop_mask_for_alignment_p (loop_vinfo))
    2592              :         {
    2593              :           /* Niters for peeled prolog loop.  */
    2594         9076 :           if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
    2595              :             {
    2596          115 :               dr_vec_info *dr_info = LOOP_VINFO_UNALIGNED_DR (loop_vinfo);
    2597          115 :               tree vectype = STMT_VINFO_VECTYPE (dr_info->stmt);
    2598          115 :               niters_th += TYPE_VECTOR_SUBPARTS (vectype) - 1;
    2599              :             }
    2600              :           else
    2601         8961 :             niters_th += LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
    2602              :         }
    2603              : 
    2604              :       /* Niters for at least one iteration of vectorized loop.  */
    2605         9076 :       if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    2606         9072 :         niters_th += LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    2607              :       /* One additional iteration because of peeling for gap.  */
    2608         9076 :       if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
    2609           75 :         niters_th += 1;
    2610              : 
    2611              :       /*  Use the same condition as vect_transform_loop to decide when to use
    2612              :           the cost to determine a versioning threshold.  */
    2613         9076 :       if (vect_apply_runtime_profitability_check_p (loop_vinfo)
    2614         9076 :           && ordered_p (th, niters_th))
    2615         6783 :         niters_th = ordered_max (poly_uint64 (th), niters_th);
    2616              : 
    2617         9076 :       LOOP_VINFO_VERSIONING_THRESHOLD (loop_vinfo) = niters_th;
    2618              :     }
    2619              : 
    2620        95462 :   gcc_assert (known_eq (vectorization_factor,
    2621              :                         LOOP_VINFO_VECT_FACTOR (loop_vinfo)));
    2622              : 
    2623        95462 :   single_lane_slp_done_for_suggested_uf = force_single_lane;
    2624              : 
    2625              :   /* Ok to vectorize!  */
    2626        95462 :   LOOP_VINFO_VECTORIZABLE_P (loop_vinfo) = 1;
    2627        95462 :   return opt_result::success ();
    2628              : 
    2629       289440 : again:
    2630              :   /* Ensure that "ok" is false (with an opt_problem if dumping is enabled).  */
    2631       289440 :   gcc_assert (!ok);
    2632              : 
    2633              :   /* Try again with single-lane SLP.  */
    2634       289440 :   if (force_single_lane)
    2635       143391 :     return ok;
    2636              : 
    2637              :   /* If we are applying suggested unroll factor, we don't need to
    2638              :      re-try any more as we want to keep the SLP mode fixed.  */
    2639       146049 :   if (applying_suggested_uf)
    2640           10 :     return ok;
    2641              : 
    2642              :   /* Likewise if the grouped loads or stores in the SLP cannot be handled
    2643              :      via interleaving or lane instructions.  */
    2644              :   slp_instance instance;
    2645              :   slp_tree node;
    2646              :   unsigned i, j;
    2647       393288 :   FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
    2648              :     {
    2649       248213 :       if (SLP_TREE_DEF_TYPE (SLP_INSTANCE_TREE (instance)) != vect_internal_def)
    2650            0 :         continue;
    2651              : 
    2652       248213 :       stmt_vec_info vinfo;
    2653       248213 :       vinfo = SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (instance))[0];
    2654       248213 :       if (!vinfo || !STMT_VINFO_GROUPED_ACCESS (vinfo))
    2655       245419 :         continue;
    2656         2794 :       vinfo = DR_GROUP_FIRST_ELEMENT (vinfo);
    2657         2794 :       unsigned int size = DR_GROUP_SIZE (vinfo);
    2658         2794 :       tree vectype = SLP_TREE_VECTYPE (SLP_INSTANCE_TREE (instance));
    2659         2794 :       if (vect_store_lanes_supported (vectype, size, false) == IFN_LAST
    2660         4912 :          && ! known_eq (TYPE_VECTOR_SUBPARTS (vectype), 1U)
    2661         5582 :          && ! vect_grouped_store_supported (vectype, size))
    2662          670 :         return opt_result::failure_at (vinfo->stmt,
    2663              :                                        "unsupported grouped store\n");
    2664       250854 :       FOR_EACH_VEC_ELT (SLP_INSTANCE_LOADS (instance), j, node)
    2665              :         {
    2666         2314 :           vinfo = SLP_TREE_REPRESENTATIVE (node);
    2667         2314 :           if (STMT_VINFO_GROUPED_ACCESS (vinfo))
    2668              :             {
    2669         2010 :               vinfo = DR_GROUP_FIRST_ELEMENT (vinfo);
    2670         2010 :               bool single_element_p = !DR_GROUP_NEXT_ELEMENT (vinfo);
    2671         2010 :               size = DR_GROUP_SIZE (vinfo);
    2672         2010 :               vectype = SLP_TREE_VECTYPE (node);
    2673         2010 :               if (vect_load_lanes_supported (vectype, size, false) == IFN_LAST
    2674         2010 :                   && ! vect_grouped_load_supported (vectype, single_element_p,
    2675              :                                                     size))
    2676          294 :                 return opt_result::failure_at (vinfo->stmt,
    2677              :                                                "unsupported grouped load\n");
    2678              :             }
    2679              :         }
    2680              :     }
    2681              : 
    2682              :   /* Roll back state appropriately.  Force single-lane SLP this time.  */
    2683       145075 :   force_single_lane = true;
    2684       145075 :   if (dump_enabled_p ())
    2685         3584 :     dump_printf_loc (MSG_NOTE, vect_location,
    2686              :                      "re-trying with single-lane SLP\n");
    2687              : 
    2688              :   /* Reset the vectorization factor.  */
    2689       145075 :   LOOP_VINFO_VECT_FACTOR (loop_vinfo) = 0;
    2690              :   /* Free the SLP instances.  */
    2691       392317 :   FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), j, instance)
    2692       247242 :     vect_free_slp_instance (instance);
    2693       145075 :   LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
    2694              :   /* Reset altered state on stmts.  */
    2695       695215 :   for (i = 0; i < LOOP_VINFO_LOOP (loop_vinfo)->num_nodes; ++i)
    2696              :     {
    2697       405065 :       basic_block bb = LOOP_VINFO_BBS (loop_vinfo)[i];
    2698       405065 :       for (gimple_stmt_iterator si = gsi_start_phis (bb);
    2699       731550 :            !gsi_end_p (si); gsi_next (&si))
    2700              :         {
    2701       326485 :           stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (gsi_stmt (si));
    2702       326485 :           if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
    2703       326485 :               || STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
    2704              :             {
    2705              :               /* vectorizable_reduction adjusts reduction stmt def-types,
    2706              :                  restore them to that of the PHI.  */
    2707        26538 :               STMT_VINFO_DEF_TYPE (STMT_VINFO_REDUC_DEF (stmt_info))
    2708        26538 :                 = STMT_VINFO_DEF_TYPE (stmt_info);
    2709        26538 :               STMT_VINFO_DEF_TYPE (vect_stmt_to_vectorize
    2710              :                                         (STMT_VINFO_REDUC_DEF (stmt_info)))
    2711        26538 :                 = STMT_VINFO_DEF_TYPE (stmt_info);
    2712              :             }
    2713              :         }
    2714              :     }
    2715              :   /* Free optimized alias test DDRS.  */
    2716       145075 :   LOOP_VINFO_LOWER_BOUNDS (loop_vinfo).truncate (0);
    2717       145075 :   LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).release ();
    2718       145075 :   LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo).release ();
    2719              :   /* Reset target cost data.  */
    2720       145075 :   delete loop_vinfo->vector_costs;
    2721       145075 :   loop_vinfo->vector_costs = nullptr;
    2722              :   /* Reset accumulated rgroup information.  */
    2723       145075 :   LOOP_VINFO_MASKS (loop_vinfo).mask_set.empty ();
    2724       145075 :   release_vec_loop_controls (&LOOP_VINFO_MASKS (loop_vinfo).rgc_vec);
    2725       145075 :   release_vec_loop_controls (&LOOP_VINFO_LENS (loop_vinfo));
    2726              :   /* Reset assorted flags.  */
    2727       145075 :   LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = false;
    2728       145075 :   LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) = false;
    2729       145075 :   LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = 0;
    2730       145075 :   LOOP_VINFO_VERSIONING_THRESHOLD (loop_vinfo) = 0;
    2731       145075 :   LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
    2732       145075 :     = saved_can_use_partial_vectors_p;
    2733       145075 :   LOOP_VINFO_MUST_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2734       145075 :   LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2735       145075 :   LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = false;
    2736       145075 :   LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo) = false;
    2737              : 
    2738       145075 :   if (loop_vinfo->scan_map)
    2739          122 :     loop_vinfo->scan_map->empty ();
    2740              : 
    2741       145075 :   goto start_over;
    2742              : }
    2743              : 
    2744              : /* Return true if vectorizing a loop using NEW_LOOP_VINFO appears
    2745              :    to be better than vectorizing it using OLD_LOOP_VINFO.  Assume that
    2746              :    OLD_LOOP_VINFO is better unless something specifically indicates
    2747              :    otherwise.
    2748              : 
    2749              :    Note that this deliberately isn't a partial order.  */
    2750              : 
    2751              : static bool
    2752        32751 : vect_better_loop_vinfo_p (loop_vec_info new_loop_vinfo,
    2753              :                           loop_vec_info old_loop_vinfo)
    2754              : {
    2755        32751 :   struct loop *loop = LOOP_VINFO_LOOP (new_loop_vinfo);
    2756        32751 :   gcc_assert (LOOP_VINFO_LOOP (old_loop_vinfo) == loop);
    2757              : 
    2758        32751 :   poly_int64 new_vf = LOOP_VINFO_VECT_FACTOR (new_loop_vinfo);
    2759        32751 :   poly_int64 old_vf = LOOP_VINFO_VECT_FACTOR (old_loop_vinfo);
    2760              : 
    2761              :   /* Always prefer a VF of loop->simdlen over any other VF.  */
    2762        32751 :   if (loop->simdlen)
    2763              :     {
    2764            0 :       bool new_simdlen_p = known_eq (new_vf, loop->simdlen);
    2765            0 :       bool old_simdlen_p = known_eq (old_vf, loop->simdlen);
    2766            0 :       if (new_simdlen_p != old_simdlen_p)
    2767              :         return new_simdlen_p;
    2768              :     }
    2769              : 
    2770        32751 :   const auto *old_costs = old_loop_vinfo->vector_costs;
    2771        32751 :   const auto *new_costs = new_loop_vinfo->vector_costs;
    2772        32751 :   if (loop_vec_info main_loop = LOOP_VINFO_ORIG_LOOP_INFO (old_loop_vinfo))
    2773         1502 :     return new_costs->better_epilogue_loop_than_p (old_costs, main_loop);
    2774              : 
    2775        31249 :   return new_costs->better_main_loop_than_p (old_costs);
    2776              : }
    2777              : 
    2778              : /* Decide whether to replace OLD_LOOP_VINFO with NEW_LOOP_VINFO.  Return
    2779              :    true if we should.  */
    2780              : 
    2781              : static bool
    2782        32751 : vect_joust_loop_vinfos (loop_vec_info new_loop_vinfo,
    2783              :                         loop_vec_info old_loop_vinfo)
    2784              : {
    2785        32751 :   if (!vect_better_loop_vinfo_p (new_loop_vinfo, old_loop_vinfo))
    2786              :     return false;
    2787              : 
    2788         1392 :   if (dump_enabled_p ())
    2789           18 :     dump_printf_loc (MSG_NOTE, vect_location,
    2790              :                      "***** Preferring vector mode %s to vector mode %s\n",
    2791           18 :                      GET_MODE_NAME (new_loop_vinfo->vector_mode),
    2792           18 :                      GET_MODE_NAME (old_loop_vinfo->vector_mode));
    2793              :   return true;
    2794              : }
    2795              : 
    2796              : /* Analyze LOOP with VECTOR_MODES[MODE_I] and as epilogue if ORIG_LOOP_VINFO is
    2797              :    not NULL.  When MASKED_P is not -1 override the default
    2798              :    LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P with it.
    2799              :    Set AUTODETECTED_VECTOR_MODE if VOIDmode and advance MODE_I to the next
    2800              :    mode useful to analyze.
    2801              :    Return the loop_vinfo on success and wrapped null on failure.  */
    2802              : 
    2803              : static opt_loop_vec_info
    2804       590520 : vect_analyze_loop_1 (class loop *loop, vec_info_shared *shared,
    2805              :                      const vect_loop_form_info *loop_form_info,
    2806              :                      loop_vec_info orig_loop_vinfo,
    2807              :                      const vector_modes &vector_modes, unsigned &mode_i,
    2808              :                      int masked_p,
    2809              :                      machine_mode &autodetected_vector_mode,
    2810              :                      bool &fatal)
    2811              : {
    2812       590520 :   loop_vec_info loop_vinfo
    2813       590520 :     = vect_create_loop_vinfo (loop, shared, loop_form_info, orig_loop_vinfo);
    2814              : 
    2815       590520 :   machine_mode vector_mode = vector_modes[mode_i];
    2816       590520 :   loop_vinfo->vector_mode = vector_mode;
    2817       590520 :   unsigned int suggested_unroll_factor = 1;
    2818       590520 :   bool single_lane_slp_done_for_suggested_uf = false;
    2819              : 
    2820              :   /* Run the main analysis.  */
    2821       590520 :   opt_result res = vect_analyze_loop_2 (loop_vinfo, masked_p, fatal,
    2822              :                                         &suggested_unroll_factor,
    2823              :                                         single_lane_slp_done_for_suggested_uf);
    2824       590520 :   if (dump_enabled_p ())
    2825        21534 :     dump_printf_loc (MSG_NOTE, vect_location,
    2826              :                      "***** Analysis %s with vector mode %s\n",
    2827        21534 :                      res ? "succeeded" : "failed",
    2828        21534 :                      GET_MODE_NAME (loop_vinfo->vector_mode));
    2829              : 
    2830       590520 :   auto user_unroll = LOOP_VINFO_LOOP (loop_vinfo)->unroll;
    2831       590520 :   if (res && !LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    2832              :       /* Check to see if the user wants to unroll or if the target wants to.  */
    2833       677197 :       && (suggested_unroll_factor > 1 || user_unroll > 1))
    2834              :     {
    2835          485 :       if (suggested_unroll_factor == 1)
    2836              :         {
    2837           66 :           int assumed_vf = vect_vf_for_cost (loop_vinfo);
    2838           66 :           suggested_unroll_factor = user_unroll / assumed_vf;
    2839           66 :           if (suggested_unroll_factor > 1)
    2840              :             {
    2841           40 :               if (dump_enabled_p ())
    2842           20 :                 dump_printf_loc (MSG_NOTE, vect_location,
    2843              :                          "setting unroll factor to %d based on user requested "
    2844              :                          "unroll factor %d and suggested vectorization "
    2845              :                          "factor: %d\n",
    2846              :                          suggested_unroll_factor, user_unroll, assumed_vf);
    2847              :             }
    2848              :         }
    2849              : 
    2850          485 :         if (suggested_unroll_factor > 1)
    2851              :           {
    2852          459 :             if (dump_enabled_p ())
    2853           62 :               dump_printf_loc (MSG_NOTE, vect_location,
    2854              :                          "***** Re-trying analysis for unrolling"
    2855              :                          " with unroll factor %d and %s slp.\n",
    2856              :                          suggested_unroll_factor,
    2857              :                          single_lane_slp_done_for_suggested_uf
    2858              :                          ? "single-lane" : "");
    2859          459 :             loop_vec_info unroll_vinfo
    2860          459 :                 = vect_create_loop_vinfo (loop, shared, loop_form_info, NULL);
    2861          459 :             unroll_vinfo->vector_mode = vector_mode;
    2862          459 :             unroll_vinfo->suggested_unroll_factor = suggested_unroll_factor;
    2863          459 :             opt_result new_res
    2864          459 :               = vect_analyze_loop_2 (unroll_vinfo, masked_p, fatal, NULL,
    2865              :                                      single_lane_slp_done_for_suggested_uf);
    2866          459 :             if (new_res)
    2867              :               {
    2868          400 :                 delete loop_vinfo;
    2869              :                 loop_vinfo = unroll_vinfo;
    2870              :               }
    2871              :             else
    2872           59 :               delete unroll_vinfo;
    2873              :           }
    2874              : 
    2875              :         /* Record that we have honored a user unroll factor.  */
    2876          485 :         LOOP_VINFO_USER_UNROLL (loop_vinfo) = user_unroll > 1;
    2877              :     }
    2878              : 
    2879              :   /* Remember the autodetected vector mode.  */
    2880       590520 :   if (vector_mode == VOIDmode)
    2881       273557 :     autodetected_vector_mode = loop_vinfo->vector_mode;
    2882              : 
    2883              :   /* Advance mode_i, first skipping modes that would result in the
    2884              :      same analysis result.  */
    2885      2604386 :   while (mode_i + 1 < vector_modes.length ()
    2886      1791258 :          && vect_chooses_same_modes_p (loop_vinfo,
    2887       784325 :                                        vector_modes[mode_i + 1]))
    2888              :     {
    2889       416413 :       if (dump_enabled_p ())
    2890        17214 :         dump_printf_loc (MSG_NOTE, vect_location,
    2891              :                          "***** The result for vector mode %s would"
    2892              :                          " be the same\n",
    2893        17214 :                          GET_MODE_NAME (vector_modes[mode_i + 1]));
    2894       416413 :       mode_i += 1;
    2895              :     }
    2896       590520 :   if (mode_i + 1 < vector_modes.length ()
    2897       958432 :       && vect_chooses_same_modes_p (autodetected_vector_mode,
    2898       367912 :                                     vector_modes[mode_i + 1]))
    2899              :     {
    2900          426 :       if (dump_enabled_p ())
    2901           11 :         dump_printf_loc (MSG_NOTE, vect_location,
    2902              :                          "***** Skipping vector mode %s, which would"
    2903              :                          " repeat the analysis for %s\n",
    2904           11 :                          GET_MODE_NAME (vector_modes[mode_i + 1]),
    2905           11 :                          GET_MODE_NAME (autodetected_vector_mode));
    2906          426 :       mode_i += 1;
    2907              :     }
    2908       590520 :   mode_i++;
    2909              : 
    2910       590520 :   if (!res)
    2911              :     {
    2912       495458 :       delete loop_vinfo;
    2913       495458 :       if (fatal)
    2914       104688 :         gcc_checking_assert (orig_loop_vinfo == NULL);
    2915       495458 :       return opt_loop_vec_info::propagate_failure (res);
    2916              :     }
    2917              : 
    2918        95062 :   return opt_loop_vec_info::success (loop_vinfo);
    2919              : }
    2920              : 
    2921              : /* Function vect_analyze_loop.
    2922              : 
    2923              :    Apply a set of analyses on LOOP, and create a loop_vec_info struct
    2924              :    for it.  The different analyses will record information in the
    2925              :    loop_vec_info struct.  */
    2926              : opt_loop_vec_info
    2927       474408 : vect_analyze_loop (class loop *loop, gimple *loop_vectorized_call,
    2928              :                    vec_info_shared *shared)
    2929              : {
    2930       474408 :   DUMP_VECT_SCOPE ("analyze_loop_nest");
    2931              : 
    2932       474408 :   if (loop_outer (loop)
    2933       474408 :       && loop_vec_info_for_loop (loop_outer (loop))
    2934       474992 :       && LOOP_VINFO_VECTORIZABLE_P (loop_vec_info_for_loop (loop_outer (loop))))
    2935          584 :     return opt_loop_vec_info::failure_at (vect_location,
    2936              :                                           "outer-loop already vectorized.\n");
    2937              : 
    2938       473824 :   if (!find_loop_nest (loop, &shared->loop_nest))
    2939        20941 :     return opt_loop_vec_info::failure_at
    2940        20941 :       (vect_location,
    2941              :        "not vectorized: loop nest containing two or more consecutive inner"
    2942              :        " loops cannot be vectorized\n");
    2943              : 
    2944              :   /* Analyze the loop form.  */
    2945       452883 :   vect_loop_form_info loop_form_info;
    2946       452883 :   opt_result res = vect_analyze_loop_form (loop, loop_vectorized_call,
    2947              :                                            &loop_form_info);
    2948       452883 :   if (!res)
    2949              :     {
    2950       179326 :       if (dump_enabled_p ())
    2951         1540 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2952              :                          "bad loop form.\n");
    2953       179326 :       return opt_loop_vec_info::propagate_failure (res);
    2954              :     }
    2955       273557 :   if (!integer_onep (loop_form_info.assumptions))
    2956              :     {
    2957              :       /* We consider to vectorize this loop by versioning it under
    2958              :          some assumptions.  In order to do this, we need to clear
    2959              :          existing information computed by scev and niter analyzer.  */
    2960         8501 :       scev_reset_htab ();
    2961         8501 :       free_numbers_of_iterations_estimates (loop);
    2962              :       /* Also set flag for this loop so that following scev and niter
    2963              :          analysis are done under the assumptions.  */
    2964         8501 :       loop_constraint_set (loop, LOOP_C_FINITE);
    2965              :     }
    2966              :   else
    2967              :     /* Clear the existing niter information to make sure the nonwrapping flag
    2968              :        will be calculated and set propriately.  */
    2969       265056 :     free_numbers_of_iterations_estimates (loop);
    2970              : 
    2971       273557 :   auto_vector_modes vector_modes;
    2972              :   /* Autodetect first vector size we try.  */
    2973       273557 :   vector_modes.safe_push (VOIDmode);
    2974       273557 :   unsigned int autovec_flags
    2975       547114 :     = targetm.vectorize.autovectorize_vector_modes (&vector_modes,
    2976       273557 :                                                     loop->simdlen != 0);
    2977       273557 :   bool pick_lowest_cost_p = ((autovec_flags & VECT_COMPARE_COSTS)
    2978       273557 :                              && !unlimited_cost_model (loop));
    2979       273557 :   machine_mode autodetected_vector_mode = VOIDmode;
    2980       273557 :   opt_loop_vec_info first_loop_vinfo = opt_loop_vec_info::success (NULL);
    2981       273557 :   unsigned int mode_i = 0;
    2982       273557 :   unsigned HOST_WIDE_INT simdlen = loop->simdlen;
    2983              : 
    2984              :   /* Keep track of the VF for each mode.  Initialize all to 0 which indicates
    2985              :      a mode has not been analyzed.  */
    2986       273557 :   auto_vec<poly_uint64, 8> cached_vf_per_mode;
    2987      2747152 :   for (unsigned i = 0; i < vector_modes.length (); ++i)
    2988      1100019 :     cached_vf_per_mode.safe_push (0);
    2989              : 
    2990              :   /* First determine the main loop vectorization mode, either the first
    2991              :      one that works, starting with auto-detecting the vector mode and then
    2992              :      following the targets order of preference, or the one with the
    2993              :      lowest cost if pick_lowest_cost_p.  */
    2994       879633 :   while (1)
    2995              :     {
    2996       576595 :       bool fatal;
    2997       576595 :       unsigned int last_mode_i = mode_i;
    2998              :       /* Set cached VF to -1 prior to analysis, which indicates a mode has
    2999              :          failed.  */
    3000       576595 :       cached_vf_per_mode[last_mode_i] = -1;
    3001       576595 :       opt_loop_vec_info loop_vinfo
    3002       576595 :         = vect_analyze_loop_1 (loop, shared, &loop_form_info,
    3003              :                                NULL, vector_modes, mode_i, -1,
    3004              :                                autodetected_vector_mode, fatal);
    3005       576595 :       if (fatal)
    3006              :         break;
    3007              : 
    3008       471907 :       if (loop_vinfo)
    3009              :         {
    3010              :           /*  Analysis has been successful so update the VF value.  The
    3011              :               VF should always be a multiple of unroll_factor and we want to
    3012              :               capture the original VF here.  */
    3013        86677 :           cached_vf_per_mode[last_mode_i]
    3014        86677 :             = exact_div (LOOP_VINFO_VECT_FACTOR (loop_vinfo),
    3015        86677 :                          loop_vinfo->suggested_unroll_factor);
    3016              :           /* Once we hit the desired simdlen for the first time,
    3017              :              discard any previous attempts.  */
    3018        86677 :           if (simdlen
    3019        86677 :               && known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), simdlen))
    3020              :             {
    3021           47 :               delete first_loop_vinfo;
    3022        86677 :               first_loop_vinfo = opt_loop_vec_info::success (NULL);
    3023        86677 :               simdlen = 0;
    3024              :             }
    3025        86630 :           else if (pick_lowest_cost_p
    3026        72588 :                    && first_loop_vinfo
    3027       117879 :                    && vect_joust_loop_vinfos (loop_vinfo, first_loop_vinfo))
    3028              :             {
    3029              :               /* Pick loop_vinfo over first_loop_vinfo.  */
    3030         1222 :               delete first_loop_vinfo;
    3031         1222 :               first_loop_vinfo = opt_loop_vec_info::success (NULL);
    3032              :             }
    3033        86677 :           if (first_loop_vinfo == NULL)
    3034              :             first_loop_vinfo = loop_vinfo;
    3035              :           else
    3036              :             {
    3037        30029 :               delete loop_vinfo;
    3038        30029 :               loop_vinfo = opt_loop_vec_info::success (NULL);
    3039              :             }
    3040              : 
    3041              :           /* Commit to first_loop_vinfo if we have no reason to try
    3042              :              alternatives.  */
    3043        86677 :           if (!simdlen && !pick_lowest_cost_p)
    3044              :             break;
    3045              :         }
    3046       457827 :       if (mode_i == vector_modes.length ()
    3047       457827 :           || autodetected_vector_mode == VOIDmode)
    3048              :         break;
    3049              : 
    3050              :       /* Try the next biggest vector size.  */
    3051       303038 :       if (dump_enabled_p ())
    3052         4887 :         dump_printf_loc (MSG_NOTE, vect_location,
    3053              :                          "***** Re-trying analysis with vector mode %s\n",
    3054         4887 :                          GET_MODE_NAME (vector_modes[mode_i]));
    3055       303038 :     }
    3056       273557 :   if (!first_loop_vinfo)
    3057       218136 :     return opt_loop_vec_info::propagate_failure (res);
    3058              : 
    3059        55421 :   if (dump_enabled_p ())
    3060         9652 :     dump_printf_loc (MSG_NOTE, vect_location,
    3061              :                      "***** Choosing vector mode %s\n",
    3062         9652 :                      GET_MODE_NAME (first_loop_vinfo->vector_mode));
    3063              : 
    3064              :   /* Only vectorize epilogues if PARAM_VECT_EPILOGUES_NOMASK is
    3065              :      enabled, SIMDUID is not set, it is the innermost loop and we have
    3066              :      either already found the loop's SIMDLEN or there was no SIMDLEN to
    3067              :      begin with.
    3068              :      TODO: Enable epilogue vectorization for loops with SIMDUID set.  */
    3069        55421 :   bool vect_epilogues = (!simdlen
    3070        55419 :                          && loop->inner == NULL
    3071        54834 :                          && param_vect_epilogues_nomask
    3072        53692 :                          && LOOP_VINFO_PEELING_FOR_NITER (first_loop_vinfo)
    3073              :                            /* No code motion support for multiple epilogues so for now
    3074              :                               not supported when multiple exits.  */
    3075        26277 :                          && !LOOP_VINFO_EARLY_BREAKS (first_loop_vinfo)
    3076        25768 :                          && !loop->simduid
    3077        79799 :                          && loop_cost_model (loop) > VECT_COST_MODEL_VERY_CHEAP);
    3078        55421 :   if (!vect_epilogues)
    3079        42365 :     return first_loop_vinfo;
    3080              : 
    3081              :   /* Now analyze first_loop_vinfo for epilogue vectorization.  */
    3082              : 
    3083              :   /* For epilogues start the analysis from the first mode.  The motivation
    3084              :      behind starting from the beginning comes from cases where the VECTOR_MODES
    3085              :      array may contain length-agnostic and length-specific modes.  Their
    3086              :      ordering is not guaranteed, so we could end up picking a mode for the main
    3087              :      loop that is after the epilogue's optimal mode.  */
    3088        13056 :   int masked_p = -1;
    3089        13056 :   if (!unlimited_cost_model (loop)
    3090        13056 :       && (first_loop_vinfo->vector_costs->suggested_epilogue_mode (masked_p)
    3091              :           != VOIDmode))
    3092              :     {
    3093            5 :       vector_modes[0]
    3094            5 :         = first_loop_vinfo->vector_costs->suggested_epilogue_mode (masked_p);
    3095            5 :       cached_vf_per_mode[0] = 0;
    3096              :     }
    3097              :   else
    3098        13051 :     vector_modes[0] = autodetected_vector_mode;
    3099        13056 :   mode_i = 0;
    3100              : 
    3101        13093 :   bool supports_partial_vectors = (param_vect_partial_vector_usage != 0
    3102        13056 :                                    || masked_p == 1);
    3103              :   if (supports_partial_vectors
    3104           37 :       && !partial_vectors_supported_p ()
    3105           37 :       && !LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (first_loop_vinfo))
    3106              :     supports_partial_vectors = false;
    3107        13056 :   poly_uint64 first_vinfo_vf = LOOP_VINFO_VECT_FACTOR (first_loop_vinfo);
    3108              : 
    3109        13056 :   loop_vec_info orig_loop_vinfo = first_loop_vinfo;
    3110        13220 :   do
    3111              :     {
    3112              :       /* Let the user override what the target suggests.  */
    3113        13138 :       if (OPTION_SET_P (param_vect_partial_vector_usage))
    3114           45 :         masked_p = -1;
    3115              : 
    3116        50823 :       while (1)
    3117              :         {
    3118              :           /* If the target does not support partial vectors we can shorten the
    3119              :              number of modes to analyze for the epilogue as we know we can't
    3120              :              pick a mode that would lead to a VF at least as big as the
    3121              :              FIRST_VINFO_VF.  */
    3122        67652 :           if (!supports_partial_vectors
    3123        50823 :               && maybe_ge (cached_vf_per_mode[mode_i], first_vinfo_vf))
    3124              :             {
    3125        24039 :               mode_i++;
    3126        48078 :               if (mode_i == vector_modes.length ())
    3127              :                 break;
    3128        29688 :               continue;
    3129              :             }
    3130              :           /* We would need an exhaustive search to find all modes we
    3131              :              skipped but that would lead to the same result as the
    3132              :              analysis it was skipped for and where we'd could check
    3133              :              cached_vf_per_mode against.
    3134              :              Check for the autodetected mode, which is the common
    3135              :              situation on x86 which does not perform cost comparison.  */
    3136        39643 :           if (!supports_partial_vectors
    3137        26736 :               && maybe_ge (cached_vf_per_mode[0], first_vinfo_vf)
    3138        52737 :               && vect_chooses_same_modes_p (autodetected_vector_mode,
    3139        25953 :                                             vector_modes[mode_i]))
    3140              :             {
    3141        12859 :               mode_i++;
    3142        25718 :               if (mode_i == vector_modes.length ())
    3143              :                 break;
    3144        12859 :               continue;
    3145              :             }
    3146              : 
    3147        13925 :           if (dump_enabled_p ())
    3148         3285 :             dump_printf_loc (MSG_NOTE, vect_location,
    3149              :                              "***** Re-trying epilogue analysis with vector "
    3150         3285 :                              "mode %s\n", GET_MODE_NAME (vector_modes[mode_i]));
    3151              : 
    3152        13925 :           bool fatal;
    3153        13925 :           opt_loop_vec_info loop_vinfo
    3154        13925 :             = vect_analyze_loop_1 (loop, shared, &loop_form_info,
    3155              :                                    orig_loop_vinfo,
    3156              :                                    vector_modes, mode_i, masked_p,
    3157              :                                    autodetected_vector_mode, fatal);
    3158        13925 :           if (fatal)
    3159              :             break;
    3160              : 
    3161        13925 :           if (loop_vinfo)
    3162              :             {
    3163         8385 :               if (pick_lowest_cost_p
    3164         5421 :                   && orig_loop_vinfo->epilogue_vinfo
    3165         9887 :                   && vect_joust_loop_vinfos (loop_vinfo,
    3166         1502 :                                              orig_loop_vinfo->epilogue_vinfo))
    3167              :                 {
    3168          170 :                   gcc_assert (vect_epilogues);
    3169          170 :                   delete orig_loop_vinfo->epilogue_vinfo;
    3170          170 :                   orig_loop_vinfo->epilogue_vinfo = nullptr;
    3171              :                 }
    3172         8385 :               if (!orig_loop_vinfo->epilogue_vinfo)
    3173         7053 :                 orig_loop_vinfo->epilogue_vinfo = loop_vinfo;
    3174              :               else
    3175              :                 {
    3176         1332 :                   delete loop_vinfo;
    3177         1332 :                   loop_vinfo = opt_loop_vec_info::success (NULL);
    3178              :                 }
    3179              : 
    3180              :               /* For now only allow one epilogue loop, but allow
    3181              :                  pick_lowest_cost_p to replace it, so commit to the
    3182              :                  first epilogue if we have no reason to try alternatives.  */
    3183         8385 :               if (!pick_lowest_cost_p)
    3184              :                 break;
    3185              :             }
    3186              : 
    3187              :           /* Revert back to the default from the suggested preferred
    3188              :              epilogue vectorization mode.  */
    3189        10961 :           masked_p = -1;
    3190        21922 :           if (mode_i == vector_modes.length ())
    3191              :             break;
    3192              :         }
    3193              : 
    3194        13138 :       orig_loop_vinfo = orig_loop_vinfo->epilogue_vinfo;
    3195        13138 :       if (!orig_loop_vinfo)
    3196              :         break;
    3197              : 
    3198              :       /* When we selected a first vectorized epilogue, see if the target
    3199              :          suggests to have another one.  */
    3200         6883 :       masked_p = -1;
    3201         6883 :       if (!unlimited_cost_model (loop)
    3202         3925 :           && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (orig_loop_vinfo)
    3203        10801 :           && (orig_loop_vinfo->vector_costs->suggested_epilogue_mode (masked_p)
    3204              :               != VOIDmode))
    3205              :         {
    3206          164 :           vector_modes[0]
    3207           82 :             = orig_loop_vinfo->vector_costs->suggested_epilogue_mode (masked_p);
    3208           82 :           cached_vf_per_mode[0] = 0;
    3209           82 :           mode_i = 0;
    3210              :         }
    3211              :       else
    3212              :         break;
    3213           82 :     }
    3214              :   while (1);
    3215              : 
    3216        13056 :   if (first_loop_vinfo->epilogue_vinfo)
    3217              :     {
    3218         6808 :       poly_uint64 lowest_th
    3219         6808 :         = LOOP_VINFO_VERSIONING_THRESHOLD (first_loop_vinfo);
    3220         6808 :       loop_vec_info epilog_vinfo = first_loop_vinfo->epilogue_vinfo;
    3221         6883 :       do
    3222              :         {
    3223         6883 :           poly_uint64 th = LOOP_VINFO_VERSIONING_THRESHOLD (epilog_vinfo);
    3224         6883 :           gcc_assert (!LOOP_REQUIRES_VERSIONING (epilog_vinfo)
    3225              :                       || maybe_ne (lowest_th, 0U));
    3226              :           /* Keep track of the known smallest versioning threshold.  */
    3227         6883 :           if (ordered_p (lowest_th, th))
    3228         6883 :             lowest_th = ordered_min (lowest_th, th);
    3229         6883 :           epilog_vinfo = epilog_vinfo->epilogue_vinfo;
    3230              :         }
    3231         6883 :       while (epilog_vinfo);
    3232         6808 :       LOOP_VINFO_VERSIONING_THRESHOLD (first_loop_vinfo) = lowest_th;
    3233         6808 :       if (dump_enabled_p ())
    3234         1468 :         dump_printf_loc (MSG_NOTE, vect_location,
    3235              :                          "***** Choosing epilogue vector mode %s\n",
    3236         1468 :                          GET_MODE_NAME
    3237              :                            (first_loop_vinfo->epilogue_vinfo->vector_mode));
    3238              :     }
    3239              : 
    3240        13056 :   return first_loop_vinfo;
    3241       726440 : }
    3242              : 
    3243              : /* Return true if there is an in-order reduction function for CODE, storing
    3244              :    it in *REDUC_FN if so.  */
    3245              : 
    3246              : static bool
    3247         5191 : fold_left_reduction_fn (code_helper code, internal_fn *reduc_fn)
    3248              : {
    3249              :   /* We support MINUS_EXPR by negating the operand.  This also preserves an
    3250              :      initial -0.0 since -0.0 - 0.0 (neutral op for MINUS_EXPR) == -0.0 +
    3251              :      (-0.0) = -0.0.  */
    3252         5191 :   if (code == PLUS_EXPR || code == MINUS_EXPR)
    3253              :     {
    3254         4519 :       *reduc_fn = IFN_FOLD_LEFT_PLUS;
    3255            0 :       return true;
    3256              :     }
    3257              :   return false;
    3258              : }
    3259              : 
    3260              : /* Function reduction_fn_for_scalar_code
    3261              : 
    3262              :    Input:
    3263              :    CODE - tree_code of a reduction operations.
    3264              : 
    3265              :    Output:
    3266              :    REDUC_FN - the corresponding internal function to be used to reduce the
    3267              :       vector of partial results into a single scalar result, or IFN_LAST
    3268              :       if the operation is a supported reduction operation, but does not have
    3269              :       such an internal function.
    3270              : 
    3271              :    Return FALSE if CODE currently cannot be vectorized as reduction.  */
    3272              : 
    3273              : bool
    3274      2216681 : reduction_fn_for_scalar_code (code_helper code, internal_fn *reduc_fn)
    3275              : {
    3276      2216681 :   if (code.is_tree_code ())
    3277      2216623 :     switch (tree_code (code))
    3278              :       {
    3279        13896 :       case MAX_EXPR:
    3280        13896 :         *reduc_fn = IFN_REDUC_MAX;
    3281        13896 :         return true;
    3282              : 
    3283        47837 :       case MIN_EXPR:
    3284        47837 :         *reduc_fn = IFN_REDUC_MIN;
    3285        47837 :         return true;
    3286              : 
    3287      1218170 :       case PLUS_EXPR:
    3288      1218170 :         *reduc_fn = IFN_REDUC_PLUS;
    3289      1218170 :         return true;
    3290              : 
    3291       235428 :       case BIT_AND_EXPR:
    3292       235428 :         *reduc_fn = IFN_REDUC_AND;
    3293       235428 :         return true;
    3294              : 
    3295       259012 :       case BIT_IOR_EXPR:
    3296       259012 :         *reduc_fn = IFN_REDUC_IOR;
    3297       259012 :         return true;
    3298              : 
    3299        43610 :       case BIT_XOR_EXPR:
    3300        43610 :         *reduc_fn = IFN_REDUC_XOR;
    3301        43610 :         return true;
    3302              : 
    3303       398670 :       case MULT_EXPR:
    3304       398670 :       case MINUS_EXPR:
    3305       398670 :         *reduc_fn = IFN_LAST;
    3306       398670 :         return true;
    3307              : 
    3308              :       default:
    3309              :         return false;
    3310              :       }
    3311              :   else
    3312           58 :     switch (combined_fn (code))
    3313              :       {
    3314           34 :       CASE_CFN_FMAX:
    3315           34 :         *reduc_fn = IFN_REDUC_FMAX;
    3316           34 :         return true;
    3317              : 
    3318           24 :       CASE_CFN_FMIN:
    3319           24 :         *reduc_fn = IFN_REDUC_FMIN;
    3320           24 :         return true;
    3321              : 
    3322              :       default:
    3323              :         return false;
    3324              :       }
    3325              : }
    3326              : 
    3327              : /* Set *SBOOL_FN to the corresponding function working on vector masks
    3328              :    for REDUC_FN.  Return true if that exists, false otherwise.  */
    3329              : 
    3330              : static bool
    3331            0 : sbool_reduction_fn_for_fn (internal_fn reduc_fn, internal_fn *sbool_fn)
    3332              : {
    3333            0 :   switch (reduc_fn)
    3334              :     {
    3335            0 :     case IFN_REDUC_AND:
    3336            0 :       *sbool_fn = IFN_REDUC_SBOOL_AND;
    3337            0 :       return true;
    3338            0 :     case IFN_REDUC_IOR:
    3339            0 :       *sbool_fn = IFN_REDUC_SBOOL_IOR;
    3340            0 :       return true;
    3341            0 :     case IFN_REDUC_XOR:
    3342            0 :       *sbool_fn = IFN_REDUC_SBOOL_XOR;
    3343            0 :       return true;
    3344              :     default:
    3345              :       return false;
    3346              :     }
    3347              : }
    3348              : 
    3349              : /* If there is a neutral value X such that a reduction would not be affected
    3350              :    by the introduction of additional X elements, return that X, otherwise
    3351              :    return null.  CODE is the code of the reduction and SCALAR_TYPE is type
    3352              :    of the scalar elements.  If the reduction has just a single initial value
    3353              :    then INITIAL_VALUE is that value, otherwise it is null.
    3354              :    If AS_INITIAL is TRUE the value is supposed to be used as initial value.
    3355              :    In that case no signed zero is returned.  */
    3356              : 
    3357              : tree
    3358        78095 : neutral_op_for_reduction (tree scalar_type, code_helper code,
    3359              :                           tree initial_value, bool as_initial)
    3360              : {
    3361        78095 :   if (code.is_tree_code ())
    3362        78037 :     switch (tree_code (code))
    3363              :       {
    3364        13939 :       case DOT_PROD_EXPR:
    3365        13939 :       case SAD_EXPR:
    3366        13939 :       case MINUS_EXPR:
    3367        13939 :       case BIT_IOR_EXPR:
    3368        13939 :       case BIT_XOR_EXPR:
    3369        13939 :         return build_zero_cst (scalar_type);
    3370        57787 :       case WIDEN_SUM_EXPR:
    3371        57787 :       case PLUS_EXPR:
    3372        57787 :         if (!as_initial && HONOR_SIGNED_ZEROS (scalar_type))
    3373           92 :           return build_real (scalar_type, dconstm0);
    3374              :         else
    3375        57695 :           return build_zero_cst (scalar_type);
    3376              : 
    3377         2258 :       case MULT_EXPR:
    3378         2258 :         return build_one_cst (scalar_type);
    3379              : 
    3380         1563 :       case BIT_AND_EXPR:
    3381         1563 :         return build_all_ones_cst (scalar_type);
    3382              : 
    3383              :       case MAX_EXPR:
    3384              :       case MIN_EXPR:
    3385              :         return initial_value;
    3386              : 
    3387          437 :       default:
    3388          437 :         return NULL_TREE;
    3389              :       }
    3390              :   else
    3391           58 :     switch (combined_fn (code))
    3392              :       {
    3393              :       CASE_CFN_FMIN:
    3394              :       CASE_CFN_FMAX:
    3395              :         return initial_value;
    3396              : 
    3397            0 :       default:
    3398            0 :         return NULL_TREE;
    3399              :       }
    3400              : }
    3401              : 
    3402              : /* Error reporting helper for vect_is_simple_reduction below.  GIMPLE statement
    3403              :    STMT is printed with a message MSG. */
    3404              : 
    3405              : static void
    3406          578 : report_vect_op (dump_flags_t msg_type, gimple *stmt, const char *msg)
    3407              : {
    3408          578 :   dump_printf_loc (msg_type, vect_location, "%s%G", msg, stmt);
    3409          578 : }
    3410              : 
    3411              : /* Return true if we need an in-order reduction for operation CODE
    3412              :    on type TYPE.  NEED_WRAPPING_INTEGRAL_OVERFLOW is true if integer
    3413              :    overflow must wrap.  */
    3414              : 
    3415              : bool
    3416       362171 : needs_fold_left_reduction_p (tree type, code_helper code)
    3417              : {
    3418              :   /* CHECKME: check for !flag_finite_math_only too?  */
    3419       362171 :   if (SCALAR_FLOAT_TYPE_P (type))
    3420              :     {
    3421       101483 :       if (code.is_tree_code ())
    3422       101429 :         switch (tree_code (code))
    3423              :           {
    3424              :           case MIN_EXPR:
    3425              :           case MAX_EXPR:
    3426              :             return false;
    3427              : 
    3428       100853 :           default:
    3429       100853 :             return !flag_associative_math;
    3430              :           }
    3431              :       else
    3432           54 :         switch (combined_fn (code))
    3433              :           {
    3434              :           CASE_CFN_FMIN:
    3435              :           CASE_CFN_FMAX:
    3436              :             return false;
    3437              : 
    3438            2 :           default:
    3439            2 :             return !flag_associative_math;
    3440              :           }
    3441              :     }
    3442              : 
    3443       260688 :   if (INTEGRAL_TYPE_P (type))
    3444       260578 :     return (!code.is_tree_code ()
    3445       260578 :             || !operation_no_trapping_overflow (type, tree_code (code)));
    3446              : 
    3447          110 :   if (SAT_FIXED_POINT_TYPE_P (type))
    3448              :     return true;
    3449              : 
    3450              :   return false;
    3451              : }
    3452              : 
    3453              : /* Return true if the reduction PHI in LOOP with latch arg LOOP_ARG and
    3454              :    has a handled computation expression.  Store the main reduction
    3455              :    operation in *CODE.  */
    3456              : 
    3457              : static bool
    3458       103110 : check_reduction_path (dump_user_location_t loc, loop_p loop, gphi *phi,
    3459              :                       tree loop_arg, code_helper *code,
    3460              :                       vec<std::pair<ssa_op_iter, use_operand_p> > &path,
    3461              :                       bool inner_loop_of_double_reduc)
    3462              : {
    3463       103110 :   auto_bitmap visited;
    3464       103110 :   tree lookfor = PHI_RESULT (phi);
    3465       103110 :   ssa_op_iter curri;
    3466       103110 :   use_operand_p curr = op_iter_init_phiuse (&curri, phi, SSA_OP_USE);
    3467       214415 :   while (USE_FROM_PTR (curr) != loop_arg)
    3468         8195 :     curr = op_iter_next_use (&curri);
    3469       103110 :   curri.i = curri.numops;
    3470       953827 :   do
    3471              :     {
    3472       953827 :       path.safe_push (std::make_pair (curri, curr));
    3473       953827 :       tree use = USE_FROM_PTR (curr);
    3474       953827 :       if (use == lookfor)
    3475              :         break;
    3476       851210 :       gimple *def = SSA_NAME_DEF_STMT (use);
    3477       851210 :       if (gimple_nop_p (def)
    3478       851210 :           || ! flow_bb_inside_loop_p (loop, gimple_bb (def)))
    3479              :         {
    3480       240179 : pop:
    3481       718272 :           do
    3482              :             {
    3483       718272 :               std::pair<ssa_op_iter, use_operand_p> x = path.pop ();
    3484       718272 :               curri = x.first;
    3485       718272 :               curr = x.second;
    3486       786215 :               do
    3487       786215 :                 curr = op_iter_next_use (&curri);
    3488              :               /* Skip already visited or non-SSA operands (from iterating
    3489              :                  over PHI args).  */
    3490              :               while (curr != NULL_USE_OPERAND_P
    3491      1093844 :                      && (TREE_CODE (USE_FROM_PTR (curr)) != SSA_NAME
    3492       271534 :                          || ! bitmap_set_bit (visited,
    3493       271534 :                                               SSA_NAME_VERSION
    3494              :                                                 (USE_FROM_PTR (curr)))));
    3495              :             }
    3496      1436544 :           while (curr == NULL_USE_OPERAND_P && ! path.is_empty ());
    3497       240179 :           if (curr == NULL_USE_OPERAND_P)
    3498              :             break;
    3499              :         }
    3500              :       else
    3501              :         {
    3502       715736 :           if (gimple_code (def) == GIMPLE_PHI)
    3503        73080 :             curr = op_iter_init_phiuse (&curri, as_a <gphi *>(def), SSA_OP_USE);
    3504              :           else
    3505       642656 :             curr = op_iter_init_use (&curri, def, SSA_OP_USE);
    3506              :           while (curr != NULL_USE_OPERAND_P
    3507       855388 :                  && (TREE_CODE (USE_FROM_PTR (curr)) != SSA_NAME
    3508       745262 :                      || ! bitmap_set_bit (visited,
    3509       745262 :                                           SSA_NAME_VERSION
    3510              :                                             (USE_FROM_PTR (curr)))))
    3511       139652 :             curr = op_iter_next_use (&curri);
    3512       715736 :           if (curr == NULL_USE_OPERAND_P)
    3513       104705 :             goto pop;
    3514              :         }
    3515              :     }
    3516              :   while (1);
    3517       103110 :   if (dump_file && (dump_flags & TDF_DETAILS))
    3518              :     {
    3519         4174 :       dump_printf_loc (MSG_NOTE, loc, "reduction path: ");
    3520         4174 :       unsigned i;
    3521         4174 :       std::pair<ssa_op_iter, use_operand_p> *x;
    3522        14235 :       FOR_EACH_VEC_ELT (path, i, x)
    3523        10061 :         dump_printf (MSG_NOTE, "%T ", USE_FROM_PTR (x->second));
    3524         4174 :       dump_printf (MSG_NOTE, "\n");
    3525              :     }
    3526              : 
    3527              :   /* Check whether the reduction path detected is valid.  */
    3528       103110 :   bool fail = path.length () == 0;
    3529       103110 :   bool neg = false;
    3530       103110 :   int sign = -1;
    3531       103110 :   *code = ERROR_MARK;
    3532       225369 :   for (unsigned i = 1; i < path.length (); ++i)
    3533              :     {
    3534       125795 :       gimple *use_stmt = USE_STMT (path[i].second);
    3535       125795 :       gimple_match_op op;
    3536       125795 :       if (!gimple_extract_op (use_stmt, &op))
    3537              :         {
    3538              :           fail = true;
    3539         3536 :           break;
    3540              :         }
    3541       124879 :       unsigned int opi = op.num_ops;
    3542       124879 :       if (gassign *assign = dyn_cast<gassign *> (use_stmt))
    3543              :         {
    3544              :           /* The following make sure we can compute the operand index
    3545              :              easily plus it mostly disallows chaining via COND_EXPR condition
    3546              :              operands.  */
    3547       192826 :           for (opi = 0; opi < op.num_ops; ++opi)
    3548       191796 :             if (gimple_assign_rhs1_ptr (assign) + opi == path[i].second->use)
    3549              :               break;
    3550              :         }
    3551         6238 :       else if (gcall *call = dyn_cast<gcall *> (use_stmt))
    3552              :         {
    3553        12485 :           for (opi = 0; opi < op.num_ops; ++opi)
    3554        12485 :             if (gimple_call_arg_ptr (call, opi) == path[i].second->use)
    3555              :               break;
    3556              :         }
    3557       124879 :       if (opi == op.num_ops)
    3558              :         {
    3559              :           fail = true;
    3560              :           break;
    3561              :         }
    3562       123849 :       op.code = canonicalize_code (op.code, op.type);
    3563       123849 :       if (op.code == MINUS_EXPR)
    3564              :         {
    3565         5691 :           op.code = PLUS_EXPR;
    3566              :           /* Track whether we negate the reduction value each iteration.  */
    3567         5691 :           if (op.ops[1] == op.ops[opi])
    3568           34 :             neg = ! neg;
    3569              :         }
    3570       118158 :       else if (op.code == IFN_COND_SUB)
    3571              :         {
    3572            9 :           op.code = IFN_COND_ADD;
    3573              :           /* Track whether we negate the reduction value each iteration.  */
    3574            9 :           if (op.ops[2] == op.ops[opi])
    3575            0 :             neg = ! neg;
    3576              :         }
    3577              :       /* For an FMA the reduction code is the PLUS if the addition chain
    3578              :          is the reduction.  */
    3579       118149 :       else if (op.code == IFN_FMA && opi == 2)
    3580           33 :         op.code = PLUS_EXPR;
    3581       123849 :       if (CONVERT_EXPR_CODE_P (op.code)
    3582       123849 :           && tree_nop_conversion_p (op.type, TREE_TYPE (op.ops[0])))
    3583              :         ;
    3584       118245 :       else if (*code == ERROR_MARK)
    3585              :         {
    3586       100781 :           *code = op.code;
    3587       100781 :           sign = TYPE_SIGN (op.type);
    3588              :         }
    3589        17464 :       else if (op.code != *code)
    3590              :         {
    3591              :           fail = true;
    3592              :           break;
    3593              :         }
    3594        16127 :       else if ((op.code == MIN_EXPR
    3595        15971 :                 || op.code == MAX_EXPR)
    3596        16142 :                && sign != TYPE_SIGN (op.type))
    3597              :         {
    3598              :           fail = true;
    3599              :           break;
    3600              :         }
    3601              :       /* Check there's only a single stmt the op is used on.  For the
    3602              :          not value-changing tail and the last stmt allow out-of-loop uses,
    3603              :          but not when this is the inner loop of a double reduction.
    3604              :          ???  We could relax this and handle arbitrary live stmts by
    3605              :          forcing a scalar epilogue for example.  */
    3606       122509 :       imm_use_iterator imm_iter;
    3607       122509 :       use_operand_p use_p;
    3608       122509 :       gimple *op_use_stmt;
    3609       122509 :       unsigned cnt = 0;
    3610       128712 :       bool cond_fn_p = op.code.is_internal_fn ()
    3611         6203 :         && (conditional_internal_fn_code (internal_fn (op.code))
    3612       122509 :             != ERROR_MARK);
    3613              : 
    3614       294514 :       FOR_EACH_IMM_USE_STMT (op_use_stmt, imm_iter, op.ops[opi])
    3615              :         {
    3616              :           /* In case of a COND_OP (mask, op1, op2, op1) reduction we should
    3617              :              have op1 twice (once as definition, once as else) in the same
    3618              :              operation.  Enforce this.  */
    3619       172005 :           if (cond_fn_p && op_use_stmt == use_stmt)
    3620              :             {
    3621         6121 :               gcall *call = as_a<gcall *> (use_stmt);
    3622         6121 :               unsigned else_pos
    3623         6121 :                 = internal_fn_else_index (internal_fn (op.code));
    3624         6121 :               if (gimple_call_arg (call, else_pos) != op.ops[opi])
    3625              :                 {
    3626              :                   fail = true;
    3627              :                   break;
    3628              :                 }
    3629        30605 :               for (unsigned int j = 0; j < gimple_call_num_args (call); ++j)
    3630              :                 {
    3631        24484 :                   if (j == else_pos)
    3632         6121 :                     continue;
    3633        18363 :                   if (gimple_call_arg (call, j) == op.ops[opi])
    3634         6121 :                     cnt++;
    3635              :                 }
    3636              :             }
    3637       165884 :           else if (!is_gimple_debug (op_use_stmt)
    3638       165884 :                    && ((*code != ERROR_MARK || inner_loop_of_double_reduc)
    3639         2828 :                        || flow_bb_inside_loop_p (loop,
    3640         2828 :                                                  gimple_bb (op_use_stmt))))
    3641       233423 :             FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
    3642       116716 :               cnt++;
    3643       122509 :         }
    3644              : 
    3645       122509 :       if (cnt != 1)
    3646              :         {
    3647              :           fail = true;
    3648              :           break;
    3649              :         }
    3650              :     }
    3651       107150 :   return ! fail && ! neg && *code != ERROR_MARK;
    3652       103110 : }
    3653              : 
    3654              : bool
    3655           21 : check_reduction_path (dump_user_location_t loc, loop_p loop, gphi *phi,
    3656              :                       tree loop_arg, enum tree_code code)
    3657              : {
    3658           21 :   auto_vec<std::pair<ssa_op_iter, use_operand_p> > path;
    3659           21 :   code_helper code_;
    3660           21 :   return (check_reduction_path (loc, loop, phi, loop_arg, &code_, path, false)
    3661           21 :           && code_ == code);
    3662           21 : }
    3663              : 
    3664              : 
    3665              : 
    3666              : /* Function vect_is_simple_reduction
    3667              : 
    3668              :    (1) Detect a cross-iteration def-use cycle that represents a simple
    3669              :    reduction computation.  We look for the following pattern:
    3670              : 
    3671              :    loop_header:
    3672              :      a1 = phi < a0, a2 >
    3673              :      a3 = ...
    3674              :      a2 = operation (a3, a1)
    3675              : 
    3676              :    or
    3677              : 
    3678              :    a3 = ...
    3679              :    loop_header:
    3680              :      a1 = phi < a0, a2 >
    3681              :      a2 = operation (a3, a1)
    3682              : 
    3683              :    such that:
    3684              :    1. operation is commutative and associative and it is safe to
    3685              :       change the order of the computation
    3686              :    2. no uses for a2 in the loop (a2 is used out of the loop)
    3687              :    3. no uses of a1 in the loop besides the reduction operation
    3688              :    4. no uses of a1 outside the loop.
    3689              : 
    3690              :    Conditions 1,4 are tested here.
    3691              :    Conditions 2,3 are tested in vect_mark_stmts_to_be_vectorized.
    3692              : 
    3693              :    (2) Detect a cross-iteration def-use cycle in nested loops, i.e.,
    3694              :    nested cycles.
    3695              : 
    3696              :    (3) Detect cycles of phi nodes in outer-loop vectorization, i.e., double
    3697              :    reductions:
    3698              : 
    3699              :      a1 = phi < a0, a2 >
    3700              :      inner loop (def of a3)
    3701              :      a2 = phi < a3 >
    3702              : 
    3703              :    (4) Detect condition expressions, ie:
    3704              :      for (int i = 0; i < N; i++)
    3705              :        if (a[i] < val)
    3706              :         ret_val = a[i];
    3707              : 
    3708              : */
    3709              : 
    3710              : static stmt_vec_info
    3711       168753 : vect_is_simple_reduction (loop_vec_info loop_info, stmt_vec_info phi_info,
    3712              :                           gphi **double_reduc)
    3713              : {
    3714       168753 :   gphi *phi = as_a <gphi *> (phi_info->stmt);
    3715       168753 :   gimple *phi_use_stmt = NULL;
    3716       168753 :   imm_use_iterator imm_iter;
    3717       168753 :   use_operand_p use_p;
    3718              : 
    3719              :   /* When double_reduc is NULL we are testing the inner loop of a
    3720              :      double reduction.  */
    3721       168753 :   bool inner_loop_of_double_reduc = double_reduc == NULL;
    3722       168753 :   if (double_reduc)
    3723       167634 :     *double_reduc = NULL;
    3724       168753 :   STMT_VINFO_REDUC_TYPE (phi_info) = TREE_CODE_REDUCTION;
    3725              : 
    3726       168753 :   tree phi_name = PHI_RESULT (phi);
    3727              :   /* ???  If there are no uses of the PHI result the inner loop reduction
    3728              :      won't be detected as possibly double-reduction by vectorizable_reduction
    3729              :      because that tries to walk the PHI arg from the preheader edge which
    3730              :      can be constant.  See PR60382.  */
    3731       168753 :   if (has_zero_uses (phi_name))
    3732              :     return NULL;
    3733       168621 :   class loop *loop = (gimple_bb (phi))->loop_father;
    3734       168621 :   unsigned nphi_def_loop_uses = 0;
    3735       477268 :   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, phi_name)
    3736              :     {
    3737       320699 :       gimple *use_stmt = USE_STMT (use_p);
    3738       320699 :       if (is_gimple_debug (use_stmt))
    3739        93323 :         continue;
    3740              : 
    3741       227376 :       if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
    3742              :         {
    3743        12052 :           if (dump_enabled_p ())
    3744           31 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3745              :                              "intermediate value used outside loop.\n");
    3746              : 
    3747        12052 :           return NULL;
    3748              :         }
    3749              : 
    3750              :       /* In case of a COND_OP (mask, op1, op2, op1) reduction we might have
    3751              :          op1 twice (once as definition, once as else) in the same operation.
    3752              :          Only count it as one. */
    3753       215324 :       if (use_stmt != phi_use_stmt)
    3754              :         {
    3755       208843 :           nphi_def_loop_uses++;
    3756       208843 :           phi_use_stmt = use_stmt;
    3757              :         }
    3758        12052 :     }
    3759              : 
    3760       156569 :   tree latch_def = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
    3761       156569 :   if (TREE_CODE (latch_def) != SSA_NAME)
    3762              :     {
    3763         1496 :       if (dump_enabled_p ())
    3764            8 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3765              :                          "reduction: not ssa_name: %T\n", latch_def);
    3766              :       return NULL;
    3767              :     }
    3768              : 
    3769       155073 :   stmt_vec_info def_stmt_info = loop_info->lookup_def (latch_def);
    3770       155073 :   if (!def_stmt_info
    3771       155073 :       || !flow_bb_inside_loop_p (loop, gimple_bb (def_stmt_info->stmt)))
    3772              :     return NULL;
    3773              : 
    3774       154899 :   bool nested_in_vect_loop
    3775       154899 :     = flow_loop_nested_p (LOOP_VINFO_LOOP (loop_info), loop);
    3776       154899 :   unsigned nlatch_def_loop_uses = 0;
    3777       154899 :   auto_vec<gphi *, 3> lcphis;
    3778       613018 :   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, latch_def)
    3779              :     {
    3780       458119 :       gimple *use_stmt = USE_STMT (use_p);
    3781       458119 :       if (is_gimple_debug (use_stmt))
    3782       143500 :         continue;
    3783       314619 :       if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
    3784       197066 :         nlatch_def_loop_uses++;
    3785              :       else
    3786              :         /* We can have more than one loop-closed PHI.  */
    3787       117553 :         lcphis.safe_push (as_a <gphi *> (use_stmt));
    3788       154899 :     }
    3789              : 
    3790              :   /* If we are vectorizing an inner reduction we are executing that
    3791              :      in the original order only in case we are not dealing with a
    3792              :      double reduction.  */
    3793       154899 :   if (nested_in_vect_loop && !inner_loop_of_double_reduc)
    3794              :     {
    3795         2313 :       if (dump_enabled_p ())
    3796          434 :         report_vect_op (MSG_NOTE, def_stmt_info->stmt,
    3797              :                         "detected nested cycle: ");
    3798              :       return def_stmt_info;
    3799              :     }
    3800              : 
    3801              :   /* When the inner loop of a double reduction ends up with more than
    3802              :      one loop-closed PHI we have failed to classify alternate such
    3803              :      PHIs as double reduction, leading to wrong code.  See PR103237.  */
    3804       153693 :   if (inner_loop_of_double_reduc && lcphis.length () != 1)
    3805              :     {
    3806            1 :       if (dump_enabled_p ())
    3807            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3808              :                          "unhandle double reduction\n");
    3809              :       return NULL;
    3810              :     }
    3811              : 
    3812              :   /* If this isn't a nested cycle or if the nested cycle reduction value
    3813              :      is used outside of the inner loop we cannot handle uses of the reduction
    3814              :      value.  */
    3815       152585 :   if (nlatch_def_loop_uses > 1 || nphi_def_loop_uses > 1)
    3816              :     {
    3817        48121 :       if (dump_enabled_p ())
    3818          412 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3819              :                          "reduction used in loop.\n");
    3820              :       return NULL;
    3821              :     }
    3822              : 
    3823              :   /* If DEF_STMT is a phi node itself, we expect it to have a single argument
    3824              :      defined in the inner loop.  */
    3825       104464 :   if (gphi *def_stmt = dyn_cast <gphi *> (def_stmt_info->stmt))
    3826              :     {
    3827         1375 :       tree op1 = PHI_ARG_DEF (def_stmt, 0);
    3828         1375 :       if (gimple_phi_num_args (def_stmt) != 1
    3829         1375 :           || TREE_CODE (op1) != SSA_NAME)
    3830              :         {
    3831           92 :           if (dump_enabled_p ())
    3832            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3833              :                              "unsupported phi node definition.\n");
    3834              : 
    3835              :           return NULL;
    3836              :         }
    3837              : 
    3838              :       /* Verify there is an inner cycle composed of the PHI phi_use_stmt
    3839              :          and the latch definition op1.  */
    3840         1283 :       gimple *def1 = SSA_NAME_DEF_STMT (op1);
    3841         1283 :       if (gimple_bb (def1)
    3842         1283 :           && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
    3843         1283 :           && loop->inner
    3844         1229 :           && flow_bb_inside_loop_p (loop->inner, gimple_bb (def1))
    3845         1229 :           && (is_gimple_assign (def1) || is_gimple_call (def1))
    3846         1220 :           && is_a <gphi *> (phi_use_stmt)
    3847         1208 :           && flow_bb_inside_loop_p (loop->inner, gimple_bb (phi_use_stmt))
    3848         1208 :           && (op1 == PHI_ARG_DEF_FROM_EDGE (phi_use_stmt,
    3849              :                                             loop_latch_edge (loop->inner)))
    3850       157301 :           && lcphis.length () == 1)
    3851              :         {
    3852         1119 :           if (dump_enabled_p ())
    3853          144 :             report_vect_op (MSG_NOTE, def_stmt,
    3854              :                             "detected double reduction: ");
    3855              : 
    3856         1119 :           *double_reduc = as_a <gphi *> (phi_use_stmt);
    3857         1119 :           return def_stmt_info;
    3858              :         }
    3859              : 
    3860              :       return NULL;
    3861              :     }
    3862              : 
    3863              :   /* Look for the expression computing latch_def from then loop PHI result.  */
    3864       103089 :   auto_vec<std::pair<ssa_op_iter, use_operand_p> > path;
    3865       103089 :   code_helper code;
    3866       103089 :   if (check_reduction_path (vect_location, loop, phi, latch_def, &code,
    3867              :                             path, inner_loop_of_double_reduc))
    3868              :     {
    3869        99049 :       STMT_VINFO_REDUC_CODE (phi_info) = code;
    3870        99049 :       if (code == COND_EXPR && !nested_in_vect_loop)
    3871         8310 :         STMT_VINFO_REDUC_TYPE (phi_info) = COND_REDUCTION;
    3872              : 
    3873              :       /* Fill in STMT_VINFO_REDUC_IDX.  */
    3874        99049 :       unsigned i;
    3875       318664 :       for (i = path.length () - 1; i >= 1; --i)
    3876              :         {
    3877       120566 :           gimple *stmt = USE_STMT (path[i].second);
    3878       120566 :           stmt_vec_info stmt_info = loop_info->lookup_stmt (stmt);
    3879       120566 :           gimple_match_op op;
    3880       120566 :           if (!gimple_extract_op (stmt, &op))
    3881            0 :             gcc_unreachable ();
    3882       120566 :           if (gassign *assign = dyn_cast<gassign *> (stmt))
    3883       114348 :             STMT_VINFO_REDUC_IDX (stmt_info)
    3884       114348 :               = path[i].second->use - gimple_assign_rhs1_ptr (assign);
    3885              :           else
    3886              :             {
    3887         6218 :               gcall *call = as_a<gcall *> (stmt);
    3888         6218 :               STMT_VINFO_REDUC_IDX (stmt_info)
    3889         6218 :                 = path[i].second->use - gimple_call_arg_ptr (call, 0);
    3890              :             }
    3891              :         }
    3892        99049 :       if (dump_enabled_p ())
    3893         4160 :         dump_printf_loc (MSG_NOTE, vect_location,
    3894              :                          "reduction: detected reduction\n");
    3895              : 
    3896              :       return def_stmt_info;
    3897              :     }
    3898              : 
    3899         4040 :   if (dump_enabled_p ())
    3900           95 :     dump_printf_loc (MSG_NOTE, vect_location,
    3901              :                      "reduction: unknown pattern\n");
    3902              : 
    3903              :   return NULL;
    3904       257988 : }
    3905              : 
    3906              : /* Estimate the number of peeled epilogue iterations for LOOP_VINFO.
    3907              :    PEEL_ITERS_PROLOGUE is the number of peeled prologue iterations,
    3908              :    or -1 if not known.  */
    3909              : 
    3910              : static int
    3911       506801 : vect_get_peel_iters_epilogue (loop_vec_info loop_vinfo, int peel_iters_prologue)
    3912              : {
    3913       506801 :   int assumed_vf = vect_vf_for_cost (loop_vinfo);
    3914       506801 :   if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) || peel_iters_prologue == -1)
    3915              :     {
    3916       211054 :       if (dump_enabled_p ())
    3917         3726 :         dump_printf_loc (MSG_NOTE, vect_location,
    3918              :                          "cost model: epilogue peel iters set to vf/2 "
    3919              :                          "because loop iterations are unknown .\n");
    3920       211054 :       return assumed_vf / 2;
    3921              :     }
    3922              :   else
    3923              :     {
    3924       295747 :       int niters = LOOP_VINFO_INT_NITERS (loop_vinfo);
    3925       295747 :       peel_iters_prologue = MIN (niters, peel_iters_prologue);
    3926       295747 :       int peel_iters_epilogue = (niters - peel_iters_prologue) % assumed_vf;
    3927              :       /* If we need to peel for gaps, but no peeling is required, we have to
    3928              :          peel VF iterations.  */
    3929       295747 :       if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) && !peel_iters_epilogue)
    3930       506801 :         peel_iters_epilogue = assumed_vf;
    3931              :       return peel_iters_epilogue;
    3932              :     }
    3933              : }
    3934              : 
    3935              : /* Calculate cost of peeling the scalar loop PEEL_ITERS_PROLOGUE times for
    3936              :    a prologue and the corresponding times for the epilogue.  */
    3937              : int
    3938       381072 : vect_get_known_peeling_cost (loop_vec_info loop_vinfo, int peel_iters_prologue)
    3939              : {
    3940       381072 :   int retval = 0;
    3941              : 
    3942       381072 :   int peel_iters_epilogue
    3943       381072 :     = vect_get_peel_iters_epilogue (loop_vinfo, peel_iters_prologue);
    3944              : 
    3945       381072 :   if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
    3946              :     {
    3947              :       /* If peeled iterations are known but number of scalar loop
    3948              :          iterations are unknown, count a taken branch per peeled loop.  */
    3949       144630 :       if (peel_iters_prologue > 0)
    3950        89250 :         retval = builtin_vectorization_cost (cond_branch_taken, NULL_TREE, 0);
    3951       144630 :       if (peel_iters_epilogue > 0)
    3952       144521 :         retval += builtin_vectorization_cost (cond_branch_taken, NULL_TREE, 0);
    3953              :     }
    3954              : 
    3955       762144 :   retval += ((peel_iters_prologue + peel_iters_epilogue)
    3956       381072 :              * loop_vinfo->scalar_costs->body_cost ());
    3957       762144 :   retval += (((peel_iters_prologue != 0) + (peel_iters_epilogue != 0))
    3958       381072 :              * loop_vinfo->scalar_costs->outside_cost ());
    3959              : 
    3960       381072 :   return retval;
    3961              : }
    3962              : 
    3963              : /* Function vect_estimate_min_profitable_iters
    3964              : 
    3965              :    Return the number of iterations required for the vector version of the
    3966              :    loop to be profitable relative to the cost of the scalar version of the
    3967              :    loop.
    3968              : 
    3969              :    *RET_MIN_PROFITABLE_NITERS is a cost model profitability threshold
    3970              :    of iterations for vectorization.  -1 value means loop vectorization
    3971              :    is not profitable.  This returned value may be used for dynamic
    3972              :    profitability check.
    3973              : 
    3974              :    *RET_MIN_PROFITABLE_ESTIMATE is a profitability threshold to be used
    3975              :    for static check against estimated number of iterations.  */
    3976              : 
    3977              : static void
    3978       143097 : vect_estimate_min_profitable_iters (loop_vec_info loop_vinfo,
    3979              :                                     int *ret_min_profitable_niters,
    3980              :                                     int *ret_min_profitable_estimate,
    3981              :                                     unsigned *suggested_unroll_factor)
    3982              : {
    3983       143097 :   int min_profitable_iters;
    3984       143097 :   int min_profitable_estimate;
    3985       143097 :   int peel_iters_prologue;
    3986       143097 :   int peel_iters_epilogue;
    3987       143097 :   unsigned vec_inside_cost = 0;
    3988       143097 :   int vec_outside_cost = 0;
    3989       143097 :   unsigned vec_prologue_cost = 0;
    3990       143097 :   unsigned vec_epilogue_cost = 0;
    3991       143097 :   int scalar_single_iter_cost = 0;
    3992       143097 :   int scalar_outside_cost = 0;
    3993       143097 :   int assumed_vf = vect_vf_for_cost (loop_vinfo);
    3994       143097 :   int npeel = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
    3995       143097 :   vector_costs *target_cost_data = loop_vinfo->vector_costs;
    3996              : 
    3997              :   /* Cost model disabled.  */
    3998       143097 :   if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
    3999              :     {
    4000        17057 :       if (dump_enabled_p ())
    4001        10753 :         dump_printf_loc (MSG_NOTE, vect_location, "cost model disabled.\n");
    4002        17057 :       *ret_min_profitable_niters = 0;
    4003        17057 :       *ret_min_profitable_estimate = 0;
    4004        17057 :       return;
    4005              :     }
    4006              : 
    4007              :   /* Requires loop versioning tests to handle misalignment.  */
    4008       126040 :   if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo))
    4009              :     {
    4010              :       /*  FIXME: Make cost depend on complexity of individual check.  */
    4011           18 :       unsigned len = LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).length ();
    4012           18 :       (void) add_stmt_cost (target_cost_data, len, scalar_stmt, vect_prologue);
    4013           18 :       if (dump_enabled_p ())
    4014            2 :         dump_printf (MSG_NOTE,
    4015              :                      "cost model: Adding cost of checks for loop "
    4016              :                      "versioning to treat misalignment.\n");
    4017              :     }
    4018              : 
    4019              :   /* Requires loop versioning with alias checks.  */
    4020       126040 :   if (LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
    4021              :     {
    4022              :       /*  FIXME: Make cost depend on complexity of individual check.  */
    4023         7213 :       unsigned len = LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).length ();
    4024         7213 :       (void) add_stmt_cost (target_cost_data, len, scalar_stmt, vect_prologue);
    4025         7213 :       len = LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo).length ();
    4026            4 :       if (len)
    4027              :         /* Count LEN - 1 ANDs and LEN comparisons.  */
    4028            4 :         (void) add_stmt_cost (target_cost_data, len * 2 - 1,
    4029              :                               scalar_stmt, vect_prologue);
    4030         7213 :       len = LOOP_VINFO_LOWER_BOUNDS (loop_vinfo).length ();
    4031         1263 :       if (len)
    4032              :         {
    4033              :           /* Count LEN - 1 ANDs and LEN comparisons.  */
    4034         1263 :           unsigned int nstmts = len * 2 - 1;
    4035              :           /* +1 for each bias that needs adding.  */
    4036         2526 :           for (unsigned int i = 0; i < len; ++i)
    4037         1263 :             if (!LOOP_VINFO_LOWER_BOUNDS (loop_vinfo)[i].unsigned_p)
    4038          154 :               nstmts += 1;
    4039         1263 :           (void) add_stmt_cost (target_cost_data, nstmts,
    4040              :                                 scalar_stmt, vect_prologue);
    4041              :         }
    4042         7213 :       if (dump_enabled_p ())
    4043           32 :         dump_printf (MSG_NOTE,
    4044              :                      "cost model: Adding cost of checks for loop "
    4045              :                      "versioning aliasing.\n");
    4046              :     }
    4047              : 
    4048              :   /* Requires loop versioning with niter checks.  */
    4049       126040 :   if (LOOP_REQUIRES_VERSIONING_FOR_NITERS (loop_vinfo))
    4050              :     {
    4051              :       /*  FIXME: Make cost depend on complexity of individual check.  */
    4052          763 :       (void) add_stmt_cost (target_cost_data, 1, vector_stmt,
    4053              :                             NULL, NULL, NULL_TREE, 0, vect_prologue);
    4054          763 :       if (dump_enabled_p ())
    4055            1 :         dump_printf (MSG_NOTE,
    4056              :                      "cost model: Adding cost of checks for loop "
    4057              :                      "versioning niters.\n");
    4058              :     }
    4059              : 
    4060       126040 :   if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
    4061         7988 :     (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
    4062              :                           vect_prologue);
    4063              : 
    4064              :   /* Count statements in scalar loop.  Using this as scalar cost for a single
    4065              :      iteration for now.
    4066              : 
    4067              :      TODO: Add outer loop support.
    4068              : 
    4069              :      TODO: Consider assigning different costs to different scalar
    4070              :      statements.  */
    4071              : 
    4072       126040 :   scalar_single_iter_cost = loop_vinfo->scalar_costs->total_cost ();
    4073              : 
    4074              :   /* Add additional cost for the peeled instructions in prologue and epilogue
    4075              :      loop.  (For fully-masked loops there will be no peeling.)
    4076              : 
    4077              :      FORNOW: If we don't know the value of peel_iters for prologue or epilogue
    4078              :      at compile-time - we assume it's vf/2 (the worst would be vf-1).
    4079              : 
    4080              :      TODO: Build an expression that represents peel_iters for prologue and
    4081              :      epilogue to be used in a run-time test.  */
    4082              : 
    4083       126040 :   bool prologue_need_br_taken_cost = false;
    4084       126040 :   bool prologue_need_br_not_taken_cost = false;
    4085              : 
    4086              :   /* Calculate peel_iters_prologue.  */
    4087       126040 :   if (vect_use_loop_mask_for_alignment_p (loop_vinfo))
    4088              :     peel_iters_prologue = 0;
    4089       126040 :   else if (npeel < 0)
    4090              :     {
    4091          282 :       peel_iters_prologue = assumed_vf / 2;
    4092          282 :       if (dump_enabled_p ())
    4093           11 :         dump_printf (MSG_NOTE, "cost model: "
    4094              :                      "prologue peel iters set to vf/2.\n");
    4095              : 
    4096              :       /* If peeled iterations are unknown, count a taken branch and a not taken
    4097              :          branch per peeled loop.  Even if scalar loop iterations are known,
    4098              :          vector iterations are not known since peeled prologue iterations are
    4099              :          not known.  Hence guards remain the same.  */
    4100              :       prologue_need_br_taken_cost = true;
    4101              :       prologue_need_br_not_taken_cost = true;
    4102              :     }
    4103              :   else
    4104              :     {
    4105       125758 :       peel_iters_prologue = npeel;
    4106       125758 :       if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && peel_iters_prologue > 0)
    4107              :         /* If peeled iterations are known but number of scalar loop
    4108              :            iterations are unknown, count a taken branch per peeled loop.  */
    4109       126040 :         prologue_need_br_taken_cost = true;
    4110              :     }
    4111              : 
    4112       126040 :   bool epilogue_need_br_taken_cost = false;
    4113       126040 :   bool epilogue_need_br_not_taken_cost = false;
    4114              : 
    4115              :   /* Calculate peel_iters_epilogue.  */
    4116       126040 :   if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    4117              :     /* We need to peel exactly one iteration for gaps.  */
    4118           29 :     peel_iters_epilogue = LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) ? 1 : 0;
    4119       126011 :   else if (npeel < 0)
    4120              :     {
    4121              :       /* If peeling for alignment is unknown, loop bound of main loop
    4122              :          becomes unknown.  */
    4123          282 :       peel_iters_epilogue = assumed_vf / 2;
    4124          282 :       if (dump_enabled_p ())
    4125           11 :         dump_printf (MSG_NOTE, "cost model: "
    4126              :                      "epilogue peel iters set to vf/2 because "
    4127              :                      "peeling for alignment is unknown.\n");
    4128              : 
    4129              :       /* See the same reason above in peel_iters_prologue calculation.  */
    4130              :       epilogue_need_br_taken_cost = true;
    4131              :       epilogue_need_br_not_taken_cost = true;
    4132              :     }
    4133              :   else
    4134              :     {
    4135       125729 :       peel_iters_epilogue = vect_get_peel_iters_epilogue (loop_vinfo, npeel);
    4136       125729 :       if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && peel_iters_epilogue > 0)
    4137              :         /* If peeled iterations are known but number of scalar loop
    4138              :            iterations are unknown, count a taken branch per peeled loop.  */
    4139       126040 :         epilogue_need_br_taken_cost = true;
    4140              :     }
    4141              : 
    4142              :   /* The way we cummulate peeling costs into the vector prologue/epilogue
    4143              :      cost is a bit awkward given we cannot reuse scalar_costs which is
    4144              :      already computed and also because it cannot take into account any
    4145              :      epilogue vectorization we'll carry out in the end.  */
    4146              : 
    4147       126040 :   stmt_info_for_cost *si;
    4148       126040 :   int j;
    4149              :   /* Add costs associated with peel_iters_prologue.  */
    4150       126040 :   if (peel_iters_prologue)
    4151         1083 :     FOR_EACH_VEC_ELT (LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo), j, si)
    4152              :       {
    4153          785 :         (void) add_stmt_cost (target_cost_data,
    4154          785 :                               si->count * peel_iters_prologue, si->kind,
    4155              :                               si->stmt_info, si->node, si->vectype,
    4156              :                               si->misalign, vect_prologue);
    4157              :       }
    4158              : 
    4159              :   /* Add costs associated with peel_iters_epilogue.  */
    4160       126040 :   if (peel_iters_epilogue)
    4161       391445 :     FOR_EACH_VEC_ELT (LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo), j, si)
    4162              :       {
    4163       313507 :         (void) add_stmt_cost (target_cost_data,
    4164       313507 :                               si->count * peel_iters_epilogue, si->kind,
    4165              :                               si->stmt_info, si->node, si->vectype,
    4166              :                               si->misalign, vect_epilogue);
    4167              :       }
    4168              : 
    4169              :   /* Add possible cond_branch_taken/cond_branch_not_taken cost.  */
    4170              : 
    4171       126040 :   if (prologue_need_br_taken_cost)
    4172          282 :     (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
    4173              :                           vect_prologue);
    4174              : 
    4175       126040 :   if (prologue_need_br_not_taken_cost)
    4176          282 :     (void) add_stmt_cost (target_cost_data, 1,
    4177              :                           cond_branch_not_taken, vect_prologue);
    4178              : 
    4179       126040 :   if (epilogue_need_br_taken_cost)
    4180        65810 :     (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
    4181              :                           vect_epilogue);
    4182              : 
    4183       126040 :   if (epilogue_need_br_not_taken_cost)
    4184          282 :     (void) add_stmt_cost (target_cost_data, 1,
    4185              :                           cond_branch_not_taken, vect_epilogue);
    4186              : 
    4187              :   /* Take care of special costs for rgroup controls of partial vectors.  */
    4188           29 :   if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
    4189       126069 :       && (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo)
    4190              :           == vect_partial_vectors_avx512))
    4191              :     {
    4192              :       /* Calculate how many masks we need to generate.  */
    4193           29 :       unsigned int num_masks = 0;
    4194           29 :       bool need_saturation = false;
    4195          121 :       for (auto rgm : LOOP_VINFO_MASKS (loop_vinfo).rgc_vec)
    4196           34 :         if (rgm.type)
    4197              :           {
    4198           29 :             unsigned nvectors = rgm.factor;
    4199           29 :             num_masks += nvectors;
    4200           29 :             if (TYPE_PRECISION (TREE_TYPE (rgm.compare_type))
    4201           29 :                 < TYPE_PRECISION (LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo)))
    4202           10 :               need_saturation = true;
    4203              :           }
    4204              : 
    4205              :       /* ???  The target isn't able to identify the costs below as
    4206              :          producing masks so it cannot penaltize cases where we'd run
    4207              :          out of mask registers for example.  */
    4208              : 
    4209              :       /* ???  We are also failing to account for smaller vector masks
    4210              :          we generate by splitting larger masks in vect_get_loop_mask.  */
    4211              : 
    4212              :       /* In the worst case, we need to generate each mask in the prologue
    4213              :          and in the loop body.  We need one splat per group and one
    4214              :          compare per mask.
    4215              : 
    4216              :          Sometimes the prologue mask will fold to a constant,
    4217              :          so the actual prologue cost might be smaller.  However, it's
    4218              :          simpler and safer to use the worst-case cost; if this ends up
    4219              :          being the tie-breaker between vectorizing or not, then it's
    4220              :          probably better not to vectorize.  */
    4221           29 :       (void) add_stmt_cost (target_cost_data,
    4222              :                             num_masks
    4223           29 :                             + LOOP_VINFO_MASKS (loop_vinfo).rgc_vec.length (),
    4224              :                             vector_stmt, NULL, NULL, NULL_TREE, 0,
    4225              :                             vect_prologue);
    4226           58 :       (void) add_stmt_cost (target_cost_data,
    4227              :                             num_masks
    4228           58 :                             + LOOP_VINFO_MASKS (loop_vinfo).rgc_vec.length (),
    4229              :                             vector_stmt, NULL, NULL, NULL_TREE, 0, vect_body);
    4230              : 
    4231              :       /* When we need saturation we need it both in the prologue and
    4232              :          the epilogue.  */
    4233           29 :       if (need_saturation)
    4234              :         {
    4235           10 :           (void) add_stmt_cost (target_cost_data, 1, scalar_stmt,
    4236              :                                 NULL, NULL, NULL_TREE, 0, vect_prologue);
    4237           10 :           (void) add_stmt_cost (target_cost_data, 1, scalar_stmt,
    4238              :                                 NULL, NULL, NULL_TREE, 0, vect_body);
    4239              :         }
    4240              :     }
    4241            0 :   else if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
    4242       126011 :            && (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo)
    4243              :                == vect_partial_vectors_while_ult))
    4244              :     {
    4245              :       /* Calculate how many masks we need to generate.  */
    4246              :       unsigned int num_masks = 0;
    4247              :       rgroup_controls *rgm;
    4248              :       unsigned int num_vectors_m1;
    4249            0 :       FOR_EACH_VEC_ELT (LOOP_VINFO_MASKS (loop_vinfo).rgc_vec,
    4250              :                         num_vectors_m1, rgm)
    4251            0 :         if (rgm->type)
    4252            0 :           num_masks += num_vectors_m1 + 1;
    4253            0 :       gcc_assert (num_masks > 0);
    4254              : 
    4255              :       /* In the worst case, we need to generate each mask in the prologue
    4256              :          and in the loop body.  One of the loop body mask instructions
    4257              :          replaces the comparison in the scalar loop, and since we don't
    4258              :          count the scalar comparison against the scalar body, we shouldn't
    4259              :          count that vector instruction against the vector body either.
    4260              : 
    4261              :          Sometimes we can use unpacks instead of generating prologue
    4262              :          masks and sometimes the prologue mask will fold to a constant,
    4263              :          so the actual prologue cost might be smaller.  However, it's
    4264              :          simpler and safer to use the worst-case cost; if this ends up
    4265              :          being the tie-breaker between vectorizing or not, then it's
    4266              :          probably better not to vectorize.  */
    4267            0 :       (void) add_stmt_cost (target_cost_data, num_masks,
    4268              :                             vector_stmt, NULL, NULL, NULL_TREE, 0,
    4269              :                             vect_prologue);
    4270            0 :       (void) add_stmt_cost (target_cost_data, num_masks - 1,
    4271              :                             vector_stmt, NULL, NULL, NULL_TREE, 0,
    4272              :                             vect_body);
    4273              :     }
    4274       126011 :   else if (LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
    4275              :     {
    4276              :       /* Referring to the functions vect_set_loop_condition_partial_vectors
    4277              :          and vect_set_loop_controls_directly, we need to generate each
    4278              :          length in the prologue and in the loop body if required. Although
    4279              :          there are some possible optimizations, we consider the worst case
    4280              :          here.  */
    4281              : 
    4282            0 :       bool niters_known_p = LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo);
    4283            0 :       signed char partial_load_store_bias
    4284              :         = LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo);
    4285            0 :       bool need_iterate_p
    4286            0 :         = (!LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    4287            0 :            && !vect_known_niters_smaller_than_vf (loop_vinfo));
    4288              : 
    4289              :       /* Calculate how many statements to be added.  */
    4290            0 :       unsigned int prologue_stmts = 0;
    4291            0 :       unsigned int body_stmts = 0;
    4292              : 
    4293            0 :       rgroup_controls *rgc;
    4294            0 :       unsigned int num_vectors_m1;
    4295            0 :       FOR_EACH_VEC_ELT (LOOP_VINFO_LENS (loop_vinfo), num_vectors_m1, rgc)
    4296            0 :         if (rgc->type)
    4297              :           {
    4298              :             /* May need one SHIFT for nitems_total computation.  */
    4299            0 :             unsigned nitems = rgc->max_nscalars_per_iter * rgc->factor;
    4300            0 :             if (nitems != 1 && !niters_known_p)
    4301            0 :               prologue_stmts += 1;
    4302              : 
    4303              :             /* May need one MAX and one MINUS for wrap around.  */
    4304            0 :             if (vect_rgroup_iv_might_wrap_p (loop_vinfo, rgc))
    4305            0 :               prologue_stmts += 2;
    4306              : 
    4307              :             /* Need one MAX and one MINUS for each batch limit excepting for
    4308              :                the 1st one.  */
    4309            0 :             prologue_stmts += num_vectors_m1 * 2;
    4310              : 
    4311            0 :             unsigned int num_vectors = num_vectors_m1 + 1;
    4312              : 
    4313              :             /* Need to set up lengths in prologue, only one MIN required
    4314              :                for each since start index is zero.  */
    4315            0 :             prologue_stmts += num_vectors;
    4316              : 
    4317              :             /* If we have a non-zero partial load bias, we need one PLUS
    4318              :                to adjust the load length.  */
    4319            0 :             if (partial_load_store_bias != 0)
    4320            0 :               body_stmts += 1;
    4321              : 
    4322            0 :             unsigned int length_update_cost = 0;
    4323            0 :             if (LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo))
    4324              :               /* For decrement IV style, Each only need a single SELECT_VL
    4325              :                  or MIN since beginning to calculate the number of elements
    4326              :                  need to be processed in current iteration.  */
    4327              :               length_update_cost = 1;
    4328              :             else
    4329              :               /* For increment IV stype, Each may need two MINs and one MINUS to
    4330              :                  update lengths in body for next iteration.  */
    4331            0 :               length_update_cost = 3;
    4332              : 
    4333            0 :             if (need_iterate_p)
    4334            0 :               body_stmts += length_update_cost * num_vectors;
    4335              :           }
    4336              : 
    4337            0 :       (void) add_stmt_cost (target_cost_data, prologue_stmts,
    4338              :                             scalar_stmt, vect_prologue);
    4339            0 :       (void) add_stmt_cost (target_cost_data, body_stmts,
    4340              :                             scalar_stmt, vect_body);
    4341              :     }
    4342              : 
    4343              :   /* FORNOW: The scalar outside cost is incremented in one of the
    4344              :      following ways:
    4345              : 
    4346              :      1. The vectorizer checks for alignment and aliasing and generates
    4347              :      a condition that allows dynamic vectorization.  A cost model
    4348              :      check is ANDED with the versioning condition.  Hence scalar code
    4349              :      path now has the added cost of the versioning check.
    4350              : 
    4351              :        if (cost > th & versioning_check)
    4352              :          jmp to vector code
    4353              : 
    4354              :      Hence run-time scalar is incremented by not-taken branch cost.
    4355              : 
    4356              :      2. The vectorizer then checks if a prologue is required.  If the
    4357              :      cost model check was not done before during versioning, it has to
    4358              :      be done before the prologue check.
    4359              : 
    4360              :        if (cost <= th)
    4361              :          prologue = scalar_iters
    4362              :        if (prologue == 0)
    4363              :          jmp to vector code
    4364              :        else
    4365              :          execute prologue
    4366              :        if (prologue == num_iters)
    4367              :          go to exit
    4368              : 
    4369              :      Hence the run-time scalar cost is incremented by a taken branch,
    4370              :      plus a not-taken branch, plus a taken branch cost.
    4371              : 
    4372              :      3. The vectorizer then checks if an epilogue is required.  If the
    4373              :      cost model check was not done before during prologue check, it
    4374              :      has to be done with the epilogue check.
    4375              : 
    4376              :        if (prologue == 0)
    4377              :          jmp to vector code
    4378              :        else
    4379              :          execute prologue
    4380              :        if (prologue == num_iters)
    4381              :          go to exit
    4382              :        vector code:
    4383              :          if ((cost <= th) | (scalar_iters-prologue-epilogue == 0))
    4384              :            jmp to epilogue
    4385              : 
    4386              :      Hence the run-time scalar cost should be incremented by 2 taken
    4387              :      branches.
    4388              : 
    4389              :      TODO: The back end may reorder the BBS's differently and reverse
    4390              :      conditions/branch directions.  Change the estimates below to
    4391              :      something more reasonable.  */
    4392              : 
    4393              :   /* If the number of iterations is known and we do not do versioning, we can
    4394              :      decide whether to vectorize at compile time.  Hence the scalar version
    4395              :      do not carry cost model guard costs.  */
    4396        59354 :   if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    4397       185394 :       || LOOP_REQUIRES_VERSIONING (loop_vinfo))
    4398              :     {
    4399              :       /* Cost model check occurs at versioning.  */
    4400        67804 :       if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
    4401         7988 :         scalar_outside_cost += vect_get_stmt_cost (cond_branch_not_taken);
    4402              :       else
    4403              :         {
    4404              :           /* Cost model check occurs at prologue generation.  */
    4405        59816 :           if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
    4406          155 :             scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken)
    4407          155 :               + vect_get_stmt_cost (cond_branch_not_taken);
    4408              :           /* Cost model check occurs at epilogue generation.  */
    4409              :           else
    4410        59661 :             scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken);
    4411              :         }
    4412              :     }
    4413              : 
    4414              :   /* Complete the target-specific cost calculations.  */
    4415       126040 :   loop_vinfo->vector_costs->finish_cost (loop_vinfo->scalar_costs);
    4416       126040 :   vec_prologue_cost = loop_vinfo->vector_costs->prologue_cost ();
    4417       126040 :   vec_inside_cost = loop_vinfo->vector_costs->body_cost ();
    4418       126040 :   vec_epilogue_cost = loop_vinfo->vector_costs->epilogue_cost ();
    4419       126040 :   if (suggested_unroll_factor)
    4420       125650 :     *suggested_unroll_factor
    4421       125650 :       = loop_vinfo->vector_costs->suggested_unroll_factor ();
    4422              : 
    4423       125650 :   if (suggested_unroll_factor && *suggested_unroll_factor > 1
    4424          419 :       && LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo) != MAX_VECTORIZATION_FACTOR
    4425            0 :       && !known_le (LOOP_VINFO_VECT_FACTOR (loop_vinfo) *
    4426              :                     *suggested_unroll_factor,
    4427              :                     LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo)))
    4428              :     {
    4429            0 :       if (dump_enabled_p ())
    4430            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    4431              :                          "can't unroll as unrolled vectorization factor larger"
    4432              :                          " than maximum vectorization factor: "
    4433              :                          HOST_WIDE_INT_PRINT_UNSIGNED "\n",
    4434              :                          LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo));
    4435            0 :       *suggested_unroll_factor = 1;
    4436              :     }
    4437              : 
    4438       126040 :   vec_outside_cost = (int)(vec_prologue_cost + vec_epilogue_cost);
    4439              : 
    4440       126040 :   if (dump_enabled_p ())
    4441              :     {
    4442         1121 :       dump_printf_loc (MSG_NOTE, vect_location, "Cost model analysis: \n");
    4443         1121 :       dump_printf (MSG_NOTE, "  Vector inside of loop cost: %d\n",
    4444              :                    vec_inside_cost);
    4445         1121 :       dump_printf (MSG_NOTE, "  Vector prologue cost: %d\n",
    4446              :                    vec_prologue_cost);
    4447         1121 :       dump_printf (MSG_NOTE, "  Vector epilogue cost: %d\n",
    4448              :                    vec_epilogue_cost);
    4449         1121 :       dump_printf (MSG_NOTE, "  Scalar iteration cost: %d\n",
    4450              :                    scalar_single_iter_cost);
    4451         1121 :       dump_printf (MSG_NOTE, "  Scalar outside cost: %d\n",
    4452              :                    scalar_outside_cost);
    4453         1121 :       dump_printf (MSG_NOTE, "  Vector outside cost: %d\n",
    4454              :                    vec_outside_cost);
    4455         1121 :       dump_printf (MSG_NOTE, "  prologue iterations: %d\n",
    4456              :                    peel_iters_prologue);
    4457         1121 :       dump_printf (MSG_NOTE, "  epilogue iterations: %d\n",
    4458              :                    peel_iters_epilogue);
    4459              :     }
    4460              : 
    4461              :   /* Calculate number of iterations required to make the vector version
    4462              :      profitable, relative to the loop bodies only.  The following condition
    4463              :      must hold true:
    4464              :      SIC * niters + SOC > VIC * ((niters - NPEEL) / VF) + VOC
    4465              :      where
    4466              :      SIC = scalar iteration cost, VIC = vector iteration cost,
    4467              :      VOC = vector outside cost, VF = vectorization factor,
    4468              :      NPEEL = prologue iterations + epilogue iterations,
    4469              :      SOC = scalar outside cost for run time cost model check.  */
    4470              : 
    4471       126040 :   int saving_per_viter = (scalar_single_iter_cost * assumed_vf
    4472       126040 :                           - vec_inside_cost);
    4473       126040 :   if (saving_per_viter <= 0)
    4474              :     {
    4475        24332 :       if (LOOP_VINFO_LOOP (loop_vinfo)->force_vectorize)
    4476            0 :         warning_at (vect_location.get_location_t (), OPT_Wopenmp_simd,
    4477              :                     "vectorization did not happen for a simd loop");
    4478              : 
    4479        24332 :       if (dump_enabled_p ())
    4480           30 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    4481              :                          "cost model: the vector iteration cost = %d "
    4482              :                          "divided by the scalar iteration cost = %d "
    4483              :                          "is greater or equal to the vectorization factor = %d"
    4484              :                          ".\n",
    4485              :                          vec_inside_cost, scalar_single_iter_cost, assumed_vf);
    4486        24332 :       *ret_min_profitable_niters = -1;
    4487        24332 :       *ret_min_profitable_estimate = -1;
    4488        24332 :       return;
    4489              :     }
    4490              : 
    4491              :   /* ??? The "if" arm is written to handle all cases; see below for what
    4492              :      we would do for !LOOP_VINFO_USING_PARTIAL_VECTORS_P.  */
    4493       101708 :   if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    4494              :     {
    4495              :       /* Rewriting the condition above in terms of the number of
    4496              :          vector iterations (vniters) rather than the number of
    4497              :          scalar iterations (niters) gives:
    4498              : 
    4499              :          SIC * (vniters * VF + NPEEL) + SOC > VIC * vniters + VOC
    4500              : 
    4501              :          <==> vniters * (SIC * VF - VIC) > VOC - SIC * NPEEL - SOC
    4502              : 
    4503              :          For integer N, X and Y when X > 0:
    4504              : 
    4505              :          N * X > Y <==> N >= (Y /[floor] X) + 1.  */
    4506           21 :       int outside_overhead = (vec_outside_cost
    4507           21 :                               - scalar_single_iter_cost * peel_iters_prologue
    4508           21 :                               - scalar_single_iter_cost * peel_iters_epilogue
    4509              :                               - scalar_outside_cost);
    4510              :       /* We're only interested in cases that require at least one
    4511              :          vector iteration.  */
    4512           21 :       int min_vec_niters = 1;
    4513           21 :       if (outside_overhead > 0)
    4514           16 :         min_vec_niters = outside_overhead / saving_per_viter + 1;
    4515              : 
    4516           21 :       if (dump_enabled_p ())
    4517            8 :         dump_printf (MSG_NOTE, "  Minimum number of vector iterations: %d\n",
    4518              :                      min_vec_niters);
    4519              : 
    4520           21 :       if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    4521              :         {
    4522              :           /* Now that we know the minimum number of vector iterations,
    4523              :              find the minimum niters for which the scalar cost is larger:
    4524              : 
    4525              :              SIC * niters > VIC * vniters + VOC - SOC
    4526              : 
    4527              :              We know that the minimum niters is no more than
    4528              :              vniters * VF + NPEEL, but it might be (and often is) less
    4529              :              than that if a partial vector iteration is cheaper than the
    4530              :              equivalent scalar code.  */
    4531           21 :           int threshold = (vec_inside_cost * min_vec_niters
    4532           21 :                            + vec_outside_cost
    4533           21 :                            - scalar_outside_cost);
    4534           21 :           if (threshold <= 0)
    4535              :             min_profitable_iters = 1;
    4536              :           else
    4537           21 :             min_profitable_iters = threshold / scalar_single_iter_cost + 1;
    4538              :         }
    4539              :       else
    4540              :         /* Convert the number of vector iterations into a number of
    4541              :            scalar iterations.  */
    4542            0 :         min_profitable_iters = (min_vec_niters * assumed_vf
    4543            0 :                                 + peel_iters_prologue
    4544              :                                 + peel_iters_epilogue);
    4545              :     }
    4546              :   else
    4547              :     {
    4548       101687 :       min_profitable_iters = ((vec_outside_cost - scalar_outside_cost)
    4549       101687 :                               * assumed_vf
    4550       101687 :                               - vec_inside_cost * peel_iters_prologue
    4551       101687 :                               - vec_inside_cost * peel_iters_epilogue);
    4552       101687 :       if (min_profitable_iters <= 0)
    4553              :         min_profitable_iters = 0;
    4554              :       else
    4555              :         {
    4556        86413 :           min_profitable_iters /= saving_per_viter;
    4557              : 
    4558        86413 :           if ((scalar_single_iter_cost * assumed_vf * min_profitable_iters)
    4559        86413 :               <= (((int) vec_inside_cost * min_profitable_iters)
    4560        86413 :                   + (((int) vec_outside_cost - scalar_outside_cost)
    4561              :                      * assumed_vf)))
    4562        86413 :             min_profitable_iters++;
    4563              :         }
    4564              :     }
    4565              : 
    4566       101708 :   if (dump_enabled_p ())
    4567         1091 :     dump_printf (MSG_NOTE,
    4568              :                  "  Calculated minimum iters for profitability: %d\n",
    4569              :                  min_profitable_iters);
    4570              : 
    4571       101708 :   if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    4572       101687 :       && min_profitable_iters < (assumed_vf + peel_iters_prologue))
    4573              :     /* We want the vectorized loop to execute at least once.  */
    4574              :     min_profitable_iters = assumed_vf + peel_iters_prologue;
    4575        22240 :   else if (min_profitable_iters < peel_iters_prologue)
    4576              :     /* For LOOP_VINFO_USING_PARTIAL_VECTORS_P, we need to ensure the
    4577              :        vectorized loop executes at least once.  */
    4578              :     min_profitable_iters = peel_iters_prologue;
    4579              : 
    4580       101708 :   if (dump_enabled_p ())
    4581         1091 :     dump_printf_loc (MSG_NOTE, vect_location,
    4582              :                      "  Runtime profitability threshold = %d\n",
    4583              :                      min_profitable_iters);
    4584              : 
    4585       101708 :   *ret_min_profitable_niters = min_profitable_iters;
    4586              : 
    4587              :   /* Calculate number of iterations required to make the vector version
    4588              :      profitable, relative to the loop bodies only.
    4589              : 
    4590              :      Non-vectorized variant is SIC * niters and it must win over vector
    4591              :      variant on the expected loop trip count.  The following condition must hold true:
    4592              :      SIC * niters > VIC * ((niters - NPEEL) / VF) + VOC + SOC  */
    4593              : 
    4594       101708 :   if (vec_outside_cost <= 0)
    4595              :     min_profitable_estimate = 0;
    4596              :   /* ??? This "else if" arm is written to handle all cases; see below for
    4597              :      what we would do for !LOOP_VINFO_USING_PARTIAL_VECTORS_P.  */
    4598        90935 :   else if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    4599              :     {
    4600              :       /* This is a repeat of the code above, but with + SOC rather
    4601              :          than - SOC.  */
    4602           21 :       int outside_overhead = (vec_outside_cost
    4603           21 :                               - scalar_single_iter_cost * peel_iters_prologue
    4604           21 :                               - scalar_single_iter_cost * peel_iters_epilogue
    4605              :                               + scalar_outside_cost);
    4606           21 :       int min_vec_niters = 1;
    4607           21 :       if (outside_overhead > 0)
    4608           21 :         min_vec_niters = outside_overhead / saving_per_viter + 1;
    4609              : 
    4610           21 :       if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    4611              :         {
    4612           21 :           int threshold = (vec_inside_cost * min_vec_niters
    4613           21 :                            + vec_outside_cost
    4614           21 :                            + scalar_outside_cost);
    4615           21 :           min_profitable_estimate = threshold / scalar_single_iter_cost + 1;
    4616              :         }
    4617              :       else
    4618              :         min_profitable_estimate = (min_vec_niters * assumed_vf
    4619              :                                    + peel_iters_prologue
    4620              :                                    + peel_iters_epilogue);
    4621              :     }
    4622              :   else
    4623              :     {
    4624        90914 :       min_profitable_estimate = ((vec_outside_cost + scalar_outside_cost)
    4625        90914 :                                  * assumed_vf
    4626        90914 :                                  - vec_inside_cost * peel_iters_prologue
    4627        90914 :                                  - vec_inside_cost * peel_iters_epilogue)
    4628        90914 :                                  / ((scalar_single_iter_cost * assumed_vf)
    4629              :                                    - vec_inside_cost);
    4630              :     }
    4631       101708 :   min_profitable_estimate = MAX (min_profitable_estimate, min_profitable_iters);
    4632       101708 :   if (dump_enabled_p ())
    4633         1091 :     dump_printf_loc (MSG_NOTE, vect_location,
    4634              :                      "  Static estimate profitability threshold = %d\n",
    4635              :                      min_profitable_estimate);
    4636              : 
    4637       101708 :   *ret_min_profitable_estimate = min_profitable_estimate;
    4638              : }
    4639              : 
    4640              : /* Writes into SEL a mask for a vec_perm, equivalent to a vec_shr by OFFSET
    4641              :    vector elements (not bits) for a vector with NELT elements.  */
    4642              : static void
    4643         2291 : calc_vec_perm_mask_for_shift (unsigned int offset, unsigned int nelt,
    4644              :                               vec_perm_builder *sel)
    4645              : {
    4646              :   /* The encoding is a single stepped pattern.  Any wrap-around is handled
    4647              :      by vec_perm_indices.  */
    4648         2291 :   sel->new_vector (nelt, 1, 3);
    4649         9164 :   for (unsigned int i = 0; i < 3; i++)
    4650         6873 :     sel->quick_push (i + offset);
    4651         2291 : }
    4652              : 
    4653              : /* Checks whether the target supports whole-vector shifts for vectors of mode
    4654              :    MODE.  This is the case if _either_ the platform handles vec_shr_optab, _or_
    4655              :    it supports vec_perm_const with masks for all necessary shift amounts.  */
    4656              : static bool
    4657        13895 : have_whole_vector_shift (machine_mode mode)
    4658              : {
    4659        13895 :   if (can_implement_p (vec_shr_optab, mode))
    4660              :     return true;
    4661              : 
    4662              :   /* Variable-length vectors should be handled via the optab.  */
    4663           63 :   unsigned int nelt;
    4664          126 :   if (!GET_MODE_NUNITS (mode).is_constant (&nelt))
    4665              :     return false;
    4666              : 
    4667           63 :   vec_perm_builder sel;
    4668           63 :   vec_perm_indices indices;
    4669          315 :   for (unsigned int i = nelt / 2; i >= 1; i /= 2)
    4670              :     {
    4671          252 :       calc_vec_perm_mask_for_shift (i, nelt, &sel);
    4672          252 :       indices.new_vector (sel, 2, nelt);
    4673          252 :       if (!can_vec_perm_const_p (mode, mode, indices, false))
    4674              :         return false;
    4675              :     }
    4676              :   return true;
    4677           63 : }
    4678              : 
    4679              : /* Return true if (a) STMT_INFO is a DOT_PROD_EXPR reduction whose
    4680              :    multiplication operands have differing signs and (b) we intend
    4681              :    to emulate the operation using a series of signed DOT_PROD_EXPRs.
    4682              :    See vect_emulate_mixed_dot_prod for the actual sequence used.  */
    4683              : 
    4684              : static bool
    4685         2512 : vect_is_emulated_mixed_dot_prod (slp_tree slp_node)
    4686              : {
    4687         2512 :   stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (slp_node);
    4688         2512 :   gassign *assign = dyn_cast<gassign *> (stmt_info->stmt);
    4689         2059 :   if (!assign || gimple_assign_rhs_code (assign) != DOT_PROD_EXPR)
    4690              :     return false;
    4691              : 
    4692          856 :   tree rhs1 = gimple_assign_rhs1 (assign);
    4693          856 :   tree rhs2 = gimple_assign_rhs2 (assign);
    4694          856 :   if (TYPE_SIGN (TREE_TYPE (rhs1)) == TYPE_SIGN (TREE_TYPE (rhs2)))
    4695              :     return false;
    4696              : 
    4697          645 :   return !directly_supported_p (DOT_PROD_EXPR,
    4698              :                                 SLP_TREE_VECTYPE (slp_node),
    4699          215 :                                 SLP_TREE_VECTYPE
    4700              :                                   (SLP_TREE_CHILDREN (slp_node)[0]),
    4701          215 :                                 optab_vector_mixed_sign);
    4702              : }
    4703              : 
    4704              : /* TODO: Close dependency between vect_model_*_cost and vectorizable_*
    4705              :    functions. Design better to avoid maintenance issues.  */
    4706              : 
    4707              : /* Function vect_model_reduction_cost.
    4708              : 
    4709              :    Models cost for a reduction operation, including the vector ops
    4710              :    generated within the strip-mine loop in some cases, the initial
    4711              :    definition before the loop, and the epilogue code that must be generated.  */
    4712              : 
    4713              : static void
    4714        72729 : vect_model_reduction_cost (loop_vec_info loop_vinfo,
    4715              :                            slp_tree node, internal_fn reduc_fn,
    4716              :                            vect_reduction_type reduction_type,
    4717              :                            int ncopies, stmt_vector_for_cost *cost_vec)
    4718              : {
    4719        72729 :   int prologue_cost = 0, epilogue_cost = 0, inside_cost = 0;
    4720        72729 :   tree vectype;
    4721        72729 :   machine_mode mode;
    4722        72729 :   class loop *loop = NULL;
    4723              : 
    4724        72729 :   if (loop_vinfo)
    4725        72729 :     loop = LOOP_VINFO_LOOP (loop_vinfo);
    4726              : 
    4727              :   /* Condition reductions generate two reductions in the loop.  */
    4728        72729 :   if (reduction_type == COND_REDUCTION)
    4729          333 :     ncopies *= 2;
    4730              : 
    4731        72729 :   vectype = SLP_TREE_VECTYPE (node);
    4732        72729 :   mode = TYPE_MODE (vectype);
    4733        72729 :   stmt_vec_info orig_stmt_info
    4734        72729 :     = vect_orig_stmt (SLP_TREE_REPRESENTATIVE (node));
    4735              : 
    4736        72729 :   gimple_match_op op;
    4737        72729 :   if (!gimple_extract_op (orig_stmt_info->stmt, &op))
    4738            0 :     gcc_unreachable ();
    4739              : 
    4740        72729 :   if (reduction_type == EXTRACT_LAST_REDUCTION)
    4741              :     /* No extra instructions are needed in the prologue.  The loop body
    4742              :        operations are costed in vectorizable_condition.  */
    4743              :     inside_cost = 0;
    4744        72729 :   else if (reduction_type == FOLD_LEFT_REDUCTION)
    4745              :     {
    4746              :       /* No extra instructions needed in the prologue.  */
    4747         4381 :       prologue_cost = 0;
    4748              : 
    4749         4381 :       if (reduc_fn != IFN_LAST)
    4750              :         /* Count one reduction-like operation per vector.  */
    4751            0 :         inside_cost = record_stmt_cost (cost_vec, ncopies, vec_to_scalar,
    4752              :                                         node, 0, vect_body);
    4753              :       else
    4754              :         {
    4755              :           /* Use NCOPIES deconstructs and NELEMENTS scalar ops.  */
    4756         4381 :           unsigned int nelements = ncopies * vect_nunits_for_cost (vectype);
    4757         4381 :           inside_cost = record_stmt_cost (cost_vec, ncopies,
    4758              :                                           vec_deconstruct, node, 0,
    4759              :                                           vect_body);
    4760         4381 :           inside_cost += record_stmt_cost (cost_vec, nelements,
    4761              :                                            scalar_stmt, node, 0,
    4762              :                                            vect_body);
    4763              :         }
    4764              :     }
    4765              :   else
    4766              :     {
    4767              :       /* Add in the cost of the initial definitions.  */
    4768        68348 :       int prologue_stmts;
    4769        68348 :       if (reduction_type == COND_REDUCTION)
    4770              :         /* For cond reductions we have four vectors: initial index, step,
    4771              :            initial result of the data reduction, initial value of the index
    4772              :            reduction.  */
    4773              :         prologue_stmts = 4;
    4774              :       else
    4775              :         /* We need the initial reduction value.  */
    4776        68015 :         prologue_stmts = 1;
    4777        68348 :       prologue_cost += record_stmt_cost (cost_vec, prologue_stmts,
    4778              :                                          scalar_to_vec, node, 0,
    4779              :                                          vect_prologue);
    4780              :     }
    4781              : 
    4782              :   /* Determine cost of epilogue code.
    4783              : 
    4784              :      We have a reduction operator that will reduce the vector in one statement.
    4785              :      Also requires scalar extract.  */
    4786              : 
    4787        72729 :   if (!loop || !nested_in_vect_loop_p (loop, orig_stmt_info))
    4788              :     {
    4789        72545 :       if (reduc_fn != IFN_LAST)
    4790              :         {
    4791        52659 :           if (reduction_type == COND_REDUCTION)
    4792              :             {
    4793              :               /* An EQ stmt and an COND_EXPR stmt.  */
    4794           18 :               epilogue_cost += record_stmt_cost (cost_vec, 2,
    4795              :                                                  vector_stmt, node, 0,
    4796              :                                                  vect_epilogue);
    4797              :               /* Reduction of the max index and a reduction of the found
    4798              :                  values.  */
    4799           18 :               epilogue_cost += record_stmt_cost (cost_vec, 2,
    4800              :                                                  vec_to_scalar, node, 0,
    4801              :                                                  vect_epilogue);
    4802              :               /* A broadcast of the max value.  */
    4803           18 :               epilogue_cost += record_stmt_cost (cost_vec, 1,
    4804              :                                                  scalar_to_vec, node, 0,
    4805              :                                                  vect_epilogue);
    4806              :             }
    4807              :           else
    4808              :             {
    4809        52641 :               epilogue_cost += record_stmt_cost (cost_vec, 1, vector_stmt,
    4810              :                                                  node, 0, vect_epilogue);
    4811        52641 :               epilogue_cost += record_stmt_cost (cost_vec, 1,
    4812              :                                                  vec_to_scalar, node, 0,
    4813              :                                                  vect_epilogue);
    4814              :             }
    4815              :         }
    4816        19886 :       else if (reduction_type == COND_REDUCTION)
    4817              :         {
    4818          315 :           unsigned estimated_nunits = vect_nunits_for_cost (vectype);
    4819              :           /* Extraction of scalar elements.  */
    4820          315 :           epilogue_cost += record_stmt_cost (cost_vec, 2,
    4821              :                                              vec_deconstruct, node, 0,
    4822              :                                              vect_epilogue);
    4823              :           /* Scalar max reductions via COND_EXPR / MAX_EXPR.  */
    4824          315 :           epilogue_cost += record_stmt_cost (cost_vec,
    4825          315 :                                              2 * estimated_nunits - 3,
    4826              :                                              scalar_stmt, node, 0,
    4827              :                                              vect_epilogue);
    4828              :         }
    4829        19571 :       else if (reduction_type == EXTRACT_LAST_REDUCTION
    4830        19571 :                || reduction_type == FOLD_LEFT_REDUCTION)
    4831              :         /* No extra instructions need in the epilogue.  */
    4832              :         ;
    4833              :       else
    4834              :         {
    4835        15190 :           int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
    4836        15190 :           tree bitsize = TYPE_SIZE (op.type);
    4837        15190 :           int element_bitsize = tree_to_uhwi (bitsize);
    4838        15190 :           int nelements = vec_size_in_bits / element_bitsize;
    4839              : 
    4840        15190 :           if (op.code == COND_EXPR)
    4841           31 :             op.code = MAX_EXPR;
    4842              : 
    4843              :           /* We have a whole vector shift available.  */
    4844         3154 :           if (VECTOR_MODE_P (mode)
    4845        15190 :               && directly_supported_p (op.code, vectype)
    4846        27101 :               && have_whole_vector_shift (mode))
    4847              :             {
    4848              :               /* Final reduction via vector shifts and the reduction operator.
    4849              :                  Also requires scalar extract.  */
    4850        35733 :               epilogue_cost += record_stmt_cost (cost_vec,
    4851        23822 :                                                  exact_log2 (nelements) * 2,
    4852              :                                                  vector_stmt, node, 0,
    4853              :                                                  vect_epilogue);
    4854        11911 :               epilogue_cost += record_stmt_cost (cost_vec, 1,
    4855              :                                                  vec_to_scalar, node, 0,
    4856              :                                                  vect_epilogue);
    4857              :             }
    4858              :           else
    4859              :             /* Use extracts and reduction op for final reduction.  For N
    4860              :                elements, we have N extracts and N-1 reduction ops.  */
    4861         3279 :             epilogue_cost += record_stmt_cost (cost_vec,
    4862         3279 :                                                nelements + nelements - 1,
    4863              :                                                vector_stmt, node, 0,
    4864              :                                                vect_epilogue);
    4865              :         }
    4866              :     }
    4867              : 
    4868        72729 :   if (dump_enabled_p ())
    4869         3035 :     dump_printf (MSG_NOTE,
    4870              :                  "vect_model_reduction_cost: inside_cost = %d, "
    4871              :                  "prologue_cost = %d, epilogue_cost = %d .\n", inside_cost,
    4872              :                  prologue_cost, epilogue_cost);
    4873        72729 : }
    4874              : 
    4875              : /* SEQ is a sequence of instructions that initialize the reduction
    4876              :    described by REDUC_INFO.  Emit them in the appropriate place.  */
    4877              : 
    4878              : static void
    4879          465 : vect_emit_reduction_init_stmts (loop_vec_info loop_vinfo,
    4880              :                                 vect_reduc_info reduc_info, gimple *seq)
    4881              : {
    4882          465 :   if (VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info))
    4883              :     {
    4884              :       /* When reusing an accumulator from the main loop, we only need
    4885              :          initialization instructions if the main loop can be skipped.
    4886              :          In that case, emit the initialization instructions at the end
    4887              :          of the guard block that does the skip.  */
    4888           18 :       edge skip_edge = loop_vinfo->skip_main_loop_edge;
    4889           18 :       gcc_assert (skip_edge);
    4890           18 :       gimple_stmt_iterator gsi = gsi_last_bb (skip_edge->src);
    4891           18 :       gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
    4892              :     }
    4893              :   else
    4894              :     {
    4895              :       /* The normal case: emit the initialization instructions on the
    4896              :          preheader edge.  */
    4897          447 :       class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    4898          447 :       gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), seq);
    4899              :     }
    4900          465 : }
    4901              : 
    4902              : /* Get at the initial defs for the reduction PHIs for REDUC_INFO,
    4903              :    which performs a reduction involving GROUP_SIZE scalar statements.
    4904              :    NUMBER_OF_VECTORS is the number of vector defs to create.  If NEUTRAL_OP
    4905              :    is nonnull, introducing extra elements of that value will not change the
    4906              :    result.  */
    4907              : 
    4908              : static void
    4909        21869 : get_initial_defs_for_reduction (loop_vec_info loop_vinfo,
    4910              :                                 vect_reduc_info reduc_info,
    4911              :                                 tree vector_type,
    4912              :                                 vec<tree> *vec_oprnds,
    4913              :                                 unsigned int number_of_vectors,
    4914              :                                 unsigned int group_size, tree neutral_op)
    4915              : {
    4916        21869 :   vec<tree> &initial_values = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info);
    4917        21869 :   unsigned HOST_WIDE_INT nunits;
    4918        21869 :   unsigned j, number_of_places_left_in_vector;
    4919        21869 :   unsigned int i;
    4920              : 
    4921        43738 :   gcc_assert (group_size == initial_values.length () || neutral_op);
    4922              : 
    4923              :   /* NUMBER_OF_COPIES is the number of times we need to use the same values in
    4924              :      created vectors. It is greater than 1 if unrolling is performed.
    4925              : 
    4926              :      For example, we have two scalar operands, s1 and s2 (e.g., group of
    4927              :      strided accesses of size two), while NUNITS is four (i.e., four scalars
    4928              :      of this type can be packed in a vector).  The output vector will contain
    4929              :      two copies of each scalar operand: {s1, s2, s1, s2}.  (NUMBER_OF_COPIES
    4930              :      will be 2).
    4931              : 
    4932              :      If GROUP_SIZE > NUNITS, the scalars will be split into several
    4933              :      vectors containing the operands.
    4934              : 
    4935              :      For example, NUNITS is four as before, and the group size is 8
    4936              :      (s1, s2, ..., s8).  We will create two vectors {s1, s2, s3, s4} and
    4937              :      {s5, s6, s7, s8}.  */
    4938              : 
    4939        21869 :   if (!TYPE_VECTOR_SUBPARTS (vector_type).is_constant (&nunits))
    4940              :     nunits = group_size;
    4941              : 
    4942        21869 :   tree vector_elt_type = TREE_TYPE (vector_type);
    4943        21869 :   number_of_places_left_in_vector = nunits;
    4944        21869 :   bool constant_p = true;
    4945        21869 :   tree_vector_builder elts (vector_type, nunits, 1);
    4946        21869 :   elts.quick_grow (nunits);
    4947        21869 :   gimple_seq ctor_seq = NULL;
    4948        21869 :   if (neutral_op
    4949        43146 :       && !useless_type_conversion_p (vector_elt_type,
    4950        21277 :                                      TREE_TYPE (neutral_op)))
    4951              :     {
    4952          244 :       if (VECTOR_BOOLEAN_TYPE_P (vector_type))
    4953          223 :         neutral_op = gimple_build (&ctor_seq, COND_EXPR,
    4954              :                                    vector_elt_type,
    4955              :                                    neutral_op,
    4956              :                                    build_all_ones_cst (vector_elt_type),
    4957              :                                    build_zero_cst (vector_elt_type));
    4958              :       else
    4959           21 :         neutral_op = gimple_convert (&ctor_seq, vector_elt_type, neutral_op);
    4960              :     }
    4961       204561 :   for (j = 0; j < nunits * number_of_vectors; ++j)
    4962              :     {
    4963       182692 :       tree op;
    4964       182692 :       i = j % group_size;
    4965              : 
    4966              :       /* Get the def before the loop.  In reduction chain we have only
    4967              :          one initial value.  Else we have as many as PHIs in the group.  */
    4968       182692 :       if (i >= initial_values.length () || (j > i && neutral_op))
    4969              :         op = neutral_op;
    4970              :       else
    4971              :         {
    4972        51610 :           if (!useless_type_conversion_p (vector_elt_type,
    4973        25805 :                                           TREE_TYPE (initial_values[i])))
    4974              :             {
    4975          259 :               if (VECTOR_BOOLEAN_TYPE_P (vector_type))
    4976          470 :                 initial_values[i] = gimple_build (&ctor_seq, COND_EXPR,
    4977              :                                                   vector_elt_type,
    4978          235 :                                                   initial_values[i],
    4979              :                                                   build_all_ones_cst
    4980              :                                                     (vector_elt_type),
    4981              :                                                   build_zero_cst
    4982              :                                                     (vector_elt_type));
    4983              :               else
    4984           48 :                 initial_values[i] = gimple_convert (&ctor_seq,
    4985              :                                                     vector_elt_type,
    4986           24 :                                                     initial_values[i]);
    4987              :             }
    4988        25805 :           op = initial_values[i];
    4989              :         }
    4990              : 
    4991              :       /* Create 'vect_ = {op0,op1,...,opn}'.  */
    4992       182692 :       number_of_places_left_in_vector--;
    4993       182692 :       elts[nunits - number_of_places_left_in_vector - 1] = op;
    4994       182692 :       if (!CONSTANT_CLASS_P (op))
    4995         2507 :         constant_p = false;
    4996              : 
    4997       182692 :       if (number_of_places_left_in_vector == 0)
    4998              :         {
    4999        23450 :           tree init;
    5000        46900 :           if (constant_p && !neutral_op
    5001        46611 :               ? multiple_p (TYPE_VECTOR_SUBPARTS (vector_type), nunits)
    5002        23450 :               : known_eq (TYPE_VECTOR_SUBPARTS (vector_type), nunits))
    5003              :             /* Build the vector directly from ELTS.  */
    5004        23450 :             init = gimple_build_vector (&ctor_seq, &elts);
    5005            0 :           else if (neutral_op)
    5006              :             {
    5007              :               /* Build a vector of the neutral value and shift the
    5008              :                  other elements into place.  */
    5009            0 :               init = gimple_build_vector_from_val (&ctor_seq, vector_type,
    5010              :                                                    neutral_op);
    5011            0 :               int k = nunits;
    5012            0 :               while (k > 0 && operand_equal_p (elts[k - 1], neutral_op))
    5013            0 :                 k -= 1;
    5014            0 :               while (k > 0)
    5015              :                 {
    5016            0 :                   k -= 1;
    5017            0 :                   init = gimple_build (&ctor_seq, CFN_VEC_SHL_INSERT,
    5018            0 :                                        vector_type, init, elts[k]);
    5019              :                 }
    5020              :             }
    5021              :           else
    5022              :             {
    5023              :               /* First time round, duplicate ELTS to fill the
    5024              :                  required number of vectors.  */
    5025            0 :               duplicate_and_interleave (loop_vinfo, &ctor_seq, vector_type,
    5026              :                                         elts, number_of_vectors, *vec_oprnds);
    5027            0 :               break;
    5028              :             }
    5029        23450 :           vec_oprnds->quick_push (init);
    5030              : 
    5031        23450 :           number_of_places_left_in_vector = nunits;
    5032        23450 :           elts.new_vector (vector_type, nunits, 1);
    5033        23450 :           elts.quick_grow (nunits);
    5034        23450 :           constant_p = true;
    5035              :         }
    5036              :     }
    5037        21869 :   if (ctor_seq != NULL)
    5038          465 :     vect_emit_reduction_init_stmts (loop_vinfo, reduc_info, ctor_seq);
    5039        21869 : }
    5040              : 
    5041              : vect_reduc_info
    5042       218856 : info_for_reduction (loop_vec_info loop_vinfo, slp_tree node)
    5043              : {
    5044       218856 :   if (node->cycle_info.id == -1)
    5045              :     return NULL;
    5046       214106 :   return loop_vinfo->reduc_infos[node->cycle_info.id];
    5047              : }
    5048              : 
    5049              : /* See if LOOP_VINFO is an epilogue loop whose main loop had a reduction that
    5050              :    REDUC_INFO can build on.  Adjust REDUC_INFO and return true if so, otherwise
    5051              :    return false.  */
    5052              : 
    5053              : static bool
    5054        21510 : vect_find_reusable_accumulator (loop_vec_info loop_vinfo,
    5055              :                                 vect_reduc_info reduc_info, tree vectype)
    5056              : {
    5057        21510 :   loop_vec_info main_loop_vinfo = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
    5058        21510 :   if (!main_loop_vinfo)
    5059              :     return false;
    5060              : 
    5061         4678 :   if (VECT_REDUC_INFO_TYPE (reduc_info) != TREE_CODE_REDUCTION)
    5062              :     return false;
    5063              : 
    5064              :   /* We are not set up to handle vector bools when they are not mapped
    5065              :      to vector integer data types.  */
    5066         4663 :   if (VECTOR_BOOLEAN_TYPE_P (vectype)
    5067         4735 :       && GET_MODE_CLASS (TYPE_MODE (vectype)) != MODE_VECTOR_INT)
    5068              :     return false;
    5069              : 
    5070         4661 :   unsigned int num_phis = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info).length ();
    5071         4661 :   auto_vec<tree, 16> main_loop_results (num_phis);
    5072         4661 :   auto_vec<tree, 16> initial_values (num_phis);
    5073         4661 :   if (edge main_loop_edge = loop_vinfo->main_loop_edge)
    5074              :     {
    5075              :       /* The epilogue loop can be entered either from the main loop or
    5076              :          from an earlier guard block.  */
    5077         4438 :       edge skip_edge = loop_vinfo->skip_main_loop_edge;
    5078        17772 :       for (tree incoming_value : VECT_REDUC_INFO_INITIAL_VALUES (reduc_info))
    5079              :         {
    5080              :           /* Look for:
    5081              : 
    5082              :                INCOMING_VALUE = phi<MAIN_LOOP_RESULT(main loop),
    5083              :                                     INITIAL_VALUE(guard block)>.  */
    5084         4458 :           gcc_assert (TREE_CODE (incoming_value) == SSA_NAME);
    5085              : 
    5086         4458 :           gphi *phi = as_a <gphi *> (SSA_NAME_DEF_STMT (incoming_value));
    5087         4458 :           gcc_assert (gimple_bb (phi) == main_loop_edge->dest);
    5088              : 
    5089         4458 :           tree from_main_loop = PHI_ARG_DEF_FROM_EDGE (phi, main_loop_edge);
    5090         4458 :           tree from_skip = PHI_ARG_DEF_FROM_EDGE (phi, skip_edge);
    5091              : 
    5092         4458 :           main_loop_results.quick_push (from_main_loop);
    5093         4458 :           initial_values.quick_push (from_skip);
    5094              :         }
    5095              :     }
    5096              :   else
    5097              :     /* The main loop dominates the epilogue loop.  */
    5098          223 :     main_loop_results.splice (VECT_REDUC_INFO_INITIAL_VALUES (reduc_info));
    5099              : 
    5100              :   /* See if the main loop has the kind of accumulator we need.  */
    5101         4661 :   vect_reusable_accumulator *accumulator
    5102         4661 :     = main_loop_vinfo->reusable_accumulators.get (main_loop_results[0]);
    5103         4661 :   if (!accumulator
    5104         9306 :       || num_phis != VECT_REDUC_INFO_SCALAR_RESULTS (accumulator->reduc_info).length ()
    5105        13963 :       || !std::equal (main_loop_results.begin (), main_loop_results.end (),
    5106              :                       VECT_REDUC_INFO_SCALAR_RESULTS (accumulator->reduc_info).begin ()))
    5107              :     return false;
    5108              : 
    5109              :   /* Handle the case where we can reduce wider vectors to narrower ones.  */
    5110         4651 :   tree old_vectype = TREE_TYPE (accumulator->reduc_input);
    5111         4651 :   unsigned HOST_WIDE_INT m;
    5112         4651 :   if (!constant_multiple_p (TYPE_VECTOR_SUBPARTS (old_vectype),
    5113         4651 :                             TYPE_VECTOR_SUBPARTS (vectype), &m))
    5114            0 :     return false;
    5115              :   /* Check the intermediate vector types and operations are available.  */
    5116         4651 :   tree prev_vectype = old_vectype;
    5117         4651 :   poly_uint64 intermediate_nunits = TYPE_VECTOR_SUBPARTS (old_vectype);
    5118        13579 :   while (known_gt (intermediate_nunits, TYPE_VECTOR_SUBPARTS (vectype)))
    5119              :     {
    5120         4801 :       intermediate_nunits = exact_div (intermediate_nunits, 2);
    5121         4801 :       tree intermediate_vectype = get_related_vectype_for_scalar_type
    5122         4801 :         (TYPE_MODE (vectype), TREE_TYPE (vectype), intermediate_nunits);
    5123         4801 :       if (!intermediate_vectype
    5124         4801 :           || !directly_supported_p (VECT_REDUC_INFO_CODE (reduc_info),
    5125              :                                     intermediate_vectype)
    5126         9082 :           || !can_vec_extract (TYPE_MODE (prev_vectype),
    5127         4281 :                                TYPE_MODE (intermediate_vectype)))
    5128              :         return false;
    5129              :       prev_vectype = intermediate_vectype;
    5130              :     }
    5131              : 
    5132              :   /* Non-SLP reductions might apply an adjustment after the reduction
    5133              :      operation, in order to simplify the initialization of the accumulator.
    5134              :      If the epilogue loop carries on from where the main loop left off,
    5135              :      it should apply the same adjustment to the final reduction result.
    5136              : 
    5137              :      If the epilogue loop can also be entered directly (rather than via
    5138              :      the main loop), we need to be able to handle that case in the same way,
    5139              :      with the same adjustment.  (In principle we could add a PHI node
    5140              :      to select the correct adjustment, but in practice that shouldn't be
    5141              :      necessary.)  */
    5142         4127 :   tree main_adjustment
    5143         4127 :     = VECT_REDUC_INFO_EPILOGUE_ADJUSTMENT (accumulator->reduc_info);
    5144         4127 :   if (loop_vinfo->main_loop_edge && main_adjustment)
    5145              :     {
    5146         3438 :       gcc_assert (num_phis == 1);
    5147         3438 :       tree initial_value = initial_values[0];
    5148              :       /* Check that we can use INITIAL_VALUE as the adjustment and
    5149              :          initialize the accumulator with a neutral value instead.  */
    5150         3438 :       if (!operand_equal_p (initial_value, main_adjustment))
    5151              :         return false;
    5152         3428 :       initial_values[0] = VECT_REDUC_INFO_NEUTRAL_OP (reduc_info);
    5153              :     }
    5154         4117 :   VECT_REDUC_INFO_EPILOGUE_ADJUSTMENT (reduc_info) = main_adjustment;
    5155         4117 :   VECT_REDUC_INFO_INITIAL_VALUES (reduc_info).truncate (0);
    5156         4117 :   VECT_REDUC_INFO_INITIAL_VALUES (reduc_info).splice (initial_values);
    5157         4117 :   VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info) = accumulator;
    5158         4117 :   return true;
    5159         4661 : }
    5160              : 
    5161              : /* Reduce the vector VEC_DEF down to VECTYPE with reduction operation
    5162              :    CODE emitting stmts before GSI.  Returns a vector def of VECTYPE.  */
    5163              : 
    5164              : static tree
    5165         4161 : vect_create_partial_epilog (tree vec_def, tree vectype, code_helper code,
    5166              :                             gimple_seq *seq)
    5167              : {
    5168         4161 :   gcc_assert (!VECTOR_BOOLEAN_TYPE_P (TREE_TYPE (vec_def))
    5169              :               || (GET_MODE_CLASS (TYPE_MODE (TREE_TYPE (vec_def)))
    5170              :                   == MODE_VECTOR_INT));
    5171         4161 :   unsigned nunits = TYPE_VECTOR_SUBPARTS (TREE_TYPE (vec_def)).to_constant ();
    5172         4161 :   unsigned nunits1 = TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
    5173         4161 :   tree stype = TREE_TYPE (vectype);
    5174         4161 :   tree new_temp = vec_def;
    5175         8465 :   while (nunits > nunits1)
    5176              :     {
    5177         4304 :       nunits /= 2;
    5178         4304 :       tree vectype1 = get_related_vectype_for_scalar_type (TYPE_MODE (vectype),
    5179         4304 :                                                            stype, nunits);
    5180         4304 :       unsigned int bitsize = tree_to_uhwi (TYPE_SIZE (vectype1));
    5181              : 
    5182              :       /* The target has to make sure we support lowpart/highpart
    5183              :          extraction, either via direct vector extract or through
    5184              :          an integer mode punning.  */
    5185         4304 :       tree dst1, dst2;
    5186         4304 :       gimple *epilog_stmt;
    5187         4304 :       if (convert_optab_handler (vec_extract_optab,
    5188         4304 :                                  TYPE_MODE (TREE_TYPE (new_temp)),
    5189         4304 :                                  TYPE_MODE (vectype1))
    5190              :           != CODE_FOR_nothing)
    5191              :         {
    5192              :           /* Extract sub-vectors directly once vec_extract becomes
    5193              :              a conversion optab.  */
    5194         2615 :           dst1 = make_ssa_name (vectype1);
    5195         2615 :           epilog_stmt
    5196         5230 :               = gimple_build_assign (dst1, BIT_FIELD_REF,
    5197              :                                      build3 (BIT_FIELD_REF, vectype1,
    5198         2615 :                                              new_temp, TYPE_SIZE (vectype1),
    5199              :                                              bitsize_int (0)));
    5200         2615 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5201         2615 :           dst2 =  make_ssa_name (vectype1);
    5202         2615 :           epilog_stmt
    5203         2615 :               = gimple_build_assign (dst2, BIT_FIELD_REF,
    5204              :                                      build3 (BIT_FIELD_REF, vectype1,
    5205         2615 :                                              new_temp, TYPE_SIZE (vectype1),
    5206         2615 :                                              bitsize_int (bitsize)));
    5207         2615 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5208              :         }
    5209              :       else
    5210              :         {
    5211              :           /* Extract via punning to appropriately sized integer mode
    5212              :              vector.  */
    5213         1689 :           tree eltype = build_nonstandard_integer_type (bitsize, 1);
    5214         1689 :           tree etype = build_vector_type (eltype, 2);
    5215         3378 :           gcc_assert (convert_optab_handler (vec_extract_optab,
    5216              :                                              TYPE_MODE (etype),
    5217              :                                              TYPE_MODE (eltype))
    5218              :                       != CODE_FOR_nothing);
    5219         1689 :           tree tem = make_ssa_name (etype);
    5220         1689 :           epilog_stmt = gimple_build_assign (tem, VIEW_CONVERT_EXPR,
    5221              :                                              build1 (VIEW_CONVERT_EXPR,
    5222              :                                                      etype, new_temp));
    5223         1689 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5224         1689 :           new_temp = tem;
    5225         1689 :           tem = make_ssa_name (eltype);
    5226         1689 :           epilog_stmt
    5227         3378 :               = gimple_build_assign (tem, BIT_FIELD_REF,
    5228              :                                      build3 (BIT_FIELD_REF, eltype,
    5229         1689 :                                              new_temp, TYPE_SIZE (eltype),
    5230              :                                              bitsize_int (0)));
    5231         1689 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5232         1689 :           dst1 = make_ssa_name (vectype1);
    5233         1689 :           epilog_stmt = gimple_build_assign (dst1, VIEW_CONVERT_EXPR,
    5234              :                                              build1 (VIEW_CONVERT_EXPR,
    5235              :                                                      vectype1, tem));
    5236         1689 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5237         1689 :           tem = make_ssa_name (eltype);
    5238         1689 :           epilog_stmt
    5239         1689 :               = gimple_build_assign (tem, BIT_FIELD_REF,
    5240              :                                      build3 (BIT_FIELD_REF, eltype,
    5241         1689 :                                              new_temp, TYPE_SIZE (eltype),
    5242         1689 :                                              bitsize_int (bitsize)));
    5243         1689 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5244         1689 :           dst2 =  make_ssa_name (vectype1);
    5245         1689 :           epilog_stmt = gimple_build_assign (dst2, VIEW_CONVERT_EXPR,
    5246              :                                              build1 (VIEW_CONVERT_EXPR,
    5247              :                                                      vectype1, tem));
    5248         1689 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5249              :         }
    5250              : 
    5251         4304 :       new_temp = gimple_build (seq, code, vectype1, dst1, dst2);
    5252              :     }
    5253         4161 :   if (!useless_type_conversion_p (vectype, TREE_TYPE (new_temp)))
    5254              :     {
    5255           66 :       tree dst3 = make_ssa_name (vectype);
    5256           66 :       gimple *epilog_stmt = gimple_build_assign (dst3, VIEW_CONVERT_EXPR,
    5257              :                                                  build1 (VIEW_CONVERT_EXPR,
    5258              :                                                          vectype, new_temp));
    5259           66 :       gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5260           66 :       new_temp = dst3;
    5261              :     }
    5262              : 
    5263         4161 :   return new_temp;
    5264              : }
    5265              : 
    5266              : /* Function vect_create_epilog_for_reduction
    5267              : 
    5268              :    Create code at the loop-epilog to finalize the result of a reduction
    5269              :    computation.
    5270              : 
    5271              :    STMT_INFO is the scalar reduction stmt that is being vectorized.
    5272              :    SLP_NODE is an SLP node containing a group of reduction statements. The
    5273              :      first one in this group is STMT_INFO.
    5274              :    SLP_NODE_INSTANCE is the SLP node instance containing SLP_NODE
    5275              :    REDUC_INDEX says which rhs operand of the STMT_INFO is the reduction phi
    5276              :      (counting from 0)
    5277              :    LOOP_EXIT is the edge to update in the merge block.  In the case of a single
    5278              :      exit this edge is always the main loop exit.
    5279              : 
    5280              :    This function:
    5281              :    1. Completes the reduction def-use cycles.
    5282              :    2. "Reduces" each vector of partial results VECT_DEFS into a single result,
    5283              :       by calling the function specified by REDUC_FN if available, or by
    5284              :       other means (whole-vector shifts or a scalar loop).
    5285              :       The function also creates a new phi node at the loop exit to preserve
    5286              :       loop-closed form, as illustrated below.
    5287              : 
    5288              :      The flow at the entry to this function:
    5289              : 
    5290              :         loop:
    5291              :           vec_def = phi <vec_init, null>        # REDUCTION_PHI
    5292              :           VECT_DEF = vector_stmt                # vectorized form of STMT_INFO
    5293              :           s_loop = scalar_stmt                  # (scalar) STMT_INFO
    5294              :         loop_exit:
    5295              :           s_out0 = phi <s_loop>                 # (scalar) EXIT_PHI
    5296              :           use <s_out0>
    5297              :           use <s_out0>
    5298              : 
    5299              :      The above is transformed by this function into:
    5300              : 
    5301              :         loop:
    5302              :           vec_def = phi <vec_init, VECT_DEF>    # REDUCTION_PHI
    5303              :           VECT_DEF = vector_stmt                # vectorized form of STMT_INFO
    5304              :           s_loop = scalar_stmt                  # (scalar) STMT_INFO
    5305              :         loop_exit:
    5306              :           s_out0 = phi <s_loop>                 # (scalar) EXIT_PHI
    5307              :           v_out1 = phi <VECT_DEF>               # NEW_EXIT_PHI
    5308              :           v_out2 = reduce <v_out1>
    5309              :           s_out3 = extract_field <v_out2, 0>
    5310              :           s_out4 = adjust_result <s_out3>
    5311              :           use <s_out4>
    5312              :           use <s_out4>
    5313              : */
    5314              : 
    5315              : static void
    5316        22216 : vect_create_epilog_for_reduction (loop_vec_info loop_vinfo,
    5317              :                                   stmt_vec_info stmt_info,
    5318              :                                   slp_tree slp_node,
    5319              :                                   slp_instance slp_node_instance,
    5320              :                                   edge loop_exit)
    5321              : {
    5322        22216 :   vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
    5323        22216 :   code_helper code = VECT_REDUC_INFO_CODE (reduc_info);
    5324        22216 :   internal_fn reduc_fn = VECT_REDUC_INFO_FN (reduc_info);
    5325        22216 :   tree vectype;
    5326        22216 :   machine_mode mode;
    5327        22216 :   basic_block exit_bb;
    5328        22216 :   gimple *new_phi = NULL, *phi = NULL;
    5329        22216 :   gimple_stmt_iterator exit_gsi;
    5330        22216 :   tree new_temp = NULL_TREE, new_name, new_scalar_dest;
    5331        22216 :   gimple *epilog_stmt = NULL;
    5332        22216 :   gimple *exit_phi;
    5333        22216 :   tree def;
    5334        22216 :   tree orig_name, scalar_result;
    5335        22216 :   imm_use_iterator imm_iter;
    5336        22216 :   use_operand_p use_p;
    5337        22216 :   gimple *use_stmt;
    5338        22216 :   auto_vec<tree> reduc_inputs;
    5339        22216 :   int j, i;
    5340        22216 :   vec<tree> &scalar_results = VECT_REDUC_INFO_SCALAR_RESULTS (reduc_info);
    5341        22216 :   unsigned int k;
    5342              :   /* SLP reduction without reduction chain, e.g.,
    5343              :      # a1 = phi <a2, a0>
    5344              :      # b1 = phi <b2, b0>
    5345              :      a2 = operation (a1)
    5346              :      b2 = operation (b1)  */
    5347        22216 :   const bool slp_reduc = !reduc_info->is_reduc_chain;
    5348        22216 :   tree induction_index = NULL_TREE;
    5349              : 
    5350        22216 :   unsigned int group_size = SLP_TREE_LANES (slp_node);
    5351              : 
    5352        22216 :   bool double_reduc = false;
    5353        22216 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    5354        22216 :   if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
    5355              :     {
    5356            0 :       double_reduc = true;
    5357            0 :       gcc_assert (slp_reduc);
    5358              :     }
    5359              : 
    5360        22216 :   vectype = VECT_REDUC_INFO_VECTYPE (reduc_info);
    5361        22216 :   gcc_assert (vectype);
    5362        22216 :   mode = TYPE_MODE (vectype);
    5363              : 
    5364        22216 :   tree induc_val = NULL_TREE;
    5365        22216 :   tree adjustment_def = NULL;
    5366              :   /* Optimize: for induction condition reduction, if we can't use zero
    5367              :      for induc_val, use initial_def.  */
    5368        22216 :   if (VECT_REDUC_INFO_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
    5369           62 :     induc_val = VECT_REDUC_INFO_INDUC_COND_INITIAL_VAL (reduc_info);
    5370        22154 :   else if (double_reduc)
    5371              :     ;
    5372              :   else
    5373        22154 :     adjustment_def = VECT_REDUC_INFO_EPILOGUE_ADJUSTMENT (reduc_info);
    5374              : 
    5375        22216 :   stmt_vec_info single_live_out_stmt[] = { stmt_info };
    5376        22216 :   array_slice<const stmt_vec_info> live_out_stmts = single_live_out_stmt;
    5377        22216 :   if (slp_reduc)
    5378              :     /* All statements produce live-out values.  */
    5379        43974 :     live_out_stmts = SLP_TREE_SCALAR_STMTS (slp_node);
    5380              : 
    5381        22216 :   unsigned vec_num
    5382        22216 :     = SLP_TREE_VEC_DEFS (slp_node_instance->reduc_phis).length ();
    5383              : 
    5384              :   /* For cond reductions we want to create a new vector (INDEX_COND_EXPR)
    5385              :      which is updated with the current index of the loop for every match of
    5386              :      the original loop's cond_expr (VEC_STMT).  This results in a vector
    5387              :      containing the last time the condition passed for that vector lane.
    5388              :      The first match will be a 1 to allow 0 to be used for non-matching
    5389              :      indexes.  If there are no matches at all then the vector will be all
    5390              :      zeroes.
    5391              : 
    5392              :      PR92772: This algorithm is broken for architectures that support
    5393              :      masked vectors, but do not provide fold_extract_last.  */
    5394        22216 :   if (VECT_REDUC_INFO_TYPE (reduc_info) == COND_REDUCTION)
    5395              :     {
    5396           87 :       gcc_assert (!double_reduc);
    5397           87 :       auto_vec<std::pair<tree, bool>, 2> ccompares;
    5398           87 :       slp_tree cond_node = slp_node_instance->root;
    5399          183 :       while (cond_node != slp_node_instance->reduc_phis)
    5400              :         {
    5401           96 :           stmt_vec_info cond_info = SLP_TREE_REPRESENTATIVE (cond_node);
    5402           96 :           if (gimple_assign_rhs_code (cond_info->stmt) == COND_EXPR)
    5403              :             {
    5404           96 :               gimple *vec_stmt
    5405           96 :                 = SSA_NAME_DEF_STMT (SLP_TREE_VEC_DEFS (cond_node)[0]);
    5406           96 :               gcc_assert (gimple_assign_rhs_code (vec_stmt) == VEC_COND_EXPR);
    5407           96 :               ccompares.safe_push
    5408           96 :                 (std::make_pair (gimple_assign_rhs1 (vec_stmt),
    5409           96 :                                  SLP_TREE_REDUC_IDX (cond_node) == 2));
    5410              :             }
    5411           96 :           int slp_reduc_idx = SLP_TREE_REDUC_IDX (cond_node);
    5412           96 :           cond_node = SLP_TREE_CHILDREN (cond_node)[slp_reduc_idx];
    5413              :         }
    5414           87 :       gcc_assert (ccompares.length () != 0);
    5415              : 
    5416           87 :       tree indx_before_incr, indx_after_incr;
    5417           87 :       poly_uint64 nunits_out = TYPE_VECTOR_SUBPARTS (vectype);
    5418           87 :       int scalar_precision
    5419           87 :         = GET_MODE_PRECISION (SCALAR_TYPE_MODE (TREE_TYPE (vectype)));
    5420           87 :       tree cr_index_scalar_type = make_unsigned_type (scalar_precision);
    5421           87 :       tree cr_index_vector_type = get_related_vectype_for_scalar_type
    5422           87 :         (TYPE_MODE (vectype), cr_index_scalar_type,
    5423              :          TYPE_VECTOR_SUBPARTS (vectype));
    5424              : 
    5425              :       /* First we create a simple vector induction variable which starts
    5426              :          with the values {1,2,3,...} (SERIES_VECT) and increments by the
    5427              :          vector size (STEP).  */
    5428              : 
    5429              :       /* Create a {1,2,3,...} vector.  */
    5430           87 :       tree series_vect = build_index_vector (cr_index_vector_type, 1, 1);
    5431              : 
    5432              :       /* Create a vector of the step value.  */
    5433           87 :       tree step = build_int_cst (cr_index_scalar_type, nunits_out);
    5434           87 :       tree vec_step = build_vector_from_val (cr_index_vector_type, step);
    5435              : 
    5436              :       /* Create an induction variable.  */
    5437           87 :       gimple_stmt_iterator incr_gsi;
    5438           87 :       bool insert_after;
    5439           87 :       vect_iv_increment_position (LOOP_VINFO_MAIN_EXIT (loop_vinfo),
    5440              :                                   &incr_gsi, &insert_after);
    5441           87 :       create_iv (series_vect, PLUS_EXPR, vec_step, NULL_TREE, loop, &incr_gsi,
    5442              :                  insert_after, &indx_before_incr, &indx_after_incr);
    5443              : 
    5444              :       /* Next create a new phi node vector (NEW_PHI_TREE) which starts
    5445              :          filled with zeros (VEC_ZERO).  */
    5446              : 
    5447              :       /* Create a vector of 0s.  */
    5448           87 :       tree zero = build_zero_cst (cr_index_scalar_type);
    5449           87 :       tree vec_zero = build_vector_from_val (cr_index_vector_type, zero);
    5450              : 
    5451              :       /* Create a vector phi node.  */
    5452           87 :       tree new_phi_tree = make_ssa_name (cr_index_vector_type);
    5453           87 :       new_phi = create_phi_node (new_phi_tree, loop->header);
    5454           87 :       add_phi_arg (as_a <gphi *> (new_phi), vec_zero,
    5455              :                    loop_preheader_edge (loop), UNKNOWN_LOCATION);
    5456              : 
    5457              :       /* Now take the condition from the loops original cond_exprs
    5458              :          and produce a new cond_exprs (INDEX_COND_EXPR) which for
    5459              :          every match uses values from the induction variable
    5460              :          (INDEX_BEFORE_INCR) otherwise uses values from the phi node
    5461              :          (NEW_PHI_TREE).
    5462              :          Finally, we update the phi (NEW_PHI_TREE) to take the value of
    5463              :          the new cond_expr (INDEX_COND_EXPR).  */
    5464           87 :       gimple_seq stmts = NULL;
    5465          270 :       for (int i = ccompares.length () - 1; i != -1; --i)
    5466              :         {
    5467           96 :           tree ccompare = ccompares[i].first;
    5468           96 :           if (ccompares[i].second)
    5469           69 :             new_phi_tree = gimple_build (&stmts, VEC_COND_EXPR,
    5470              :                                          cr_index_vector_type,
    5471              :                                          ccompare,
    5472              :                                          indx_before_incr, new_phi_tree);
    5473              :           else
    5474           27 :             new_phi_tree = gimple_build (&stmts, VEC_COND_EXPR,
    5475              :                                          cr_index_vector_type,
    5476              :                                          ccompare,
    5477              :                                          new_phi_tree, indx_before_incr);
    5478              :         }
    5479           87 :       gsi_insert_seq_before (&incr_gsi, stmts, GSI_SAME_STMT);
    5480              : 
    5481              :       /* Update the phi with the vec cond.  */
    5482           87 :       induction_index = new_phi_tree;
    5483           87 :       add_phi_arg (as_a <gphi *> (new_phi), induction_index,
    5484              :                    loop_latch_edge (loop), UNKNOWN_LOCATION);
    5485           87 :     }
    5486              : 
    5487              :   /* 2. Create epilog code.
    5488              :         The reduction epilog code operates across the elements of the vector
    5489              :         of partial results computed by the vectorized loop.
    5490              :         The reduction epilog code consists of:
    5491              : 
    5492              :         step 1: compute the scalar result in a vector (v_out2)
    5493              :         step 2: extract the scalar result (s_out3) from the vector (v_out2)
    5494              :         step 3: adjust the scalar result (s_out3) if needed.
    5495              : 
    5496              :         Step 1 can be accomplished using one the following three schemes:
    5497              :           (scheme 1) using reduc_fn, if available.
    5498              :           (scheme 2) using whole-vector shifts, if available.
    5499              :           (scheme 3) using a scalar loop. In this case steps 1+2 above are
    5500              :                      combined.
    5501              : 
    5502              :           The overall epilog code looks like this:
    5503              : 
    5504              :           s_out0 = phi <s_loop>         # original EXIT_PHI
    5505              :           v_out1 = phi <VECT_DEF>       # NEW_EXIT_PHI
    5506              :           v_out2 = reduce <v_out1>              # step 1
    5507              :           s_out3 = extract_field <v_out2, 0>    # step 2
    5508              :           s_out4 = adjust_result <s_out3>       # step 3
    5509              : 
    5510              :           (step 3 is optional, and steps 1 and 2 may be combined).
    5511              :           Lastly, the uses of s_out0 are replaced by s_out4.  */
    5512              : 
    5513              : 
    5514              :   /* 2.1 Create new loop-exit-phis to preserve loop-closed form:
    5515              :          v_out1 = phi <VECT_DEF>
    5516              :          Store them in NEW_PHIS.  */
    5517              :   /* We need to reduce values in all exits.  */
    5518        22216 :   exit_bb = loop_exit->dest;
    5519        22216 :   exit_gsi = gsi_after_labels (exit_bb);
    5520        22216 :   reduc_inputs.create (vec_num);
    5521        68239 :   for (unsigned i = 0; i < vec_num; i++)
    5522              :     {
    5523        23807 :       gimple_seq stmts = NULL;
    5524        23807 :       def = vect_get_slp_vect_def (slp_node, i);
    5525        23807 :       tree new_def = copy_ssa_name (def);
    5526        23807 :       phi = create_phi_node (new_def, exit_bb);
    5527        23807 :       if (LOOP_VINFO_MAIN_EXIT (loop_vinfo) == loop_exit)
    5528        23780 :         SET_PHI_ARG_DEF (phi, loop_exit->dest_idx, def);
    5529              :       else
    5530              :         {
    5531           57 :           for (unsigned k = 0; k < gimple_phi_num_args (phi); k++)
    5532           30 :             SET_PHI_ARG_DEF (phi, k, def);
    5533              :         }
    5534        23807 :       new_def = gimple_convert (&stmts, vectype, new_def);
    5535        23807 :       reduc_inputs.quick_push (new_def);
    5536        23807 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5537              :     }
    5538              : 
    5539              :   /* 2.2 Get the original scalar reduction variable as defined in the loop.
    5540              :          In case STMT is a "pattern-stmt" (i.e. - it represents a reduction
    5541              :          pattern), the scalar-def is taken from the original stmt that the
    5542              :          pattern-stmt (STMT) replaces.  */
    5543              : 
    5544        23062 :   tree scalar_dest = gimple_get_lhs (vect_orig_stmt (stmt_info)->stmt);
    5545        22216 :   tree scalar_type = TREE_TYPE (scalar_dest);
    5546        22216 :   scalar_results.truncate (0);
    5547        22216 :   scalar_results.reserve_exact (group_size);
    5548        22216 :   new_scalar_dest = vect_create_destination_var (scalar_dest, NULL);
    5549              : 
    5550              :   /* True if we should implement SLP_REDUC using native reduction operations
    5551              :      instead of scalar operations.  */
    5552        22216 :   const bool direct_slp_reduc
    5553        22216 :     = (reduc_fn != IFN_LAST
    5554        22216 :        && slp_reduc
    5555        22216 :        && !TYPE_VECTOR_SUBPARTS (vectype).is_constant ());
    5556              : 
    5557              :   /* If signed overflow is undefined we might need to perform reduction
    5558              :      computations in an unsigned type.  */
    5559        22216 :   tree compute_vectype = vectype;
    5560        22216 :   if (ANY_INTEGRAL_TYPE_P (vectype)
    5561        15104 :       && TYPE_OVERFLOW_UNDEFINED (vectype)
    5562         5624 :       && code.is_tree_code ()
    5563        27840 :       && arith_code_with_undefined_signed_overflow ((tree_code) code))
    5564         4142 :     compute_vectype = unsigned_type_for (vectype);
    5565              : 
    5566              :   /* In case of reduction chain, e.g.,
    5567              :      # a1 = phi <a3, a0>
    5568              :      a2 = operation (a1)
    5569              :      a3 = operation (a2),
    5570              : 
    5571              :      we may end up with more than one vector result.  Here we reduce them
    5572              :      to one vector.
    5573              : 
    5574              :      The same is true for a SLP reduction, e.g.,
    5575              :      # a1 = phi <a2, a0>
    5576              :      # b1 = phi <b2, b0>
    5577              :      a2 = operation (a1)
    5578              :      b2 = operation (a2),
    5579              : 
    5580              :      where we can end up with more than one vector as well.  We can
    5581              :      easily accumulate vectors when the number of vector elements is
    5582              :      a multiple of the SLP group size.
    5583              : 
    5584              :      The same is true if we couldn't use a single defuse cycle.  */
    5585        22216 :   if ((!slp_reduc
    5586              :        || direct_slp_reduc
    5587              :        || (slp_reduc
    5588        22216 :            && constant_multiple_p (TYPE_VECTOR_SUBPARTS (vectype), group_size)))
    5589        44432 :       && reduc_inputs.length () > 1)
    5590              :     {
    5591          541 :       gimple_seq stmts = NULL;
    5592          541 :       tree single_input = reduc_inputs[0];
    5593          541 :       if (compute_vectype != vectype)
    5594          163 :         single_input = gimple_build (&stmts, VIEW_CONVERT_EXPR,
    5595              :                                      compute_vectype, single_input);
    5596         1977 :       for (k = 1; k < reduc_inputs.length (); k++)
    5597              :         {
    5598         1436 :           tree input = gimple_build (&stmts, VIEW_CONVERT_EXPR,
    5599         1436 :                                      compute_vectype, reduc_inputs[k]);
    5600         1436 :           single_input = gimple_build (&stmts, code, compute_vectype,
    5601              :                                        single_input, input);
    5602              :         }
    5603          541 :       if (compute_vectype != vectype)
    5604          163 :         single_input = gimple_build (&stmts, VIEW_CONVERT_EXPR,
    5605              :                                      vectype, single_input);
    5606          541 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5607              : 
    5608          541 :       reduc_inputs.truncate (0);
    5609          541 :       reduc_inputs.safe_push (single_input);
    5610              :     }
    5611              : 
    5612        22216 :   tree orig_reduc_input = reduc_inputs[0];
    5613              : 
    5614              :   /* If this loop is an epilogue loop that can be skipped after the
    5615              :      main loop, we can only share a reduction operation between the
    5616              :      main loop and the epilogue if we put it at the target of the
    5617              :      skip edge.
    5618              : 
    5619              :      We can still reuse accumulators if this check fails.  Doing so has
    5620              :      the minor(?) benefit of making the epilogue loop's scalar result
    5621              :      independent of the main loop's scalar result.  */
    5622        22216 :   bool unify_with_main_loop_p = false;
    5623        22216 :   if (VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info)
    5624         4117 :       && loop_vinfo->skip_this_loop_edge
    5625         3877 :       && single_succ_p (exit_bb)
    5626        22233 :       && single_succ (exit_bb) == loop_vinfo->skip_this_loop_edge->dest)
    5627              :     {
    5628           17 :       unify_with_main_loop_p = true;
    5629              : 
    5630           17 :       basic_block reduc_block = loop_vinfo->skip_this_loop_edge->dest;
    5631           17 :       reduc_inputs[0] = make_ssa_name (vectype);
    5632           17 :       gphi *new_phi = create_phi_node (reduc_inputs[0], reduc_block);
    5633           17 :       add_phi_arg (new_phi, orig_reduc_input, single_succ_edge (exit_bb),
    5634              :                    UNKNOWN_LOCATION);
    5635           17 :       add_phi_arg (new_phi,
    5636           17 :                    VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info)->reduc_input,
    5637              :                    loop_vinfo->skip_this_loop_edge, UNKNOWN_LOCATION);
    5638           17 :       exit_gsi = gsi_after_labels (reduc_block);
    5639              :     }
    5640              : 
    5641              :   /* Shouldn't be used beyond this point.  */
    5642        22216 :   exit_bb = nullptr;
    5643              : 
    5644              :   /* If we are operating on a mask vector and do not support direct mask
    5645              :      reduction, work on a bool data vector instead of a mask vector.  */
    5646        22216 :   if (VECTOR_BOOLEAN_TYPE_P (vectype)
    5647          251 :       && VECT_REDUC_INFO_VECTYPE_FOR_MASK (reduc_info)
    5648        22417 :       && vectype != VECT_REDUC_INFO_VECTYPE_FOR_MASK (reduc_info))
    5649              :     {
    5650          201 :       compute_vectype = vectype = VECT_REDUC_INFO_VECTYPE_FOR_MASK (reduc_info);
    5651          201 :       gimple_seq stmts = NULL;
    5652          410 :       for (unsigned i = 0; i < reduc_inputs.length (); ++i)
    5653          418 :         reduc_inputs[i] = gimple_build (&stmts, VEC_COND_EXPR, vectype,
    5654          209 :                                         reduc_inputs[i],
    5655              :                                         build_one_cst (vectype),
    5656              :                                         build_zero_cst (vectype));
    5657          201 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5658              :     }
    5659              : 
    5660        22216 :   if (VECT_REDUC_INFO_TYPE (reduc_info) == COND_REDUCTION
    5661           87 :       && reduc_fn != IFN_LAST)
    5662              :     {
    5663              :       /* For condition reductions, we have a vector (REDUC_INPUTS 0) containing
    5664              :          various data values where the condition matched and another vector
    5665              :          (INDUCTION_INDEX) containing all the indexes of those matches.  We
    5666              :          need to extract the last matching index (which will be the index with
    5667              :          highest value) and use this to index into the data vector.
    5668              :          For the case where there were no matches, the data vector will contain
    5669              :          all default values and the index vector will be all zeros.  */
    5670              : 
    5671              :       /* Get various versions of the type of the vector of indexes.  */
    5672           14 :       tree index_vec_type = TREE_TYPE (induction_index);
    5673           14 :       gcc_checking_assert (TYPE_UNSIGNED (index_vec_type));
    5674           14 :       tree index_scalar_type = TREE_TYPE (index_vec_type);
    5675           14 :       tree index_vec_cmp_type = truth_type_for (index_vec_type);
    5676              : 
    5677              :       /* Get an unsigned integer version of the type of the data vector.  */
    5678           14 :       int scalar_precision
    5679           14 :         = GET_MODE_PRECISION (SCALAR_TYPE_MODE (scalar_type));
    5680           14 :       tree scalar_type_unsigned = make_unsigned_type (scalar_precision);
    5681           14 :       tree vectype_unsigned = get_same_sized_vectype (scalar_type_unsigned,
    5682              :                                                 vectype);
    5683              : 
    5684              :       /* First we need to create a vector (ZERO_VEC) of zeros and another
    5685              :          vector (MAX_INDEX_VEC) filled with the last matching index, which we
    5686              :          can create using a MAX reduction and then expanding.
    5687              :          In the case where the loop never made any matches, the max index will
    5688              :          be zero.  */
    5689              : 
    5690              :       /* Vector of {0, 0, 0,...}.  */
    5691           14 :       tree zero_vec = build_zero_cst (vectype);
    5692              : 
    5693              :       /* Find maximum value from the vector of found indexes.  */
    5694           14 :       tree max_index = make_ssa_name (index_scalar_type);
    5695           14 :       gcall *max_index_stmt = gimple_build_call_internal (IFN_REDUC_MAX,
    5696              :                                                           1, induction_index);
    5697           14 :       gimple_call_set_lhs (max_index_stmt, max_index);
    5698           14 :       gsi_insert_before (&exit_gsi, max_index_stmt, GSI_SAME_STMT);
    5699              : 
    5700              :       /* Vector of {max_index, max_index, max_index,...}.  */
    5701           14 :       tree max_index_vec = make_ssa_name (index_vec_type);
    5702           14 :       tree max_index_vec_rhs = build_vector_from_val (index_vec_type,
    5703              :                                                       max_index);
    5704           14 :       gimple *max_index_vec_stmt = gimple_build_assign (max_index_vec,
    5705              :                                                         max_index_vec_rhs);
    5706           14 :       gsi_insert_before (&exit_gsi, max_index_vec_stmt, GSI_SAME_STMT);
    5707              : 
    5708              :       /* Next we compare the new vector (MAX_INDEX_VEC) full of max indexes
    5709              :          with the vector (INDUCTION_INDEX) of found indexes, choosing values
    5710              :          from the data vector (REDUC_INPUTS 0) for matches, 0 (ZERO_VEC)
    5711              :          otherwise.  Only one value should match, resulting in a vector
    5712              :          (VEC_COND) with one data value and the rest zeros.
    5713              :          In the case where the loop never made any matches, every index will
    5714              :          match, resulting in a vector with all data values (which will all be
    5715              :          the default value).  */
    5716              : 
    5717              :       /* Compare the max index vector to the vector of found indexes to find
    5718              :          the position of the max value.  */
    5719           14 :       tree vec_compare = make_ssa_name (index_vec_cmp_type);
    5720           14 :       gimple *vec_compare_stmt = gimple_build_assign (vec_compare, EQ_EXPR,
    5721              :                                                       induction_index,
    5722              :                                                       max_index_vec);
    5723           14 :       gsi_insert_before (&exit_gsi, vec_compare_stmt, GSI_SAME_STMT);
    5724              : 
    5725              :       /* Use the compare to choose either values from the data vector or
    5726              :          zero.  */
    5727           14 :       tree vec_cond = make_ssa_name (vectype);
    5728           14 :       gimple *vec_cond_stmt = gimple_build_assign (vec_cond, VEC_COND_EXPR,
    5729              :                                                    vec_compare,
    5730           14 :                                                    reduc_inputs[0],
    5731              :                                                    zero_vec);
    5732           14 :       gsi_insert_before (&exit_gsi, vec_cond_stmt, GSI_SAME_STMT);
    5733              : 
    5734              :       /* Finally we need to extract the data value from the vector (VEC_COND)
    5735              :          into a scalar (MATCHED_DATA_REDUC).  Logically we want to do a OR
    5736              :          reduction, but because this doesn't exist, we can use a MAX reduction
    5737              :          instead.  The data value might be signed or a float so we need to cast
    5738              :          it first.
    5739              :          In the case where the loop never made any matches, the data values are
    5740              :          all identical, and so will reduce down correctly.  */
    5741              : 
    5742              :       /* Make the matched data values unsigned.  */
    5743           14 :       tree vec_cond_cast = make_ssa_name (vectype_unsigned);
    5744           14 :       tree vec_cond_cast_rhs = build1 (VIEW_CONVERT_EXPR, vectype_unsigned,
    5745              :                                        vec_cond);
    5746           14 :       gimple *vec_cond_cast_stmt = gimple_build_assign (vec_cond_cast,
    5747              :                                                         VIEW_CONVERT_EXPR,
    5748              :                                                         vec_cond_cast_rhs);
    5749           14 :       gsi_insert_before (&exit_gsi, vec_cond_cast_stmt, GSI_SAME_STMT);
    5750              : 
    5751              :       /* Reduce down to a scalar value.  */
    5752           14 :       tree data_reduc = make_ssa_name (scalar_type_unsigned);
    5753           14 :       gcall *data_reduc_stmt = gimple_build_call_internal (IFN_REDUC_MAX,
    5754              :                                                            1, vec_cond_cast);
    5755           14 :       gimple_call_set_lhs (data_reduc_stmt, data_reduc);
    5756           14 :       gsi_insert_before (&exit_gsi, data_reduc_stmt, GSI_SAME_STMT);
    5757              : 
    5758              :       /* Convert the reduced value back to the result type and set as the
    5759              :          result.  */
    5760           14 :       gimple_seq stmts = NULL;
    5761           14 :       new_temp = gimple_build (&stmts, VIEW_CONVERT_EXPR, scalar_type,
    5762              :                                data_reduc);
    5763           14 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5764           14 :       scalar_results.safe_push (new_temp);
    5765           14 :     }
    5766        22202 :   else if (VECT_REDUC_INFO_TYPE (reduc_info) == COND_REDUCTION
    5767           73 :            && reduc_fn == IFN_LAST)
    5768              :     {
    5769              :       /* Condition reduction without supported IFN_REDUC_MAX.  Generate
    5770              :          idx = 0;
    5771              :          idx_val = induction_index[0];
    5772              :          val = data_reduc[0];
    5773              :          for (idx = 0, val = init, i = 0; i < nelts; ++i)
    5774              :            if (induction_index[i] > idx_val)
    5775              :              val = data_reduc[i], idx_val = induction_index[i];
    5776              :          return val;  */
    5777              : 
    5778           73 :       tree data_eltype = TREE_TYPE (vectype);
    5779           73 :       tree idx_eltype = TREE_TYPE (TREE_TYPE (induction_index));
    5780           73 :       unsigned HOST_WIDE_INT el_size = tree_to_uhwi (TYPE_SIZE (idx_eltype));
    5781           73 :       poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (TREE_TYPE (induction_index));
    5782              :       /* Enforced by vectorizable_reduction, which ensures we have target
    5783              :          support before allowing a conditional reduction on variable-length
    5784              :          vectors.  */
    5785           73 :       unsigned HOST_WIDE_INT v_size = el_size * nunits.to_constant ();
    5786           73 :       tree idx_val = NULL_TREE, val = NULL_TREE;
    5787          469 :       for (unsigned HOST_WIDE_INT off = 0; off < v_size; off += el_size)
    5788              :         {
    5789          396 :           tree old_idx_val = idx_val;
    5790          396 :           tree old_val = val;
    5791          396 :           idx_val = make_ssa_name (idx_eltype);
    5792          396 :           epilog_stmt = gimple_build_assign (idx_val, BIT_FIELD_REF,
    5793              :                                              build3 (BIT_FIELD_REF, idx_eltype,
    5794              :                                                      induction_index,
    5795          396 :                                                      bitsize_int (el_size),
    5796          396 :                                                      bitsize_int (off)));
    5797          396 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5798          396 :           val = make_ssa_name (data_eltype);
    5799          792 :           epilog_stmt = gimple_build_assign (val, BIT_FIELD_REF,
    5800              :                                              build3 (BIT_FIELD_REF,
    5801              :                                                      data_eltype,
    5802          396 :                                                      reduc_inputs[0],
    5803          396 :                                                      bitsize_int (el_size),
    5804          396 :                                                      bitsize_int (off)));
    5805          396 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5806          396 :           if (off != 0)
    5807              :             {
    5808          323 :               tree new_idx_val = idx_val;
    5809          323 :               if (off != v_size - el_size)
    5810              :                 {
    5811          250 :                   new_idx_val = make_ssa_name (idx_eltype);
    5812          250 :                   epilog_stmt = gimple_build_assign (new_idx_val,
    5813              :                                                      MAX_EXPR, idx_val,
    5814              :                                                      old_idx_val);
    5815          250 :                   gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5816              :                 }
    5817          323 :               tree cond = make_ssa_name (boolean_type_node);
    5818          323 :               epilog_stmt = gimple_build_assign (cond, GT_EXPR,
    5819              :                                                  idx_val, old_idx_val);
    5820          323 :               gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5821          323 :               tree new_val = make_ssa_name (data_eltype);
    5822          323 :               epilog_stmt = gimple_build_assign (new_val, COND_EXPR,
    5823              :                                                  cond, val, old_val);
    5824          323 :               gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5825          323 :               idx_val = new_idx_val;
    5826          323 :               val = new_val;
    5827              :             }
    5828              :         }
    5829              :       /* Convert the reduced value back to the result type and set as the
    5830              :          result.  */
    5831           73 :       gimple_seq stmts = NULL;
    5832           73 :       val = gimple_convert (&stmts, scalar_type, val);
    5833           73 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5834           73 :       scalar_results.safe_push (val);
    5835           73 :     }
    5836              : 
    5837              :   /* 2.3 Create the reduction code, using one of the three schemes described
    5838              :          above. In SLP we simply need to extract all the elements from the
    5839              :          vector (without reducing them), so we use scalar shifts.  */
    5840        22129 :   else if (reduc_fn != IFN_LAST && (!slp_reduc || group_size == 1))
    5841              :     {
    5842        20145 :       tree tmp;
    5843        20145 :       tree vec_elem_type;
    5844              : 
    5845              :       /* Case 1:  Create:
    5846              :          v_out2 = reduc_expr <v_out1>  */
    5847              : 
    5848        20145 :       if (dump_enabled_p ())
    5849         1529 :         dump_printf_loc (MSG_NOTE, vect_location,
    5850              :                          "Reduce using direct vector reduction.\n");
    5851              : 
    5852        20145 :       gimple_seq stmts = NULL;
    5853        20145 :       vec_elem_type = TREE_TYPE (vectype);
    5854        20145 :       new_temp = gimple_build (&stmts, as_combined_fn (reduc_fn),
    5855        20145 :                                vec_elem_type, reduc_inputs[0]);
    5856        20145 :       new_temp = gimple_convert (&stmts, scalar_type, new_temp);
    5857        20145 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5858              : 
    5859        20145 :       if ((VECT_REDUC_INFO_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
    5860           62 :           && induc_val)
    5861              :         {
    5862              :           /* Earlier we set the initial value to be a vector if induc_val
    5863              :              values.  Check the result and if it is induc_val then replace
    5864              :              with the original initial value, unless induc_val is
    5865              :              the same as initial_def already.  */
    5866           60 :           tree zcompare = make_ssa_name (boolean_type_node);
    5867           60 :           epilog_stmt = gimple_build_assign (zcompare, EQ_EXPR,
    5868              :                                              new_temp, induc_val);
    5869           60 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5870           60 :           tree initial_def = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info)[0];
    5871           60 :           tmp = make_ssa_name (new_scalar_dest);
    5872           60 :           epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
    5873              :                                              initial_def, new_temp);
    5874           60 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5875           60 :           new_temp = tmp;
    5876              :         }
    5877              : 
    5878        20145 :       scalar_results.safe_push (new_temp);
    5879        20145 :     }
    5880         1797 :   else if (direct_slp_reduc)
    5881              :     {
    5882              :       /* Here we create one vector for each of the GROUP_SIZE results,
    5883              :          with the elements for other SLP statements replaced with the
    5884              :          neutral value.  We can then do a normal reduction on each vector.  */
    5885              : 
    5886              :       /* Enforced by vectorizable_reduction.  */
    5887              :       gcc_assert (reduc_inputs.length () == 1);
    5888              :       gcc_assert (pow2p_hwi (group_size));
    5889              : 
    5890              :       gimple_seq seq = NULL;
    5891              : 
    5892              :       /* Build a vector {0, 1, 2, ...}, with the same number of elements
    5893              :          and the same element size as VECTYPE.  */
    5894              :       tree index = build_index_vector (vectype, 0, 1);
    5895              :       tree index_type = TREE_TYPE (index);
    5896              :       tree index_elt_type = TREE_TYPE (index_type);
    5897              :       tree mask_type = truth_type_for (index_type);
    5898              : 
    5899              :       /* Create a vector that, for each element, identifies which of
    5900              :          the results should use it.  */
    5901              :       tree index_mask = build_int_cst (index_elt_type, group_size - 1);
    5902              :       index = gimple_build (&seq, BIT_AND_EXPR, index_type, index,
    5903              :                             build_vector_from_val (index_type, index_mask));
    5904              : 
    5905              :       /* Get a neutral vector value.  This is simply a splat of the neutral
    5906              :          scalar value if we have one, otherwise the initial scalar value
    5907              :          is itself a neutral value.  */
    5908              :       tree vector_identity = NULL_TREE;
    5909              :       tree neutral_op = neutral_op_for_reduction (TREE_TYPE (vectype), code,
    5910              :                                                   NULL_TREE, false);
    5911              :       if (neutral_op)
    5912              :         vector_identity = gimple_build_vector_from_val (&seq, vectype,
    5913              :                                                         neutral_op);
    5914              :       for (unsigned int i = 0; i < group_size; ++i)
    5915              :         {
    5916              :           /* If there's no universal neutral value, we can use the
    5917              :              initial scalar value from the original PHI.  This is used
    5918              :              for MIN and MAX reduction, for example.  */
    5919              :           if (!neutral_op)
    5920              :             {
    5921              :               tree scalar_value
    5922              :                 = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info)[i];
    5923              :               scalar_value = gimple_convert (&seq, TREE_TYPE (vectype),
    5924              :                                              scalar_value);
    5925              :               vector_identity = gimple_build_vector_from_val (&seq, vectype,
    5926              :                                                               scalar_value);
    5927              :             }
    5928              : 
    5929              :           /* Calculate the equivalent of:
    5930              : 
    5931              :              sel[j] = (index[j] == i);
    5932              : 
    5933              :              which selects the elements of REDUC_INPUTS[0] that should
    5934              :              be included in the result.  */
    5935              :           tree compare_val = build_int_cst (index_elt_type, i);
    5936              :           compare_val = build_vector_from_val (index_type, compare_val);
    5937              :           tree sel = gimple_build (&seq, EQ_EXPR, mask_type,
    5938              :                                    index, compare_val);
    5939              : 
    5940              :           /* Calculate the equivalent of:
    5941              : 
    5942              :              vec = seq ? reduc_inputs[0] : vector_identity;
    5943              : 
    5944              :              VEC is now suitable for a full vector reduction.  */
    5945              :           tree vec = gimple_build (&seq, VEC_COND_EXPR, vectype,
    5946              :                                    sel, reduc_inputs[0], vector_identity);
    5947              : 
    5948              :           /* Do the reduction and convert it to the appropriate type.  */
    5949              :           tree scalar = gimple_build (&seq, as_combined_fn (reduc_fn),
    5950              :                                       TREE_TYPE (vectype), vec);
    5951              :           scalar = gimple_convert (&seq, scalar_type, scalar);
    5952              :           scalar_results.safe_push (scalar);
    5953              :         }
    5954              :       gsi_insert_seq_before (&exit_gsi, seq, GSI_SAME_STMT);
    5955              :     }
    5956              :   else
    5957              :     {
    5958         1797 :       bool reduce_with_shift;
    5959         1797 :       tree vec_temp;
    5960              : 
    5961         1797 :       gcc_assert (slp_reduc || reduc_inputs.length () == 1);
    5962              : 
    5963              :       /* See if the target wants to do the final (shift) reduction
    5964              :          in a vector mode of smaller size and first reduce upper/lower
    5965              :          halves against each other.  */
    5966         1984 :       enum machine_mode mode1 = mode;
    5967         1984 :       tree stype = TREE_TYPE (vectype);
    5968         1984 :       if (compute_vectype != vectype)
    5969              :         {
    5970          547 :           stype = unsigned_type_for (stype);
    5971          547 :           gimple_seq stmts = NULL;
    5972         1152 :           for (unsigned i = 0; i < reduc_inputs.length (); ++i)
    5973              :             {
    5974          605 :               tree new_temp = gimple_build (&stmts, VIEW_CONVERT_EXPR,
    5975          605 :                                             compute_vectype, reduc_inputs[i]);
    5976          605 :               reduc_inputs[i] = new_temp;
    5977              :             }
    5978          547 :           gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5979              :         }
    5980         1984 :       unsigned nunits = TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
    5981         1984 :       unsigned nunits1 = nunits;
    5982         1984 :       if ((mode1 = targetm.vectorize.split_reduction (mode)) != mode
    5983         1984 :           && reduc_inputs.length () == 1)
    5984              :         {
    5985           41 :           nunits1 = GET_MODE_NUNITS (mode1).to_constant ();
    5986              :           /* For SLP reductions we have to make sure lanes match up, but
    5987              :              since we're doing individual element final reduction reducing
    5988              :              vector width here is even more important.
    5989              :              ???  We can also separate lanes with permutes, for the common
    5990              :              case of power-of-two group-size odd/even extracts would work.  */
    5991           41 :           if (slp_reduc && nunits != nunits1)
    5992              :             {
    5993           41 :               nunits1 = least_common_multiple (nunits1, group_size);
    5994           82 :               gcc_assert (exact_log2 (nunits1) != -1 && nunits1 <= nunits);
    5995              :             }
    5996              :         }
    5997         1943 :       else if (!slp_reduc
    5998         1943 :                && (mode1 = targetm.vectorize.split_reduction (mode)) != mode)
    5999            0 :         nunits1 = GET_MODE_NUNITS (mode1).to_constant ();
    6000              : 
    6001         1984 :       tree vectype1 = compute_vectype;
    6002         1984 :       if (mode1 != mode)
    6003              :         {
    6004           47 :           vectype1 = get_related_vectype_for_scalar_type (TYPE_MODE (vectype),
    6005           47 :                                                           stype, nunits1);
    6006              :           /* First reduce the vector to the desired vector size we should
    6007              :              do shift reduction on by combining upper and lower halves.  */
    6008           47 :           gimple_seq stmts = NULL;
    6009           47 :           new_temp = vect_create_partial_epilog (reduc_inputs[0], vectype1,
    6010              :                                                  code, &stmts);
    6011           47 :           gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    6012           47 :           reduc_inputs[0] = new_temp;
    6013              :         }
    6014              : 
    6015         1984 :       reduce_with_shift = have_whole_vector_shift (mode1);
    6016          747 :       if (!VECTOR_MODE_P (mode1)
    6017         2729 :           || !directly_supported_p (code, vectype1))
    6018              :         reduce_with_shift = false;
    6019              : 
    6020         1967 :       if (reduce_with_shift && (!slp_reduc || group_size == 1))
    6021              :         {
    6022         1733 :           int element_bitsize = vector_element_bits (vectype1);
    6023              :           /* Enforced by vectorizable_reduction, which disallows SLP reductions
    6024              :              for variable-length vectors and also requires direct target support
    6025              :              for loop reductions.  */
    6026         1733 :           int nelements = TYPE_VECTOR_SUBPARTS (vectype1).to_constant ();
    6027         1733 :           vec_perm_builder sel;
    6028         1733 :           vec_perm_indices indices;
    6029              : 
    6030         1733 :           int elt_offset;
    6031              : 
    6032         1733 :           tree zero_vec = build_zero_cst (vectype1);
    6033              :           /* Case 2: Create:
    6034              :              for (offset = nelements/2; offset >= 1; offset/=2)
    6035              :                 {
    6036              :                   Create:  va' = vec_shift <va, offset>
    6037              :                   Create:  va = vop <va, va'>
    6038              :                 }  */
    6039              : 
    6040         1733 :           if (dump_enabled_p ())
    6041          380 :             dump_printf_loc (MSG_NOTE, vect_location,
    6042              :                              "Reduce using vector shifts\n");
    6043              : 
    6044         1733 :           gimple_seq stmts = NULL;
    6045         1733 :           new_temp = gimple_convert (&stmts, vectype1, reduc_inputs[0]);
    6046         1733 :           for (elt_offset = nelements / 2;
    6047         3772 :                elt_offset >= 1;
    6048         2039 :                elt_offset /= 2)
    6049              :             {
    6050         2039 :               calc_vec_perm_mask_for_shift (elt_offset, nelements, &sel);
    6051         2039 :               indices.new_vector (sel, 2, nelements);
    6052         2039 :               tree mask = vect_gen_perm_mask_any (vectype1, indices);
    6053         2039 :               new_name = gimple_build (&stmts, VEC_PERM_EXPR, vectype1,
    6054              :                                        new_temp, zero_vec, mask);
    6055         2039 :               new_temp = gimple_build (&stmts, code,
    6056              :                                        vectype1, new_name, new_temp);
    6057              :             }
    6058              : 
    6059              :           /* 2.4  Extract the final scalar result.  Create:
    6060              :              s_out3 = extract_field <v_out2, bitpos>  */
    6061              : 
    6062         1733 :           if (dump_enabled_p ())
    6063          380 :             dump_printf_loc (MSG_NOTE, vect_location,
    6064              :                              "extract scalar result\n");
    6065              : 
    6066         1733 :           new_temp = gimple_build (&stmts, BIT_FIELD_REF, TREE_TYPE (vectype1),
    6067         1733 :                                    new_temp, bitsize_int (element_bitsize),
    6068         1733 :                                    bitsize_zero_node);
    6069         1733 :           new_temp = gimple_convert (&stmts, scalar_type, new_temp);
    6070         1733 :           gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    6071         1733 :           scalar_results.safe_push (new_temp);
    6072         1733 :         }
    6073              :       else
    6074              :         {
    6075              :           /* Case 3: Create:
    6076              :              s = extract_field <v_out2, 0>
    6077              :              for (offset = element_size;
    6078              :                   offset < vector_size;
    6079              :                   offset += element_size;)
    6080              :                {
    6081              :                  Create:  s' = extract_field <v_out2, offset>
    6082              :                  Create:  s = op <s, s'>  // For non SLP cases
    6083              :                }  */
    6084              : 
    6085          251 :           if (dump_enabled_p ())
    6086          143 :             dump_printf_loc (MSG_NOTE, vect_location,
    6087              :                              "Reduce using scalar code.\n");
    6088              : 
    6089          251 :           tree compute_type = TREE_TYPE (vectype1);
    6090          251 :           unsigned element_bitsize = vector_element_bits (vectype1);
    6091          251 :           unsigned vec_size_in_bits = element_bitsize
    6092          251 :             * TYPE_VECTOR_SUBPARTS (vectype1).to_constant ();
    6093          251 :           tree bitsize = bitsize_int (element_bitsize);
    6094          251 :           gimple_seq stmts = NULL;
    6095          657 :           FOR_EACH_VEC_ELT (reduc_inputs, i, vec_temp)
    6096              :             {
    6097          406 :               unsigned bit_offset;
    6098          812 :               new_temp = gimple_build (&stmts, BIT_FIELD_REF, compute_type,
    6099          406 :                                        vec_temp, bitsize, bitsize_zero_node);
    6100              : 
    6101              :               /* In SLP we don't need to apply reduction operation, so we just
    6102              :                  collect s' values in SCALAR_RESULTS.  */
    6103          406 :               if (slp_reduc)
    6104          396 :                 scalar_results.safe_push (new_temp);
    6105              : 
    6106          406 :               for (bit_offset = element_bitsize;
    6107         1366 :                    bit_offset < vec_size_in_bits;
    6108          960 :                    bit_offset += element_bitsize)
    6109              :                 {
    6110          960 :                   tree bitpos = bitsize_int (bit_offset);
    6111          960 :                   new_name = gimple_build (&stmts, BIT_FIELD_REF,
    6112              :                                            compute_type, vec_temp,
    6113              :                                            bitsize, bitpos);
    6114          960 :                   if (slp_reduc)
    6115              :                     {
    6116              :                       /* In SLP we don't need to apply reduction operation, so
    6117              :                          we just collect s' values in SCALAR_RESULTS.  */
    6118          950 :                       new_temp = new_name;
    6119          950 :                       scalar_results.safe_push (new_name);
    6120              :                     }
    6121              :                   else
    6122           10 :                     new_temp = gimple_build (&stmts, code, compute_type,
    6123              :                                              new_name, new_temp);
    6124              :                 }
    6125              :             }
    6126              : 
    6127              :           /* The only case where we need to reduce scalar results in a SLP
    6128              :              reduction, is unrolling.  If the size of SCALAR_RESULTS is
    6129              :              greater than GROUP_SIZE, we reduce them combining elements modulo
    6130              :              GROUP_SIZE.  */
    6131          251 :           if (slp_reduc)
    6132              :             {
    6133          241 :               tree res, first_res, new_res;
    6134              : 
    6135              :               /* Reduce multiple scalar results in case of SLP unrolling.  */
    6136          881 :               for (j = group_size; scalar_results.iterate (j, &res);
    6137              :                    j++)
    6138              :                 {
    6139          640 :                   first_res = scalar_results[j % group_size];
    6140          640 :                   new_res = gimple_build (&stmts, code, compute_type,
    6141              :                                           first_res, res);
    6142          640 :                   scalar_results[j % group_size] = new_res;
    6143              :                 }
    6144          241 :               scalar_results.truncate (group_size);
    6145         1188 :               for (k = 0; k < group_size; k++)
    6146         1412 :                 scalar_results[k] = gimple_convert (&stmts, scalar_type,
    6147          706 :                                                     scalar_results[k]);
    6148              :             }
    6149              :           else
    6150              :             {
    6151              :               /* Reduction chain - we have one scalar to keep in
    6152              :                  SCALAR_RESULTS.  */
    6153           10 :               new_temp = gimple_convert (&stmts, scalar_type, new_temp);
    6154           10 :               scalar_results.safe_push (new_temp);
    6155              :             }
    6156              : 
    6157          251 :           gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    6158              :         }
    6159              : 
    6160         1984 :       if ((VECT_REDUC_INFO_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
    6161            0 :           && induc_val)
    6162              :         {
    6163              :           /* Earlier we set the initial value to be a vector if induc_val
    6164              :              values.  Check the result and if it is induc_val then replace
    6165              :              with the original initial value, unless induc_val is
    6166              :              the same as initial_def already.  */
    6167            0 :           tree zcompare = make_ssa_name (boolean_type_node);
    6168            0 :           epilog_stmt = gimple_build_assign (zcompare, EQ_EXPR,
    6169            0 :                                              scalar_results[0], induc_val);
    6170            0 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    6171            0 :           tree initial_def = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info)[0];
    6172            0 :           tree tmp = make_ssa_name (new_scalar_dest);
    6173            0 :           epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
    6174            0 :                                              initial_def, scalar_results[0]);
    6175            0 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    6176            0 :           scalar_results[0] = tmp;
    6177              :         }
    6178              :     }
    6179              : 
    6180              :   /* 2.5 Adjust the final result by the initial value of the reduction
    6181              :          variable. (When such adjustment is not needed, then
    6182              :          'adjustment_def' is zero).  For example, if code is PLUS we create:
    6183              :          new_temp = loop_exit_def + adjustment_def  */
    6184              : 
    6185        22216 :   if (adjustment_def)
    6186              :     {
    6187        15736 :       gcc_assert (!slp_reduc || group_size == 1);
    6188        15736 :       gimple_seq stmts = NULL;
    6189        15736 :       if (double_reduc)
    6190              :         {
    6191            0 :           gcc_assert (VECTOR_TYPE_P (TREE_TYPE (adjustment_def)));
    6192            0 :           adjustment_def = gimple_convert (&stmts, vectype, adjustment_def);
    6193            0 :           new_temp = gimple_build (&stmts, code, vectype,
    6194            0 :                                    reduc_inputs[0], adjustment_def);
    6195              :         }
    6196              :       else
    6197              :         {
    6198        15736 :           new_temp = scalar_results[0];
    6199        15736 :           gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) != VECTOR_TYPE);
    6200        15736 :           adjustment_def = gimple_convert (&stmts, TREE_TYPE (compute_vectype),
    6201              :                                            adjustment_def);
    6202        15736 :           new_temp = gimple_convert (&stmts, TREE_TYPE (compute_vectype),
    6203              :                                      new_temp);
    6204        15736 :           new_temp = gimple_build (&stmts, code, TREE_TYPE (compute_vectype),
    6205              :                                    new_temp, adjustment_def);
    6206        15736 :           new_temp = gimple_convert (&stmts, scalar_type, new_temp);
    6207              :         }
    6208              : 
    6209        15736 :       epilog_stmt = gimple_seq_last_stmt (stmts);
    6210        15736 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    6211        15736 :       scalar_results[0] = new_temp;
    6212              :     }
    6213              : 
    6214              :   /* Record this operation if it could be reused by the epilogue loop.  */
    6215        22216 :   if (VECT_REDUC_INFO_TYPE (reduc_info) == TREE_CODE_REDUCTION
    6216        22216 :       && reduc_inputs.length () == 1)
    6217        22011 :     loop_vinfo->reusable_accumulators.put (scalar_results[0],
    6218              :                                            { orig_reduc_input, reduc_info });
    6219              : 
    6220              :   /* 2.6  Handle the loop-exit phis.  Replace the uses of scalar loop-exit
    6221              :           phis with new adjusted scalar results, i.e., replace use <s_out0>
    6222              :           with use <s_out4>.
    6223              : 
    6224              :      Transform:
    6225              :         loop_exit:
    6226              :           s_out0 = phi <s_loop>                 # (scalar) EXIT_PHI
    6227              :           v_out1 = phi <VECT_DEF>               # NEW_EXIT_PHI
    6228              :           v_out2 = reduce <v_out1>
    6229              :           s_out3 = extract_field <v_out2, 0>
    6230              :           s_out4 = adjust_result <s_out3>
    6231              :           use <s_out0>
    6232              :           use <s_out0>
    6233              : 
    6234              :      into:
    6235              : 
    6236              :         loop_exit:
    6237              :           s_out0 = phi <s_loop>                 # (scalar) EXIT_PHI
    6238              :           v_out1 = phi <VECT_DEF>               # NEW_EXIT_PHI
    6239              :           v_out2 = reduce <v_out1>
    6240              :           s_out3 = extract_field <v_out2, 0>
    6241              :           s_out4 = adjust_result <s_out3>
    6242              :           use <s_out4>
    6243              :           use <s_out4> */
    6244              : 
    6245        44432 :   gcc_assert (live_out_stmts.size () == scalar_results.length ());
    6246        22216 :   auto_vec<gimple *> phis;
    6247        44897 :   for (k = 0; k < live_out_stmts.size (); k++)
    6248              :     {
    6249        22681 :       stmt_vec_info scalar_stmt_info = vect_orig_stmt (live_out_stmts[k]);
    6250        22681 :       tree scalar_dest = gimple_get_lhs (scalar_stmt_info->stmt);
    6251              : 
    6252              :       /* Find the loop-closed-use at the loop exit of the original scalar
    6253              :          result.  (The reduction result is expected to have two immediate uses,
    6254              :          one at the latch block, and one at the loop exit).  Note with
    6255              :          early break we can have two exit blocks, so pick the correct PHI.  */
    6256        92203 :       FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
    6257        69522 :         if (!is_gimple_debug (USE_STMT (use_p))
    6258        69522 :             && !flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
    6259              :           {
    6260        22674 :             gcc_assert (is_a <gphi *> (USE_STMT (use_p)));
    6261        22674 :             if (gimple_bb (USE_STMT (use_p)) == loop_exit->dest)
    6262        22666 :               phis.safe_push (USE_STMT (use_p));
    6263        22681 :           }
    6264              : 
    6265        45347 :       FOR_EACH_VEC_ELT (phis, i, exit_phi)
    6266              :         {
    6267              :           /* Replace the uses:  */
    6268        22666 :           orig_name = PHI_RESULT (exit_phi);
    6269              : 
    6270              :           /* Look for a single use at the target of the skip edge.  */
    6271        22666 :           if (unify_with_main_loop_p)
    6272              :             {
    6273           30 :               use_operand_p use_p;
    6274           30 :               gimple *user;
    6275           30 :               if (!single_imm_use (orig_name, &use_p, &user))
    6276            0 :                 gcc_unreachable ();
    6277           30 :               orig_name = gimple_get_lhs (user);
    6278              :             }
    6279              : 
    6280        22666 :           scalar_result = scalar_results[k];
    6281        61340 :           FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
    6282              :             {
    6283        38674 :               gphi *use_phi = dyn_cast <gphi *> (use_stmt);
    6284        77392 :               FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
    6285              :                 {
    6286        38696 :                   if (use_phi
    6287        38696 :                       && (phi_arg_edge_from_use (use_p)->flags & EDGE_ABNORMAL))
    6288              :                     {
    6289            0 :                       gcc_assert (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig_name));
    6290            0 :                       SSA_NAME_OCCURS_IN_ABNORMAL_PHI (scalar_result) = 1;
    6291              :                     }
    6292        38696 :                   SET_USE (use_p, scalar_result);
    6293              :                 }
    6294        38674 :               update_stmt (use_stmt);
    6295        22666 :             }
    6296              :         }
    6297              : 
    6298        22681 :       phis.truncate (0);
    6299              :     }
    6300        22216 : }
    6301              : 
    6302              : /* Return a vector of type VECTYPE that is equal to the vector select
    6303              :    operation "MASK ? VEC : IDENTITY".  Insert the select statements
    6304              :    before GSI.  */
    6305              : 
    6306              : static tree
    6307            9 : merge_with_identity (gimple_stmt_iterator *gsi, tree mask, tree vectype,
    6308              :                      tree vec, tree identity)
    6309              : {
    6310            9 :   tree cond = make_temp_ssa_name (vectype, NULL, "cond");
    6311            9 :   gimple *new_stmt = gimple_build_assign (cond, VEC_COND_EXPR,
    6312              :                                           mask, vec, identity);
    6313            9 :   gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
    6314            9 :   return cond;
    6315              : }
    6316              : 
    6317              : /* Successively apply CODE to each element of VECTOR_RHS, in left-to-right
    6318              :    order, starting with LHS.  Insert the extraction statements before GSI and
    6319              :    associate the new scalar SSA names with variable SCALAR_DEST.
    6320              :    If MASK is nonzero mask the input and then operate on it unconditionally.
    6321              :    Return the SSA name for the result.  */
    6322              : 
    6323              : static tree
    6324         1256 : vect_expand_fold_left (gimple_stmt_iterator *gsi, tree scalar_dest,
    6325              :                        tree_code code, tree lhs, tree vector_rhs,
    6326              :                        tree mask)
    6327              : {
    6328         1256 :   tree vectype = TREE_TYPE (vector_rhs);
    6329         1256 :   tree scalar_type = TREE_TYPE (vectype);
    6330         1256 :   tree bitsize = TYPE_SIZE (scalar_type);
    6331         1256 :   unsigned HOST_WIDE_INT vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
    6332         1256 :   unsigned HOST_WIDE_INT element_bitsize = tree_to_uhwi (bitsize);
    6333              : 
    6334              :   /* Re-create a VEC_COND_EXPR to mask the input here in order to be able
    6335              :      to perform an unconditional element-wise reduction of it.  */
    6336         1256 :   if (mask)
    6337              :     {
    6338           76 :       tree masked_vector_rhs = make_temp_ssa_name (vectype, NULL,
    6339              :                                                    "masked_vector_rhs");
    6340           76 :       tree neutral_op = neutral_op_for_reduction (scalar_type, code, NULL_TREE,
    6341              :                                                   false);
    6342           76 :       tree vector_identity = build_vector_from_val (vectype, neutral_op);
    6343           76 :       gassign *select = gimple_build_assign (masked_vector_rhs, VEC_COND_EXPR,
    6344              :                                              mask, vector_rhs, vector_identity);
    6345           76 :       gsi_insert_before (gsi, select, GSI_SAME_STMT);
    6346           76 :       vector_rhs = masked_vector_rhs;
    6347              :     }
    6348              : 
    6349         1256 :   for (unsigned HOST_WIDE_INT bit_offset = 0;
    6350         5190 :        bit_offset < vec_size_in_bits;
    6351         3934 :        bit_offset += element_bitsize)
    6352              :     {
    6353         3934 :       tree bitpos = bitsize_int (bit_offset);
    6354         3934 :       tree rhs = build3 (BIT_FIELD_REF, scalar_type, vector_rhs,
    6355              :                          bitsize, bitpos);
    6356              : 
    6357         3934 :       gassign *stmt = gimple_build_assign (scalar_dest, rhs);
    6358         3934 :       rhs = make_ssa_name (scalar_dest, stmt);
    6359         3934 :       gimple_assign_set_lhs (stmt, rhs);
    6360         3934 :       gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
    6361              :       /* Fold the vector extract, combining it with a previous reversal
    6362              :          like seen in PR90579.  */
    6363         3934 :       auto gsi2 = gsi_for_stmt (stmt);
    6364         3934 :       if (fold_stmt (&gsi2, follow_all_ssa_edges))
    6365          450 :         update_stmt (gsi_stmt  (gsi2));
    6366              : 
    6367         3934 :       stmt = gimple_build_assign (scalar_dest, code, lhs, rhs);
    6368         3934 :       tree new_name = make_ssa_name (scalar_dest, stmt);
    6369         3934 :       gimple_assign_set_lhs (stmt, new_name);
    6370         3934 :       gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
    6371         3934 :       lhs = new_name;
    6372              :     }
    6373         1256 :   return lhs;
    6374              : }
    6375              : 
    6376              : /* Get a masked internal function equivalent to REDUC_FN.  VECTYPE_IN is the
    6377              :    type of the vector input.  */
    6378              : 
    6379              : static internal_fn
    6380         3057 : get_masked_reduction_fn (internal_fn reduc_fn, tree vectype_in)
    6381              : {
    6382         3057 :   internal_fn mask_reduc_fn;
    6383         3057 :   internal_fn mask_len_reduc_fn;
    6384              : 
    6385         3057 :   switch (reduc_fn)
    6386              :     {
    6387            0 :     case IFN_FOLD_LEFT_PLUS:
    6388            0 :       mask_reduc_fn = IFN_MASK_FOLD_LEFT_PLUS;
    6389            0 :       mask_len_reduc_fn = IFN_MASK_LEN_FOLD_LEFT_PLUS;
    6390            0 :       break;
    6391              : 
    6392              :     default:
    6393              :       return IFN_LAST;
    6394              :     }
    6395              : 
    6396            0 :   if (direct_internal_fn_supported_p (mask_reduc_fn, vectype_in,
    6397              :                                       OPTIMIZE_FOR_SPEED))
    6398              :     return mask_reduc_fn;
    6399            0 :   if (direct_internal_fn_supported_p (mask_len_reduc_fn, vectype_in,
    6400              :                                       OPTIMIZE_FOR_SPEED))
    6401            0 :     return mask_len_reduc_fn;
    6402              :   return IFN_LAST;
    6403              : }
    6404              : 
    6405              : /* Perform an in-order reduction (FOLD_LEFT_REDUCTION).  STMT_INFO is the
    6406              :    statement that sets the live-out value.  REDUC_DEF_STMT is the phi
    6407              :    statement.  CODE is the operation performed by STMT_INFO and OPS are
    6408              :    its scalar operands.  REDUC_INDEX is the index of the operand in
    6409              :    OPS that is set by REDUC_DEF_STMT.  REDUC_FN is the function that
    6410              :    implements in-order reduction, or IFN_LAST if we should open-code it.
    6411              :    VECTYPE_IN is the type of the vector input.  MASKS specifies the masks
    6412              :    that should be used to control the operation in a fully-masked loop.  */
    6413              : 
    6414              : static bool
    6415          927 : vectorize_fold_left_reduction (loop_vec_info loop_vinfo,
    6416              :                                stmt_vec_info stmt_info,
    6417              :                                gimple_stmt_iterator *gsi,
    6418              :                                slp_tree slp_node,
    6419              :                                code_helper code, internal_fn reduc_fn,
    6420              :                                int num_ops, tree vectype_in,
    6421              :                                int reduc_index, vec_loop_masks *masks,
    6422              :                                vec_loop_lens *lens)
    6423              : {
    6424          927 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    6425          927 :   tree vectype_out = SLP_TREE_VECTYPE (slp_node);
    6426          927 :   internal_fn mask_reduc_fn = get_masked_reduction_fn (reduc_fn, vectype_in);
    6427              : 
    6428          927 :   gcc_assert (!nested_in_vect_loop_p (loop, stmt_info));
    6429              : 
    6430          927 :   bool is_cond_op = false;
    6431          927 :   if (!code.is_tree_code ())
    6432              :     {
    6433           29 :       code = conditional_internal_fn_code (internal_fn (code));
    6434           29 :       gcc_assert (code != ERROR_MARK);
    6435              :       is_cond_op = true;
    6436              :     }
    6437              : 
    6438          927 :   gcc_assert (TREE_CODE_LENGTH (tree_code (code)) == binary_op);
    6439              : 
    6440          927 :   gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (vectype_out),
    6441              :                         TYPE_VECTOR_SUBPARTS (vectype_in)));
    6442              : 
    6443              :   /* ???  We should, when transforming the cycle PHI, record the existing
    6444              :      scalar def as vector def so looking up the vector def works.  This
    6445              :      would also allow generalizing this for reduction paths of length > 1
    6446              :      and/or SLP reductions.  */
    6447          927 :   slp_tree reduc_node = SLP_TREE_CHILDREN (slp_node)[reduc_index];
    6448          927 :   stmt_vec_info reduc_var_def = SLP_TREE_SCALAR_STMTS (reduc_node)[0];
    6449          927 :   tree reduc_var = gimple_get_lhs (STMT_VINFO_STMT (reduc_var_def));
    6450              : 
    6451              :   /* The operands either come from a binary operation or an IFN_COND operation.
    6452              :      The former is a gimple assign with binary rhs and the latter is a
    6453              :      gimple call with four arguments.  */
    6454          927 :   gcc_assert (num_ops == 2 || num_ops == 4);
    6455              : 
    6456          927 :   auto_vec<tree> vec_oprnds0, vec_opmask;
    6457          927 :   vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[(is_cond_op ? 2 : 0)
    6458          927 :                                                   + (1 - reduc_index)],
    6459              :                                                   &vec_oprnds0);
    6460              :   /* For an IFN_COND_OP we also need the vector mask operand.  */
    6461          927 :   if (is_cond_op)
    6462           29 :     vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[0], &vec_opmask);
    6463              : 
    6464              :   /* The transform below relies on preserving the original scalar PHI
    6465              :      and its latch def which we replace.  So work backwards from there.  */
    6466          927 :   tree scalar_dest
    6467          927 :     = gimple_phi_arg_def_from_edge (as_a <gphi *> (STMT_VINFO_STMT
    6468              :                                                      (reduc_var_def)),
    6469          927 :                                     loop_latch_edge (loop));
    6470          927 :   stmt_vec_info scalar_dest_def_info
    6471          927 :     = vect_stmt_to_vectorize (loop_vinfo->lookup_def (scalar_dest));
    6472          927 :   tree scalar_type = TREE_TYPE (scalar_dest);
    6473              : 
    6474          927 :   int vec_num = vec_oprnds0.length ();
    6475          927 :   tree vec_elem_type = TREE_TYPE (vectype_out);
    6476          927 :   gcc_checking_assert (useless_type_conversion_p (scalar_type, vec_elem_type));
    6477              : 
    6478          927 :   tree vector_identity = NULL_TREE;
    6479          927 :   if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
    6480              :     {
    6481            2 :       vector_identity = build_zero_cst (vectype_out);
    6482            2 :       if (!HONOR_SIGNED_ZEROS (vectype_out))
    6483              :         ;
    6484              :       else
    6485              :         {
    6486            2 :           gcc_assert (!HONOR_SIGN_DEPENDENT_ROUNDING (vectype_out));
    6487            2 :           vector_identity = const_unop (NEGATE_EXPR, vectype_out,
    6488              :                                         vector_identity);
    6489              :         }
    6490              :     }
    6491              : 
    6492          927 :   tree scalar_dest_var = vect_create_destination_var (scalar_dest, NULL);
    6493          927 :   int i;
    6494          927 :   tree def0;
    6495         3110 :   FOR_EACH_VEC_ELT (vec_oprnds0, i, def0)
    6496              :     {
    6497         1256 :       gimple *new_stmt;
    6498         1256 :       tree mask = NULL_TREE;
    6499         1256 :       tree len = NULL_TREE;
    6500         1256 :       tree bias = NULL_TREE;
    6501         1256 :       if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
    6502              :         {
    6503            9 :           tree loop_mask = vect_get_loop_mask (loop_vinfo, gsi, masks,
    6504              :                                                vec_num, vectype_in, i);
    6505            9 :           if (is_cond_op)
    6506            9 :             mask = prepare_vec_mask (loop_vinfo, TREE_TYPE (loop_mask),
    6507            9 :                                      loop_mask, vec_opmask[i], gsi);
    6508              :           else
    6509              :             mask = loop_mask;
    6510              :         }
    6511         1247 :       else if (is_cond_op)
    6512           67 :         mask = vec_opmask[i];
    6513         1256 :       if (LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
    6514              :         {
    6515            0 :           len = vect_get_loop_len (loop_vinfo, gsi, lens, vec_num, vectype_in,
    6516              :                                    i, 1, false);
    6517            0 :           signed char biasval = LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo);
    6518            0 :           bias = build_int_cst (intQI_type_node, biasval);
    6519            0 :           if (!is_cond_op)
    6520            0 :             mask = build_minus_one_cst (truth_type_for (vectype_in));
    6521              :         }
    6522              : 
    6523              :       /* Handle MINUS by adding the negative.  */
    6524         1256 :       if (reduc_fn != IFN_LAST && code == MINUS_EXPR)
    6525              :         {
    6526            0 :           tree negated = make_ssa_name (vectype_out);
    6527            0 :           new_stmt = gimple_build_assign (negated, NEGATE_EXPR, def0);
    6528            0 :           gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
    6529            0 :           def0 = negated;
    6530              :         }
    6531              : 
    6532            9 :       if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
    6533         1265 :           && mask && mask_reduc_fn == IFN_LAST)
    6534            9 :         def0 = merge_with_identity (gsi, mask, vectype_out, def0,
    6535              :                                     vector_identity);
    6536              : 
    6537              :       /* On the first iteration the input is simply the scalar phi
    6538              :          result, and for subsequent iterations it is the output of
    6539              :          the preceding operation.  */
    6540         1256 :       if (reduc_fn != IFN_LAST || (mask && mask_reduc_fn != IFN_LAST))
    6541              :         {
    6542            0 :           if (mask && len && mask_reduc_fn == IFN_MASK_LEN_FOLD_LEFT_PLUS)
    6543            0 :             new_stmt = gimple_build_call_internal (mask_reduc_fn, 5, reduc_var,
    6544              :                                                    def0, mask, len, bias);
    6545            0 :           else if (mask && mask_reduc_fn == IFN_MASK_FOLD_LEFT_PLUS)
    6546            0 :             new_stmt = gimple_build_call_internal (mask_reduc_fn, 3, reduc_var,
    6547              :                                                    def0, mask);
    6548              :           else
    6549            0 :             new_stmt = gimple_build_call_internal (reduc_fn, 2, reduc_var,
    6550              :                                                    def0);
    6551              :           /* For chained SLP reductions the output of the previous reduction
    6552              :              operation serves as the input of the next. For the final statement
    6553              :              the output cannot be a temporary - we reuse the original
    6554              :              scalar destination of the last statement.  */
    6555            0 :           if (i != vec_num - 1)
    6556              :             {
    6557            0 :               gimple_set_lhs (new_stmt, scalar_dest_var);
    6558            0 :               reduc_var = make_ssa_name (scalar_dest_var, new_stmt);
    6559            0 :               gimple_set_lhs (new_stmt, reduc_var);
    6560              :             }
    6561              :         }
    6562              :       else
    6563              :         {
    6564         1256 :           reduc_var = vect_expand_fold_left (gsi, scalar_dest_var,
    6565              :                                              tree_code (code), reduc_var, def0,
    6566              :                                              mask);
    6567         1256 :           new_stmt = SSA_NAME_DEF_STMT (reduc_var);
    6568              :           /* Remove the statement, so that we can use the same code paths
    6569              :              as for statements that we've just created.  */
    6570         1256 :           gimple_stmt_iterator tmp_gsi = gsi_for_stmt (new_stmt);
    6571         1256 :           gsi_remove (&tmp_gsi, true);
    6572              :         }
    6573              : 
    6574         1256 :       if (i == vec_num - 1)
    6575              :         {
    6576          927 :           gimple_set_lhs (new_stmt, scalar_dest);
    6577          927 :           vect_finish_replace_stmt (loop_vinfo,
    6578              :                                     scalar_dest_def_info,
    6579              :                                     new_stmt);
    6580              :         }
    6581              :       else
    6582          329 :         vect_finish_stmt_generation (loop_vinfo,
    6583              :                                      scalar_dest_def_info,
    6584              :                                      new_stmt, gsi);
    6585              : 
    6586         1256 :       slp_node->push_vec_def (new_stmt);
    6587              :     }
    6588              : 
    6589          927 :   return true;
    6590          927 : }
    6591              : 
    6592              : /* Function is_nonwrapping_integer_induction.
    6593              : 
    6594              :    Check if STMT_VINO (which is part of loop LOOP) both increments and
    6595              :    does not cause overflow.  */
    6596              : 
    6597              : static bool
    6598          408 : is_nonwrapping_integer_induction (stmt_vec_info stmt_vinfo, class loop *loop)
    6599              : {
    6600          408 :   gphi *phi = as_a <gphi *> (stmt_vinfo->stmt);
    6601          408 :   tree base = STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo);
    6602          408 :   tree step = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo);
    6603          408 :   tree lhs_type = TREE_TYPE (gimple_phi_result (phi));
    6604          408 :   widest_int ni, max_loop_value, lhs_max;
    6605          408 :   wi::overflow_type overflow = wi::OVF_NONE;
    6606              : 
    6607              :   /* Make sure the loop is integer based.  */
    6608          408 :   if (TREE_CODE (base) != INTEGER_CST
    6609          109 :       || TREE_CODE (step) != INTEGER_CST)
    6610              :     return false;
    6611              : 
    6612              :   /* Check that the max size of the loop will not wrap.  */
    6613              : 
    6614          109 :   if (TYPE_OVERFLOW_UNDEFINED (lhs_type))
    6615              :     return true;
    6616              : 
    6617            8 :   if (! max_stmt_executions (loop, &ni))
    6618              :     return false;
    6619              : 
    6620            8 :   max_loop_value = wi::mul (wi::to_widest (step), ni, TYPE_SIGN (lhs_type),
    6621            8 :                             &overflow);
    6622            8 :   if (overflow)
    6623              :     return false;
    6624              : 
    6625            8 :   max_loop_value = wi::add (wi::to_widest (base), max_loop_value,
    6626           16 :                             TYPE_SIGN (lhs_type), &overflow);
    6627            8 :   if (overflow)
    6628              :     return false;
    6629              : 
    6630            8 :   return (wi::min_precision (max_loop_value, TYPE_SIGN (lhs_type))
    6631            8 :           <= TYPE_PRECISION (lhs_type));
    6632          408 : }
    6633              : 
    6634              : /* Check if masking can be supported by inserting a conditional expression.
    6635              :    CODE is the code for the operation.  COND_FN is the conditional internal
    6636              :    function, if it exists.  VECTYPE_IN is the type of the vector input.  */
    6637              : static bool
    6638         6100 : use_mask_by_cond_expr_p (code_helper code, internal_fn cond_fn,
    6639              :                          tree vectype_in)
    6640              : {
    6641         6100 :   if (cond_fn != IFN_LAST
    6642         6100 :       && direct_internal_fn_supported_p (cond_fn, vectype_in,
    6643              :                                          OPTIMIZE_FOR_SPEED))
    6644              :     return false;
    6645              : 
    6646         4373 :   if (code.is_tree_code ())
    6647         4353 :     switch (tree_code (code))
    6648              :       {
    6649          397 :       case DOT_PROD_EXPR:
    6650          397 :       case SAD_EXPR:
    6651          397 :         return true;
    6652              : 
    6653              :       default:
    6654              :         break;
    6655              :       }
    6656              :   return false;
    6657              : }
    6658              : 
    6659              : /* Insert a conditional expression to enable masked vectorization.  CODE is the
    6660              :    code for the operation.  VOP is the array of operands.  MASK is the loop
    6661              :    mask.  GSI is a statement iterator used to place the new conditional
    6662              :    expression.  */
    6663              : static void
    6664            4 : build_vect_cond_expr (code_helper code, tree vop[3], tree mask,
    6665              :                       gimple_stmt_iterator *gsi)
    6666              : {
    6667            4 :   switch (tree_code (code))
    6668              :     {
    6669            4 :     case DOT_PROD_EXPR:
    6670            4 :       {
    6671            4 :         tree vectype = TREE_TYPE (vop[1]);
    6672            4 :         tree zero = build_zero_cst (vectype);
    6673            4 :         tree masked_op1 = make_temp_ssa_name (vectype, NULL, "masked_op1");
    6674            4 :         gassign *select = gimple_build_assign (masked_op1, VEC_COND_EXPR,
    6675              :                                                mask, vop[1], zero);
    6676            4 :         gsi_insert_before (gsi, select, GSI_SAME_STMT);
    6677            4 :         vop[1] = masked_op1;
    6678            4 :         break;
    6679              :       }
    6680              : 
    6681            0 :     case SAD_EXPR:
    6682            0 :       {
    6683            0 :         tree vectype = TREE_TYPE (vop[1]);
    6684            0 :         tree masked_op1 = make_temp_ssa_name (vectype, NULL, "masked_op1");
    6685            0 :         gassign *select = gimple_build_assign (masked_op1, VEC_COND_EXPR,
    6686              :                                                mask, vop[1], vop[0]);
    6687            0 :         gsi_insert_before (gsi, select, GSI_SAME_STMT);
    6688            0 :         vop[1] = masked_op1;
    6689            0 :         break;
    6690              :       }
    6691              : 
    6692            0 :     default:
    6693            0 :       gcc_unreachable ();
    6694              :     }
    6695            4 : }
    6696              : 
    6697              : /* Given an operation with CODE in loop reduction path whose reduction PHI is
    6698              :    specified by REDUC_INFO, the operation has TYPE of scalar result, and its
    6699              :    input vectype is represented by VECTYPE_IN. The vectype of vectorized result
    6700              :    may be different from VECTYPE_IN, either in base type or vectype lanes,
    6701              :    lane-reducing operation is the case.  This function check if it is possible,
    6702              :    and how to perform partial vectorization on the operation in the context
    6703              :    of LOOP_VINFO.  It returns whether partial vectors are possible.  The
    6704              :    caller is responsible to register the usage appropriately.  */
    6705              : 
    6706              : static bool
    6707         4201 : vect_reduction_update_partial_vector_usage (loop_vec_info loop_vinfo,
    6708              :                                             vect_reduc_info reduc_info,
    6709              :                                             code_helper code, tree type,
    6710              :                                             tree vectype_in)
    6711              : {
    6712         4201 :   enum vect_reduction_type reduc_type = VECT_REDUC_INFO_TYPE (reduc_info);
    6713         4201 :   internal_fn reduc_fn = VECT_REDUC_INFO_FN (reduc_info);
    6714         4201 :   internal_fn cond_fn
    6715         1157 :     = ((code.is_internal_fn ()
    6716         1157 :         && internal_fn_mask_index ((internal_fn)code) != -1)
    6717         4201 :        ? (internal_fn)code : get_conditional_internal_fn (code, type));
    6718              : 
    6719         4201 :   if (reduc_type != FOLD_LEFT_REDUCTION
    6720         3401 :       && !use_mask_by_cond_expr_p (code, cond_fn, vectype_in)
    6721         7486 :       && (cond_fn == IFN_LAST
    6722         3285 :           || !direct_internal_fn_supported_p (cond_fn, vectype_in,
    6723              :                                               OPTIMIZE_FOR_SPEED)))
    6724              :     {
    6725         2071 :       if (dump_enabled_p ())
    6726          101 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6727              :                          "can't operate on partial vectors because"
    6728              :                          " no conditional operation is available.\n");
    6729         2071 :       LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    6730              :     }
    6731         2130 :   else if (reduc_type == FOLD_LEFT_REDUCTION
    6732         2130 :            && reduc_fn == IFN_LAST
    6733         2130 :            && !expand_vec_cond_expr_p (vectype_in, truth_type_for (vectype_in)))
    6734              :     {
    6735            0 :       if (dump_enabled_p ())
    6736            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6737              :                         "can't operate on partial vectors because"
    6738              :                         " no conditional operation is available.\n");
    6739            0 :       LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    6740              :     }
    6741         2130 :   else if (reduc_type == FOLD_LEFT_REDUCTION
    6742          800 :            && internal_fn_mask_index (reduc_fn) == -1
    6743          800 :            && FLOAT_TYPE_P (vectype_in)
    6744         2930 :            && HONOR_SIGN_DEPENDENT_ROUNDING (vectype_in))
    6745              :     {
    6746            0 :       if (dump_enabled_p ())
    6747            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6748              :                          "can't operate on partial vectors because"
    6749              :                          " signed zeros cannot be preserved.\n");
    6750            0 :       LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    6751              :     }
    6752              :   else
    6753              :     return true;
    6754              :   return false;
    6755              : }
    6756              : 
    6757              : /* Check if STMT_INFO is a lane-reducing operation that can be vectorized in
    6758              :    the context of LOOP_VINFO, and vector cost will be recorded in COST_VEC,
    6759              :    and the analysis is for slp if SLP_NODE is not NULL.
    6760              : 
    6761              :    For a lane-reducing operation, the loop reduction path that it lies in,
    6762              :    may contain normal operation, or other lane-reducing operation of different
    6763              :    input type size, an example as:
    6764              : 
    6765              :      int sum = 0;
    6766              :      for (i)
    6767              :        {
    6768              :          ...
    6769              :          sum += d0[i] * d1[i];       // dot-prod <vector(16) char>
    6770              :          sum += w[i];                // widen-sum <vector(16) char>
    6771              :          sum += abs(s0[i] - s1[i]);  // sad <vector(8) short>
    6772              :          sum += n[i];                // normal <vector(4) int>
    6773              :          ...
    6774              :        }
    6775              : 
    6776              :    Vectorization factor is essentially determined by operation whose input
    6777              :    vectype has the most lanes ("vector(16) char" in the example), while we
    6778              :    need to choose input vectype with the least lanes ("vector(4) int" in the
    6779              :    example) to determine effective number of vector reduction PHIs.  */
    6780              : 
    6781              : bool
    6782       404226 : vectorizable_lane_reducing (loop_vec_info loop_vinfo, stmt_vec_info stmt_info,
    6783              :                             slp_tree slp_node, stmt_vector_for_cost *cost_vec)
    6784              : {
    6785       404226 :   gimple *stmt = stmt_info->stmt;
    6786              : 
    6787       404226 :   if (!lane_reducing_stmt_p (stmt))
    6788              :     return false;
    6789              : 
    6790          740 :   tree type = TREE_TYPE (gimple_assign_lhs (stmt));
    6791              : 
    6792          740 :   if (!INTEGRAL_TYPE_P (type))
    6793              :     return false;
    6794              : 
    6795              :   /* Do not try to vectorize bit-precision reductions.  */
    6796          740 :   if (!type_has_mode_precision_p (type))
    6797              :     return false;
    6798              : 
    6799          740 :   vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
    6800              : 
    6801              :   /* TODO: Support lane-reducing operation that does not directly participate
    6802              :      in loop reduction.  */
    6803          740 :   if (!reduc_info)
    6804              :     return false;
    6805              : 
    6806              :   /* Lane-reducing pattern inside any inner loop of LOOP_VINFO is not
    6807              :      recognized.  */
    6808          740 :   gcc_assert (!nested_in_vect_loop_p (LOOP_VINFO_LOOP (loop_vinfo), stmt_info));
    6809          740 :   gcc_assert (VECT_REDUC_INFO_TYPE (reduc_info) == TREE_CODE_REDUCTION);
    6810              : 
    6811         2960 :   for (int i = 0; i < (int) gimple_num_ops (stmt) - 1; i++)
    6812              :     {
    6813         2220 :       slp_tree slp_op;
    6814         2220 :       tree op;
    6815         2220 :       tree vectype;
    6816         2220 :       enum vect_def_type dt;
    6817              : 
    6818         2220 :       if (!vect_is_simple_use (loop_vinfo, slp_node, i, &op,
    6819              :                                &slp_op, &dt, &vectype))
    6820              :         {
    6821            0 :           if (dump_enabled_p ())
    6822            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6823              :                              "use not simple.\n");
    6824            0 :           return false;
    6825              :         }
    6826              : 
    6827         2220 :       if (!vectype)
    6828              :         {
    6829           15 :           vectype = get_vectype_for_scalar_type (loop_vinfo, TREE_TYPE (op),
    6830              :                                                  slp_op);
    6831           15 :           if (!vectype)
    6832              :             return false;
    6833              :         }
    6834              : 
    6835         2220 :       if (!vect_maybe_update_slp_op_vectype (slp_op, vectype))
    6836              :         {
    6837            0 :           if (dump_enabled_p ())
    6838            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6839              :                              "incompatible vector types for invariants\n");
    6840              :           return false;
    6841              :         }
    6842              : 
    6843         2220 :       if (i == STMT_VINFO_REDUC_IDX (stmt_info))
    6844          740 :         continue;
    6845              : 
    6846              :       /* There should be at most one cycle def in the stmt.  */
    6847         1480 :       if (VECTORIZABLE_CYCLE_DEF (dt))
    6848              :         return false;
    6849              :     }
    6850              : 
    6851          740 :   slp_tree node_in = SLP_TREE_CHILDREN (slp_node)[0];
    6852          740 :   tree vectype_in = SLP_TREE_VECTYPE (node_in);
    6853          740 :   gcc_assert (vectype_in);
    6854              : 
    6855              :   /* Compute number of effective vector statements for costing from the
    6856              :      number of input lanes allow for excess lanes in the last input vector.  */
    6857          740 :   unsigned int ncopies_for_cost, excess_elts;
    6858          740 :   if (!vect_get_num_copies_for_invariant (loop_vinfo, node_in,
    6859              :                                           &ncopies_for_cost,
    6860              :                                           &excess_elts))
    6861              :     {
    6862            0 :       if (dump_enabled_p ())
    6863            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6864              :                          "incompatible vector types for invariants\n");
    6865              :       return false;
    6866              :     }
    6867          740 :   gcc_assert (ncopies_for_cost >= 1);
    6868              : 
    6869          740 :   if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
    6870              :     {
    6871          116 :       enum tree_code code = gimple_assign_rhs_code (stmt);
    6872          116 :       if (vect_reduction_update_partial_vector_usage (loop_vinfo, reduc_info,
    6873          116 :                                                       code, type, vectype_in))
    6874              :         {
    6875          116 :           internal_fn reduc_fn = VECT_REDUC_INFO_FN (reduc_info);
    6876          116 :           internal_fn mask_reduc_fn
    6877          116 :             = get_masked_reduction_fn (reduc_fn, vectype_in);
    6878          116 :           vec_loop_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
    6879          116 :           vec_loop_lens *lens = &LOOP_VINFO_LENS (loop_vinfo);
    6880          116 :           if (mask_reduc_fn == IFN_MASK_LEN_FOLD_LEFT_PLUS)
    6881            0 :             vect_record_loop_len (loop_vinfo, lens, ncopies_for_cost,
    6882              :                                   vectype_in, 1);
    6883              :           else
    6884          116 :             vect_record_loop_mask (loop_vinfo, masks, ncopies_for_cost,
    6885              :                                    vectype_in, NULL);
    6886              :         }
    6887              :     }
    6888              : 
    6889          740 :   if (vect_is_emulated_mixed_dot_prod (slp_node))
    6890              :     {
    6891              :       /* We need extra two invariants: one that contains the minimum signed
    6892              :          value and one that contains half of its negative.  */
    6893           15 :       int prologue_stmts = 2;
    6894           15 :       unsigned cost = record_stmt_cost (cost_vec, prologue_stmts,
    6895              :                                         scalar_to_vec, slp_node, 0,
    6896              :                                         vect_prologue);
    6897           15 :       if (dump_enabled_p ())
    6898            0 :         dump_printf (MSG_NOTE, "vectorizable_lane_reducing: "
    6899              :                      "extra prologue_cost = %d .\n", cost);
    6900              : 
    6901              :       /* Three dot-products and a subtraction.  */
    6902           15 :       ncopies_for_cost *= 4;
    6903              :     }
    6904              : 
    6905          740 :   record_stmt_cost (cost_vec, (int) ncopies_for_cost, vector_stmt, slp_node,
    6906              :                     0, vect_body);
    6907              : 
    6908              :   /* Transform via vect_transform_reduction.  */
    6909          740 :   SLP_TREE_TYPE (slp_node) = reduc_vec_info_type;
    6910          740 :   return true;
    6911              : }
    6912              : 
    6913              : /* Function vectorizable_reduction.
    6914              : 
    6915              :    Check if STMT_INFO performs a reduction operation that can be vectorized.
    6916              :    If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
    6917              :    stmt to replace it, put it in VEC_STMT, and insert it at GSI.
    6918              :    Return true if STMT_INFO is vectorizable in this way.
    6919              : 
    6920              :    This function also handles reduction idioms (patterns) that have been
    6921              :    recognized in advance during vect_pattern_recog.  In this case, STMT_INFO
    6922              :    may be of this form:
    6923              :      X = pattern_expr (arg0, arg1, ..., X)
    6924              :    and its STMT_VINFO_RELATED_STMT points to the last stmt in the original
    6925              :    sequence that had been detected and replaced by the pattern-stmt
    6926              :    (STMT_INFO).
    6927              : 
    6928              :    This function also handles reduction of condition expressions, for example:
    6929              :      for (int i = 0; i < N; i++)
    6930              :        if (a[i] < value)
    6931              :          last = a[i];
    6932              :    This is handled by vectorising the loop and creating an additional vector
    6933              :    containing the loop indexes for which "a[i] < value" was true.  In the
    6934              :    function epilogue this is reduced to a single max value and then used to
    6935              :    index into the vector of results.
    6936              : 
    6937              :    In some cases of reduction patterns, the type of the reduction variable X is
    6938              :    different than the type of the other arguments of STMT_INFO.
    6939              :    In such cases, the vectype that is used when transforming STMT_INFO into
    6940              :    a vector stmt is different than the vectype that is used to determine the
    6941              :    vectorization factor, because it consists of a different number of elements
    6942              :    than the actual number of elements that are being operated upon in parallel.
    6943              : 
    6944              :    For example, consider an accumulation of shorts into an int accumulator.
    6945              :    On some targets it's possible to vectorize this pattern operating on 8
    6946              :    shorts at a time (hence, the vectype for purposes of determining the
    6947              :    vectorization factor should be V8HI); on the other hand, the vectype that
    6948              :    is used to create the vector form is actually V4SI (the type of the result).
    6949              : 
    6950              :    Upon entry to this function, STMT_VINFO_VECTYPE records the vectype that
    6951              :    indicates what is the actual level of parallelism (V8HI in the example), so
    6952              :    that the right vectorization factor would be derived.  This vectype
    6953              :    corresponds to the type of arguments to the reduction stmt, and should *NOT*
    6954              :    be used to create the vectorized stmt.  The right vectype for the vectorized
    6955              :    stmt is obtained from the type of the result X:
    6956              :       get_vectype_for_scalar_type (vinfo, TREE_TYPE (X))
    6957              : 
    6958              :    This means that, contrary to "regular" reductions (or "regular" stmts in
    6959              :    general), the following equation:
    6960              :       STMT_VINFO_VECTYPE == get_vectype_for_scalar_type (vinfo, TREE_TYPE (X))
    6961              :    does *NOT* necessarily hold for reduction patterns.  */
    6962              : 
    6963              : bool
    6964       403486 : vectorizable_reduction (loop_vec_info loop_vinfo,
    6965              :                         stmt_vec_info stmt_info, slp_tree slp_node,
    6966              :                         slp_instance slp_node_instance,
    6967              :                         stmt_vector_for_cost *cost_vec)
    6968              : {
    6969       403486 :   tree vectype_in = NULL_TREE;
    6970       403486 :   enum vect_def_type cond_reduc_dt = vect_unknown_def_type;
    6971       403486 :   stmt_vec_info cond_stmt_vinfo = NULL;
    6972       403486 :   int i;
    6973       403486 :   int ncopies;
    6974       403486 :   bool single_defuse_cycle = false;
    6975       403486 :   tree cr_index_scalar_type = NULL_TREE, cr_index_vector_type = NULL_TREE;
    6976       403486 :   tree cond_reduc_val = NULL_TREE;
    6977              : 
    6978              :   /* Make sure it was already recognized as a reduction computation.  */
    6979       403486 :   if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_reduction_def
    6980              :       && STMT_VINFO_DEF_TYPE (stmt_info) != vect_double_reduction_def
    6981       403486 :       && STMT_VINFO_DEF_TYPE (stmt_info) != vect_nested_cycle)
    6982              :     return false;
    6983              : 
    6984              :   /* The reduction meta.  */
    6985        85079 :   vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
    6986              : 
    6987        85079 :   if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle)
    6988              :     {
    6989         1379 :       gcc_assert (is_a <gphi *> (stmt_info->stmt));
    6990              :       /* We eventually need to set a vector type on invariant arguments.  */
    6991              :       unsigned j;
    6992              :       slp_tree child;
    6993         4129 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), j, child)
    6994         2758 :         if (!vect_maybe_update_slp_op_vectype (child,
    6995              :                                                SLP_TREE_VECTYPE (slp_node)))
    6996              :           {
    6997            0 :             if (dump_enabled_p ())
    6998            0 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6999              :                                "incompatible vector types for "
    7000              :                                "invariants\n");
    7001              :             return false;
    7002              :           }
    7003         2758 :         else if (SLP_TREE_DEF_TYPE (child) == vect_internal_def
    7004         2758 :                  && !useless_type_conversion_p (SLP_TREE_VECTYPE (slp_node),
    7005              :                                                 SLP_TREE_VECTYPE (child)))
    7006              :           {
    7007              :             /* With bools we can have mask and non-mask precision vectors
    7008              :                or different non-mask precisions.  while pattern recog is
    7009              :                supposed to guarantee consistency here, we do not have
    7010              :                pattern stmts for PHIs (PR123316).
    7011              :                Deal with that here instead of ICEing later.  */
    7012            8 :             if (dump_enabled_p ())
    7013            8 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7014              :                                "incompatible vector type setup from "
    7015              :                                "bool pattern detection\n");
    7016              :             return false;
    7017              :           }
    7018              :       /* Analysis for double-reduction is done on the outer
    7019              :          loop PHI, nested cycles have no further restrictions.  */
    7020         1371 :       SLP_TREE_TYPE (slp_node) = cycle_phi_info_type;
    7021         1371 :       return true;
    7022              :     }
    7023              : 
    7024        83700 :   if (!is_a <gphi *> (stmt_info->stmt))
    7025              :     {
    7026         8044 :       gcc_assert (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def);
    7027         8044 :       SLP_TREE_TYPE (slp_node) = reduc_vec_info_type;
    7028         8044 :       return true;
    7029              :     }
    7030              : 
    7031        75656 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    7032        75656 :   stmt_vec_info phi_info = stmt_info;
    7033        75656 :   bool double_reduc = false;
    7034        75656 :   if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
    7035              :     {
    7036              :       /* We arrive here for both the inner loop LC PHI and the
    7037              :          outer loop PHI.  The latter is what we want to analyze the
    7038              :          reduction with.  The LC PHI is handled by vectorizable_lc_phi.  */
    7039          322 :       if (gimple_bb (stmt_info->stmt) != loop->header)
    7040            0 :         return false;
    7041              : 
    7042              :       /* Set loop and phi_info to the inner loop.  */
    7043          322 :       use_operand_p use_p;
    7044          322 :       gimple *use_stmt;
    7045          322 :       bool res = single_imm_use (gimple_phi_result (stmt_info->stmt),
    7046              :                                  &use_p, &use_stmt);
    7047          322 :       gcc_assert (res);
    7048          322 :       phi_info = loop_vinfo->lookup_stmt (use_stmt);
    7049          322 :       loop = loop->inner;
    7050          322 :       double_reduc = true;
    7051              :     }
    7052              : 
    7053        75656 :   const bool reduc_chain = reduc_info->is_reduc_chain;
    7054        75656 :   slp_node_instance->reduc_phis = slp_node;
    7055              :   /* ???  We're leaving slp_node to point to the PHIs, we only
    7056              :      need it to get at the number of vector stmts which wasn't
    7057              :      yet initialized for the instance root.  */
    7058              : 
    7059              :   /* PHIs should not participate in patterns.  */
    7060        75656 :   gcc_assert (!STMT_VINFO_RELATED_STMT (phi_info));
    7061        75656 :   gphi *reduc_def_phi = as_a <gphi *> (phi_info->stmt);
    7062              : 
    7063              :   /* Verify following REDUC_IDX from the latch def leads us back to the PHI
    7064              :      and compute the reduction chain length.  Discover the real
    7065              :      reduction operation stmt on the way (slp_for_stmt_info).  */
    7066        75656 :   unsigned reduc_chain_length = 0;
    7067        75656 :   stmt_info = NULL;
    7068        75656 :   slp_tree slp_for_stmt_info = NULL;
    7069        75656 :   slp_tree vdef_slp = slp_node_instance->root;
    7070       167172 :   while (vdef_slp != slp_node)
    7071              :     {
    7072        92608 :       int reduc_idx = SLP_TREE_REDUC_IDX (vdef_slp);
    7073        92608 :       if (reduc_idx == -1)
    7074              :         {
    7075         1084 :           if (dump_enabled_p ())
    7076            7 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7077              :                              "reduction chain broken by patterns.\n");
    7078         1092 :           return false;
    7079              :         }
    7080        91524 :       stmt_vec_info vdef = SLP_TREE_REPRESENTATIVE (vdef_slp);
    7081        91524 :       if (is_a <gphi *> (vdef->stmt))
    7082              :         {
    7083          644 :           vdef_slp = SLP_TREE_CHILDREN (vdef_slp)[reduc_idx];
    7084              :           /* Do not count PHIs towards the chain length.  */
    7085          644 :           continue;
    7086              :         }
    7087        90880 :       gimple_match_op op;
    7088        90880 :       if (!gimple_extract_op (vdef->stmt, &op))
    7089              :         {
    7090            0 :           if (dump_enabled_p ())
    7091            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7092              :                              "reduction chain includes unsupported"
    7093              :                              " statement type.\n");
    7094              :           return false;
    7095              :         }
    7096        90880 :       if (CONVERT_EXPR_CODE_P (op.code))
    7097              :         {
    7098         5402 :           if (!tree_nop_conversion_p (op.type, TREE_TYPE (op.ops[0])))
    7099              :             {
    7100            8 :               if (dump_enabled_p ())
    7101            8 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7102              :                                  "conversion in the reduction chain.\n");
    7103              :               return false;
    7104              :             }
    7105         5394 :           vdef_slp = SLP_TREE_CHILDREN (vdef_slp)[0];
    7106              :         }
    7107              :       else
    7108              :         {
    7109              :           /* First non-conversion stmt.  */
    7110        85478 :           if (!slp_for_stmt_info)
    7111        74552 :             slp_for_stmt_info = vdef_slp;
    7112              : 
    7113        85478 :           if (lane_reducing_op_p (op.code))
    7114              :             {
    7115              :               /* The last operand of lane-reducing operation is for
    7116              :                  reduction.  */
    7117          740 :               gcc_assert (reduc_idx > 0 && reduc_idx == (int) op.num_ops - 1);
    7118              : 
    7119          740 :               slp_tree op_node = SLP_TREE_CHILDREN (vdef_slp)[0];
    7120          740 :               tree vectype_op = SLP_TREE_VECTYPE (op_node);
    7121          740 :               tree type_op = TREE_TYPE (op.ops[0]);
    7122          740 :               if (!vectype_op)
    7123              :                 {
    7124           18 :                   vectype_op = get_vectype_for_scalar_type (loop_vinfo,
    7125              :                                                             type_op);
    7126           18 :                   if (!vectype_op
    7127           18 :                       || !vect_maybe_update_slp_op_vectype (op_node,
    7128              :                                                             vectype_op))
    7129              :                     return false;
    7130              :                 }
    7131              : 
    7132              :               /* To accommodate lane-reducing operations of mixed input
    7133              :                  vectypes, choose input vectype with the least lanes for the
    7134              :                  reduction PHI statement, which would result in the most
    7135              :                  ncopies for vectorized reduction results.  */
    7136          740 :               if (!vectype_in
    7137          740 :                   || (GET_MODE_SIZE (SCALAR_TYPE_MODE (TREE_TYPE (vectype_in)))
    7138          769 :                        < GET_MODE_SIZE (SCALAR_TYPE_MODE (type_op))))
    7139              :                 vectype_in = vectype_op;
    7140              :             }
    7141        84738 :           else if (!vectype_in)
    7142        73841 :             vectype_in = SLP_TREE_VECTYPE (slp_node);
    7143        85478 :           vdef_slp = SLP_TREE_CHILDREN (vdef_slp)[reduc_idx];
    7144              :         }
    7145        90872 :       reduc_chain_length++;
    7146              :     }
    7147        74564 :   if (!slp_for_stmt_info)
    7148              :     {
    7149           12 :       if (dump_enabled_p ())
    7150           12 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7151              :                          "only noop-conversions in the reduction chain.\n");
    7152              :       return false;
    7153              :     }
    7154        74552 :   stmt_info = SLP_TREE_REPRESENTATIVE (slp_for_stmt_info);
    7155              : 
    7156              :   /* PHIs should not participate in patterns.  */
    7157        74552 :   gcc_assert (!STMT_VINFO_RELATED_STMT (phi_info));
    7158              : 
    7159              :   /* 1. Is vectorizable reduction?  */
    7160              :   /* Not supportable if the reduction variable is used in the loop, unless
    7161              :      it's a reduction chain.  */
    7162        74552 :   if (STMT_VINFO_RELEVANT (stmt_info) > vect_used_in_outer
    7163            0 :       && !reduc_chain)
    7164              :     return false;
    7165              : 
    7166              :   /* Reductions that are not used even in an enclosing outer-loop,
    7167              :      are expected to be "live" (used out of the loop).  */
    7168        74552 :   if (STMT_VINFO_RELEVANT (stmt_info) == vect_unused_in_scope
    7169            0 :       && !STMT_VINFO_LIVE_P (stmt_info))
    7170              :     return false;
    7171              : 
    7172              :   /* 2. Has this been recognized as a reduction pattern?
    7173              : 
    7174              :      Check if STMT represents a pattern that has been recognized
    7175              :      in earlier analysis stages.  For stmts that represent a pattern,
    7176              :      the STMT_VINFO_RELATED_STMT field records the last stmt in
    7177              :      the original sequence that constitutes the pattern.  */
    7178              : 
    7179        74552 :   stmt_vec_info orig_stmt_info = STMT_VINFO_RELATED_STMT (stmt_info);
    7180        74552 :   if (orig_stmt_info)
    7181              :     {
    7182         5120 :       gcc_assert (STMT_VINFO_IN_PATTERN_P (orig_stmt_info));
    7183         5120 :       gcc_assert (!STMT_VINFO_IN_PATTERN_P (stmt_info));
    7184              :     }
    7185              : 
    7186              :   /* 3. Check the operands of the operation.  The first operands are defined
    7187              :         inside the loop body. The last operand is the reduction variable,
    7188              :         which is defined by the loop-header-phi.  */
    7189              : 
    7190        74552 :   tree vectype_out = SLP_TREE_VECTYPE (slp_for_stmt_info);
    7191        74552 :   VECT_REDUC_INFO_VECTYPE (reduc_info) = vectype_out;
    7192              : 
    7193        74552 :   gimple_match_op op;
    7194        74552 :   if (!gimple_extract_op (stmt_info->stmt, &op))
    7195            0 :     gcc_unreachable ();
    7196        74552 :   bool lane_reducing = lane_reducing_op_p (op.code);
    7197              : 
    7198        74552 :   if (!POINTER_TYPE_P (op.type) && !INTEGRAL_TYPE_P (op.type)
    7199        22280 :       && !SCALAR_FLOAT_TYPE_P (op.type))
    7200              :     return false;
    7201              : 
    7202              :   /* Do not try to vectorize bit-precision reductions.  */
    7203        74552 :   if (!type_has_mode_precision_p (op.type)
    7204         1757 :       && op.code != BIT_AND_EXPR
    7205         1629 :       && op.code != BIT_IOR_EXPR
    7206        75028 :       && op.code != BIT_XOR_EXPR)
    7207              :     return false;
    7208              : 
    7209              :   /* Lane-reducing ops also never can be used in a SLP reduction group
    7210              :      since we'll mix lanes belonging to different reductions.  But it's
    7211              :      OK to use them in a reduction chain or when the reduction group
    7212              :      has just one element.  */
    7213        74242 :   if (lane_reducing
    7214        74242 :       && !reduc_chain
    7215          668 :       && SLP_TREE_LANES (slp_node) > 1)
    7216              :     {
    7217            0 :       if (dump_enabled_p ())
    7218            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7219              :                          "lane-reducing reduction in reduction group.\n");
    7220              :       return false;
    7221              :     }
    7222              : 
    7223              :   /* We'll verify the reduction operation only later - avoid
    7224              :      all operations that mismatch on the number of SLP children.  */
    7225       148484 :   if (op.num_ops != SLP_TREE_CHILDREN (slp_for_stmt_info).length ())
    7226              :     {
    7227            0 :       if (dump_enabled_p ())
    7228            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7229              :                          "unsupported reduction operation.\n");
    7230              :       return false;
    7231              :     }
    7232              : 
    7233              :   /* All uses but the last are expected to be defined in the loop.
    7234              :      The last use is the reduction variable.  In case of nested cycle this
    7235              :      assumption is not true: we use reduc_index to record the index of the
    7236              :      reduction variable.  */
    7237        74242 :   slp_tree *slp_op = XALLOCAVEC (slp_tree, op.num_ops);
    7238        74242 :   tree *vectype_op = XALLOCAVEC (tree, op.num_ops);
    7239        74242 :   gcc_assert (op.code != COND_EXPR || !COMPARISON_CLASS_P (op.ops[0]));
    7240       237815 :   for (i = 0; i < (int) op.num_ops; i++)
    7241              :     {
    7242              :       /* The condition of COND_EXPR is checked in vectorizable_condition().  */
    7243       163573 :       if (i == 0 && op.code == COND_EXPR)
    7244        81864 :         continue;
    7245              : 
    7246       162710 :       stmt_vec_info def_stmt_info;
    7247       162710 :       enum vect_def_type dt;
    7248       162710 :       if (!vect_is_simple_use (loop_vinfo, slp_for_stmt_info,
    7249              :                                i, &op.ops[i], &slp_op[i], &dt,
    7250       162710 :                                &vectype_op[i], &def_stmt_info))
    7251              :         {
    7252            0 :           if (dump_enabled_p ())
    7253            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7254              :                              "use not simple.\n");
    7255            0 :           return false;
    7256              :         }
    7257              : 
    7258              :       /* Skip reduction operands, and for an IFN_COND_OP we might hit the
    7259              :          reduction operand twice (once as definition, once as else).  */
    7260       162710 :       if (SLP_TREE_CHILDREN (slp_for_stmt_info)[i]
    7261       325420 :           == SLP_TREE_CHILDREN
    7262       162710 :                (slp_for_stmt_info)[SLP_TREE_REDUC_IDX (slp_for_stmt_info)])
    7263        81001 :         continue;
    7264              : 
    7265              :       /* There should be only one cycle def in the stmt, the one
    7266              :          leading to reduc_def.  */
    7267        81709 :       if (SLP_TREE_CHILDREN (slp_for_stmt_info)[i]->cycle_info.id != -1)
    7268              :         return false;
    7269              : 
    7270        81709 :       if (!vectype_op[i])
    7271         7422 :         vectype_op[i]
    7272         7422 :           = get_vectype_for_scalar_type (loop_vinfo,
    7273         7422 :                                          TREE_TYPE (op.ops[i]), slp_op[i]);
    7274              : 
    7275              :       /* Record how the non-reduction-def value of COND_EXPR is defined.
    7276              :          ???  For a chain of multiple CONDs we'd have to match them up all.  */
    7277        81709 :       if (op.code == COND_EXPR && reduc_chain_length == 1)
    7278              :         {
    7279          840 :           if (dt == vect_constant_def)
    7280              :             {
    7281          118 :               cond_reduc_dt = dt;
    7282          118 :               cond_reduc_val = op.ops[i];
    7283              :             }
    7284          722 :           else if (dt == vect_induction_def
    7285          408 :                    && def_stmt_info
    7286         1130 :                    && is_nonwrapping_integer_induction (def_stmt_info, loop))
    7287              :             {
    7288          109 :               cond_reduc_dt = dt;
    7289          109 :               cond_stmt_vinfo = def_stmt_info;
    7290              :             }
    7291              :         }
    7292              :     }
    7293              : 
    7294        74242 :   enum vect_reduction_type reduction_type = VECT_REDUC_INFO_TYPE (reduc_info);
    7295              :   /* If we have a condition reduction, see if we can simplify it further.  */
    7296        74242 :   if (reduction_type == COND_REDUCTION)
    7297              :     {
    7298          851 :       if (SLP_TREE_LANES (slp_node) != 1)
    7299              :         return false;
    7300              : 
    7301              :       /* When the condition uses the reduction value in the condition, fail.  */
    7302          827 :       if (SLP_TREE_REDUC_IDX (slp_node) == 0)
    7303              :         {
    7304            0 :           if (dump_enabled_p ())
    7305            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7306              :                              "condition depends on previous iteration\n");
    7307              :           return false;
    7308              :         }
    7309              : 
    7310          827 :       if (reduc_chain_length == 1
    7311          827 :           && (direct_internal_fn_supported_p (IFN_FOLD_EXTRACT_LAST, vectype_in,
    7312              :                                               OPTIMIZE_FOR_SPEED)
    7313          804 :               || direct_internal_fn_supported_p (IFN_LEN_FOLD_EXTRACT_LAST,
    7314              :                                                  vectype_in,
    7315              :                                                  OPTIMIZE_FOR_SPEED)))
    7316              :         {
    7317            0 :           if (dump_enabled_p ())
    7318            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7319              :                              "optimizing condition reduction with"
    7320              :                              " FOLD_EXTRACT_LAST.\n");
    7321            0 :           VECT_REDUC_INFO_TYPE (reduc_info) = EXTRACT_LAST_REDUCTION;
    7322              :         }
    7323          827 :       else if (cond_reduc_dt == vect_induction_def)
    7324              :         {
    7325          109 :           tree base
    7326              :             = STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (cond_stmt_vinfo);
    7327          109 :           tree step = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (cond_stmt_vinfo);
    7328              : 
    7329          109 :           gcc_assert (TREE_CODE (base) == INTEGER_CST
    7330              :                       && TREE_CODE (step) == INTEGER_CST);
    7331          109 :           cond_reduc_val = NULL_TREE;
    7332          109 :           enum tree_code cond_reduc_op_code = ERROR_MARK;
    7333          109 :           tree res = PHI_RESULT (STMT_VINFO_STMT (cond_stmt_vinfo));
    7334          109 :           if (!types_compatible_p (TREE_TYPE (res), TREE_TYPE (base)))
    7335              :             ;
    7336              :           /* Find a suitable value, for MAX_EXPR below base, for MIN_EXPR
    7337              :              above base; punt if base is the minimum value of the type for
    7338              :              MAX_EXPR or maximum value of the type for MIN_EXPR for now.  */
    7339           97 :           else if (tree_int_cst_sgn (step) == -1)
    7340              :             {
    7341           18 :               cond_reduc_op_code = MIN_EXPR;
    7342           18 :               if (tree_int_cst_sgn (base) == -1)
    7343            0 :                 cond_reduc_val = build_int_cst (TREE_TYPE (base), 0);
    7344           18 :               else if (tree_int_cst_lt (base,
    7345           18 :                                         TYPE_MAX_VALUE (TREE_TYPE (base))))
    7346           18 :                 cond_reduc_val
    7347           18 :                   = int_const_binop (PLUS_EXPR, base, integer_one_node);
    7348              :             }
    7349              :           else
    7350              :             {
    7351           79 :               cond_reduc_op_code = MAX_EXPR;
    7352           79 :               if (tree_int_cst_sgn (base) == 1)
    7353            0 :                 cond_reduc_val = build_int_cst (TREE_TYPE (base), 0);
    7354           79 :               else if (tree_int_cst_lt (TYPE_MIN_VALUE (TREE_TYPE (base)),
    7355              :                                         base))
    7356           79 :                 cond_reduc_val
    7357           79 :                   = int_const_binop (MINUS_EXPR, base, integer_one_node);
    7358              :             }
    7359           97 :           if (cond_reduc_val)
    7360              :             {
    7361           97 :               if (dump_enabled_p ())
    7362           61 :                 dump_printf_loc (MSG_NOTE, vect_location,
    7363              :                                  "condition expression based on "
    7364              :                                  "integer induction.\n");
    7365           97 :               VECT_REDUC_INFO_CODE (reduc_info) = cond_reduc_op_code;
    7366           97 :               VECT_REDUC_INFO_INDUC_COND_INITIAL_VAL (reduc_info)
    7367           97 :                 = cond_reduc_val;
    7368           97 :               VECT_REDUC_INFO_TYPE (reduc_info) = INTEGER_INDUC_COND_REDUCTION;
    7369              :             }
    7370              :         }
    7371          718 :       else if (cond_reduc_dt == vect_constant_def)
    7372              :         {
    7373          108 :           enum vect_def_type cond_initial_dt;
    7374          108 :           tree cond_initial_val = vect_phi_initial_value (reduc_def_phi);
    7375          108 :           vect_is_simple_use (cond_initial_val, loop_vinfo, &cond_initial_dt);
    7376          108 :           if (cond_initial_dt == vect_constant_def
    7377          133 :               && types_compatible_p (TREE_TYPE (cond_initial_val),
    7378           25 :                                      TREE_TYPE (cond_reduc_val)))
    7379              :             {
    7380           25 :               tree e = fold_binary (LE_EXPR, boolean_type_node,
    7381              :                                     cond_initial_val, cond_reduc_val);
    7382           25 :               if (e && (integer_onep (e) || integer_zerop (e)))
    7383              :                 {
    7384           25 :                   if (dump_enabled_p ())
    7385           16 :                     dump_printf_loc (MSG_NOTE, vect_location,
    7386              :                                      "condition expression based on "
    7387              :                                      "compile time constant.\n");
    7388              :                   /* Record reduction code at analysis stage.  */
    7389           25 :                   VECT_REDUC_INFO_CODE (reduc_info)
    7390           25 :                     = integer_onep (e) ? MAX_EXPR : MIN_EXPR;
    7391           25 :                   VECT_REDUC_INFO_TYPE (reduc_info) = CONST_COND_REDUCTION;
    7392              :                 }
    7393              :             }
    7394              :         }
    7395              :     }
    7396              : 
    7397        74218 :   if (STMT_VINFO_LIVE_P (phi_info))
    7398              :     return false;
    7399              : 
    7400        74218 :   ncopies = vect_get_num_copies (loop_vinfo, slp_node);
    7401              : 
    7402        74218 :   gcc_assert (ncopies >= 1);
    7403              : 
    7404        74218 :   poly_uint64 nunits_out = TYPE_VECTOR_SUBPARTS (vectype_out);
    7405              : 
    7406              :   /* 4.2. Check support for the epilog operation.
    7407              : 
    7408              :           If STMT represents a reduction pattern, then the type of the
    7409              :           reduction variable may be different than the type of the rest
    7410              :           of the arguments.  For example, consider the case of accumulation
    7411              :           of shorts into an int accumulator; The original code:
    7412              :                         S1: int_a = (int) short_a;
    7413              :           orig_stmt->   S2: int_acc = plus <int_a ,int_acc>;
    7414              : 
    7415              :           was replaced with:
    7416              :                         STMT: int_acc = widen_sum <short_a, int_acc>
    7417              : 
    7418              :           This means that:
    7419              :           1. The tree-code that is used to create the vector operation in the
    7420              :              epilog code (that reduces the partial results) is not the
    7421              :              tree-code of STMT, but is rather the tree-code of the original
    7422              :              stmt from the pattern that STMT is replacing.  I.e, in the example
    7423              :              above we want to use 'widen_sum' in the loop, but 'plus' in the
    7424              :              epilog.
    7425              :           2. The type (mode) we use to check available target support
    7426              :              for the vector operation to be created in the *epilog*, is
    7427              :              determined by the type of the reduction variable (in the example
    7428              :              above we'd check this: optab_handler (plus_optab, vect_int_mode])).
    7429              :              However the type (mode) we use to check available target support
    7430              :              for the vector operation to be created *inside the loop*, is
    7431              :              determined by the type of the other arguments to STMT (in the
    7432              :              example we'd check this: optab_handler (widen_sum_optab,
    7433              :              vect_short_mode)).
    7434              : 
    7435              :           This is contrary to "regular" reductions, in which the types of all
    7436              :           the arguments are the same as the type of the reduction variable.
    7437              :           For "regular" reductions we can therefore use the same vector type
    7438              :           (and also the same tree-code) when generating the epilog code and
    7439              :           when generating the code inside the loop.  */
    7440              : 
    7441        74218 :   code_helper orig_code = VECT_REDUC_INFO_CODE (reduc_info);
    7442              : 
    7443              :   /* If conversion might have created a conditional operation like
    7444              :      IFN_COND_ADD already.  Use the internal code for the following checks.  */
    7445        74218 :   if (orig_code.is_internal_fn ())
    7446              :     {
    7447         6835 :       tree_code new_code = conditional_internal_fn_code (internal_fn (orig_code));
    7448         6835 :       orig_code = new_code != ERROR_MARK ? new_code : orig_code;
    7449              :     }
    7450              : 
    7451        74218 :   VECT_REDUC_INFO_CODE (reduc_info) = orig_code;
    7452              : 
    7453        74218 :   reduction_type = VECT_REDUC_INFO_TYPE (reduc_info);
    7454        74218 :   if (reduction_type == TREE_CODE_REDUCTION)
    7455              :     {
    7456              :       /* Check whether it's ok to change the order of the computation.
    7457              :          Generally, when vectorizing a reduction we change the order of the
    7458              :          computation.  This may change the behavior of the program in some
    7459              :          cases, so we need to check that this is ok.  One exception is when
    7460              :          vectorizing an outer-loop: the inner-loop is executed sequentially,
    7461              :          and therefore vectorizing reductions in the inner-loop during
    7462              :          outer-loop vectorization is safe.  Likewise when we are vectorizing
    7463              :          a series of reductions using SLP and the VF is one the reductions
    7464              :          are performed in scalar order.  */
    7465        73391 :       if (!reduc_chain
    7466        73391 :           && known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), 1u))
    7467              :         ;
    7468        73219 :       else if (needs_fold_left_reduction_p (op.type, orig_code))
    7469              :         {
    7470              :           /* When vectorizing a reduction chain w/o SLP the reduction PHI
    7471              :              is not directly used in stmt.  */
    7472         5306 :           if (reduc_chain_length != 1)
    7473              :             {
    7474           97 :               if (dump_enabled_p ())
    7475           20 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7476              :                                  "in-order reduction chain without SLP.\n");
    7477              :               return false;
    7478              :             }
    7479              :           /* Code generation doesn't support function calls other
    7480              :              than .COND_*.  */
    7481         5209 :           if (!op.code.is_tree_code ()
    7482         5397 :               && !(op.code.is_internal_fn ()
    7483           94 :                    && conditional_internal_fn_code (internal_fn (op.code))
    7484              :                         != ERROR_MARK))
    7485              :             {
    7486           18 :               if (dump_enabled_p ())
    7487           16 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7488              :                                  "in-order reduction chain operation not "
    7489              :                                  "supported.\n");
    7490              :               return false;
    7491              :             }
    7492         5191 :           VECT_REDUC_INFO_TYPE (reduc_info)
    7493         5191 :             = reduction_type = FOLD_LEFT_REDUCTION;
    7494              :         }
    7495        67913 :       else if (!commutative_binary_op_p (orig_code, op.type)
    7496        67913 :                || !associative_binary_op_p (orig_code, op.type))
    7497              :         {
    7498          172 :           if (dump_enabled_p ())
    7499           28 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7500              :                             "reduction: not commutative/associative\n");
    7501              :           return false;
    7502              :         }
    7503              :     }
    7504              : 
    7505         5191 :   if ((reduction_type == COND_REDUCTION
    7506              :        || reduction_type == INTEGER_INDUC_COND_REDUCTION
    7507              :        || reduction_type == CONST_COND_REDUCTION
    7508        68740 :        || reduction_type == EXTRACT_LAST_REDUCTION)
    7509          827 :       && ncopies > 1)
    7510              :     {
    7511          276 :       if (dump_enabled_p ())
    7512           60 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7513              :                          "multiple types in condition reduction.\n");
    7514              :       return false;
    7515              :     }
    7516              : 
    7517              :   /* See if we can convert a mask vector to a corresponding bool data vector
    7518              :      to perform the epilogue reduction.  */
    7519        73655 :   tree alt_vectype_out = NULL_TREE;
    7520        73655 :   if (VECTOR_BOOLEAN_TYPE_P (vectype_out))
    7521              :     {
    7522         1153 :       alt_vectype_out
    7523         2306 :         = get_related_vectype_for_scalar_type (loop_vinfo->vector_mode,
    7524         1153 :                                                TREE_TYPE (vectype_out),
    7525              :                                                TYPE_VECTOR_SUBPARTS
    7526              :                                                  (vectype_out));
    7527         1153 :       if (!alt_vectype_out
    7528         1153 :           || maybe_ne (TYPE_VECTOR_SUBPARTS (alt_vectype_out),
    7529         2306 :                        TYPE_VECTOR_SUBPARTS (vectype_out))
    7530         2306 :           || !expand_vec_cond_expr_p (alt_vectype_out, vectype_out))
    7531              :         alt_vectype_out = NULL_TREE;
    7532              :     }
    7533              : 
    7534        73655 :   internal_fn reduc_fn = IFN_LAST;
    7535        73655 :   if (reduction_type == TREE_CODE_REDUCTION
    7536        73655 :       || reduction_type == FOLD_LEFT_REDUCTION
    7537              :       || reduction_type == INTEGER_INDUC_COND_REDUCTION
    7538          551 :       || reduction_type == CONST_COND_REDUCTION)
    7539              :     {
    7540        68027 :       if (reduction_type == FOLD_LEFT_REDUCTION
    7541        77623 :           ? fold_left_reduction_fn (orig_code, &reduc_fn)
    7542        68027 :           : reduction_fn_for_scalar_code (orig_code, &reduc_fn))
    7543              :         {
    7544        72546 :           internal_fn sbool_fn = IFN_LAST;
    7545        72546 :           if (reduc_fn == IFN_LAST)
    7546              :             ;
    7547        70446 :           else if ((!VECTOR_BOOLEAN_TYPE_P (vectype_out)
    7548         1153 :                     || (GET_MODE_CLASS (TYPE_MODE (vectype_out))
    7549              :                         == MODE_VECTOR_BOOL))
    7550       139739 :                    && direct_internal_fn_supported_p (reduc_fn, vectype_out,
    7551              :                                                       OPTIMIZE_FOR_SPEED))
    7552              :             ;
    7553        18632 :           else if (VECTOR_BOOLEAN_TYPE_P (vectype_out)
    7554         1153 :                    && sbool_reduction_fn_for_fn (reduc_fn, &sbool_fn)
    7555        19785 :                    && direct_internal_fn_supported_p (sbool_fn, vectype_out,
    7556              :                                                       OPTIMIZE_FOR_SPEED))
    7557          131 :             reduc_fn = sbool_fn;
    7558        18501 :           else if (reduction_type != FOLD_LEFT_REDUCTION
    7559        18501 :                    && alt_vectype_out
    7560        18501 :                    && direct_internal_fn_supported_p (reduc_fn, alt_vectype_out,
    7561              :                                                       OPTIMIZE_FOR_SPEED))
    7562          801 :             VECT_REDUC_INFO_VECTYPE_FOR_MASK (reduc_info) = alt_vectype_out;
    7563              :           else
    7564              :             {
    7565        17700 :               if (dump_enabled_p ())
    7566          958 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7567              :                                  "reduc op not supported by target.\n");
    7568              : 
    7569        17700 :               reduc_fn = IFN_LAST;
    7570              :             }
    7571              :         }
    7572              :       else
    7573              :         {
    7574          672 :           if (dump_enabled_p ())
    7575           48 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7576              :                              "no reduc code for scalar code.\n");
    7577              : 
    7578              :           return false;
    7579              :         }
    7580        72546 :       if (reduc_fn == IFN_LAST
    7581        72546 :           && VECTOR_BOOLEAN_TYPE_P (vectype_out))
    7582              :         {
    7583          221 :           if (!alt_vectype_out)
    7584              :             {
    7585           12 :               if (dump_enabled_p ())
    7586            8 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7587              :                                  "cannot turn mask into bool data vector for "
    7588              :                                  "reduction epilogue.\n");
    7589              :               return false;
    7590              :             }
    7591          209 :           VECT_REDUC_INFO_VECTYPE_FOR_MASK (reduc_info) = alt_vectype_out;
    7592              :         }
    7593              :     }
    7594          437 :   else if (reduction_type == COND_REDUCTION)
    7595              :     {
    7596          437 :       int scalar_precision
    7597          437 :         = GET_MODE_PRECISION (SCALAR_TYPE_MODE (op.type));
    7598          437 :       cr_index_scalar_type = make_unsigned_type (scalar_precision);
    7599          437 :       cr_index_vector_type = get_same_sized_vectype (cr_index_scalar_type,
    7600              :                                                 vectype_out);
    7601              : 
    7602          437 :       if (direct_internal_fn_supported_p (IFN_REDUC_MAX, cr_index_vector_type,
    7603              :                                           OPTIMIZE_FOR_SPEED))
    7604           22 :         reduc_fn = IFN_REDUC_MAX;
    7605              :     }
    7606        72971 :   VECT_REDUC_INFO_FN (reduc_info) = reduc_fn;
    7607              : 
    7608        72971 :   if (reduction_type != EXTRACT_LAST_REDUCTION
    7609              :       && reduc_fn == IFN_LAST
    7610              :       && !nunits_out.is_constant ())
    7611              :     {
    7612              :       if (dump_enabled_p ())
    7613              :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7614              :                          "missing target support for reduction on"
    7615              :                          " variable-length vectors.\n");
    7616              :       return false;
    7617              :     }
    7618              : 
    7619              :   /* For SLP reductions, see if there is a neutral value we can use.  */
    7620        72971 :   tree neutral_op = NULL_TREE;
    7621        72971 :   tree initial_value = NULL_TREE;
    7622        72971 :   if (reduc_chain)
    7623         2288 :     initial_value = vect_phi_initial_value (reduc_def_phi);
    7624        72971 :   neutral_op = neutral_op_for_reduction (TREE_TYPE
    7625              :                                            (gimple_phi_result (reduc_def_phi)),
    7626              :                                          orig_code, initial_value);
    7627        72971 :   VECT_REDUC_INFO_NEUTRAL_OP (reduc_info) = neutral_op;
    7628              : 
    7629        72971 :   if (double_reduc && reduction_type == FOLD_LEFT_REDUCTION)
    7630              :     {
    7631              :       /* We can't support in-order reductions of code such as this:
    7632              : 
    7633              :            for (int i = 0; i < n1; ++i)
    7634              :              for (int j = 0; j < n2; ++j)
    7635              :                l += a[j];
    7636              : 
    7637              :          since GCC effectively transforms the loop when vectorizing:
    7638              : 
    7639              :            for (int i = 0; i < n1 / VF; ++i)
    7640              :              for (int j = 0; j < n2; ++j)
    7641              :                for (int k = 0; k < VF; ++k)
    7642              :                  l += a[j];
    7643              : 
    7644              :          which is a reassociation of the original operation.  */
    7645           66 :       if (dump_enabled_p ())
    7646           20 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7647              :                          "in-order double reduction not supported.\n");
    7648              : 
    7649              :       return false;
    7650              :     }
    7651              : 
    7652        72905 :   if (reduction_type == FOLD_LEFT_REDUCTION
    7653         4453 :       && SLP_TREE_LANES (slp_node) > 1
    7654          194 :       && !reduc_chain)
    7655              :     {
    7656              :       /* We cannot use in-order reductions in this case because there is
    7657              :          an implicit reassociation of the operations involved.  */
    7658           72 :       if (dump_enabled_p ())
    7659            6 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7660              :                          "in-order unchained SLP reductions not supported.\n");
    7661              :       return false;
    7662              :     }
    7663              : 
    7664              :   /* For double reductions, and for SLP reductions with a neutral value,
    7665              :      we construct a variable-length initial vector by loading a vector
    7666              :      full of the neutral value and then shift-and-inserting the start
    7667              :      values into the low-numbered elements.  This is however not needed
    7668              :      when neutral and initial value are equal or we can handle the
    7669              :      initial value via adjustment in the epilogue.  */
    7670        72833 :   if ((double_reduc || neutral_op)
    7671              :       && !nunits_out.is_constant ()
    7672              :       && reduction_type != INTEGER_INDUC_COND_REDUCTION
    7673              :       && !((SLP_TREE_LANES (slp_node) == 1 || reduc_chain)
    7674              :            && neutral_op
    7675              :            && (!double_reduc
    7676              :                || operand_equal_p (neutral_op,
    7677              :                                    vect_phi_initial_value (reduc_def_phi))))
    7678              :       && !direct_internal_fn_supported_p (IFN_VEC_SHL_INSERT,
    7679              :                                           vectype_out, OPTIMIZE_FOR_BOTH))
    7680              :     {
    7681              :       if (dump_enabled_p ())
    7682              :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7683              :                          "reduction on variable-length vectors requires"
    7684              :                          " target support for a vector-shift-and-insert"
    7685              :                          " operation.\n");
    7686              :       return false;
    7687              :     }
    7688              : 
    7689              :   /* Check extra constraints for variable-length unchained SLP reductions.  */
    7690        72833 :   if (!reduc_chain
    7691              :       && !nunits_out.is_constant ())
    7692              :     {
    7693              :       /* We checked above that we could build the initial vector when
    7694              :          there's a neutral element value.  Check here for the case in
    7695              :          which each SLP statement has its own initial value and in which
    7696              :          that value needs to be repeated for every instance of the
    7697              :          statement within the initial vector.  */
    7698              :       unsigned int group_size = SLP_TREE_LANES (slp_node);
    7699              :       if (!neutral_op
    7700              :           && !can_duplicate_and_interleave_p (loop_vinfo, group_size,
    7701              :                                               TREE_TYPE (vectype_out)))
    7702              :         {
    7703              :           if (dump_enabled_p ())
    7704              :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7705              :                              "unsupported form of SLP reduction for"
    7706              :                              " variable-length vectors: cannot build"
    7707              :                              " initial vector.\n");
    7708              :           return false;
    7709              :         }
    7710              :       /* The epilogue code relies on the number of elements being a multiple
    7711              :          of the group size.  The duplicate-and-interleave approach to setting
    7712              :          up the initial vector does too.  */
    7713              :       if (!multiple_p (nunits_out, group_size))
    7714              :         {
    7715              :           if (dump_enabled_p ())
    7716              :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7717              :                              "unsupported form of SLP reduction for"
    7718              :                              " variable-length vectors: the vector size"
    7719              :                              " is not a multiple of the number of results.\n");
    7720              :           return false;
    7721              :         }
    7722              :     }
    7723              : 
    7724        72833 :   if (reduction_type == COND_REDUCTION)
    7725              :     {
    7726          437 :       widest_int ni;
    7727              : 
    7728          437 :       if (! max_loop_iterations (loop, &ni))
    7729              :         {
    7730           14 :           if (dump_enabled_p ())
    7731            0 :             dump_printf_loc (MSG_NOTE, vect_location,
    7732              :                              "loop count not known, cannot create cond "
    7733              :                              "reduction.\n");
    7734              :           return false;
    7735              :         }
    7736              :       /* Convert backedges to iterations.  */
    7737          423 :       ni += 1;
    7738              : 
    7739              :       /* The additional index will be the same type as the condition.  Check
    7740              :          that the loop can fit into this less one (because we'll use up the
    7741              :          zero slot for when there are no matches).  */
    7742          423 :       tree max_index = TYPE_MAX_VALUE (cr_index_scalar_type);
    7743          423 :       if (wi::geu_p (ni, wi::to_widest (max_index)))
    7744              :         {
    7745           90 :           if (dump_enabled_p ())
    7746           54 :             dump_printf_loc (MSG_NOTE, vect_location,
    7747              :                              "loop size is greater than data size.\n");
    7748              :           return false;
    7749              :         }
    7750          437 :     }
    7751              : 
    7752              :   /* In case the vectorization factor (VF) is bigger than the number
    7753              :      of elements that we can fit in a vectype (nunits), we have to generate
    7754              :      more than one vector stmt - i.e - we need to "unroll" the
    7755              :      vector stmt by a factor VF/nunits.  For more details see documentation
    7756              :      in vectorizable_operation.  */
    7757              : 
    7758              :   /* If the reduction is used in an outer loop we need to generate
    7759              :      VF intermediate results, like so (e.g. for ncopies=2):
    7760              :         r0 = phi (init, r0)
    7761              :         r1 = phi (init, r1)
    7762              :         r0 = x0 + r0;
    7763              :         r1 = x1 + r1;
    7764              :     (i.e. we generate VF results in 2 registers).
    7765              :     In this case we have a separate def-use cycle for each copy, and therefore
    7766              :     for each copy we get the vector def for the reduction variable from the
    7767              :     respective phi node created for this copy.
    7768              : 
    7769              :     Otherwise (the reduction is unused in the loop nest), we can combine
    7770              :     together intermediate results, like so (e.g. for ncopies=2):
    7771              :         r = phi (init, r)
    7772              :         r = x0 + r;
    7773              :         r = x1 + r;
    7774              :    (i.e. we generate VF/2 results in a single register).
    7775              :    In this case for each copy we get the vector def for the reduction variable
    7776              :    from the vectorized reduction operation generated in the previous iteration.
    7777              : 
    7778              :    This only works when we see both the reduction PHI and its only consumer
    7779              :    in vectorizable_reduction and there are no intermediate stmts
    7780              :    participating.  When unrolling we want each unrolled iteration to have its
    7781              :    own reduction accumulator since one of the main goals of unrolling a
    7782              :    reduction is to reduce the aggregate loop-carried latency.  */
    7783        72729 :   if (ncopies > 1
    7784        72729 :       && !reduc_chain
    7785         8140 :       && SLP_TREE_LANES (slp_node) == 1
    7786         7972 :       && (STMT_VINFO_RELEVANT (stmt_info) <= vect_used_only_live)
    7787         7949 :       && reduc_chain_length == 1
    7788         7545 :       && loop_vinfo->suggested_unroll_factor == 1)
    7789        72729 :     single_defuse_cycle = true;
    7790              : 
    7791        72729 :   if (single_defuse_cycle && !lane_reducing)
    7792              :     {
    7793         6588 :       gcc_assert (op.code != COND_EXPR);
    7794              : 
    7795              :       /* 4. check support for the operation in the loop
    7796              : 
    7797              :          This isn't necessary for the lane reduction codes, since they
    7798              :          can only be produced by pattern matching, and it's up to the
    7799              :          pattern matcher to test for support.  The main reason for
    7800              :          specifically skipping this step is to avoid rechecking whether
    7801              :          mixed-sign dot-products can be implemented using signed
    7802              :          dot-products.  */
    7803         6588 :       machine_mode vec_mode = TYPE_MODE (vectype_in);
    7804         6588 :       if (!directly_supported_p (op.code, vectype_in, optab_vector))
    7805              :         {
    7806         2077 :           if (dump_enabled_p ())
    7807           36 :             dump_printf (MSG_NOTE, "op not supported by target.\n");
    7808         4154 :           if (maybe_ne (GET_MODE_SIZE (vec_mode), UNITS_PER_WORD)
    7809         2077 :               || !vect_can_vectorize_without_simd_p (op.code))
    7810              :             single_defuse_cycle = false;
    7811              :           else
    7812           11 :             if (dump_enabled_p ())
    7813            0 :               dump_printf (MSG_NOTE, "proceeding using word mode.\n");
    7814              :         }
    7815              : 
    7816         6588 :       if (vect_emulated_vector_p (vectype_in)
    7817         6588 :           && !vect_can_vectorize_without_simd_p (op.code))
    7818              :         {
    7819            0 :           if (dump_enabled_p ())
    7820            0 :             dump_printf (MSG_NOTE, "using word mode not possible.\n");
    7821              :           return false;
    7822              :         }
    7823              :     }
    7824        72729 :   if (dump_enabled_p () && single_defuse_cycle)
    7825          710 :     dump_printf_loc (MSG_NOTE, vect_location,
    7826              :                      "using single def-use cycle for reduction by reducing "
    7827              :                      "multiple vectors to one in the loop body\n");
    7828        72729 :   VECT_REDUC_INFO_FORCE_SINGLE_CYCLE (reduc_info) = single_defuse_cycle;
    7829              : 
    7830              :   /* For lane-reducing operation, the below processing related to single
    7831              :      defuse-cycle will be done in its own vectorizable function.  One more
    7832              :      thing to note is that the operation must not be involved in fold-left
    7833              :      reduction.  */
    7834        72729 :   single_defuse_cycle &= !lane_reducing;
    7835              : 
    7836        72729 :   if (single_defuse_cycle || reduction_type == FOLD_LEFT_REDUCTION)
    7837        28814 :     for (i = 0; i < (int) op.num_ops; i++)
    7838        20002 :       if (!vect_maybe_update_slp_op_vectype (slp_op[i], vectype_op[i]))
    7839              :         {
    7840            0 :           if (dump_enabled_p ())
    7841            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7842              :                              "incompatible vector types for invariants\n");
    7843              :           return false;
    7844              :         }
    7845              : 
    7846        72729 :   vect_model_reduction_cost (loop_vinfo, slp_for_stmt_info, reduc_fn,
    7847              :                              reduction_type, ncopies, cost_vec);
    7848              :   /* Cost the reduction op inside the loop if transformed via
    7849              :      vect_transform_reduction for non-lane-reducing operation.  Otherwise
    7850              :      this is costed by the separate vectorizable_* routines.  */
    7851        72729 :   if (single_defuse_cycle)
    7852         4522 :     record_stmt_cost (cost_vec, ncopies, vector_stmt,
    7853              :                       slp_for_stmt_info, 0, vect_body);
    7854              : 
    7855        72729 :   if (dump_enabled_p ()
    7856        72729 :       && reduction_type == FOLD_LEFT_REDUCTION)
    7857          262 :     dump_printf_loc (MSG_NOTE, vect_location,
    7858              :                      "using an in-order (fold-left) reduction.\n");
    7859        72729 :   SLP_TREE_TYPE (slp_node) = cycle_phi_info_type;
    7860              : 
    7861              :   /* All but single defuse-cycle optimized and fold-left reductions go
    7862              :      through their own vectorizable_* routines.  */
    7863        72729 :   stmt_vec_info tem
    7864        72729 :     = SLP_TREE_REPRESENTATIVE (SLP_INSTANCE_TREE (slp_node_instance));
    7865        72729 :   if (!single_defuse_cycle && reduction_type != FOLD_LEFT_REDUCTION)
    7866        63917 :     STMT_VINFO_DEF_TYPE (tem) = vect_internal_def;
    7867              :   else
    7868              :     {
    7869         8812 :       STMT_VINFO_DEF_TYPE (tem) = vect_reduction_def;
    7870         8812 :       if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
    7871         8812 :           && vect_reduction_update_partial_vector_usage (loop_vinfo, reduc_info,
    7872              :                                                          op.code, op.type,
    7873              :                                                          vectype_in))
    7874              :         {
    7875         2014 :           internal_fn reduc_fn = VECT_REDUC_INFO_FN (reduc_info);
    7876         2014 :           internal_fn mask_reduc_fn
    7877         2014 :             = get_masked_reduction_fn (reduc_fn, vectype_in);
    7878         2014 :           vec_loop_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
    7879         2014 :           vec_loop_lens *lens = &LOOP_VINFO_LENS (loop_vinfo);
    7880         2014 :           if (mask_reduc_fn == IFN_MASK_LEN_FOLD_LEFT_PLUS)
    7881            0 :             vect_record_loop_len (loop_vinfo, lens, ncopies, vectype_in, 1);
    7882              :           else
    7883         2014 :             vect_record_loop_mask (loop_vinfo, masks, ncopies,
    7884              :                                    vectype_in, NULL);
    7885              :         }
    7886              :     }
    7887              :   return true;
    7888              : }
    7889              : 
    7890              : /* STMT_INFO is a dot-product reduction whose multiplication operands
    7891              :    have different signs.  Emit a sequence to emulate the operation
    7892              :    using a series of signed DOT_PROD_EXPRs and return the last
    7893              :    statement generated.  VEC_DEST is the result of the vector operation
    7894              :    and VOP lists its inputs.  */
    7895              : 
    7896              : static gassign *
    7897            4 : vect_emulate_mixed_dot_prod (loop_vec_info loop_vinfo, stmt_vec_info stmt_info,
    7898              :                              gimple_stmt_iterator *gsi, tree vec_dest,
    7899              :                              tree vop[3])
    7900              : {
    7901            4 :   tree wide_vectype = signed_type_for (TREE_TYPE (vec_dest));
    7902            4 :   tree narrow_vectype = signed_type_for (TREE_TYPE (vop[0]));
    7903            4 :   tree narrow_elttype = TREE_TYPE (narrow_vectype);
    7904            4 :   gimple *new_stmt;
    7905              : 
    7906              :   /* Make VOP[0] the unsigned operand VOP[1] the signed operand.  */
    7907            4 :   if (!TYPE_UNSIGNED (TREE_TYPE (vop[0])))
    7908            0 :     std::swap (vop[0], vop[1]);
    7909              : 
    7910              :   /* Convert all inputs to signed types.  */
    7911           12 :   for (int i = 1; i < 3; ++i)
    7912            8 :     if (TYPE_UNSIGNED (TREE_TYPE (vop[i])))
    7913              :       {
    7914            0 :         tree tmp = make_ssa_name (signed_type_for (TREE_TYPE (vop[i])));
    7915            0 :         new_stmt = gimple_build_assign (tmp, NOP_EXPR, vop[i]);
    7916            0 :         vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    7917            0 :         vop[i] = tmp;
    7918              :       }
    7919              : 
    7920              :   /* In the comments below we assume 8-bit inputs for simplicity,
    7921              :      but the approach works for any full integer type.  */
    7922              : 
    7923              :   /* Create a vector of -128.  */
    7924            4 :   tree min_narrow_elttype = TYPE_MIN_VALUE (narrow_elttype);
    7925            4 :   tree min_narrow = build_vector_from_val (TREE_TYPE (vop[0]),
    7926            4 :                                            fold_convert
    7927              :                                              (TREE_TYPE (TREE_TYPE (vop[0])),
    7928              :                                               min_narrow_elttype));
    7929              : 
    7930              :   /* Create a vector of 64.  */
    7931            4 :   auto half_wi = wi::lrshift (wi::to_wide (min_narrow_elttype), 1);
    7932            4 :   tree half_narrow = wide_int_to_tree (narrow_elttype, half_wi);
    7933            4 :   half_narrow = build_vector_from_val (narrow_vectype, half_narrow);
    7934              : 
    7935              :   /* Emit: SUB_RES = VOP[0] - 128 in an unsigned type.  */
    7936            4 :   tree sub_res = make_ssa_name (TREE_TYPE (vop[0]));
    7937            4 :   new_stmt = gimple_build_assign (sub_res, PLUS_EXPR, vop[0], min_narrow);
    7938            4 :   vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    7939              : 
    7940            4 :   vop[0] = make_ssa_name (narrow_vectype);
    7941            4 :   new_stmt = gimple_build_assign (vop[0], VIEW_CONVERT_EXPR,
    7942              :                                   build1 (VIEW_CONVERT_EXPR, narrow_vectype,
    7943              :                                           sub_res));
    7944            4 :   vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    7945              : 
    7946              :   /* Emit:
    7947              : 
    7948              :        STAGE1 = DOT_PROD_EXPR <VOP[1], 64, VOP[2]>;
    7949              :        STAGE2 = DOT_PROD_EXPR <VOP[1], 64, STAGE1>;
    7950              :        STAGE3 = DOT_PROD_EXPR <SUB_RES, -128, STAGE2>;
    7951              : 
    7952              :      on the basis that x * y == (x - 128) * y + 64 * y + 64 * y
    7953              :      Doing the two 64 * y steps first allows more time to compute x.  */
    7954            4 :   tree stage1 = make_ssa_name (wide_vectype);
    7955            4 :   new_stmt = gimple_build_assign (stage1, DOT_PROD_EXPR,
    7956              :                                   vop[1], half_narrow, vop[2]);
    7957            4 :   vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    7958              : 
    7959            4 :   tree stage2 = make_ssa_name (wide_vectype);
    7960            4 :   new_stmt = gimple_build_assign (stage2, DOT_PROD_EXPR,
    7961              :                                   vop[1], half_narrow, stage1);
    7962            4 :   vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    7963              : 
    7964            4 :   tree stage3 = make_ssa_name (wide_vectype);
    7965            4 :   new_stmt = gimple_build_assign (stage3, DOT_PROD_EXPR,
    7966              :                                   vop[0], vop[1], stage2);
    7967            4 :   vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    7968              : 
    7969              :   /* Convert STAGE3 to the reduction type.  */
    7970            4 :   return gimple_build_assign (vec_dest, CONVERT_EXPR, stage3);
    7971            4 : }
    7972              : 
    7973              : /* Transform the definition stmt STMT_INFO of a reduction PHI backedge
    7974              :    value.  */
    7975              : 
    7976              : bool
    7977         2699 : vect_transform_reduction (loop_vec_info loop_vinfo,
    7978              :                           stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
    7979              :                           slp_tree slp_node)
    7980              : {
    7981         2699 :   tree vectype_out = SLP_TREE_VECTYPE (slp_node);
    7982         2699 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    7983              : 
    7984         2699 :   vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
    7985              : 
    7986         2699 :   if (nested_in_vect_loop_p (loop, stmt_info))
    7987              :     {
    7988            0 :       loop = loop->inner;
    7989            0 :       gcc_assert (VECT_REDUC_INFO_DEF_TYPE (reduc_info)
    7990              :                   == vect_double_reduction_def);
    7991              :     }
    7992              : 
    7993         2699 :   gimple_match_op op;
    7994         2699 :   if (!gimple_extract_op (stmt_info->stmt, &op))
    7995            0 :     gcc_unreachable ();
    7996              : 
    7997              :   /* All uses but the last are expected to be defined in the loop.
    7998              :      The last use is the reduction variable.  In case of nested cycle this
    7999              :      assumption is not true: we use reduc_index to record the index of the
    8000              :      reduction variable.  */
    8001         2699 :   int reduc_index = SLP_TREE_REDUC_IDX (slp_node);
    8002         2699 :   tree vectype_in = SLP_TREE_VECTYPE (slp_node);
    8003         2699 :   if (lane_reducing_op_p (op.code))
    8004          281 :     vectype_in = SLP_TREE_VECTYPE (SLP_TREE_CHILDREN (slp_node)[0]);
    8005              : 
    8006         2699 :   code_helper code = canonicalize_code (op.code, op.type);
    8007         2699 :   internal_fn cond_fn
    8008          482 :     = ((code.is_internal_fn ()
    8009          482 :         && internal_fn_mask_index ((internal_fn)code) != -1)
    8010         2699 :        ? (internal_fn)code : get_conditional_internal_fn (code, op.type));
    8011              : 
    8012         2699 :   vec_loop_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
    8013         2699 :   vec_loop_lens *lens = &LOOP_VINFO_LENS (loop_vinfo);
    8014         2699 :   bool mask_by_cond_expr = use_mask_by_cond_expr_p (code, cond_fn, vectype_in);
    8015              : 
    8016              :   /* Transform.  */
    8017         2699 :   tree new_temp = NULL_TREE;
    8018        18893 :   auto_vec<tree> vec_oprnds[3];
    8019              : 
    8020         2699 :   if (dump_enabled_p ())
    8021          792 :     dump_printf_loc (MSG_NOTE, vect_location, "transform reduction.\n");
    8022              : 
    8023              :   /* A binary COND_OP reduction must have the same definition and else
    8024              :      value. */
    8025         3181 :   bool cond_fn_p = code.is_internal_fn ()
    8026          482 :     && conditional_internal_fn_code (internal_fn (code)) != ERROR_MARK;
    8027          482 :   if (cond_fn_p)
    8028              :     {
    8029          482 :       gcc_assert (code == IFN_COND_ADD || code == IFN_COND_SUB
    8030              :                   || code == IFN_COND_MUL || code == IFN_COND_AND
    8031              :                   || code == IFN_COND_IOR || code == IFN_COND_XOR
    8032              :                   || code == IFN_COND_MIN || code == IFN_COND_MAX);
    8033          482 :       gcc_assert (op.num_ops == 4
    8034              :                   && (op.ops[reduc_index]
    8035              :                       == op.ops[internal_fn_else_index ((internal_fn) code)]));
    8036              :     }
    8037              : 
    8038         2699 :   bool masked_loop_p = LOOP_VINFO_FULLY_MASKED_P (loop_vinfo);
    8039              : 
    8040         2699 :   vect_reduction_type reduction_type = VECT_REDUC_INFO_TYPE (reduc_info);
    8041         2699 :   if (reduction_type == FOLD_LEFT_REDUCTION)
    8042              :     {
    8043          927 :       internal_fn reduc_fn = VECT_REDUC_INFO_FN (reduc_info);
    8044          927 :       gcc_assert (code.is_tree_code () || cond_fn_p);
    8045          927 :       return vectorize_fold_left_reduction
    8046          927 :           (loop_vinfo, stmt_info, gsi, slp_node,
    8047          927 :            code, reduc_fn, op.num_ops, vectype_in,
    8048          927 :            reduc_index, masks, lens);
    8049              :     }
    8050              : 
    8051         1772 :   bool single_defuse_cycle = VECT_REDUC_INFO_FORCE_SINGLE_CYCLE (reduc_info);
    8052         1772 :   bool lane_reducing = lane_reducing_op_p (code);
    8053         1491 :   gcc_assert (single_defuse_cycle || lane_reducing);
    8054              : 
    8055         1772 :   if (lane_reducing)
    8056              :     {
    8057              :       /* The last operand of lane-reducing op is for reduction.  */
    8058          281 :       gcc_assert (reduc_index == (int) op.num_ops - 1);
    8059              :     }
    8060              : 
    8061              :   /* Create the destination vector  */
    8062         1772 :   tree scalar_dest = gimple_get_lhs (stmt_info->stmt);
    8063         1772 :   tree vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
    8064              : 
    8065              :   /* Get NCOPIES vector definitions for all operands except the reduction
    8066              :      definition.  */
    8067         1772 :   if (!cond_fn_p)
    8068              :     {
    8069         1319 :       gcc_assert (reduc_index >= 0 && reduc_index <= 2);
    8070         1319 :       vect_get_vec_defs (loop_vinfo, slp_node,
    8071         1319 :                          single_defuse_cycle && reduc_index == 0
    8072         1319 :                          ? NULL_TREE : op.ops[0], &vec_oprnds[0],
    8073         1319 :                          single_defuse_cycle && reduc_index == 1
    8074         1319 :                          ? NULL_TREE : op.ops[1], &vec_oprnds[1],
    8075         1319 :                          op.num_ops == 3
    8076          281 :                          && !(single_defuse_cycle && reduc_index == 2)
    8077         1426 :                          ? op.ops[2] : NULL_TREE, &vec_oprnds[2]);
    8078              :     }
    8079              :   else
    8080              :     {
    8081              :       /* For a conditional operation pass the truth type as mask
    8082              :          vectype.  */
    8083          453 :       gcc_assert (single_defuse_cycle
    8084              :                   && (reduc_index == 1 || reduc_index == 2));
    8085          453 :       vect_get_vec_defs (loop_vinfo, slp_node, op.ops[0],
    8086              :                          &vec_oprnds[0],
    8087            2 :                          reduc_index == 1 ? NULL_TREE : op.ops[1],
    8088              :                          &vec_oprnds[1],
    8089          453 :                          reduc_index == 2 ? NULL_TREE : op.ops[2],
    8090              :                          &vec_oprnds[2]);
    8091              :     }
    8092              : 
    8093              :   /* For single def-use cycles get one copy of the vectorized reduction
    8094              :      definition.  */
    8095         3058 :   unsigned vec_in_num = vec_oprnds[reduc_index == 0 ? 1 : 0].length ();
    8096         1772 :   if (single_defuse_cycle)
    8097              :     {
    8098         1665 :       vect_get_vec_defs (loop_vinfo, slp_node,
    8099         1665 :                          reduc_index == 0 ? op.ops[0] : NULL_TREE,
    8100              :                          &vec_oprnds[0],
    8101         1665 :                          reduc_index == 1 ? op.ops[1] : NULL_TREE,
    8102              :                          &vec_oprnds[1],
    8103         1665 :                          reduc_index == 2 ? op.ops[2] : NULL_TREE,
    8104              :                          &vec_oprnds[2]);
    8105              :     }
    8106          107 :   else if (lane_reducing)
    8107              :     {
    8108              :       /* For normal reduction, consistency between vectorized def/use is
    8109              :          naturally ensured when mapping from scalar statement.  But if lane-
    8110              :          reducing op is involved in reduction, thing would become somewhat
    8111              :          complicated in that the op's result and operand for accumulation are
    8112              :          limited to less lanes than other operands, which certainly causes
    8113              :          def/use mismatch on adjacent statements around the op if do not have
    8114              :          any kind of specific adjustment.  One approach is to refit lane-
    8115              :          reducing op in the way of introducing new trivial pass-through copies
    8116              :          to fix possible def/use gap, so as to make it behave like a normal op.
    8117              :          And vector reduction PHIs are always generated to the full extent, no
    8118              :          matter lane-reducing op exists or not.  If some copies or PHIs are
    8119              :          actually superfluous, they would be cleaned up by passes after
    8120              :          vectorization.  An example for single-lane slp, lane-reducing ops
    8121              :          with mixed input vectypes in a reduction chain, is given as below.
    8122              :          Similarly, this handling is applicable for multiple-lane slp as well.
    8123              : 
    8124              :            int sum = 1;
    8125              :            for (i)
    8126              :              {
    8127              :                sum += d0[i] * d1[i];      // dot-prod <vector(16) char>
    8128              :                sum += w[i];               // widen-sum <vector(16) char>
    8129              :                sum += abs(s0[i] - s1[i]); // sad <vector(8) short>
    8130              :                sum += n[i];               // normal <vector(4) int>
    8131              :              }
    8132              : 
    8133              :          The vector size is 128-bit,vectorization factor is 16.  Reduction
    8134              :          statements would be transformed as:
    8135              : 
    8136              :            vector<4> int sum_v0 = { 0, 0, 0, 1 };
    8137              :            vector<4> int sum_v1 = { 0, 0, 0, 0 };
    8138              :            vector<4> int sum_v2 = { 0, 0, 0, 0 };
    8139              :            vector<4> int sum_v3 = { 0, 0, 0, 0 };
    8140              : 
    8141              :            for (i / 16)
    8142              :              {
    8143              :                sum_v0 = DOT_PROD (d0_v0[i: 0 ~ 15], d1_v0[i: 0 ~ 15], sum_v0);
    8144              :                sum_v1 = sum_v1;  // copy
    8145              :                sum_v2 = sum_v2;  // copy
    8146              :                sum_v3 = sum_v3;  // copy
    8147              : 
    8148              :                sum_v0 = sum_v0;  // copy
    8149              :                sum_v1 = WIDEN_SUM (w_v1[i: 0 ~ 15], sum_v1);
    8150              :                sum_v2 = sum_v2;  // copy
    8151              :                sum_v3 = sum_v3;  // copy
    8152              : 
    8153              :                sum_v0 = sum_v0;  // copy
    8154              :                sum_v1 = SAD (s0_v1[i: 0 ~ 7 ], s1_v1[i: 0 ~ 7 ], sum_v1);
    8155              :                sum_v2 = SAD (s0_v2[i: 8 ~ 15], s1_v2[i: 8 ~ 15], sum_v2);
    8156              :                sum_v3 = sum_v3;  // copy
    8157              : 
    8158              :                sum_v0 += n_v0[i: 0  ~ 3 ];
    8159              :                sum_v1 += n_v1[i: 4  ~ 7 ];
    8160              :                sum_v2 += n_v2[i: 8  ~ 11];
    8161              :                sum_v3 += n_v3[i: 12 ~ 15];
    8162              :              }
    8163              : 
    8164              :          Moreover, for a higher instruction parallelism in final vectorized
    8165              :          loop, it is considered to make those effective vector lane-reducing
    8166              :          ops be distributed evenly among all def-use cycles.  In the above
    8167              :          example, DOT_PROD, WIDEN_SUM and SADs are generated into disparate
    8168              :          cycles, instruction dependency among them could be eliminated.  */
    8169          107 :       unsigned effec_ncopies = vec_oprnds[0].length ();
    8170          107 :       unsigned total_ncopies = vec_oprnds[reduc_index].length ();
    8171              : 
    8172          107 :       gcc_assert (effec_ncopies <= total_ncopies);
    8173              : 
    8174          107 :       if (effec_ncopies < total_ncopies)
    8175              :         {
    8176          294 :           for (unsigned i = 0; i < op.num_ops - 1; i++)
    8177              :             {
    8178          392 :               gcc_assert (vec_oprnds[i].length () == effec_ncopies);
    8179          196 :               vec_oprnds[i].safe_grow_cleared (total_ncopies);
    8180              :             }
    8181              :         }
    8182              : 
    8183          107 :       tree reduc_vectype_in = vectype_in;
    8184          107 :       gcc_assert (reduc_vectype_in);
    8185              :     }
    8186              : 
    8187         1772 :   bool emulated_mixed_dot_prod = vect_is_emulated_mixed_dot_prod (slp_node);
    8188         1772 :   unsigned num = vec_oprnds[reduc_index == 0 ? 1 : 0].length ();
    8189         1772 :   unsigned mask_index = 0;
    8190              : 
    8191         7777 :   for (unsigned i = 0; i < num; ++i)
    8192              :     {
    8193         6005 :       gimple *new_stmt;
    8194         6005 :       tree vop[3] = { vec_oprnds[0][i], vec_oprnds[1][i], NULL_TREE };
    8195         6005 :       if (!vop[0] || !vop[1])
    8196              :         {
    8197          503 :           tree reduc_vop = vec_oprnds[reduc_index][i];
    8198              : 
    8199              :           /* If could not generate an effective vector statement for current
    8200              :              portion of reduction operand, insert a trivial copy to simply
    8201              :              handle over the operand to other dependent statements.  */
    8202          503 :           gcc_assert (reduc_vop);
    8203              : 
    8204          503 :           if (TREE_CODE (reduc_vop) == SSA_NAME
    8205          503 :               && !SSA_NAME_IS_DEFAULT_DEF (reduc_vop))
    8206          503 :             new_stmt = SSA_NAME_DEF_STMT (reduc_vop);
    8207              :           else
    8208              :             {
    8209            0 :               new_temp = make_ssa_name (vec_dest);
    8210            0 :               new_stmt = gimple_build_assign (new_temp, reduc_vop);
    8211            0 :               vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt,
    8212              :                                            gsi);
    8213              :             }
    8214              :         }
    8215         5502 :       else if (masked_loop_p && !mask_by_cond_expr)
    8216              :         {
    8217              :           /* No conditional ifns have been defined for lane-reducing op
    8218              :              yet.  */
    8219           16 :           gcc_assert (!lane_reducing);
    8220              : 
    8221           16 :           tree mask = vect_get_loop_mask (loop_vinfo, gsi, masks,
    8222              :                                           vec_in_num, vectype_in,
    8223              :                                           mask_index++);
    8224           16 :           gcall *call;
    8225           24 :           if (code.is_internal_fn () && cond_fn_p)
    8226              :             {
    8227           16 :               gcc_assert (op.num_ops >= 3
    8228              :                           && internal_fn_mask_index (internal_fn (code)) == 0);
    8229            8 :               vop[2] = vec_oprnds[2][i];
    8230            8 :               mask = prepare_vec_mask (loop_vinfo, TREE_TYPE (mask),
    8231              :                                        mask, vop[0], gsi);
    8232            8 :               call = gimple_build_call_internal (cond_fn, 4, mask, vop[1],
    8233              :                                                  vop[2], vop[reduc_index]);
    8234              :             }
    8235              :           else
    8236            8 :             call = gimple_build_call_internal (cond_fn, 4, mask, vop[0],
    8237              :                                                vop[1], vop[reduc_index]);
    8238           16 :           new_temp = make_ssa_name (vec_dest, call);
    8239           16 :           gimple_call_set_lhs (call, new_temp);
    8240           16 :           gimple_call_set_nothrow (call, true);
    8241           16 :           vect_finish_stmt_generation (loop_vinfo, stmt_info, call, gsi);
    8242           16 :           new_stmt = call;
    8243              :         }
    8244              :       else
    8245              :         {
    8246         5486 :           if (op.num_ops >= 3)
    8247         1792 :             vop[2] = vec_oprnds[2][i];
    8248              : 
    8249         5486 :           if (masked_loop_p && mask_by_cond_expr)
    8250              :             {
    8251            4 :               tree mask = vect_get_loop_mask (loop_vinfo, gsi, masks,
    8252              :                                               vec_in_num, vectype_in,
    8253              :                                               mask_index++);
    8254            4 :               build_vect_cond_expr (code, vop, mask, gsi);
    8255              :             }
    8256              : 
    8257         5486 :           if (emulated_mixed_dot_prod)
    8258            4 :             new_stmt = vect_emulate_mixed_dot_prod (loop_vinfo, stmt_info, gsi,
    8259              :                                                     vec_dest, vop);
    8260              : 
    8261         6824 :           else if (code.is_internal_fn () && !cond_fn_p)
    8262            0 :             new_stmt = gimple_build_call_internal (internal_fn (code),
    8263              :                                                    op.num_ops,
    8264              :                                                    vop[0], vop[1], vop[2]);
    8265         6824 :           else if (code.is_internal_fn () && cond_fn_p)
    8266         1342 :             new_stmt = gimple_build_call_internal (internal_fn (code),
    8267              :                                                    op.num_ops,
    8268              :                                                    vop[0], vop[1], vop[2],
    8269              :                                                    vop[reduc_index]);
    8270              :           else
    8271         4140 :             new_stmt = gimple_build_assign (vec_dest, tree_code (op.code),
    8272              :                                             vop[0], vop[1], vop[2]);
    8273         5486 :           new_temp = make_ssa_name (vec_dest, new_stmt);
    8274         5486 :           gimple_set_lhs (new_stmt, new_temp);
    8275         5486 :           vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    8276              :         }
    8277              : 
    8278         6005 :       if (single_defuse_cycle && i < num - 1)
    8279         3571 :         vec_oprnds[reduc_index].safe_push (gimple_get_lhs (new_stmt));
    8280              :       else
    8281         2434 :         slp_node->push_vec_def (new_stmt);
    8282              :     }
    8283              : 
    8284              :   return true;
    8285        10796 : }
    8286              : 
    8287              : /* Transform phase of a cycle PHI.  */
    8288              : 
    8289              : bool
    8290        23769 : vect_transform_cycle_phi (loop_vec_info loop_vinfo,
    8291              :                           stmt_vec_info stmt_info,
    8292              :                           slp_tree slp_node, slp_instance slp_node_instance)
    8293              : {
    8294        23769 :   tree vectype_out = SLP_TREE_VECTYPE (slp_node);
    8295        23769 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    8296        23769 :   int i;
    8297        23769 :   bool nested_cycle = false;
    8298        23769 :   int vec_num;
    8299              : 
    8300        23769 :   if (nested_in_vect_loop_p (loop, stmt_info))
    8301              :     {
    8302        23769 :       loop = loop->inner;
    8303        23769 :       nested_cycle = true;
    8304              :     }
    8305              : 
    8306        23769 :   vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
    8307        23769 :   if (reduc_info
    8308        23167 :       && (VECT_REDUC_INFO_TYPE (reduc_info) == EXTRACT_LAST_REDUCTION
    8309        23167 :           || VECT_REDUC_INFO_TYPE (reduc_info) == FOLD_LEFT_REDUCTION))
    8310              :     /* Leave the scalar phi in place.  */
    8311              :     return true;
    8312              : 
    8313        22240 :   if (reduc_info && reduc_info->is_reduc_chain && dump_enabled_p ())
    8314          133 :     dump_printf_loc (MSG_NOTE, vect_location,
    8315              :                      "vectorizing a reduction chain\n");
    8316              : 
    8317        22842 :   vec_num = vect_get_num_copies (loop_vinfo, slp_node);
    8318              : 
    8319              :   /* Check whether we should use a single PHI node and accumulate
    8320              :      vectors to one before the backedge.  */
    8321        22842 :   if (reduc_info && VECT_REDUC_INFO_FORCE_SINGLE_CYCLE (reduc_info))
    8322        22842 :     vec_num = 1;
    8323              : 
    8324              :   /* Create the destination vector  */
    8325        22842 :   gphi *phi = as_a <gphi *> (stmt_info->stmt);
    8326        22842 :   tree vec_dest = vect_create_destination_var (gimple_phi_result (phi),
    8327              :                                                vectype_out);
    8328              : 
    8329              :   /* Get the loop-entry arguments.  */
    8330        22842 :   auto_vec<tree> vec_initial_defs;
    8331        22842 :   vec_initial_defs.reserve (vec_num);
    8332              :   /* Optimize: if initial_def is for REDUC_MAX smaller than the base
    8333              :      and we can't use zero for induc_val, use initial_def.  Similarly
    8334              :      for REDUC_MIN and initial_def larger than the base.  */
    8335        22842 :   if (reduc_info
    8336        22240 :       && VECT_REDUC_INFO_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
    8337              :     {
    8338           62 :       gcc_assert (SLP_TREE_LANES (slp_node) == 1);
    8339           62 :       tree initial_def = vect_phi_initial_value (phi);
    8340           62 :       VECT_REDUC_INFO_INITIAL_VALUES (reduc_info).safe_push (initial_def);
    8341           62 :       tree induc_val = VECT_REDUC_INFO_INDUC_COND_INITIAL_VAL (reduc_info);
    8342           62 :       if (TREE_CODE (initial_def) == INTEGER_CST
    8343           60 :           && !integer_zerop (induc_val)
    8344          122 :           && ((VECT_REDUC_INFO_CODE (reduc_info) == MAX_EXPR
    8345           42 :                && tree_int_cst_lt (initial_def, induc_val))
    8346           58 :               || (VECT_REDUC_INFO_CODE (reduc_info) == MIN_EXPR
    8347           18 :                   && tree_int_cst_lt (induc_val, initial_def))))
    8348              :         {
    8349            2 :           induc_val = initial_def;
    8350              :           /* Communicate we used the initial_def to epilouge
    8351              :              generation.  */
    8352            2 :           VECT_REDUC_INFO_INDUC_COND_INITIAL_VAL (reduc_info) = NULL_TREE;
    8353              :         }
    8354           62 :       vec_initial_defs.quick_push
    8355           62 :         (build_vector_from_val (vectype_out, induc_val));
    8356           62 :     }
    8357        22780 :   else if (nested_cycle)
    8358              :     {
    8359          688 :       unsigned phi_idx = loop_preheader_edge (loop)->dest_idx;
    8360          688 :       vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[phi_idx],
    8361              :                          &vec_initial_defs);
    8362              :     }
    8363              :   else
    8364              :     {
    8365        22092 :       gcc_assert (slp_node == slp_node_instance->reduc_phis);
    8366        22092 :       vec<tree> &initial_values = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info);
    8367        22092 :       vec<stmt_vec_info> &stmts = SLP_TREE_SCALAR_STMTS (slp_node);
    8368              : 
    8369        22092 :       unsigned int num_phis = stmts.length ();
    8370        22092 :       if (reduc_info->is_reduc_chain)
    8371          213 :         num_phis = 1;
    8372        22092 :       initial_values.reserve (num_phis);
    8373        66736 :       for (unsigned int i = 0; i < num_phis; ++i)
    8374              :         {
    8375        22552 :           gphi *this_phi = as_a<gphi *> (stmts[i]->stmt);
    8376        22552 :           initial_values.quick_push (vect_phi_initial_value (this_phi));
    8377              :         }
    8378        22092 :       tree neutral_op = VECT_REDUC_INFO_NEUTRAL_OP (reduc_info);
    8379        22092 :       if (vec_num == 1
    8380        22092 :           && vect_find_reusable_accumulator (loop_vinfo,
    8381              :                                              reduc_info, vectype_out))
    8382              :         ;
    8383              :       /* Try to simplify the vector initialization by applying an
    8384              :          adjustment after the reduction has been performed.  This
    8385              :          can also break a critical path but on the other hand
    8386              :          requires to keep the initial value live across the loop.  */
    8387        17975 :       else if (neutral_op
    8388        17392 :                && initial_values.length () == 1
    8389        17193 :                && STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
    8390        35091 :                && !operand_equal_p (neutral_op, initial_values[0]))
    8391              :         {
    8392        12150 :           VECT_REDUC_INFO_EPILOGUE_ADJUSTMENT (reduc_info)
    8393        12150 :             = initial_values[0];
    8394        12150 :           initial_values[0] = neutral_op;
    8395              :         }
    8396        22092 :       if (!VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info)
    8397         4117 :           || loop_vinfo->main_loop_edge)
    8398        43738 :         get_initial_defs_for_reduction (loop_vinfo, reduc_info, vectype_out,
    8399              :                                         &vec_initial_defs, vec_num,
    8400              :                                         stmts.length (), neutral_op);
    8401              :     }
    8402              : 
    8403        22842 :   if (reduc_info)
    8404        22240 :   if (auto *accumulator = VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info))
    8405              :     {
    8406         4117 :       tree def = accumulator->reduc_input;
    8407         4117 :       if (!useless_type_conversion_p (vectype_out, TREE_TYPE (def)))
    8408              :         {
    8409         4114 :           unsigned int nreduc;
    8410         8228 :           bool res = constant_multiple_p (TYPE_VECTOR_SUBPARTS
    8411         4114 :                                             (TREE_TYPE (def)),
    8412         4114 :                                           TYPE_VECTOR_SUBPARTS (vectype_out),
    8413              :                                           &nreduc);
    8414            0 :           gcc_assert (res);
    8415         4114 :           gimple_seq stmts = NULL;
    8416              :           /* Reduce the single vector to a smaller one.  */
    8417         4114 :           if (nreduc != 1)
    8418              :             {
    8419              :               /* Perform the reduction in the appropriate type.  */
    8420         4114 :               tree rvectype = vectype_out;
    8421         4114 :               if (!useless_type_conversion_p (TREE_TYPE (vectype_out),
    8422         4114 :                                               TREE_TYPE (TREE_TYPE (def))))
    8423          235 :                 rvectype = build_vector_type (TREE_TYPE (TREE_TYPE (def)),
    8424              :                                               TYPE_VECTOR_SUBPARTS
    8425          470 :                                                 (vectype_out));
    8426         4114 :               def = vect_create_partial_epilog (def, rvectype,
    8427              :                                                 VECT_REDUC_INFO_CODE
    8428              :                                                   (reduc_info),
    8429              :                                                 &stmts);
    8430              :             }
    8431              :           /* The epilogue loop might use a different vector mode, like
    8432              :              VNx2DI vs. V2DI.  */
    8433         4114 :           if (TYPE_MODE (vectype_out) != TYPE_MODE (TREE_TYPE (def)))
    8434              :             {
    8435            0 :               tree reduc_type = build_vector_type_for_mode
    8436            0 :                 (TREE_TYPE (TREE_TYPE (def)), TYPE_MODE (vectype_out));
    8437            0 :               def = gimple_convert (&stmts, reduc_type, def);
    8438              :             }
    8439              :           /* Adjust the input so we pick up the partially reduced value
    8440              :              for the skip edge in vect_create_epilog_for_reduction.  */
    8441         4114 :           accumulator->reduc_input = def;
    8442              :           /* And the reduction could be carried out using a different sign.  */
    8443         4114 :           if (!useless_type_conversion_p (vectype_out, TREE_TYPE (def)))
    8444          235 :             def = gimple_convert (&stmts, vectype_out, def);
    8445         4114 :           edge e;
    8446         4114 :           if ((e = loop_vinfo->main_loop_edge)
    8447         4114 :               || (e = loop_vinfo->skip_this_loop_edge))
    8448              :             {
    8449              :               /* While we'd like to insert on the edge this will split
    8450              :                  blocks and disturb bookkeeping, we also will eventually
    8451              :                  need this on the skip edge.  Rely on sinking to
    8452              :                  fixup optimal placement and insert in the pred.  */
    8453         3891 :               gimple_stmt_iterator gsi = gsi_last_bb (e->src);
    8454              :               /* Insert before a cond that eventually skips the
    8455              :                  epilogue.  */
    8456         3891 :               if (!gsi_end_p (gsi) && stmt_ends_bb_p (gsi_stmt (gsi)))
    8457         3874 :                 gsi_prev (&gsi);
    8458         3891 :               gsi_insert_seq_after (&gsi, stmts, GSI_CONTINUE_LINKING);
    8459              :             }
    8460              :           else
    8461          223 :             gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop),
    8462              :                                               stmts);
    8463              :         }
    8464         4117 :       if (loop_vinfo->main_loop_edge)
    8465         3894 :         vec_initial_defs[0]
    8466         3894 :           = vect_get_main_loop_result (loop_vinfo, def,
    8467         3894 :                                        vec_initial_defs[0]);
    8468              :       else
    8469          223 :         vec_initial_defs.safe_push (def);
    8470              :     }
    8471              : 
    8472              :   /* Generate the reduction PHIs upfront.  */
    8473        47540 :   for (i = 0; i < vec_num; i++)
    8474              :     {
    8475        24698 :       tree vec_init_def = vec_initial_defs[i];
    8476              :       /* Create the reduction-phi that defines the reduction
    8477              :          operand.  */
    8478        24698 :       gphi *new_phi = create_phi_node (vec_dest, loop->header);
    8479        24698 :       add_phi_arg (new_phi, vec_init_def, loop_preheader_edge (loop),
    8480              :                    UNKNOWN_LOCATION);
    8481              : 
    8482              :       /* The loop-latch arg is set in epilogue processing.  */
    8483              : 
    8484        24698 :       slp_node->push_vec_def (new_phi);
    8485              :     }
    8486              : 
    8487        22842 :   return true;
    8488        22842 : }
    8489              : 
    8490              : /* Vectorizes LC PHIs.  */
    8491              : 
    8492              : bool
    8493       196991 : vectorizable_lc_phi (loop_vec_info loop_vinfo,
    8494              :                      stmt_vec_info stmt_info,
    8495              :                      slp_tree slp_node)
    8496              : {
    8497       196991 :   if (!loop_vinfo
    8498       196991 :       || !is_a <gphi *> (stmt_info->stmt)
    8499       236172 :       || gimple_phi_num_args (stmt_info->stmt) != 1)
    8500              :     return false;
    8501              : 
    8502          791 :   if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
    8503            0 :       && STMT_VINFO_DEF_TYPE (stmt_info) != vect_double_reduction_def)
    8504              :     return false;
    8505              : 
    8506              :   /* Deal with copies from externs or constants that disguise as
    8507              :      loop-closed PHI nodes (PR97886).  */
    8508          791 :   if (!vect_maybe_update_slp_op_vectype (SLP_TREE_CHILDREN (slp_node)[0],
    8509              :                                          SLP_TREE_VECTYPE (slp_node)))
    8510              :     {
    8511            0 :       if (dump_enabled_p ())
    8512            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8513              :                          "incompatible vector types for invariants\n");
    8514              :       return false;
    8515              :     }
    8516              : 
    8517              :   /* ???  This can happen with data vs. mask uses of boolean.  */
    8518          791 :   if (!useless_type_conversion_p (SLP_TREE_VECTYPE (slp_node),
    8519          791 :                                   SLP_TREE_VECTYPE
    8520              :                                     (SLP_TREE_CHILDREN (slp_node)[0])))
    8521              :     {
    8522            0 :       if (dump_enabled_p ())
    8523            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8524              :                          "missed mask promotion\n");
    8525              :       return false;
    8526              :     }
    8527              : 
    8528          791 :   SLP_TREE_TYPE (slp_node) = lc_phi_info_type;
    8529          791 :   return true;
    8530              : }
    8531              : 
    8532              : bool
    8533          515 : vect_transform_lc_phi (loop_vec_info loop_vinfo,
    8534              :                        stmt_vec_info stmt_info,
    8535              :                        slp_tree slp_node)
    8536              : {
    8537              : 
    8538          515 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
    8539          515 :   tree scalar_dest = gimple_phi_result (stmt_info->stmt);
    8540          515 :   basic_block bb = gimple_bb (stmt_info->stmt);
    8541          515 :   edge e = single_pred_edge (bb);
    8542          515 :   tree vec_dest = vect_create_destination_var (scalar_dest, vectype);
    8543          515 :   auto_vec<tree> vec_oprnds;
    8544          515 :   vect_get_vec_defs (loop_vinfo, slp_node, true, &vec_oprnds);
    8545         1660 :   for (unsigned i = 0; i < vec_oprnds.length (); i++)
    8546              :     {
    8547              :       /* Create the vectorized LC PHI node.  */
    8548          630 :       gphi *new_phi = create_phi_node (vec_dest, bb);
    8549          630 :       add_phi_arg (new_phi, vec_oprnds[i], e, UNKNOWN_LOCATION);
    8550          630 :       slp_node->push_vec_def (new_phi);
    8551              :     }
    8552              : 
    8553          515 :   return true;
    8554          515 : }
    8555              : 
    8556              : /* Vectorizes PHIs.  */
    8557              : 
    8558              : bool
    8559       157003 : vectorizable_phi (bb_vec_info vinfo,
    8560              :                   stmt_vec_info stmt_info,
    8561              :                   slp_tree slp_node, stmt_vector_for_cost *cost_vec)
    8562              : {
    8563       157003 :   if (!is_a <gphi *> (stmt_info->stmt) || !slp_node)
    8564              :     return false;
    8565              : 
    8566        76019 :   if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def)
    8567              :     return false;
    8568              : 
    8569        76019 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
    8570              : 
    8571        76019 :   if (cost_vec) /* transformation not required.  */
    8572              :     {
    8573              :       slp_tree child;
    8574              :       unsigned i;
    8575       205146 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), i, child)
    8576       144450 :         if (!child)
    8577              :           {
    8578            0 :             if (dump_enabled_p ())
    8579            0 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8580              :                                "PHI node with unvectorized backedge def\n");
    8581              :             return false;
    8582              :           }
    8583       144450 :         else if (!vect_maybe_update_slp_op_vectype (child, vectype))
    8584              :           {
    8585           26 :             if (dump_enabled_p ())
    8586            2 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8587              :                                "incompatible vector types for invariants\n");
    8588              :             return false;
    8589              :           }
    8590       144424 :         else if (SLP_TREE_DEF_TYPE (child) == vect_internal_def
    8591       144424 :                  && !useless_type_conversion_p (vectype,
    8592              :                                                 SLP_TREE_VECTYPE (child)))
    8593              :           {
    8594              :             /* With bools we can have mask and non-mask precision vectors
    8595              :                or different non-mask precisions.  while pattern recog is
    8596              :                supposed to guarantee consistency here bugs in it can cause
    8597              :                mismatches (PR103489 and PR103800 for example).
    8598              :                Deal with them here instead of ICEing later.  */
    8599           18 :             if (dump_enabled_p ())
    8600            8 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8601              :                                "incompatible vector type setup from "
    8602              :                                "bool pattern detection\n");
    8603              :             return false;
    8604              :           }
    8605              : 
    8606              :       /* For single-argument PHIs assume coalescing which means zero cost
    8607              :          for the scalar and the vector PHIs.  This avoids artificially
    8608              :          favoring the vector path (but may pessimize it in some cases).  */
    8609        60696 :       if (gimple_phi_num_args (as_a <gphi *> (stmt_info->stmt)) > 1)
    8610        54956 :         record_stmt_cost (cost_vec, vect_get_num_copies (vinfo, slp_node),
    8611              :                           vector_stmt, slp_node, vectype, 0, vect_body);
    8612        60696 :       SLP_TREE_TYPE (slp_node) = phi_info_type;
    8613        60696 :       return true;
    8614              :     }
    8615              : 
    8616        15279 :   tree scalar_dest = gimple_phi_result (stmt_info->stmt);
    8617        15279 :   basic_block bb = gimple_bb (stmt_info->stmt);
    8618        15279 :   tree vec_dest = vect_create_destination_var (scalar_dest, vectype);
    8619        15279 :   auto_vec<gphi *> new_phis;
    8620        54712 :   for (unsigned i = 0; i < gimple_phi_num_args (stmt_info->stmt); ++i)
    8621              :     {
    8622        39433 :       slp_tree child = SLP_TREE_CHILDREN (slp_node)[i];
    8623              : 
    8624              :       /* Skip not yet vectorized defs.  */
    8625        40177 :       if (SLP_TREE_DEF_TYPE (child) == vect_internal_def
    8626        39433 :           && SLP_TREE_VEC_DEFS (child).is_empty ())
    8627          744 :         continue;
    8628              : 
    8629        38689 :       auto_vec<tree> vec_oprnds;
    8630        38689 :       vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[i], &vec_oprnds);
    8631        38689 :       if (!new_phis.exists ())
    8632              :         {
    8633        15279 :           new_phis.create (vec_oprnds.length ());
    8634        47339 :           for (unsigned j = 0; j < vec_oprnds.length (); j++)
    8635              :             {
    8636              :               /* Create the vectorized LC PHI node.  */
    8637        16781 :               new_phis.quick_push (create_phi_node (vec_dest, bb));
    8638        16781 :               slp_node->push_vec_def (new_phis[j]);
    8639              :             }
    8640              :         }
    8641        38689 :       edge e = gimple_phi_arg_edge (as_a <gphi *> (stmt_info->stmt), i);
    8642        82462 :       for (unsigned j = 0; j < vec_oprnds.length (); j++)
    8643        43773 :         add_phi_arg (new_phis[j], vec_oprnds[j], e, UNKNOWN_LOCATION);
    8644        38689 :     }
    8645              :   /* We should have at least one already vectorized child.  */
    8646        15279 :   gcc_assert (new_phis.exists ());
    8647              : 
    8648        15279 :   return true;
    8649        15279 : }
    8650              : 
    8651              : /* Vectorizes first order recurrences.  An overview of the transformation
    8652              :    is described below. Suppose we have the following loop.
    8653              : 
    8654              :      int t = 0;
    8655              :      for (int i = 0; i < n; ++i)
    8656              :        {
    8657              :          b[i] = a[i] - t;
    8658              :          t = a[i];
    8659              :        }
    8660              : 
    8661              :    There is a first-order recurrence on 'a'. For this loop, the scalar IR
    8662              :    looks (simplified) like:
    8663              : 
    8664              :     scalar.preheader:
    8665              :       init = 0;
    8666              : 
    8667              :     scalar.body:
    8668              :       i = PHI <0(scalar.preheader), i+1(scalar.body)>
    8669              :       _2 = PHI <(init(scalar.preheader), <_1(scalar.body)>
    8670              :       _1 = a[i]
    8671              :       b[i] = _1 - _2
    8672              :       if (i < n) goto scalar.body
    8673              : 
    8674              :    In this example, _2 is a recurrence because it's value depends on the
    8675              :    previous iteration.  We vectorize this as (VF = 4)
    8676              : 
    8677              :     vector.preheader:
    8678              :       vect_init = vect_cst(..., ..., ..., 0)
    8679              : 
    8680              :     vector.body
    8681              :       i = PHI <0(vector.preheader), i+4(vector.body)>
    8682              :       vect_1 = PHI <vect_init(vector.preheader), v2(vector.body)>
    8683              :       vect_2 = a[i, i+1, i+2, i+3];
    8684              :       vect_3 = vec_perm (vect_1, vect_2, { 3, 4, 5, 6 })
    8685              :       b[i, i+1, i+2, i+3] = vect_2 - vect_3
    8686              :       if (..) goto vector.body
    8687              : 
    8688              :    In this function, vectorizable_recurr, we code generate both the
    8689              :    vector PHI node and the permute since those together compute the
    8690              :    vectorized value of the scalar PHI.  We do not yet have the
    8691              :    backedge value to fill in there nor into the vec_perm.  Those
    8692              :    are filled in vect_schedule_scc.
    8693              : 
    8694              :    TODO:  Since the scalar loop does not have a use of the recurrence
    8695              :    outside of the loop the natural way to implement peeling via
    8696              :    vectorizing the live value doesn't work.  For now peeling of loops
    8697              :    with a recurrence is not implemented.  For SLP the supported cases
    8698              :    are restricted to those requiring a single vector recurrence PHI.  */
    8699              : 
    8700              : bool
    8701       196243 : vectorizable_recurr (loop_vec_info loop_vinfo, stmt_vec_info stmt_info,
    8702              :                      slp_tree slp_node, stmt_vector_for_cost *cost_vec)
    8703              : {
    8704       196243 :   if (!loop_vinfo || !is_a<gphi *> (stmt_info->stmt))
    8705              :     return false;
    8706              : 
    8707        38433 :   gphi *phi = as_a<gphi *> (stmt_info->stmt);
    8708              : 
    8709              :   /* So far we only support first-order recurrence auto-vectorization.  */
    8710        38433 :   if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_first_order_recurrence)
    8711              :     return false;
    8712              : 
    8713          424 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
    8714          424 :   unsigned ncopies = vect_get_num_copies (loop_vinfo, slp_node);
    8715          424 :   poly_int64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
    8716          424 :   unsigned dist = SLP_TREE_LANES (slp_node);
    8717              :   /* We need to be able to make progress with a single vector.  */
    8718          424 :   if (maybe_gt (dist * 2, nunits))
    8719              :     {
    8720            0 :       if (dump_enabled_p ())
    8721            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8722              :                          "first order recurrence exceeds half of "
    8723              :                          "a vector\n");
    8724              :       return false;
    8725              :     }
    8726              : 
    8727              :   /* We need to be able to build a { ..., a, b } init vector with
    8728              :      dist number of distinct trailing values.  Always possible
    8729              :      when dist == 1 or when nunits is constant or when the initializations
    8730              :      are uniform.  */
    8731          424 :   tree uniform_initval = NULL_TREE;
    8732          424 :   edge pe = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
    8733         1720 :   for (stmt_vec_info s : SLP_TREE_SCALAR_STMTS (slp_node))
    8734              :     {
    8735          460 :       gphi *phi = as_a <gphi *> (s->stmt);
    8736          460 :       if (! uniform_initval)
    8737          424 :         uniform_initval = PHI_ARG_DEF_FROM_EDGE (phi, pe);
    8738           36 :       else if (! operand_equal_p (uniform_initval,
    8739           36 :                                   PHI_ARG_DEF_FROM_EDGE (phi, pe)))
    8740              :         {
    8741              :           uniform_initval = NULL_TREE;
    8742              :           break;
    8743              :         }
    8744              :     }
    8745          424 :   if (!uniform_initval && !nunits.is_constant ())
    8746              :     {
    8747              :       if (dump_enabled_p ())
    8748              :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8749              :                          "cannot build initialization vector for "
    8750              :                          "first order recurrence\n");
    8751              :       return false;
    8752              :     }
    8753              : 
    8754              :   /* First-order recurrence autovectorization needs to handle permutation
    8755              :      with indices = [nunits-1, nunits, nunits+1, ...].  */
    8756          424 :   vec_perm_builder sel (nunits, 1, 3);
    8757         1696 :   for (int i = 0; i < 3; ++i)
    8758         1272 :     sel.quick_push (nunits - dist + i);
    8759          424 :   vec_perm_indices indices (sel, 2, nunits);
    8760              : 
    8761          424 :   if (cost_vec) /* transformation not required.  */
    8762              :     {
    8763          381 :       if (!can_vec_perm_const_p (TYPE_MODE (vectype), TYPE_MODE (vectype),
    8764              :                                  indices))
    8765              :         return false;
    8766              : 
    8767              :       /* We eventually need to set a vector type on invariant
    8768              :          arguments.  */
    8769              :       unsigned j;
    8770              :       slp_tree child;
    8771          807 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), j, child)
    8772          538 :         if (!vect_maybe_update_slp_op_vectype (child, vectype))
    8773              :           {
    8774            0 :             if (dump_enabled_p ())
    8775            0 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8776              :                                "incompatible vector types for "
    8777              :                                "invariants\n");
    8778              :             return false;
    8779              :           }
    8780              : 
    8781              :       /* Verify we have set up compatible types.  */
    8782          269 :       edge le = loop_latch_edge (LOOP_VINFO_LOOP (loop_vinfo));
    8783          269 :       slp_tree latch_def = SLP_TREE_CHILDREN (slp_node)[le->dest_idx];
    8784          269 :       tree latch_vectype = SLP_TREE_VECTYPE (latch_def);
    8785          269 :       if (!types_compatible_p (latch_vectype, vectype))
    8786              :         return false;
    8787              : 
    8788              :       /* The recurrence costs the initialization vector and one permute
    8789              :          for each copy.  With SLP the prologue value is explicitly
    8790              :          represented and costed separately.  */
    8791          269 :       unsigned prologue_cost = 0;
    8792          269 :       unsigned inside_cost = record_stmt_cost (cost_vec, ncopies, vector_stmt,
    8793              :                                                slp_node, 0, vect_body);
    8794          269 :       if (dump_enabled_p ())
    8795           51 :         dump_printf_loc (MSG_NOTE, vect_location,
    8796              :                          "vectorizable_recurr: inside_cost = %d, "
    8797              :                          "prologue_cost = %d .\n", inside_cost,
    8798              :                          prologue_cost);
    8799              : 
    8800          269 :       SLP_TREE_TYPE (slp_node) = recurr_info_type;
    8801          269 :       return true;
    8802              :     }
    8803              : 
    8804           43 :   tree vec_init;
    8805           43 :   if (! uniform_initval)
    8806              :     {
    8807            6 :       vec<constructor_elt, va_gc> *v = NULL;
    8808            6 :       vec_alloc (v, nunits.to_constant ());
    8809           39 :       for (unsigned i = 0; i < nunits.to_constant () - dist; ++i)
    8810           27 :         CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
    8811              :                                 build_zero_cst (TREE_TYPE (vectype)));
    8812           39 :       for (stmt_vec_info s : SLP_TREE_SCALAR_STMTS (slp_node))
    8813              :         {
    8814           21 :           gphi *phi = as_a <gphi *> (s->stmt);
    8815           21 :           tree preheader = PHI_ARG_DEF_FROM_EDGE (phi, pe);
    8816           21 :           if (!useless_type_conversion_p (TREE_TYPE (vectype),
    8817           21 :                                           TREE_TYPE (preheader)))
    8818              :             {
    8819            0 :               gimple_seq stmts = NULL;
    8820            0 :               preheader = gimple_convert (&stmts,
    8821            0 :                                           TREE_TYPE (vectype), preheader);
    8822            0 :               gsi_insert_seq_on_edge_immediate (pe, stmts);
    8823              :             }
    8824           21 :           CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, preheader);
    8825              :         }
    8826            6 :       vec_init = build_constructor (vectype, v);
    8827              :     }
    8828              :   else
    8829              :     vec_init = uniform_initval;
    8830           43 :   vec_init = vect_init_vector (loop_vinfo, stmt_info, vec_init, vectype, NULL);
    8831              : 
    8832              :   /* Create the vectorized first-order PHI node.  */
    8833           43 :   tree vec_dest = vect_get_new_vect_var (vectype,
    8834              :                                          vect_simple_var, "vec_recur_");
    8835           43 :   basic_block bb = gimple_bb (phi);
    8836           43 :   gphi *new_phi = create_phi_node (vec_dest, bb);
    8837           43 :   add_phi_arg (new_phi, vec_init, pe, UNKNOWN_LOCATION);
    8838              : 
    8839              :   /* Insert shuffles the first-order recurrence autovectorization.
    8840              :        result = VEC_PERM <vec_recur, vect_1, index[nunits-1, nunits, ...]>.  */
    8841           43 :   tree perm = vect_gen_perm_mask_checked (vectype, indices);
    8842              : 
    8843              :   /* Insert the required permute after the latch definition.  The
    8844              :      second and later operands are tentative and will be updated when we have
    8845              :      vectorized the latch definition.  */
    8846           43 :   edge le = loop_latch_edge (LOOP_VINFO_LOOP (loop_vinfo));
    8847           43 :   gimple *latch_def = SSA_NAME_DEF_STMT (PHI_ARG_DEF_FROM_EDGE (phi, le));
    8848           43 :   gimple_stmt_iterator gsi2 = gsi_for_stmt (latch_def);
    8849           49 :   do
    8850              :     {
    8851           49 :       gsi_next (&gsi2);
    8852              :     }
    8853              :   /* Skip inserted vectorized stmts for the latch definition.  We have to
    8854              :      insert after those.  */
    8855           92 :   while (gsi_stmt (gsi2) && gimple_uid (gsi_stmt (gsi2)) == 0);
    8856              : 
    8857          123 :   for (unsigned i = 0; i < ncopies; ++i)
    8858              :     {
    8859           80 :       vec_dest = make_ssa_name (vectype);
    8860           80 :       gassign *vperm
    8861          123 :           = gimple_build_assign (vec_dest, VEC_PERM_EXPR,
    8862           43 :                                  i == 0 ? gimple_phi_result (new_phi) : NULL,
    8863              :                                  NULL, perm);
    8864           80 :       vect_finish_stmt_generation (loop_vinfo, stmt_info, vperm, &gsi2);
    8865              : 
    8866           80 :       slp_node->push_vec_def (vperm);
    8867              :     }
    8868              : 
    8869              :   return true;
    8870          424 : }
    8871              : 
    8872              : /* Return true if VECTYPE represents a vector that requires lowering
    8873              :    by the vector lowering pass.  */
    8874              : 
    8875              : bool
    8876       670134 : vect_emulated_vector_p (tree vectype)
    8877              : {
    8878      1340268 :   return (!VECTOR_MODE_P (TYPE_MODE (vectype))
    8879       674268 :           && (!VECTOR_BOOLEAN_TYPE_P (vectype)
    8880         4116 :               || TYPE_PRECISION (TREE_TYPE (vectype)) != 1));
    8881              : }
    8882              : 
    8883              : /* Return true if we can emulate CODE on an integer mode representation
    8884              :    of a vector.  */
    8885              : 
    8886              : bool
    8887        12169 : vect_can_vectorize_without_simd_p (tree_code code)
    8888              : {
    8889        12169 :   switch (code)
    8890              :     {
    8891              :     case PLUS_EXPR:
    8892              :     case MINUS_EXPR:
    8893              :     case NEGATE_EXPR:
    8894              :     case BIT_AND_EXPR:
    8895              :     case BIT_IOR_EXPR:
    8896              :     case BIT_XOR_EXPR:
    8897              :     case BIT_NOT_EXPR:
    8898              :       return true;
    8899              : 
    8900        11556 :     default:
    8901        11556 :       return false;
    8902              :     }
    8903              : }
    8904              : 
    8905              : /* Likewise, but taking a code_helper.  */
    8906              : 
    8907              : bool
    8908         1004 : vect_can_vectorize_without_simd_p (code_helper code)
    8909              : {
    8910         1004 :   return (code.is_tree_code ()
    8911         1004 :           && vect_can_vectorize_without_simd_p (tree_code (code)));
    8912              : }
    8913              : 
    8914              : /* Create vector init for vectorized iv.  */
    8915              : static tree
    8916          919 : vect_create_nonlinear_iv_init (gimple_seq* stmts, tree init_expr,
    8917              :                                tree step_expr, poly_uint64 nunits,
    8918              :                                tree vectype,
    8919              :                                enum vect_induction_op_type induction_type)
    8920              : {
    8921          919 :   unsigned HOST_WIDE_INT const_nunits;
    8922          919 :   tree vec_shift, vec_init, new_name;
    8923          919 :   unsigned i;
    8924          919 :   tree itype = TREE_TYPE (vectype);
    8925              : 
    8926              :   /* iv_loop is the loop to be vectorized. Create:
    8927              :      vec_init = [X, X+S, X+2*S, X+3*S] (S = step_expr, X = init_expr).  */
    8928          919 :   new_name = gimple_convert (stmts, itype, init_expr);
    8929          919 :   switch (induction_type)
    8930              :     {
    8931           18 :     case vect_step_op_shr:
    8932           18 :     case vect_step_op_shl:
    8933              :       /* Build the Initial value from shift_expr.  */
    8934           18 :       vec_init = gimple_build_vector_from_val (stmts,
    8935              :                                                vectype,
    8936              :                                                new_name);
    8937           18 :       vec_shift = gimple_build (stmts, VEC_SERIES_EXPR, vectype,
    8938              :                                 build_zero_cst (itype), step_expr);
    8939           18 :       vec_init = gimple_build (stmts,
    8940              :                                (induction_type == vect_step_op_shr
    8941              :                                 ? RSHIFT_EXPR : LSHIFT_EXPR),
    8942              :                                vectype, vec_init, vec_shift);
    8943           18 :       break;
    8944              : 
    8945          825 :     case vect_step_op_neg:
    8946          825 :       {
    8947          825 :         vec_init = gimple_build_vector_from_val (stmts,
    8948              :                                                  vectype,
    8949              :                                                  new_name);
    8950          825 :         tree vec_neg = gimple_build (stmts, NEGATE_EXPR,
    8951              :                                      vectype, vec_init);
    8952              :         /* The encoding has 2 interleaved stepped patterns.  */
    8953          825 :         vec_perm_builder sel (nunits, 2, 3);
    8954          825 :         sel.quick_grow (6);
    8955         4125 :         for (i = 0; i < 3; i++)
    8956              :           {
    8957         2475 :             sel[2 * i] = i;
    8958         2475 :             sel[2 * i + 1] = i + nunits;
    8959              :           }
    8960          825 :         vec_perm_indices indices (sel, 2, nunits);
    8961              :         /* Don't use vect_gen_perm_mask_checked since can_vec_perm_const_p may
    8962              :            fail when vec_init is const vector. In that situation vec_perm is not
    8963              :            really needed.  */
    8964          825 :         tree perm_mask_even
    8965          825 :           = vect_gen_perm_mask_any (vectype, indices);
    8966          825 :         vec_init = gimple_build (stmts, VEC_PERM_EXPR,
    8967              :                                  vectype,
    8968              :                                  vec_init, vec_neg,
    8969              :                                  perm_mask_even);
    8970          825 :       }
    8971          825 :       break;
    8972              : 
    8973           76 :     case vect_step_op_mul:
    8974           76 :       {
    8975              :         /* Use unsigned mult to avoid UD integer overflow.  */
    8976           76 :         gcc_assert (nunits.is_constant (&const_nunits));
    8977           76 :         tree utype = unsigned_type_for (itype);
    8978           76 :         tree uvectype = build_vector_type (utype,
    8979           76 :                                            TYPE_VECTOR_SUBPARTS (vectype));
    8980           76 :         new_name = gimple_convert (stmts, utype, new_name);
    8981           76 :         vec_init = gimple_build_vector_from_val (stmts,
    8982              :                                                  uvectype,
    8983              :                                                  new_name);
    8984           76 :         tree_vector_builder elts (uvectype, const_nunits, 1);
    8985           76 :         tree elt_step = build_one_cst (utype);
    8986              : 
    8987           76 :         elts.quick_push (elt_step);
    8988          660 :         for (i = 1; i < const_nunits; i++)
    8989              :           {
    8990              :             /* Create: new_name_i = new_name + step_expr.  */
    8991          508 :             elt_step = gimple_build (stmts, MULT_EXPR,
    8992              :                                      utype, elt_step, step_expr);
    8993          508 :             elts.quick_push (elt_step);
    8994              :           }
    8995              :         /* Create a vector from [new_name_0, new_name_1, ...,
    8996              :            new_name_nunits-1].  */
    8997           76 :         tree vec_mul = gimple_build_vector (stmts, &elts);
    8998           76 :         vec_init = gimple_build (stmts, MULT_EXPR, uvectype,
    8999              :                                  vec_init, vec_mul);
    9000           76 :         vec_init = gimple_convert (stmts, vectype, vec_init);
    9001           76 :       }
    9002           76 :       break;
    9003              : 
    9004            0 :     default:
    9005            0 :       gcc_unreachable ();
    9006              :     }
    9007              : 
    9008          919 :   return vec_init;
    9009              : }
    9010              : 
    9011              : /* Peel init_expr by skip_niter for induction_type.  */
    9012              : tree
    9013           84 : vect_peel_nonlinear_iv_init (gimple_seq* stmts, tree init_expr,
    9014              :                              tree skip_niters, tree step_expr,
    9015              :                              enum vect_induction_op_type induction_type,
    9016              :                              bool early_exit_p)
    9017              : {
    9018           84 :   gcc_assert (TREE_CODE (skip_niters) == INTEGER_CST || early_exit_p);
    9019           84 :   tree type = TREE_TYPE (init_expr);
    9020           84 :   unsigned prec = TYPE_PRECISION (type);
    9021           84 :   switch (induction_type)
    9022              :     {
    9023              :     /* neg inductions are typically not used for loop termination conditions but
    9024              :        are typically implemented as b = -b.  That is every scalar iteration b is
    9025              :        negated.  That means that for the initial value of b we will have to
    9026              :        determine whether the number of skipped iteration is a multiple of 2
    9027              :        because every 2 scalar iterations we are back at "b".  */
    9028            0 :     case vect_step_op_neg:
    9029              :       /* For early exits the neg induction will always be the same value at the
    9030              :          start of the iteration.  */
    9031            0 :       if (early_exit_p)
    9032              :         break;
    9033              : 
    9034            0 :       if (TREE_INT_CST_LOW (skip_niters) % 2)
    9035            0 :         init_expr = gimple_build (stmts, NEGATE_EXPR, type, init_expr);
    9036              :       /* else no change.  */
    9037              :       break;
    9038              : 
    9039           12 :     case vect_step_op_shr:
    9040           12 :     case vect_step_op_shl:
    9041           12 :       skip_niters = fold_build1 (NOP_EXPR, type, skip_niters);
    9042           12 :       step_expr = fold_build1 (NOP_EXPR, type, step_expr);
    9043           12 :       step_expr = fold_build2 (MULT_EXPR, type, step_expr, skip_niters);
    9044              :       /* When shift mount >= precision, need to avoid UD.
    9045              :          In the original loop, there's no UD, and according to semantic,
    9046              :          init_expr should be 0 for lshr, ashl, and >>= (prec - 1) for ashr.  */
    9047           12 :       if ((!tree_fits_uhwi_p (step_expr)
    9048           12 :           || tree_to_uhwi (step_expr) >= prec)
    9049            6 :           && !early_exit_p)
    9050              :         {
    9051            6 :           if (induction_type == vect_step_op_shl
    9052            6 :               || TYPE_UNSIGNED (type))
    9053            4 :             init_expr = build_zero_cst (type);
    9054              :           else
    9055            2 :             init_expr = gimple_build (stmts, RSHIFT_EXPR, type,
    9056              :                                       init_expr,
    9057            4 :                                       wide_int_to_tree (type, prec - 1));
    9058              :         }
    9059              :       else
    9060              :         {
    9061            8 :           init_expr = fold_build2 ((induction_type == vect_step_op_shr
    9062              :                                           ? RSHIFT_EXPR : LSHIFT_EXPR),
    9063              :                                     type, init_expr, step_expr);
    9064            6 :           init_expr = force_gimple_operand (init_expr, stmts, false, NULL);
    9065              :         }
    9066              :       break;
    9067              : 
    9068           72 :     case vect_step_op_mul:
    9069           72 :       {
    9070              :         /* Due to UB we can't support vect_step_op_mul with early break for now.
    9071              :            so assert and block.  */
    9072           72 :         gcc_assert (TREE_CODE (skip_niters) == INTEGER_CST);
    9073           72 :         tree utype = unsigned_type_for (type);
    9074           72 :         init_expr = gimple_convert (stmts, utype, init_expr);
    9075           72 :         wide_int skipn = wi::to_wide (skip_niters);
    9076           72 :         wide_int begin = wi::to_wide (step_expr);
    9077           72 :         auto_mpz base, exp, mod, res;
    9078           72 :         wi::to_mpz (begin, base, TYPE_SIGN (type));
    9079           72 :         wi::to_mpz (skipn, exp, UNSIGNED);
    9080           72 :         mpz_ui_pow_ui (mod, 2, TYPE_PRECISION (type));
    9081           72 :         mpz_powm (res, base, exp, mod);
    9082           72 :         begin = wi::from_mpz (utype, res, true);
    9083           72 :         tree mult_expr = wide_int_to_tree (utype, begin);
    9084           72 :         init_expr = gimple_build (stmts, MULT_EXPR, utype,
    9085              :                                   init_expr, mult_expr);
    9086           72 :         init_expr = gimple_convert (stmts, type, init_expr);
    9087           72 :       }
    9088           72 :       break;
    9089              : 
    9090            0 :     default:
    9091            0 :       gcc_unreachable ();
    9092              :     }
    9093              : 
    9094           84 :   return init_expr;
    9095              : }
    9096              : 
    9097              : /* Create vector step for vectorized iv.  */
    9098              : static tree
    9099         1205 : vect_create_nonlinear_iv_step (gimple_seq* stmts, tree step_expr,
    9100              :                                poly_uint64 vf,
    9101              :                                enum vect_induction_op_type induction_type)
    9102              : {
    9103         1205 :   tree expr = build_int_cst (TREE_TYPE (step_expr), vf);
    9104         1205 :   tree new_name = NULL;
    9105              :   /* Step should be pow (step, vf) for mult induction.  */
    9106         1205 :   if (induction_type == vect_step_op_mul)
    9107              :     {
    9108           76 :       gcc_assert (vf.is_constant ());
    9109           76 :       wide_int begin = wi::to_wide (step_expr);
    9110              : 
    9111          584 :       for (unsigned i = 0; i != vf.to_constant () - 1; i++)
    9112          508 :         begin = wi::mul (begin, wi::to_wide (step_expr));
    9113              : 
    9114           76 :       new_name = wide_int_to_tree (TREE_TYPE (step_expr), begin);
    9115           76 :     }
    9116         1129 :   else if (induction_type == vect_step_op_neg)
    9117              :     /* Do nothing.  */
    9118              :     ;
    9119              :   else
    9120           18 :     new_name = gimple_build (stmts, MULT_EXPR, TREE_TYPE (step_expr),
    9121              :                              expr, step_expr);
    9122         1205 :   return new_name;
    9123              : }
    9124              : 
    9125              : static tree
    9126         1205 : vect_create_nonlinear_iv_vec_step (loop_vec_info loop_vinfo,
    9127              :                                    stmt_vec_info stmt_info,
    9128              :                                    tree new_name, tree vectype,
    9129              :                                    enum vect_induction_op_type induction_type)
    9130              : {
    9131              :   /* No step is needed for neg induction.  */
    9132         1205 :   if (induction_type == vect_step_op_neg)
    9133              :     return NULL;
    9134              : 
    9135           94 :   tree t = unshare_expr (new_name);
    9136           94 :   gcc_assert (CONSTANT_CLASS_P (new_name)
    9137              :               || TREE_CODE (new_name) == SSA_NAME);
    9138           94 :   tree new_vec = build_vector_from_val (vectype, t);
    9139           94 :   tree vec_step = vect_init_vector (loop_vinfo, stmt_info,
    9140              :                                     new_vec, vectype, NULL);
    9141           94 :   return vec_step;
    9142              : }
    9143              : 
    9144              : /* Update vectorized iv with vect_step, induc_def is init.  */
    9145              : static tree
    9146         1393 : vect_update_nonlinear_iv (gimple_seq* stmts, tree vectype,
    9147              :                           tree induc_def, tree vec_step,
    9148              :                           enum vect_induction_op_type induction_type)
    9149              : {
    9150         1393 :   tree vec_def = induc_def;
    9151         1393 :   switch (induction_type)
    9152              :     {
    9153           76 :     case vect_step_op_mul:
    9154           76 :       {
    9155              :         /* Use unsigned mult to avoid UD integer overflow.  */
    9156           76 :         tree uvectype = unsigned_type_for (vectype);
    9157           76 :         vec_def = gimple_convert (stmts, uvectype, vec_def);
    9158           76 :         vec_step = gimple_convert (stmts, uvectype, vec_step);
    9159           76 :         vec_def = gimple_build (stmts, MULT_EXPR, uvectype,
    9160              :                                 vec_def, vec_step);
    9161           76 :         vec_def = gimple_convert (stmts, vectype, vec_def);
    9162              :       }
    9163           76 :       break;
    9164              : 
    9165           12 :     case vect_step_op_shr:
    9166           12 :       vec_def = gimple_build (stmts, RSHIFT_EXPR, vectype,
    9167              :                               vec_def, vec_step);
    9168           12 :       break;
    9169              : 
    9170            6 :     case vect_step_op_shl:
    9171            6 :       vec_def = gimple_build (stmts, LSHIFT_EXPR, vectype,
    9172              :                               vec_def, vec_step);
    9173            6 :       break;
    9174              :     case vect_step_op_neg:
    9175              :       vec_def = induc_def;
    9176              :       /* Do nothing.  */
    9177              :       break;
    9178            0 :     default:
    9179            0 :       gcc_unreachable ();
    9180              :     }
    9181              : 
    9182         1393 :   return vec_def;
    9183              : 
    9184              : }
    9185              : 
    9186              : /* Function vectorizable_nonlinear_induction
    9187              : 
    9188              :    Check if STMT_INFO performs an nonlinear induction computation that can be
    9189              :    vectorized. If VEC_STMT is also passed, vectorize the induction PHI: create
    9190              :    a vectorized phi to replace it, put it in VEC_STMT, and add it to the same
    9191              :    basic block.
    9192              :    Return true if STMT_INFO is vectorizable in this way.  */
    9193              : 
    9194              : static bool
    9195         9573 : vectorizable_nonlinear_induction (loop_vec_info loop_vinfo,
    9196              :                                   stmt_vec_info stmt_info,
    9197              :                                   slp_tree slp_node,
    9198              :                                   stmt_vector_for_cost *cost_vec)
    9199              : {
    9200         9573 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    9201         9573 :   unsigned ncopies;
    9202         9573 :   bool nested_in_vect_loop = false;
    9203         9573 :   class loop *iv_loop;
    9204         9573 :   tree vec_def;
    9205         9573 :   edge pe = loop_preheader_edge (loop);
    9206         9573 :   basic_block new_bb;
    9207         9573 :   tree vec_init, vec_step;
    9208         9573 :   tree new_name;
    9209         9573 :   gimple *new_stmt;
    9210         9573 :   gphi *induction_phi;
    9211         9573 :   tree induc_def, vec_dest;
    9212         9573 :   tree init_expr, step_expr;
    9213         9573 :   tree niters_skip;
    9214         9573 :   poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    9215         9573 :   unsigned i;
    9216         9573 :   gimple_stmt_iterator si;
    9217              : 
    9218         9573 :   gphi *phi = dyn_cast <gphi *> (stmt_info->stmt);
    9219              : 
    9220         9573 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
    9221         9573 :   poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
    9222         9573 :   enum vect_induction_op_type induction_type
    9223              :     = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info);
    9224              : 
    9225         9573 :   gcc_assert (induction_type > vect_step_op_add);
    9226              : 
    9227         9573 :   ncopies = vect_get_num_copies (loop_vinfo, slp_node);
    9228         9573 :   gcc_assert (ncopies >= 1);
    9229              : 
    9230              :   /* FORNOW. Only handle nonlinear induction in the same loop.  */
    9231         9573 :   if (nested_in_vect_loop_p (loop, stmt_info))
    9232              :     {
    9233            0 :       if (dump_enabled_p ())
    9234            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9235              :                          "nonlinear induction in nested loop.\n");
    9236              :       return false;
    9237              :     }
    9238              : 
    9239         9573 :   iv_loop = loop;
    9240         9573 :   gcc_assert (iv_loop == (gimple_bb (phi))->loop_father);
    9241              : 
    9242              :   /* TODO: Support multi-lane SLP for nonlinear iv. There should be separate
    9243              :      vector iv update for each iv and a permutation to generate wanted
    9244              :      vector iv.  */
    9245         9573 :   if (SLP_TREE_LANES (slp_node) > 1)
    9246              :     {
    9247            0 :       if (dump_enabled_p ())
    9248            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9249              :                          "SLP induction not supported for nonlinear"
    9250              :                          " induction.\n");
    9251              :       return false;
    9252              :     }
    9253              : 
    9254         9573 :   if (!INTEGRAL_TYPE_P (TREE_TYPE (vectype)))
    9255              :     {
    9256            0 :       if (dump_enabled_p ())
    9257            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9258              :                          "floating point nonlinear induction vectorization"
    9259              :                          " not supported.\n");
    9260              :       return false;
    9261              :     }
    9262              : 
    9263         9573 :   step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info);
    9264         9573 :   init_expr = vect_phi_initial_value (phi);
    9265         9573 :   gcc_assert (step_expr != NULL_TREE && init_expr != NULL
    9266              :               && TREE_CODE (step_expr) == INTEGER_CST);
    9267              :   /* step_expr should be aligned with init_expr,
    9268              :      .i.e. uint64 a >> 1, step is int, but vector<uint64> shift is used.  */
    9269         9573 :   step_expr = fold_convert (TREE_TYPE (vectype), step_expr);
    9270              : 
    9271         9573 :   if (TREE_CODE (init_expr) == INTEGER_CST)
    9272         4090 :     init_expr = fold_convert (TREE_TYPE (vectype), init_expr);
    9273         5483 :   else if (!tree_nop_conversion_p (TREE_TYPE (vectype), TREE_TYPE (init_expr)))
    9274              :     {
    9275              :       /* INIT_EXPR could be a bit_field, bail out for such case.  */
    9276            4 :       if (dump_enabled_p ())
    9277            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9278              :                          "nonlinear induction vectorization failed:"
    9279              :                          " component type of vectype is not a nop conversion"
    9280              :                          " from type of init_expr.\n");
    9281              :       return false;
    9282              :     }
    9283              : 
    9284         9569 :   switch (induction_type)
    9285              :     {
    9286         3729 :     case vect_step_op_neg:
    9287         3729 :       if (maybe_eq (TYPE_VECTOR_SUBPARTS (vectype), 1u))
    9288              :         return false;
    9289         3567 :       if (TREE_CODE (init_expr) != INTEGER_CST
    9290          282 :           && TREE_CODE (init_expr) != REAL_CST)
    9291              :         {
    9292              :           /* Check for backend support of NEGATE_EXPR and vec_perm.  */
    9293          282 :           if (!directly_supported_p (NEGATE_EXPR, vectype))
    9294            0 :             return false;
    9295              : 
    9296              :           /* The encoding has 2 interleaved stepped patterns.  */
    9297          282 :           vec_perm_builder sel (nunits, 2, 3);
    9298          282 :           machine_mode mode = TYPE_MODE (vectype);
    9299          282 :           sel.quick_grow (6);
    9300         1410 :           for (i = 0; i < 3; i++)
    9301              :             {
    9302          846 :               sel[i * 2] = i;
    9303          846 :               sel[i * 2 + 1] = i + nunits;
    9304              :             }
    9305          282 :           vec_perm_indices indices (sel, 2, nunits);
    9306          282 :           if (!can_vec_perm_const_p (mode, mode, indices))
    9307            0 :             return false;
    9308          282 :         }
    9309              :       break;
    9310              : 
    9311         1064 :     case vect_step_op_mul:
    9312         1064 :       {
    9313              :         /* Check for backend support of MULT_EXPR.  */
    9314         1064 :         if (!directly_supported_p (MULT_EXPR, vectype))
    9315              :           return false;
    9316              : 
    9317              :         /* ?? How to construct vector step for variable number vector.
    9318              :            [ 1, step, pow (step, 2), pow (step, 4), .. ].  */
    9319              :         if (!vf.is_constant ())
    9320              :           return false;
    9321              :       }
    9322              :       break;
    9323              : 
    9324         4432 :     case vect_step_op_shr:
    9325              :       /* Check for backend support of RSHIFT_EXPR.  */
    9326         4432 :       if (!directly_supported_p (RSHIFT_EXPR, vectype, optab_vector))
    9327              :         return false;
    9328              : 
    9329              :       /* Don't shift more than type precision to avoid UD.  */
    9330           26 :       if (!tree_fits_uhwi_p (step_expr)
    9331           26 :           || maybe_ge (nunits * tree_to_uhwi (step_expr),
    9332              :                        TYPE_PRECISION (TREE_TYPE (init_expr))))
    9333              :         return false;
    9334              :       break;
    9335              : 
    9336          344 :     case vect_step_op_shl:
    9337              :       /* Check for backend support of RSHIFT_EXPR.  */
    9338          344 :       if (!directly_supported_p (LSHIFT_EXPR, vectype, optab_vector))
    9339              :         return false;
    9340              : 
    9341              :       /* Don't shift more than type precision to avoid UD.  */
    9342           12 :       if (!tree_fits_uhwi_p (step_expr)
    9343           12 :           || maybe_ge (nunits * tree_to_uhwi (step_expr),
    9344              :                        TYPE_PRECISION (TREE_TYPE (init_expr))))
    9345              :         return false;
    9346              : 
    9347              :       break;
    9348              : 
    9349            0 :     default:
    9350            0 :       gcc_unreachable ();
    9351              :     }
    9352              : 
    9353         4433 :   if (cost_vec) /* transformation not required.  */
    9354              :     {
    9355         3514 :       unsigned inside_cost = 0, prologue_cost = 0;
    9356              :       /* loop cost for vec_loop. Neg induction doesn't have any
    9357              :          inside_cost.  */
    9358         3514 :       inside_cost = record_stmt_cost (cost_vec, ncopies, vector_stmt,
    9359              :                                       slp_node, 0, vect_body);
    9360              : 
    9361              :       /* loop cost for vec_loop. Neg induction doesn't have any
    9362              :          inside_cost.  */
    9363         3514 :       if (induction_type == vect_step_op_neg)
    9364         2742 :         inside_cost = 0;
    9365              : 
    9366              :       /* prologue cost for vec_init and vec_step.  */
    9367         3514 :       prologue_cost = record_stmt_cost (cost_vec, 2, scalar_to_vec,
    9368              :                                         slp_node, 0, vect_prologue);
    9369              : 
    9370         3514 :       if (dump_enabled_p ())
    9371           68 :         dump_printf_loc (MSG_NOTE, vect_location,
    9372              :                          "vect_model_induction_cost: inside_cost = %d, "
    9373              :                          "prologue_cost = %d. \n", inside_cost,
    9374              :                          prologue_cost);
    9375              : 
    9376         3514 :       SLP_TREE_TYPE (slp_node) = induc_vec_info_type;
    9377         3514 :       DUMP_VECT_SCOPE ("vectorizable_nonlinear_induction");
    9378         3514 :       return true;
    9379              :     }
    9380              : 
    9381              :   /* Transform.  */
    9382              : 
    9383              :   /* Compute a vector variable, initialized with the first VF values of
    9384              :      the induction variable.  E.g., for an iv with IV_PHI='X' and
    9385              :      evolution S, for a vector of 4 units, we want to compute:
    9386              :      [X, X + S, X + 2*S, X + 3*S].  */
    9387              : 
    9388          919 :   if (dump_enabled_p ())
    9389           32 :     dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
    9390              : 
    9391          919 :   pe = loop_preheader_edge (iv_loop);
    9392              :   /* Find the first insertion point in the BB.  */
    9393          919 :   basic_block bb = gimple_bb (phi);
    9394          919 :   si = gsi_after_labels (bb);
    9395              : 
    9396          919 :   gimple_seq stmts = NULL;
    9397              : 
    9398          919 :   niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
    9399              :   /* If we are using the loop mask to "peel" for alignment then we need
    9400              :      to adjust the start value here.  */
    9401          919 :   if (niters_skip != NULL_TREE)
    9402            0 :     init_expr = vect_peel_nonlinear_iv_init (&stmts, init_expr, niters_skip,
    9403              :                                              step_expr, induction_type, false);
    9404              : 
    9405          919 :   vec_init = vect_create_nonlinear_iv_init (&stmts, init_expr,
    9406              :                                             step_expr, nunits, vectype,
    9407              :                                             induction_type);
    9408          919 :   if (stmts)
    9409              :     {
    9410          162 :       new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
    9411          162 :       gcc_assert (!new_bb);
    9412              :     }
    9413              : 
    9414          919 :   stmts = NULL;
    9415          919 :   new_name = vect_create_nonlinear_iv_step (&stmts, step_expr,
    9416              :                                             vf, induction_type);
    9417          919 :   if (stmts)
    9418              :     {
    9419            0 :       new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
    9420            0 :       gcc_assert (!new_bb);
    9421              :     }
    9422              : 
    9423          919 :   vec_step = vect_create_nonlinear_iv_vec_step (loop_vinfo, stmt_info,
    9424              :                                                 new_name, vectype,
    9425              :                                                 induction_type);
    9426              :   /* Create the following def-use cycle:
    9427              :      loop prolog:
    9428              :      vec_init = ...
    9429              :      vec_step = ...
    9430              :      loop:
    9431              :      vec_iv = PHI <vec_init, vec_loop>
    9432              :      ...
    9433              :      STMT
    9434              :      ...
    9435              :      vec_loop = vec_iv + vec_step;  */
    9436              : 
    9437              :   /* Create the induction-phi that defines the induction-operand.  */
    9438          919 :   vec_dest = vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_");
    9439          919 :   induction_phi = create_phi_node (vec_dest, iv_loop->header);
    9440          919 :   induc_def = PHI_RESULT (induction_phi);
    9441              : 
    9442              :   /* Create the iv update inside the loop.  */
    9443          919 :   stmts = NULL;
    9444          919 :   vec_def = vect_update_nonlinear_iv (&stmts, vectype,
    9445              :                                       induc_def, vec_step,
    9446              :                                       induction_type);
    9447              : 
    9448          919 :   gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
    9449          919 :   new_stmt = SSA_NAME_DEF_STMT (vec_def);
    9450              : 
    9451              :   /* Set the arguments of the phi node:  */
    9452          919 :   add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
    9453          919 :   add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
    9454              :                UNKNOWN_LOCATION);
    9455              : 
    9456          919 :   slp_node->push_vec_def (induction_phi);
    9457              : 
    9458              :   /* In case that vectorization factor (VF) is bigger than the number
    9459              :      of elements that we can fit in a vectype (nunits), we have to generate
    9460              :      more than one vector stmt - i.e - we need to "unroll" the
    9461              :      vector stmt by a factor VF/nunits.  For more details see documentation
    9462              :      in vectorizable_operation.  */
    9463              : 
    9464          919 :   if (ncopies > 1)
    9465              :     {
    9466          286 :       stmts = NULL;
    9467              :       /* FORNOW. This restriction should be relaxed.  */
    9468          286 :       gcc_assert (!nested_in_vect_loop);
    9469              : 
    9470          286 :       new_name = vect_create_nonlinear_iv_step (&stmts, step_expr,
    9471              :                                                 nunits, induction_type);
    9472              : 
    9473          286 :       vec_step = vect_create_nonlinear_iv_vec_step (loop_vinfo, stmt_info,
    9474              :                                                     new_name, vectype,
    9475              :                                                     induction_type);
    9476          286 :       vec_def = induc_def;
    9477         1046 :       for (i = 1; i < ncopies; i++)
    9478              :         {
    9479              :           /* vec_i = vec_prev + vec_step.  */
    9480          474 :           stmts = NULL;
    9481          474 :           vec_def = vect_update_nonlinear_iv (&stmts, vectype,
    9482              :                                               vec_def, vec_step,
    9483              :                                               induction_type);
    9484          474 :           gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
    9485          474 :           new_stmt = SSA_NAME_DEF_STMT (vec_def);
    9486          474 :           slp_node->push_vec_def (new_stmt);
    9487              :         }
    9488              :     }
    9489              : 
    9490          919 :   if (dump_enabled_p ())
    9491           64 :     dump_printf_loc (MSG_NOTE, vect_location,
    9492              :                      "transform induction: created def-use cycle: %G%G",
    9493           32 :                      (gimple *) induction_phi, SSA_NAME_DEF_STMT (vec_def));
    9494              : 
    9495              :   return true;
    9496              : }
    9497              : 
    9498              : /* Return true if the scalar initial values and steps of the SLP induction
    9499              :    lanes allow the first CANDIDATE_NIVS IVs to be reused circularly for the
    9500              :    remaining lanes.  */
    9501              : static bool
    9502           26 : vect_slp_induction_reuse_p (tree *steps, tree *inits, unsigned group_size,
    9503              :                           unsigned HOST_WIDE_INT const_nunits,
    9504              :                           unsigned candidate_nivs, unsigned nivs)
    9505              : {
    9506           26 :   gcc_assert (candidate_nivs > 0);
    9507           26 :   gcc_assert (candidate_nivs < nivs);
    9508              : 
    9509              :   /* This function compares only STEPS and INITS, so all checked lanes must
    9510              :      precede the first wrap of the SLP group.  */
    9511           26 :   gcc_assert (nivs * const_nunits <= group_size);
    9512              : 
    9513           62 :   for (unsigned ivn = candidate_nivs; ivn < nivs; ++ivn)
    9514              :     {
    9515           42 :       unsigned reuse_ivn = ivn % candidate_nivs;
    9516          172 :       for (unsigned HOST_WIDE_INT eltn = 0; eltn < const_nunits; ++eltn)
    9517              :         {
    9518          136 :           unsigned HOST_WIDE_INT elt = ivn * const_nunits + eltn;
    9519          136 :           unsigned HOST_WIDE_INT reused_elt
    9520          136 :             = reuse_ivn * const_nunits + eltn;
    9521              : 
    9522          136 :           if (!operand_equal_p (steps[elt], steps[reused_elt], 0)
    9523          136 :               || !operand_equal_p (inits[elt], inits[reused_elt], 0))
    9524              :             return false;
    9525              :         }
    9526              :     }
    9527              : 
    9528              :   return true;
    9529              : }
    9530              : 
    9531              : /* Function vectorizable_induction
    9532              : 
    9533              :    Check if STMT_INFO performs an induction computation that can be vectorized.
    9534              :    If VEC_STMT is also passed, vectorize the induction PHI: create a vectorized
    9535              :    phi to replace it, put it in VEC_STMT, and add it to the same basic block.
    9536              :    Return true if STMT_INFO is vectorizable in this way.  */
    9537              : 
    9538              : bool
    9539       337770 : vectorizable_induction (loop_vec_info loop_vinfo,
    9540              :                         stmt_vec_info stmt_info,
    9541              :                         slp_tree slp_node, stmt_vector_for_cost *cost_vec)
    9542              : {
    9543       337770 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    9544       337770 :   bool nested_in_vect_loop = false;
    9545       337770 :   class loop *iv_loop;
    9546       337770 :   tree vec_def;
    9547       337770 :   edge pe = loop_preheader_edge (loop);
    9548       337770 :   basic_block new_bb;
    9549       337770 :   tree vec_init = NULL_TREE, vec_step, t;
    9550       337770 :   tree new_name;
    9551       337770 :   gphi *induction_phi;
    9552       337770 :   tree induc_def, vec_dest;
    9553       337770 :   unsigned i;
    9554       337770 :   tree index_vectype = NULL_TREE;
    9555       337770 :   gimple_stmt_iterator si;
    9556       337770 :   enum vect_induction_op_type induction_type
    9557              :     = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info);
    9558              : 
    9559       337770 :   gphi *phi = dyn_cast <gphi *> (stmt_info->stmt);
    9560       179960 :   if (!phi)
    9561              :     return false;
    9562              : 
    9563       179960 :   if (!STMT_VINFO_RELEVANT_P (stmt_info))
    9564              :     return false;
    9565              : 
    9566              :   /* Make sure it was recognized as induction computation.  */
    9567       179960 :   if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_induction_def)
    9568              :     return false;
    9569              : 
    9570              :   /* Handle nonlinear induction in a separate place.  */
    9571       175853 :   if (induction_type != vect_step_op_add)
    9572         9573 :     return vectorizable_nonlinear_induction (loop_vinfo, stmt_info,
    9573         9573 :                                              slp_node, cost_vec);
    9574              : 
    9575       166280 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
    9576       166280 :   poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
    9577              : 
    9578              :   /* FORNOW. These restrictions should be relaxed.  */
    9579       166280 :   if (nested_in_vect_loop_p (loop, stmt_info))
    9580              :     {
    9581          772 :       imm_use_iterator imm_iter;
    9582          772 :       use_operand_p use_p;
    9583          772 :       gimple *exit_phi;
    9584          772 :       edge latch_e;
    9585          772 :       tree loop_arg;
    9586              : 
    9587          772 :       exit_phi = NULL;
    9588          772 :       latch_e = loop_latch_edge (loop->inner);
    9589          772 :       loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
    9590         1582 :       FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
    9591              :         {
    9592          832 :           gimple *use_stmt = USE_STMT (use_p);
    9593          832 :           if (is_gimple_debug (use_stmt))
    9594           36 :             continue;
    9595              : 
    9596          796 :           if (!flow_bb_inside_loop_p (loop->inner, gimple_bb (use_stmt)))
    9597              :             {
    9598              :               exit_phi = use_stmt;
    9599              :               break;
    9600              :             }
    9601          772 :         }
    9602          772 :       if (exit_phi)
    9603              :         {
    9604           22 :           stmt_vec_info exit_phi_vinfo = loop_vinfo->lookup_stmt (exit_phi);
    9605           22 :           if (!(STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
    9606            6 :                 && !STMT_VINFO_LIVE_P (exit_phi_vinfo)))
    9607              :             {
    9608           16 :               if (dump_enabled_p ())
    9609           16 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9610              :                                  "inner-loop induction only used outside "
    9611              :                                  "of the outer vectorized loop.\n");
    9612           16 :               return false;
    9613              :             }
    9614              :         }
    9615              : 
    9616          756 :       nested_in_vect_loop = true;
    9617          756 :       iv_loop = loop->inner;
    9618              :     }
    9619              :   else
    9620              :     iv_loop = loop;
    9621       166264 :   gcc_assert (iv_loop == (gimple_bb (phi))->loop_father);
    9622              : 
    9623       166264 :   if (!nunits.is_constant () && SLP_TREE_LANES (slp_node) != 1)
    9624              :     {
    9625              :       /* The current SLP code creates the step value element-by-element.  */
    9626              :       if (dump_enabled_p ())
    9627              :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9628              :                          "SLP induction not supported for variable-length"
    9629              :                          " vectors.\n");
    9630              :       return false;
    9631              :     }
    9632              : 
    9633       166264 :   if (FLOAT_TYPE_P (vectype) && !param_vect_induction_float)
    9634              :     {
    9635           12 :       if (dump_enabled_p ())
    9636           12 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9637              :                          "floating point induction vectorization disabled\n");
    9638              :       return false;
    9639              :     }
    9640              : 
    9641       166252 :   tree step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info);
    9642       166252 :   gcc_assert (step_expr != NULL_TREE);
    9643       332480 :   if (INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
    9644       332379 :       && !type_has_mode_precision_p (TREE_TYPE (step_expr)))
    9645              :     {
    9646           12 :       if (dump_enabled_p ())
    9647           12 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9648              :                          "bit-precision induction vectorization not "
    9649              :                          "supported.\n");
    9650              :       return false;
    9651              :     }
    9652       166240 :   tree stept = TREE_TYPE (step_expr);
    9653       166240 :   tree step_vectype = get_same_sized_vectype (stept, vectype);
    9654       166240 :   stept = TREE_TYPE (step_vectype);
    9655              : 
    9656              :   /* Check for target support of the vectorized arithmetic used here.  */
    9657       166240 :   if (!target_supports_op_p (step_vectype, PLUS_EXPR, optab_default)
    9658       166240 :       || !target_supports_op_p (step_vectype, MINUS_EXPR, optab_default))
    9659              :       return false;
    9660       136346 :   if (!nunits.is_constant ()
    9661       136346 :       || !LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
    9662              :     {
    9663            0 :       if (!target_supports_op_p (step_vectype, MULT_EXPR, optab_default))
    9664              :         return false;
    9665              :       /* FLOAT_EXPR when computing VEC_INIT for float inductions.  */
    9666            0 :       if (SCALAR_FLOAT_TYPE_P (stept))
    9667              :         {
    9668            0 :           tree index_type = build_nonstandard_integer_type
    9669            0 :                 (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (stept)), 1);
    9670              : 
    9671            0 :           index_vectype = build_vector_type (index_type, nunits);
    9672            0 :           if (!can_float_p (TYPE_MODE (step_vectype),
    9673            0 :                             TYPE_MODE (index_vectype), 1))
    9674              :             return false;
    9675              :         }
    9676              :     }
    9677              : 
    9678       136346 :   unsigned nvects = vect_get_num_copies (loop_vinfo, slp_node);
    9679       136346 :   if (cost_vec) /* transformation not required.  */
    9680              :     {
    9681       362511 :       unsigned inside_cost = 0, prologue_cost = 0;
    9682              :       /* We eventually need to set a vector type on invariant
    9683              :          arguments.  */
    9684              :       unsigned j;
    9685              :       slp_tree child;
    9686       362511 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), j, child)
    9687       241674 :         if (!vect_maybe_update_slp_op_vectype
    9688       241674 :             (child, SLP_TREE_VECTYPE (slp_node)))
    9689              :           {
    9690            0 :             if (dump_enabled_p ())
    9691            0 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9692              :                                "incompatible vector types for "
    9693              :                                "invariants\n");
    9694              :             return false;
    9695              :           }
    9696              :       /* loop cost for vec_loop.  */
    9697       120837 :       inside_cost = record_stmt_cost (cost_vec, nvects,
    9698              :                                       vector_stmt, slp_node, 0, vect_body);
    9699              :       /* prologue cost for vec_init (if not nested) and step.  */
    9700       120837 :       prologue_cost = record_stmt_cost (cost_vec, 1 + !nested_in_vect_loop,
    9701              :                                         scalar_to_vec,
    9702              :                                         slp_node, 0, vect_prologue);
    9703       120837 :       if (dump_enabled_p ())
    9704         4183 :         dump_printf_loc (MSG_NOTE, vect_location,
    9705              :                          "vect_model_induction_cost: inside_cost = %d, "
    9706              :                          "prologue_cost = %d .\n", inside_cost,
    9707              :                          prologue_cost);
    9708              : 
    9709       120837 :       SLP_TREE_TYPE (slp_node) = induc_vec_info_type;
    9710       120837 :       DUMP_VECT_SCOPE ("vectorizable_induction");
    9711       120837 :       return true;
    9712              :     }
    9713              : 
    9714              :   /* Transform.  */
    9715              : 
    9716              :   /* Compute a vector variable, initialized with the first VF values of
    9717              :      the induction variable.  E.g., for an iv with IV_PHI='X' and
    9718              :      evolution S, for a vector of 4 units, we want to compute:
    9719              :      [X, X + S, X + 2*S, X + 3*S].  */
    9720              : 
    9721        15509 :   if (dump_enabled_p ())
    9722         2811 :     dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
    9723              : 
    9724        15509 :   pe = loop_preheader_edge (iv_loop);
    9725              :   /* Find the first insertion point in the BB.  */
    9726        15509 :   basic_block bb = gimple_bb (phi);
    9727        15509 :   si = gsi_after_labels (bb);
    9728              : 
    9729              :   /* For SLP induction we have to generate several IVs as for example
    9730              :      with group size 3 we need
    9731              :        [i0, i1, i2, i0 + S0] [i1 + S1, i2 + S2, i0 + 2*S0, i1 + 2*S1]
    9732              :        [i2 + 2*S2, i0 + 3*S0, i1 + 3*S1, i2 + 3*S2].  */
    9733        15509 :   gimple_stmt_iterator incr_si;
    9734        15509 :   bool insert_after;
    9735        15509 :   standard_iv_increment_position (iv_loop, &incr_si, &insert_after);
    9736              : 
    9737              :   /* The initial values are vectorized, but any lanes > group_size
    9738              :      need adjustment.  */
    9739        15509 :   slp_tree init_node
    9740        15509 :       = SLP_TREE_CHILDREN (slp_node)[pe->dest_idx];
    9741              : 
    9742              :   /* Gather steps.  Since we do not vectorize inductions as
    9743              :      cycles we have to reconstruct the step from SCEV data.  */
    9744        15509 :   unsigned group_size = SLP_TREE_LANES (slp_node);
    9745        15509 :   tree *steps = XALLOCAVEC (tree, group_size);
    9746        15509 :   tree *inits = XALLOCAVEC (tree, group_size);
    9747        15509 :   stmt_vec_info phi_info;
    9748        47912 :   FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (slp_node), i, phi_info)
    9749              :     {
    9750        16894 :       steps[i] = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (phi_info);
    9751        16894 :       if (!init_node)
    9752        16662 :         inits[i] = gimple_phi_arg_def (as_a<gphi *> (phi_info->stmt),
    9753              :                                        pe->dest_idx);
    9754              :     }
    9755              : 
    9756              :   /* Now generate the IVs.  */
    9757        31018 :   gcc_assert (multiple_p (nunits * nvects, group_size));
    9758        15509 :   unsigned nivs;
    9759        15509 :   unsigned HOST_WIDE_INT const_nunits;
    9760        15509 :   if (nested_in_vect_loop)
    9761              :     nivs = nvects;
    9762        15298 :   else if (nunits.is_constant (&const_nunits)
    9763        15298 :            && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
    9764              :     {
    9765        15298 :       gcc_assert (!init_node);
    9766              :       /* Compute the number of distinct IVs we need.  We can reduce the
    9767              :          number when later vector chunks are equal to earlier chunks.  */
    9768        15298 :       nivs = least_common_multiple (group_size, const_nunits) / const_nunits;
    9769        15298 :       unsigned group_sizep = group_size;
    9770        15298 :       if (group_sizep % const_nunits == 0)
    9771              :         {
    9772          122 :           group_sizep = group_sizep / const_nunits;
    9773          122 :           unsigned candidate_nivs
    9774          122 :             = least_common_multiple (group_sizep, const_nunits) / const_nunits;
    9775          122 :           if (candidate_nivs < nivs
    9776          122 :               && vect_slp_induction_reuse_p (steps, inits, group_size,
    9777              :                                            const_nunits, candidate_nivs, nivs))
    9778              :             {
    9779           20 :               if (dump_enabled_p ())
    9780           16 :                 dump_printf_loc (MSG_NOTE, vect_location,
    9781              :                                  "reusing %u SLP induction IVs for %u "
    9782              :                                  "vector chunks\n",
    9783              :                                  candidate_nivs, nivs);
    9784              :               nivs = candidate_nivs;
    9785              :             }
    9786              :         }
    9787              :     }
    9788              :   else
    9789              :     {
    9790            0 :       gcc_assert (SLP_TREE_LANES (slp_node) == 1);
    9791              :       nivs = 1;
    9792              :     }
    9793        15509 :   gimple_seq init_stmts = NULL;
    9794        15509 :   gimple_seq lupdate_mul_stmts = NULL;
    9795        15509 :   tree lupdate_mul = NULL_TREE;
    9796        15509 :   if (!nested_in_vect_loop)
    9797              :     {
    9798        15298 :       if (nunits.is_constant (&const_nunits)
    9799        15298 :           && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
    9800              :         {
    9801              :           /* The number of iterations covered in one vector iteration.  */
    9802        15298 :           unsigned lup_mul = (nvects * const_nunits) / group_size;
    9803        15298 :           lupdate_mul
    9804        15298 :             = build_vector_from_val (step_vectype,
    9805        15298 :                                      SCALAR_FLOAT_TYPE_P (stept)
    9806           28 :                                      ? build_real_from_wide (stept, lup_mul,
    9807              :                                                              UNSIGNED)
    9808        30568 :                                      : build_int_cstu (stept, lup_mul));
    9809              :         }
    9810              :       else
    9811              :         {
    9812            0 :           gimple_seq *update_stmts
    9813              :             = LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo)
    9814              :                 ? &init_stmts
    9815              :                 : &lupdate_mul_stmts;
    9816            0 :           if (SCALAR_FLOAT_TYPE_P (stept))
    9817              :             {
    9818            0 :               tree increment
    9819            0 :                 = gimple_convert (update_stmts, integer_type_node,
    9820              :                                   LOOP_VINFO_IV_INCREMENT (loop_vinfo));
    9821            0 :               lupdate_mul = gimple_build (update_stmts, FLOAT_EXPR, stept,
    9822              :                                           increment);
    9823              :             }
    9824              :           else
    9825            0 :             lupdate_mul = gimple_convert (update_stmts, stept,
    9826              :                                          LOOP_VINFO_IV_INCREMENT (loop_vinfo));
    9827            0 :           lupdate_mul = gimple_build_vector_from_val (update_stmts,
    9828              :                                                       step_vectype,
    9829              :                                                       lupdate_mul);
    9830              :         }
    9831              :     }
    9832        15509 :   tree peel_mul = NULL_TREE;
    9833        15509 :   if (LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo))
    9834              :     {
    9835            0 :       if (SCALAR_FLOAT_TYPE_P (stept))
    9836            0 :         peel_mul = gimple_build (&init_stmts, FLOAT_EXPR, stept,
    9837              :                                  LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo));
    9838              :       else
    9839            0 :         peel_mul = gimple_convert (&init_stmts, stept,
    9840              :                                    LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo));
    9841            0 :       peel_mul = gimple_build_vector_from_val (&init_stmts,
    9842              :                                                step_vectype, peel_mul);
    9843              :     }
    9844        15509 :   tree step_mul = NULL_TREE;
    9845        15509 :   unsigned ivn;
    9846        15509 :   auto_vec<tree> vec_steps;
    9847        31606 :   for (ivn = 0; ivn < nivs; ++ivn)
    9848              :     {
    9849        16097 :       gimple_seq stmts = NULL;
    9850        16097 :       bool invariant = true;
    9851        16097 :       if (nunits.is_constant (&const_nunits)
    9852        16097 :           && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
    9853              :         {
    9854        16097 :           tree_vector_builder step_elts (step_vectype, const_nunits, 1);
    9855        16097 :           tree_vector_builder init_elts (vectype, const_nunits, 1);
    9856        16097 :           tree_vector_builder mul_elts (step_vectype, const_nunits, 1);
    9857       119636 :           for (unsigned eltn = 0; eltn < const_nunits; ++eltn)
    9858              :             {
    9859              :               /* The scalar steps of the IVs.  */
    9860        87442 :               tree elt = steps[(ivn*const_nunits + eltn) % group_size];
    9861        87442 :               elt = gimple_convert (&init_stmts, TREE_TYPE (step_vectype), elt);
    9862        87442 :               step_elts.quick_push (elt);
    9863        87442 :               if (!init_node)
    9864              :                 {
    9865              :                   /* The scalar inits of the IVs if not vectorized.  */
    9866        86232 :                   elt = inits[(ivn*const_nunits + eltn) % group_size];
    9867        86232 :                   if (!useless_type_conversion_p (TREE_TYPE (vectype),
    9868        86232 :                                                   TREE_TYPE (elt)))
    9869          278 :                     elt = gimple_build (&init_stmts, VIEW_CONVERT_EXPR,
    9870          278 :                                         TREE_TYPE (vectype), elt);
    9871        86232 :                   init_elts.quick_push (elt);
    9872              :                 }
    9873              :               /* The number of steps to add to the initial values.  */
    9874        87442 :               unsigned mul_elt = (ivn*const_nunits + eltn) / group_size;
    9875       174884 :               mul_elts.quick_push (SCALAR_FLOAT_TYPE_P (stept)
    9876       174782 :                                    ? build_real_from_wide (stept, mul_elt,
    9877              :                                                            UNSIGNED)
    9878       174782 :                                    : build_int_cstu (stept, mul_elt));
    9879              :             }
    9880        16097 :           vec_step = gimple_build_vector (&init_stmts, &step_elts);
    9881        16097 :           step_mul = gimple_build_vector (&init_stmts, &mul_elts);
    9882        16097 :           if (!init_node)
    9883        15852 :             vec_init = gimple_build_vector (&init_stmts, &init_elts);
    9884        16097 :         }
    9885              :       else
    9886              :         {
    9887            0 :           tree step = gimple_convert (&init_stmts, stept, steps[0]);
    9888            0 :           if (init_node)
    9889              :             ;
    9890            0 :           else if (INTEGRAL_TYPE_P (stept))
    9891              :             {
    9892            0 :               new_name = gimple_convert (&init_stmts, stept, inits[0]);
    9893              :               /* Build the initial value directly as a VEC_SERIES_EXPR.  */
    9894            0 :               vec_init = gimple_build (&init_stmts, VEC_SERIES_EXPR,
    9895              :                                        step_vectype, new_name, step);
    9896            0 :               if (!useless_type_conversion_p (vectype, step_vectype))
    9897            0 :                 vec_init = gimple_build (&init_stmts, VIEW_CONVERT_EXPR,
    9898              :                                          vectype, vec_init);
    9899              :             }
    9900              :           else
    9901              :             {
    9902              :               /* Build:
    9903              :                  [base, base, base, ...]
    9904              :                  + (vectype) [0, 1, 2, ...] * [step, step, step, ...].  */
    9905            0 :               gcc_assert (SCALAR_FLOAT_TYPE_P (stept));
    9906            0 :               gcc_assert (flag_associative_math);
    9907            0 :               gcc_assert (index_vectype != NULL_TREE);
    9908              : 
    9909            0 :               tree index = build_index_vector (index_vectype, 0, 1);
    9910            0 :               new_name = gimple_convert (&init_stmts, stept, inits[0]);
    9911            0 :               tree base_vec = gimple_build_vector_from_val (&init_stmts,
    9912              :                                                             step_vectype,
    9913              :                                                             new_name);
    9914            0 :               tree step_vec = gimple_build_vector_from_val (&init_stmts,
    9915              :                                                             step_vectype,
    9916              :                                                             step);
    9917            0 :               vec_init = gimple_build (&init_stmts, FLOAT_EXPR,
    9918              :                                        step_vectype, index);
    9919            0 :               vec_init = gimple_build (&init_stmts, MULT_EXPR,
    9920              :                                        step_vectype, vec_init, step_vec);
    9921            0 :               vec_init = gimple_build (&init_stmts, PLUS_EXPR,
    9922              :                                        step_vectype, vec_init, base_vec);
    9923            0 :               if (!useless_type_conversion_p (vectype, step_vectype))
    9924            0 :                 vec_init = gimple_build (&init_stmts, VIEW_CONVERT_EXPR,
    9925              :                                          vectype, vec_init);
    9926              :             }
    9927              :           /* iv_loop is nested in the loop to be vectorized. Generate:
    9928              :              vec_step = [S, S, S, S]  */
    9929            0 :           t = unshare_expr (step);
    9930            0 :           gcc_assert (CONSTANT_CLASS_P (t)
    9931              :                       || TREE_CODE (t) == SSA_NAME);
    9932            0 :           vec_step = gimple_build_vector_from_val (&init_stmts,
    9933              :                                                    step_vectype, t);
    9934              :         }
    9935        16097 :       vec_steps.safe_push (vec_step);
    9936        16097 :       if (peel_mul)
    9937              :         {
    9938            0 :           if (!step_mul)
    9939              :             {
    9940            0 :               gcc_assert (!nunits.is_constant ());
    9941              :               step_mul = gimple_build (&init_stmts,
    9942              :                                        MINUS_EXPR, step_vectype,
    9943              :                                        build_zero_cst (step_vectype), peel_mul);
    9944              :             }
    9945              :           else
    9946            0 :             step_mul = gimple_build (&init_stmts,
    9947              :                                      MINUS_EXPR, step_vectype,
    9948              :                                      step_mul, peel_mul);
    9949              :         }
    9950              : 
    9951              :       /* Create the induction-phi that defines the induction-operand.  */
    9952        16097 :       vec_dest = vect_get_new_vect_var (vectype, vect_simple_var,
    9953              :                                         "vec_iv_");
    9954        16097 :       induction_phi = create_phi_node (vec_dest, iv_loop->header);
    9955        16097 :       induc_def = PHI_RESULT (induction_phi);
    9956              : 
    9957              :       /* Create the iv update inside the loop  */
    9958        16097 :       tree up = vec_step;
    9959        16097 :       if (lupdate_mul)
    9960              :          {
    9961        15852 :            if (lupdate_mul_stmts)
    9962            0 :              gimple_seq_add_seq (&stmts, lupdate_mul_stmts);
    9963        15852 :            up = gimple_build (&stmts, MULT_EXPR, step_vectype, vec_step,
    9964              :                               lupdate_mul);
    9965              :          }
    9966        16097 :       vec_def = gimple_convert (&stmts, step_vectype, induc_def);
    9967        16097 :       vec_def = gimple_build (&stmts, PLUS_EXPR, step_vectype, vec_def, up);
    9968        16097 :       vec_def = gimple_convert (&stmts, vectype, vec_def);
    9969        16097 :       insert_iv_increment (&incr_si, insert_after, stmts);
    9970        16097 :       add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
    9971              :                    UNKNOWN_LOCATION);
    9972              : 
    9973        16097 :       if (init_node)
    9974          245 :         vec_init = vect_get_slp_vect_def (init_node, ivn);
    9975        16097 :       if (!nested_in_vect_loop
    9976        16097 :           && step_mul
    9977        16097 :           && !integer_zerop (step_mul))
    9978              :         {
    9979        15384 :           gcc_assert (invariant);
    9980        15384 :           vec_def = gimple_convert (&init_stmts, step_vectype, vec_init);
    9981        15384 :           up = gimple_build (&init_stmts, MULT_EXPR, step_vectype,
    9982              :                              vec_step, step_mul);
    9983        15384 :           vec_def = gimple_build (&init_stmts, PLUS_EXPR, step_vectype,
    9984              :                                   vec_def, up);
    9985        15384 :           vec_init = gimple_convert (&init_stmts, vectype, vec_def);
    9986              :         }
    9987              : 
    9988              :       /* Set the arguments of the phi node:  */
    9989        16097 :       add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
    9990              : 
    9991        16097 :       slp_node->push_vec_def (induction_phi);
    9992              :     }
    9993        15509 :   if (!nested_in_vect_loop)
    9994              :     {
    9995              :       /* Fill up to the number of vectors we need for the whole group.  */
    9996        15298 :       if (nunits.is_constant (&const_nunits)
    9997        15298 :           && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
    9998        15298 :         nivs = least_common_multiple (group_size, const_nunits) / const_nunits;
    9999              :       else
   10000              :         nivs = 1;
   10001        15298 :       vec_steps.reserve (nivs-ivn);
   10002        15298 :       unsigned generated_nivs = ivn;
   10003        15298 :       gcc_assert (generated_nivs > 0);
   10004        15334 :       for (; ivn < nivs; ++ivn)
   10005              :         {
   10006           36 :           unsigned reuse_ivn = ivn % generated_nivs;
   10007           36 :           slp_node->push_vec_def (SLP_TREE_VEC_DEFS (slp_node)[reuse_ivn]);
   10008           36 :           vec_steps.quick_push (vec_steps[reuse_ivn]);
   10009              :         }
   10010              :     }
   10011              : 
   10012              :   /* Re-use IVs when we can.  We are generating further vector
   10013              :      stmts by adding VF' * stride to the IVs generated above.  */
   10014        15509 :   if (ivn < nvects)
   10015              :     {
   10016         3427 :       if (nunits.is_constant (&const_nunits)
   10017         3427 :           && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
   10018              :         {
   10019         3427 :           unsigned vfp = (least_common_multiple (group_size, const_nunits)
   10020         3427 :                           / group_size);
   10021         3427 :           lupdate_mul
   10022         3427 :               = build_vector_from_val (step_vectype,
   10023         3427 :                                        SCALAR_FLOAT_TYPE_P (stept)
   10024            8 :                                        ? build_real_from_wide (stept,
   10025            8 :                                                                vfp, UNSIGNED)
   10026         6846 :                                        : build_int_cstu (stept, vfp));
   10027              :         }
   10028              :       else
   10029              :         {
   10030            0 :           if (SCALAR_FLOAT_TYPE_P (stept))
   10031              :             {
   10032            0 :               tree tem = build_int_cst (integer_type_node, nunits);
   10033            0 :               lupdate_mul = gimple_build (&init_stmts, FLOAT_EXPR, stept, tem);
   10034              :             }
   10035              :           else
   10036            0 :             lupdate_mul = build_int_cst (stept, nunits);
   10037            0 :           lupdate_mul = gimple_build_vector_from_val (&init_stmts, step_vectype,
   10038              :                                                       lupdate_mul);
   10039              :         }
   10040        11072 :       for (; ivn < nvects; ++ivn)
   10041              :         {
   10042         7645 :           gimple *iv
   10043         7645 :             = SSA_NAME_DEF_STMT (SLP_TREE_VEC_DEFS (slp_node)[ivn - nivs]);
   10044         7645 :           tree def = gimple_get_lhs (iv);
   10045         7645 :           if (ivn < 2*nivs)
   10046         3525 :             vec_steps[ivn - nivs]
   10047         3525 :               = gimple_build (&init_stmts, MULT_EXPR, step_vectype,
   10048         3525 :                               vec_steps[ivn - nivs], lupdate_mul);
   10049         7645 :           gimple_seq stmts = NULL;
   10050         7645 :           def = gimple_convert (&stmts, step_vectype, def);
   10051        22935 :           def = gimple_build (&stmts, PLUS_EXPR, step_vectype,
   10052         7645 :                               def, vec_steps[ivn % nivs]);
   10053         7645 :           def = gimple_convert (&stmts, vectype, def);
   10054         7645 :           if (gimple_code (iv) == GIMPLE_PHI)
   10055         3525 :             gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
   10056              :           else
   10057              :             {
   10058         4120 :               gimple_stmt_iterator tgsi = gsi_for_stmt (iv);
   10059         4120 :               gsi_insert_seq_after (&tgsi, stmts, GSI_CONTINUE_LINKING);
   10060              :             }
   10061         7645 :           slp_node->push_vec_def (def);
   10062              :         }
   10063              :     }
   10064              : 
   10065        15509 :   new_bb = gsi_insert_seq_on_edge_immediate (pe, init_stmts);
   10066        15509 :   gcc_assert (!new_bb);
   10067              : 
   10068        15509 :   return true;
   10069        15509 : }
   10070              : 
   10071              : /* Function vectorizable_live_operation_1.
   10072              : 
   10073              :    helper function for vectorizable_live_operation.  */
   10074              : 
   10075              : static tree
   10076         2898 : vectorizable_live_operation_1 (loop_vec_info loop_vinfo, basic_block exit_bb,
   10077              :                                tree vectype, slp_tree slp_node,
   10078              :                                tree bitsize, tree bitstart, tree vec_lhs,
   10079              :                                tree lhs_type, gimple_stmt_iterator *exit_gsi)
   10080              : {
   10081         2898 :   gcc_assert (single_pred_p (exit_bb) || LOOP_VINFO_EARLY_BREAKS (loop_vinfo));
   10082              : 
   10083         2898 :   tree vec_lhs_phi = copy_ssa_name (vec_lhs);
   10084         2898 :   gimple *phi = create_phi_node (vec_lhs_phi, exit_bb);
   10085         8696 :   for (unsigned i = 0; i < gimple_phi_num_args (phi); i++)
   10086         2900 :     SET_PHI_ARG_DEF (phi, i, vec_lhs);
   10087              : 
   10088         2898 :   gimple_seq stmts = NULL;
   10089         2898 :   tree new_tree;
   10090              : 
   10091              :   /* If bitstart is 0 then we can use a BIT_FIELD_REF  */
   10092         2898 :   if (integer_zerop (bitstart))
   10093              :     {
   10094          258 :       tree scalar_res = gimple_build (&stmts, BIT_FIELD_REF, TREE_TYPE (vectype),
   10095              :                                       vec_lhs_phi, bitsize, bitstart);
   10096              : 
   10097              :       /* Convert the extracted vector element to the scalar type.  */
   10098          258 :       new_tree = gimple_convert (&stmts, lhs_type, scalar_res);
   10099              :     }
   10100         2640 :   else if (LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
   10101              :     {
   10102              :       /* Emit:
   10103              : 
   10104              :          SCALAR_RES = VEC_EXTRACT <VEC_LHS, LEN - 1>
   10105              : 
   10106              :          where VEC_LHS is the vectorized live-out result, LEN is the length of
   10107              :          the vector, BIAS is the load-store bias.  The bias should not be used
   10108              :          at all since we are not using load/store operations, but LEN will be
   10109              :          REALLEN + BIAS, so subtract it to get to the correct position.  */
   10110            0 :       gcc_assert (SLP_TREE_LANES (slp_node) == 1);
   10111            0 :       gimple_seq tem = NULL;
   10112            0 :       gimple_stmt_iterator gsi = gsi_last (tem);
   10113            0 :       tree len = vect_get_loop_len (loop_vinfo, &gsi,
   10114              :                                     &LOOP_VINFO_LENS (loop_vinfo),
   10115              :                                     1, vectype, 0, 1, false);
   10116            0 :       gimple_seq_add_seq (&stmts, tem);
   10117              : 
   10118              :       /* LAST_INDEX = LEN - 1.  */
   10119            0 :       tree last_index = gimple_build (&stmts, MINUS_EXPR, TREE_TYPE (len),
   10120            0 :                                      len, build_one_cst (TREE_TYPE (len)));
   10121              : 
   10122              :       /* SCALAR_RES = VEC_EXTRACT <VEC_LHS, LEN - 1>.  */
   10123            0 :       tree scalar_res
   10124            0 :         = gimple_build (&stmts, CFN_VEC_EXTRACT, TREE_TYPE (vectype),
   10125              :                         vec_lhs_phi, last_index);
   10126              : 
   10127              :       /* Convert the extracted vector element to the scalar type.  */
   10128            0 :       new_tree = gimple_convert (&stmts, lhs_type, scalar_res);
   10129              :     }
   10130         2640 :   else if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
   10131              :     {
   10132              :       /* Emit:
   10133              : 
   10134              :          SCALAR_RES = EXTRACT_LAST <VEC_LHS, MASK>
   10135              : 
   10136              :          where VEC_LHS is the vectorized live-out result and MASK is
   10137              :          the loop mask for the final iteration.  */
   10138            0 :       gcc_assert (SLP_TREE_LANES (slp_node) == 1);
   10139            0 :       tree scalar_type = TREE_TYPE (vectype);
   10140            0 :       gimple_seq tem = NULL;
   10141            0 :       gimple_stmt_iterator gsi = gsi_last (tem);
   10142            0 :       tree mask = vect_get_loop_mask (loop_vinfo, &gsi,
   10143              :                                       &LOOP_VINFO_MASKS (loop_vinfo),
   10144              :                                       1, vectype, 0);
   10145            0 :       tree scalar_res;
   10146            0 :       gimple_seq_add_seq (&stmts, tem);
   10147              : 
   10148            0 :       scalar_res = gimple_build (&stmts, CFN_EXTRACT_LAST, scalar_type,
   10149              :                                  mask, vec_lhs_phi);
   10150              : 
   10151              :       /* Convert the extracted vector element to the scalar type.  */
   10152            0 :       new_tree = gimple_convert (&stmts, lhs_type, scalar_res);
   10153              :     }
   10154              :   else
   10155              :     {
   10156         2640 :       tree bftype = TREE_TYPE (vectype);
   10157         2640 :       if (VECTOR_BOOLEAN_TYPE_P (vectype))
   10158           85 :         bftype = build_nonstandard_integer_type (tree_to_uhwi (bitsize), 1);
   10159         2640 :       new_tree = build3 (BIT_FIELD_REF, bftype, vec_lhs_phi, bitsize, bitstart);
   10160         2640 :       new_tree = force_gimple_operand (fold_convert (lhs_type, new_tree),
   10161              :                                        &stmts, true, NULL_TREE);
   10162              :     }
   10163              : 
   10164         2898 :   *exit_gsi = gsi_after_labels (exit_bb);
   10165         2898 :   if (stmts)
   10166         2898 :     gsi_insert_seq_before (exit_gsi, stmts, GSI_SAME_STMT);
   10167              : 
   10168         2898 :   return new_tree;
   10169              : }
   10170              : 
   10171              : /* Function vectorizable_live_operation.
   10172              : 
   10173              :    STMT_INFO computes a value that is used outside the loop.  Check if
   10174              :    it can be supported.  */
   10175              : 
   10176              : bool
   10177       318431 : vectorizable_live_operation (vec_info *vinfo, stmt_vec_info stmt_info,
   10178              :                              slp_tree slp_node, slp_instance slp_node_instance,
   10179              :                              int slp_index, bool vec_stmt_p,
   10180              :                              stmt_vector_for_cost *cost_vec)
   10181              : {
   10182       318431 :   loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
   10183       318431 :   imm_use_iterator imm_iter;
   10184       318431 :   tree lhs, lhs_type, bitsize;
   10185       318431 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
   10186       318431 :   poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
   10187       318431 :   gimple *use_stmt;
   10188       318431 :   use_operand_p use_p;
   10189       318431 :   auto_vec<tree> vec_oprnds;
   10190       318431 :   int vec_entry = 0;
   10191       318431 :   poly_uint64 vec_index = 0;
   10192              : 
   10193       318431 :   gcc_assert (STMT_VINFO_LIVE_P (stmt_info)
   10194              :               || LOOP_VINFO_EARLY_BREAKS (loop_vinfo));
   10195              : 
   10196              :   /* If a stmt of a reduction is live, vectorize it via
   10197              :      vect_create_epilog_for_reduction.  vectorizable_reduction assessed
   10198              :      validity so just trigger the transform here.  */
   10199       318431 :   if (vect_is_reduction (slp_node))
   10200              :     {
   10201        87535 :       if (!vec_stmt_p)
   10202              :         {
   10203        63952 :           SLP_TREE_LIVE_LANES (slp_node).safe_push (slp_index);
   10204        63952 :           return true;
   10205              :         }
   10206              :       /* For SLP reductions we vectorize the epilogue for all involved stmts
   10207              :          together.  For SLP reduction chains we only get here once.  */
   10208        23583 :       if (SLP_INSTANCE_KIND (slp_node_instance) == slp_inst_kind_reduc_group
   10209        23286 :           && slp_index != 0)
   10210              :         return true;
   10211        23120 :       vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
   10212        23120 :       if (VECT_REDUC_INFO_TYPE (reduc_info) == FOLD_LEFT_REDUCTION
   10213        23120 :           || VECT_REDUC_INFO_TYPE (reduc_info) == EXTRACT_LAST_REDUCTION)
   10214              :         return true;
   10215              : 
   10216        22193 :       if (!LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
   10217        22193 :           || !LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
   10218        22184 :         vect_create_epilog_for_reduction (loop_vinfo, stmt_info, slp_node,
   10219              :                                           slp_node_instance,
   10220              :                                           LOOP_VINFO_MAIN_EXIT (loop_vinfo));
   10221              : 
   10222              :       /* If early break we only have to materialize the reduction on the merge
   10223              :          block, but we have to find an alternate exit first.  */
   10224        22193 :       if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
   10225              :         {
   10226           28 :           slp_tree phis_node = slp_node_instance->reduc_phis;
   10227           28 :           stmt_info = SLP_TREE_REPRESENTATIVE (phis_node);
   10228           89 :           for (auto exit : get_loop_exit_edges (LOOP_VINFO_LOOP (loop_vinfo)))
   10229           28 :             if (exit != LOOP_VINFO_MAIN_EXIT (loop_vinfo))
   10230              :               {
   10231           23 :                 vect_create_epilog_for_reduction (loop_vinfo, stmt_info,
   10232              :                                                   phis_node, slp_node_instance,
   10233              :                                                   exit);
   10234           23 :                 break;
   10235           28 :               }
   10236           28 :           if (LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
   10237            9 :             vect_create_epilog_for_reduction (loop_vinfo, stmt_info,
   10238              :                                               phis_node, slp_node_instance,
   10239              :                                               LOOP_VINFO_MAIN_EXIT
   10240              :                                               (loop_vinfo));
   10241              :         }
   10242              : 
   10243              :       return true;
   10244              :     }
   10245              : 
   10246              :   /* If STMT is not relevant and it is a simple assignment and its inputs are
   10247              :      invariant then it can remain in place, unvectorized.  The original last
   10248              :      scalar value that it computes will be used.  */
   10249       230896 :   if (!STMT_VINFO_RELEVANT_P (stmt_info))
   10250              :     {
   10251            0 :       gcc_assert (is_simple_and_all_uses_invariant (stmt_info, loop_vinfo));
   10252            0 :       if (dump_enabled_p ())
   10253            0 :         dump_printf_loc (MSG_NOTE, vect_location,
   10254              :                          "statement is simple and uses invariant.  Leaving in "
   10255              :                          "place.\n");
   10256              :       return true;
   10257              :     }
   10258              : 
   10259       230896 :   gcc_assert (slp_index >= 0);
   10260              : 
   10261              :   /* Get the last occurrence of the scalar index from the concatenation of
   10262              :      all the slp vectors. Calculate which slp vector it is and the index
   10263              :      within.  */
   10264       230896 :   int num_scalar = SLP_TREE_LANES (slp_node);
   10265       230896 :   int num_vec = vect_get_num_copies (vinfo, slp_node);
   10266       230896 :   poly_uint64 pos = (num_vec * nunits) - num_scalar + slp_index;
   10267              : 
   10268              :   /* Calculate which vector contains the result, and which lane of
   10269              :      that vector we need.  */
   10270       230896 :   if (!can_div_trunc_p (pos, nunits, &vec_entry, &vec_index))
   10271              :     {
   10272              :       if (dump_enabled_p ())
   10273              :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10274              :                          "Cannot determine which vector holds the"
   10275              :                          " final result.\n");
   10276              :       return false;
   10277              :     }
   10278              : 
   10279       230896 :   if (!vec_stmt_p)
   10280              :     {
   10281              :       /* No transformation required.  */
   10282       179111 :       if (loop_vinfo && LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
   10283              :         {
   10284        29125 :           if (SLP_TREE_LANES (slp_node) != 1)
   10285              :             {
   10286           19 :               if (dump_enabled_p ())
   10287           19 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10288              :                                  "can't operate on partial vectors "
   10289              :                                  "because an SLP statement is live after "
   10290              :                                  "the loop.\n");
   10291           19 :               LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
   10292              :             }
   10293        29106 :           else if (num_vec > 1)
   10294              :             {
   10295        17109 :               if (dump_enabled_p ())
   10296           53 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10297              :                                  "can't operate on partial vectors "
   10298              :                                  "because ncopies is greater than 1.\n");
   10299        17109 :               LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
   10300              :             }
   10301              :           else
   10302              :             {
   10303        11997 :               if (direct_internal_fn_supported_p (IFN_EXTRACT_LAST, vectype,
   10304              :                                                   OPTIMIZE_FOR_SPEED))
   10305            0 :                 vect_record_loop_mask (loop_vinfo,
   10306              :                                        &LOOP_VINFO_MASKS (loop_vinfo),
   10307              :                                        1, vectype, NULL);
   10308        11997 :               else if (can_vec_extract_var_idx_p (
   10309        11997 :                          TYPE_MODE (vectype), TYPE_MODE (TREE_TYPE (vectype))))
   10310            0 :                 vect_record_loop_len (loop_vinfo,
   10311              :                                       &LOOP_VINFO_LENS (loop_vinfo),
   10312              :                                       1, vectype, 1);
   10313              :               else
   10314              :                 {
   10315        11997 :                   if (dump_enabled_p ())
   10316          685 :                     dump_printf_loc (
   10317          685 :                       MSG_MISSED_OPTIMIZATION, vect_location,
   10318              :                       "can't operate on partial vectors "
   10319              :                       "because the target doesn't support extract "
   10320              :                       "last reduction.\n");
   10321        11997 :                   LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
   10322              :                 }
   10323              :             }
   10324              :         }
   10325              :       /* ???  Enable for loop costing as well.  */
   10326        29125 :       if (!loop_vinfo)
   10327       104993 :         record_stmt_cost (cost_vec, 1, vec_to_scalar, slp_node,
   10328              :                           0, vect_epilogue);
   10329       179111 :       SLP_TREE_LIVE_LANES (slp_node).safe_push (slp_index);
   10330       179111 :       return true;
   10331              :     }
   10332              : 
   10333              :   /* Use the lhs of the original scalar statement.  */
   10334        51785 :   gimple *stmt = vect_orig_stmt (stmt_info)->stmt;
   10335        51785 :   if (dump_enabled_p ())
   10336         1019 :     dump_printf_loc (MSG_NOTE, vect_location, "extracting lane for live "
   10337              :                      "stmt %G", stmt);
   10338              : 
   10339        51785 :   lhs = gimple_get_lhs (stmt);
   10340        51785 :   lhs_type = TREE_TYPE (lhs);
   10341              : 
   10342        51785 :   bitsize = vector_element_bits_tree (vectype);
   10343              : 
   10344              :   /* Get the vectorized lhs of STMT and the lane to use (counted in bits).  */
   10345        51785 :   gcc_assert (!loop_vinfo
   10346              :               || ((!LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
   10347              :                    && !LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
   10348              :                   || SLP_TREE_LANES (slp_node) == 1));
   10349              : 
   10350              :   /* Get the correct slp vectorized stmt.  */
   10351        51785 :   tree vec_lhs = SLP_TREE_VEC_DEFS (slp_node)[vec_entry];
   10352              : 
   10353              :   /* In case we need to early break vectorize also get the first stmt.  */
   10354        51785 :   tree vec_lhs0 = SLP_TREE_VEC_DEFS (slp_node)[0];
   10355              : 
   10356              :   /* Get entry to use.  */
   10357        51785 :   tree bitstart = bitsize_int (vec_index);
   10358        51785 :   bitstart = int_const_binop (MULT_EXPR, bitsize, bitstart);
   10359              : 
   10360        51785 :   if (loop_vinfo)
   10361              :     {
   10362              :       /* Ensure the VEC_LHS for lane extraction stmts satisfy loop-closed PHI
   10363              :          requirement, insert one phi node for it.  It looks like:
   10364              :            loop;
   10365              :          BB:
   10366              :            # lhs' = PHI <lhs>
   10367              :          ==>
   10368              :            loop;
   10369              :          BB:
   10370              :            # vec_lhs' = PHI <vec_lhs>
   10371              :            new_tree = lane_extract <vec_lhs', ...>;
   10372              :            lhs' = new_tree;  */
   10373              : 
   10374         2939 :       class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
   10375              :       /* Check if we have a loop where the chosen exit is not the main exit,
   10376              :          in these cases for an early break we restart the iteration the vector code
   10377              :          did.  For the live values we want the value at the start of the iteration
   10378              :          rather than at the end.  */
   10379         2939 :       edge main_e = LOOP_VINFO_MAIN_EXIT (loop_vinfo);
   10380         2939 :       bool all_exits_as_early_p = LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo);
   10381        12347 :       FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
   10382         9408 :         if (!is_gimple_debug (use_stmt)
   10383         9408 :             && !flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
   10384         2898 :           FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
   10385              :             {
   10386         2898 :               edge e = gimple_phi_arg_edge (as_a <gphi *> (use_stmt),
   10387         2898 :                                            phi_arg_index_from_use (use_p));
   10388         2898 :               gcc_assert (loop_exit_edge_p (loop, e));
   10389         2898 :               bool main_exit_edge = e == main_e;
   10390         2898 :               tree tmp_vec_lhs = vec_lhs;
   10391         2898 :               tree tmp_bitstart = bitstart;
   10392              : 
   10393              :               /* For early exit where the exit is not in the BB that leads
   10394              :                  to the latch then we're restarting the iteration in the
   10395              :                  scalar loop.  So get the first live value.  */
   10396         2898 :               bool early_break_first_element_p
   10397         2898 :                 = all_exits_as_early_p || !main_exit_edge;
   10398         2898 :               if (early_break_first_element_p)
   10399              :                 {
   10400          240 :                   tmp_vec_lhs = vec_lhs0;
   10401          240 :                   tmp_bitstart = build_zero_cst (TREE_TYPE (bitstart));
   10402              :                 }
   10403              : 
   10404         2898 :               gimple_stmt_iterator exit_gsi;
   10405         2898 :               tree new_tree
   10406         2898 :                   = vectorizable_live_operation_1 (loop_vinfo,
   10407              :                                                    e->dest, vectype,
   10408              :                                                    slp_node, bitsize,
   10409              :                                                    tmp_bitstart, tmp_vec_lhs,
   10410              :                                                    lhs_type, &exit_gsi);
   10411              : 
   10412         2898 :               auto gsi = gsi_for_stmt (use_stmt);
   10413         2898 :               tree lhs_phi = gimple_phi_result (use_stmt);
   10414         2898 :               remove_phi_node (&gsi, false);
   10415         2898 :               gimple *copy = gimple_build_assign (lhs_phi, new_tree);
   10416         2898 :               gsi_insert_before (&exit_gsi, copy, GSI_SAME_STMT);
   10417         2898 :               break;
   10418         2939 :             }
   10419              : 
   10420              :       /* There a no further out-of-loop uses of lhs by LC-SSA construction.  */
   10421         9449 :       FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
   10422         6510 :         gcc_assert (is_gimple_debug (use_stmt)
   10423         2939 :                     || flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)));
   10424              :     }
   10425              :   else
   10426              :     {
   10427              :       /* For basic-block vectorization simply insert the lane-extraction.  */
   10428        48846 :       tree bftype = TREE_TYPE (vectype);
   10429        48846 :       if (VECTOR_BOOLEAN_TYPE_P (vectype))
   10430           52 :         bftype = build_nonstandard_integer_type (tree_to_uhwi (bitsize), 1);
   10431        48846 :       tree new_tree = build3 (BIT_FIELD_REF, bftype,
   10432              :                               vec_lhs, bitsize, bitstart);
   10433        48846 :       gimple_seq stmts = NULL;
   10434        48846 :       new_tree = force_gimple_operand (fold_convert (lhs_type, new_tree),
   10435              :                                        &stmts, true, NULL_TREE);
   10436        48846 :       if (TREE_CODE (new_tree) == SSA_NAME
   10437        97692 :           && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
   10438            2 :         SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_tree) = 1;
   10439        48846 :       gimple *vec_stmt = SSA_NAME_DEF_STMT (vec_lhs);
   10440        48846 :       if (TREE_CODE (vec_lhs) != SSA_NAME || SSA_NAME_IS_DEFAULT_DEF (vec_lhs))
   10441            0 :         vinfo->insert_seq_on_entry (stmt_info, stmts);
   10442        48846 :       else if (is_a <gphi *> (vec_stmt))
   10443              :         {
   10444         3149 :           gimple_stmt_iterator si = gsi_after_labels (gimple_bb (vec_stmt));
   10445         3149 :           gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
   10446              :         }
   10447              :       else
   10448              :         {
   10449        45697 :           gimple_stmt_iterator si = gsi_for_stmt (vec_stmt);
   10450        45697 :           gsi_insert_seq_after (&si, stmts, GSI_SAME_STMT);
   10451              :         }
   10452              : 
   10453              :       /* Replace use of lhs with newly computed result.  If the use stmt is a
   10454              :          single arg PHI, just replace all uses of PHI result.  It's necessary
   10455              :          because lcssa PHI defining lhs may be before newly inserted stmt.  */
   10456        48846 :       use_operand_p use_p;
   10457        48846 :       stmt_vec_info use_stmt_info;
   10458       232361 :       FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
   10459       183515 :         if (!is_gimple_debug (use_stmt)
   10460       183515 :             && (!(use_stmt_info = vinfo->lookup_stmt (use_stmt))
   10461       133889 :                 || !PURE_SLP_STMT (use_stmt_info)))
   10462              :           {
   10463              :             /* ???  This can happen when the live lane ends up being
   10464              :                rooted in a vector construction code-generated by an
   10465              :                external SLP node (and code-generation for that already
   10466              :                happened).
   10467              :                Doing this is what would happen if that vector CTOR
   10468              :                were not code-generated yet so it is not too bad.
   10469              :                ???  In fact we'd likely want to avoid this situation
   10470              :                in the first place.  */
   10471        81717 :             if (TREE_CODE (new_tree) == SSA_NAME
   10472        81717 :                 && !SSA_NAME_IS_DEFAULT_DEF (new_tree)
   10473        81717 :                 && gimple_code (use_stmt) != GIMPLE_PHI
   10474       151921 :                 && !vect_stmt_dominates_stmt_p (SSA_NAME_DEF_STMT (new_tree),
   10475              :                                                 use_stmt))
   10476              :               {
   10477            0 :                 if (dump_enabled_p ())
   10478            0 :                   dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10479              :                                    "Using original scalar computation for "
   10480              :                                    "live lane because use precedes vector "
   10481              :                                    "def\n");
   10482            0 :                 continue;
   10483              :               }
   10484       171222 :             FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
   10485              :               {
   10486              :                 /* ???  It can also happen that we end up pulling a def into
   10487              :                    a loop where replacing out-of-loop uses would require
   10488              :                    a new LC SSA PHI node.  Retain the original scalar in
   10489              :                    those cases as well.  PR98064.  */
   10490        85611 :                 edge e;
   10491        85611 :                 if (TREE_CODE (new_tree) == SSA_NAME
   10492        85611 :                     && !SSA_NAME_IS_DEFAULT_DEF (new_tree)
   10493        85611 :                     && TREE_CODE (vec_lhs) == SSA_NAME
   10494        85611 :                     && !SSA_NAME_IS_DEFAULT_DEF (vec_lhs)
   10495        85611 :                     && (gimple_bb (use_stmt)->loop_father
   10496        85611 :                         != gimple_bb (vec_stmt)->loop_father)
   10497              :                     /* But a replacement in a LC PHI is OK.  This happens
   10498              :                        in gcc.dg/vect/bb-slp-57.c for example.  */
   10499        12799 :                     && (gimple_code (use_stmt) != GIMPLE_PHI
   10500         4021 :                         || (((e = phi_arg_edge_from_use (use_p)), true)
   10501         4021 :                             && !loop_exit_edge_p
   10502         4021 :                                   (gimple_bb (vec_stmt)->loop_father, e)))
   10503        96097 :                     && !flow_loop_nested_p (gimple_bb (vec_stmt)->loop_father,
   10504        10486 :                                             gimple_bb (use_stmt)->loop_father))
   10505              :                   {
   10506            0 :                     if (dump_enabled_p ())
   10507            0 :                       dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10508              :                                        "Using original scalar computation for "
   10509              :                                        "live lane because there is an "
   10510              :                                        "out-of-loop definition for it\n");
   10511            0 :                     continue;
   10512              :                   }
   10513        85611 :                 SET_USE (use_p, new_tree);
   10514              :               }
   10515        81717 :             update_stmt (use_stmt);
   10516        48846 :           }
   10517              :     }
   10518              : 
   10519              :   return true;
   10520       318431 : }
   10521              : 
   10522              : /* Given loop represented by LOOP_VINFO, return true if computation of
   10523              :    LOOP_VINFO_NITERS (= LOOP_VINFO_NITERSM1 + 1) doesn't overflow, false
   10524              :    otherwise.  */
   10525              : 
   10526              : static bool
   10527        62257 : loop_niters_no_overflow (loop_vec_info loop_vinfo)
   10528              : {
   10529        62257 :   gcc_assert (!LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo));
   10530              : 
   10531              :   /* Constant case.  */
   10532        62257 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
   10533              :     {
   10534        36265 :       tree cst_niters = LOOP_VINFO_NITERS (loop_vinfo);
   10535        36265 :       tree cst_nitersm1 = LOOP_VINFO_NITERSM1 (loop_vinfo);
   10536              : 
   10537        36265 :       gcc_assert (TREE_CODE (cst_niters) == INTEGER_CST);
   10538        36265 :       gcc_assert (TREE_CODE (cst_nitersm1) == INTEGER_CST);
   10539        36265 :       if (wi::to_widest (cst_nitersm1) < wi::to_widest (cst_niters))
   10540              :         return true;
   10541              :     }
   10542              : 
   10543        25992 :   widest_int max;
   10544        25992 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
   10545              :   /* Check the upper bound of loop niters.  */
   10546        25992 :   if (get_max_loop_iterations (loop, &max))
   10547              :     {
   10548        25992 :       tree type = TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo));
   10549        25992 :       signop sgn = TYPE_SIGN (type);
   10550        25992 :       widest_int type_max = widest_int::from (wi::max_value (type), sgn);
   10551        25992 :       if (max < type_max)
   10552        25817 :         return true;
   10553        25992 :     }
   10554              :   return false;
   10555        62257 : }
   10556              : 
   10557              : /* Return a mask type with half the number of elements as OLD_TYPE,
   10558              :    given that it should have mode NEW_MODE.  */
   10559              : 
   10560              : tree
   10561         4713 : vect_halve_mask_nunits (tree old_type, machine_mode new_mode)
   10562              : {
   10563         4713 :   poly_uint64 nunits = exact_div (TYPE_VECTOR_SUBPARTS (old_type), 2);
   10564         4713 :   return build_truth_vector_type_for_mode (nunits, new_mode);
   10565              : }
   10566              : 
   10567              : /* Return a mask type with twice as many elements as OLD_TYPE,
   10568              :    given that it should have mode NEW_MODE.  */
   10569              : 
   10570              : tree
   10571         6997 : vect_double_mask_nunits (tree old_type, machine_mode new_mode)
   10572              : {
   10573         6997 :   poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (old_type) * 2;
   10574         6997 :   return build_truth_vector_type_for_mode (nunits, new_mode);
   10575              : }
   10576              : 
   10577              : /* Record that a fully-masked version of LOOP_VINFO would need MASKS to
   10578              :    contain a sequence of NVECTORS masks that each control a vector of type
   10579              :    VECTYPE.  If SCALAR_MASK is nonnull, the fully-masked loop would AND
   10580              :    these vector masks with the vector version of SCALAR_MASK.  */
   10581              : 
   10582              : void
   10583       106262 : vect_record_loop_mask (loop_vec_info loop_vinfo, vec_loop_masks *masks,
   10584              :                        unsigned int nvectors, tree vectype, tree scalar_mask)
   10585              : {
   10586       106262 :   gcc_assert (nvectors != 0);
   10587              : 
   10588       106262 :   if (scalar_mask)
   10589              :     {
   10590         4968 :       scalar_cond_masked_key cond (scalar_mask, nvectors);
   10591         4968 :       loop_vinfo->scalar_cond_masked_set.add (cond);
   10592              :     }
   10593              : 
   10594       106262 :   masks->mask_set.add (std::make_pair (vectype, nvectors));
   10595       106262 : }
   10596              : 
   10597              : /* Given a complete set of masks MASKS, extract mask number INDEX
   10598              :    for an rgroup that operates on NVECTORS vectors of type VECTYPE,
   10599              :    where 0 <= INDEX < NVECTORS.  Insert any set-up statements before GSI.
   10600              : 
   10601              :    See the comment above vec_loop_masks for more details about the mask
   10602              :    arrangement.  */
   10603              : 
   10604              : tree
   10605          214 : vect_get_loop_mask (loop_vec_info loop_vinfo,
   10606              :                     gimple_stmt_iterator *gsi, vec_loop_masks *masks,
   10607              :                     unsigned int nvectors, tree vectype, unsigned int index)
   10608              : {
   10609          214 :   if (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo)
   10610              :       == vect_partial_vectors_while_ult)
   10611              :     {
   10612            0 :       rgroup_controls *rgm = &(masks->rgc_vec)[nvectors - 1];
   10613            0 :       tree mask_type = rgm->type;
   10614              : 
   10615              :       /* Populate the rgroup's mask array, if this is the first time we've
   10616              :          used it.  */
   10617            0 :       if (rgm->controls.is_empty ())
   10618              :         {
   10619            0 :           rgm->controls.safe_grow_cleared (nvectors, true);
   10620            0 :           for (unsigned int i = 0; i < nvectors; ++i)
   10621              :             {
   10622            0 :               tree mask = make_temp_ssa_name (mask_type, NULL, "loop_mask");
   10623              :               /* Provide a dummy definition until the real one is available.  */
   10624            0 :               SSA_NAME_DEF_STMT (mask) = gimple_build_nop ();
   10625            0 :               rgm->controls[i] = mask;
   10626              :             }
   10627              :         }
   10628              : 
   10629            0 :       tree mask = rgm->controls[index];
   10630            0 :       if (maybe_ne (TYPE_VECTOR_SUBPARTS (mask_type),
   10631            0 :                     TYPE_VECTOR_SUBPARTS (vectype)))
   10632              :         {
   10633              :           /* A loop mask for data type X can be reused for data type Y
   10634              :              if X has N times more elements than Y and if Y's elements
   10635              :              are N times bigger than X's.  In this case each sequence
   10636              :              of N elements in the loop mask will be all-zero or all-one.
   10637              :              We can then view-convert the mask so that each sequence of
   10638              :              N elements is replaced by a single element.  */
   10639            0 :           gcc_assert (multiple_p (TYPE_VECTOR_SUBPARTS (mask_type),
   10640              :                                   TYPE_VECTOR_SUBPARTS (vectype)));
   10641            0 :           gimple_seq seq = NULL;
   10642            0 :           mask_type = truth_type_for (vectype);
   10643            0 :           mask = gimple_build (&seq, VIEW_CONVERT_EXPR, mask_type, mask);
   10644            0 :           if (seq)
   10645            0 :             gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
   10646              :         }
   10647              :       return mask;
   10648              :     }
   10649          214 :   else if (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo)
   10650              :            == vect_partial_vectors_avx512)
   10651              :     {
   10652              :       /* The number of scalars per iteration and the number of vectors are
   10653              :          both compile-time constants.  */
   10654          214 :       unsigned int nscalars_per_iter
   10655          214 :         = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
   10656          214 :                      LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
   10657              : 
   10658          214 :       rgroup_controls *rgm = &masks->rgc_vec[nscalars_per_iter - 1];
   10659              : 
   10660              :       /* The stored nV is dependent on the mask type produced.  */
   10661          214 :       gcc_assert (exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
   10662              :                              TYPE_VECTOR_SUBPARTS (rgm->type)).to_constant ()
   10663              :                   == rgm->factor);
   10664          214 :       nvectors = rgm->factor;
   10665              : 
   10666              :       /* Populate the rgroup's mask array, if this is the first time we've
   10667              :          used it.  */
   10668          214 :       if (rgm->controls.is_empty ())
   10669              :         {
   10670           23 :           rgm->controls.safe_grow_cleared (nvectors, true);
   10671          135 :           for (unsigned int i = 0; i < nvectors; ++i)
   10672              :             {
   10673           89 :               tree mask = make_temp_ssa_name (rgm->type, NULL, "loop_mask");
   10674              :               /* Provide a dummy definition until the real one is available.  */
   10675           89 :               SSA_NAME_DEF_STMT (mask) = gimple_build_nop ();
   10676           89 :               rgm->controls[i] = mask;
   10677              :             }
   10678              :         }
   10679          214 :       if (known_eq (TYPE_VECTOR_SUBPARTS (rgm->type),
   10680              :                     TYPE_VECTOR_SUBPARTS (vectype)))
   10681          166 :         return rgm->controls[index];
   10682              : 
   10683              :       /* Split the vector if needed.  Since we are dealing with integer mode
   10684              :          masks with AVX512 we can operate on the integer representation
   10685              :          performing the whole vector shifting.  */
   10686           48 :       unsigned HOST_WIDE_INT factor;
   10687           48 :       bool ok = constant_multiple_p (TYPE_VECTOR_SUBPARTS (rgm->type),
   10688           48 :                                      TYPE_VECTOR_SUBPARTS (vectype), &factor);
   10689            0 :       gcc_assert (ok);
   10690           48 :       gcc_assert (GET_MODE_CLASS (TYPE_MODE (rgm->type)) == MODE_INT);
   10691           48 :       tree mask_type = truth_type_for (vectype);
   10692           48 :       gcc_assert (GET_MODE_CLASS (TYPE_MODE (mask_type)) == MODE_INT);
   10693           48 :       unsigned vi = index / factor;
   10694           48 :       unsigned vpart = index % factor;
   10695           48 :       tree vec = rgm->controls[vi];
   10696           48 :       gimple_seq seq = NULL;
   10697           48 :       vec = gimple_build (&seq, VIEW_CONVERT_EXPR,
   10698           48 :                           lang_hooks.types.type_for_mode
   10699           48 :                                 (TYPE_MODE (rgm->type), 1), vec);
   10700              :       /* For integer mode masks simply shift the right bits into position.  */
   10701           48 :       if (vpart != 0)
   10702           40 :         vec = gimple_build (&seq, RSHIFT_EXPR, TREE_TYPE (vec), vec,
   10703              :                             build_int_cst (integer_type_node,
   10704           80 :                                            (TYPE_VECTOR_SUBPARTS (vectype)
   10705           40 :                                             * vpart)));
   10706           48 :       vec = gimple_convert (&seq, lang_hooks.types.type_for_mode
   10707           48 :                                     (TYPE_MODE (mask_type), 1), vec);
   10708           48 :       vec = gimple_build (&seq, VIEW_CONVERT_EXPR, mask_type, vec);
   10709           48 :       if (seq)
   10710           48 :         gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
   10711              :       return vec;
   10712              :     }
   10713              :   else
   10714            0 :     gcc_unreachable ();
   10715              : }
   10716              : 
   10717              : /* Record that LOOP_VINFO would need LENS to contain a sequence of NVECTORS
   10718              :    lengths for controlling an operation on VECTYPE.  The operation splits
   10719              :    each element of VECTYPE into FACTOR separate subelements, measuring the
   10720              :    length as a number of these subelements.  */
   10721              : 
   10722              : void
   10723            0 : vect_record_loop_len (loop_vec_info loop_vinfo, vec_loop_lens *lens,
   10724              :                       unsigned int nvectors, tree vectype, unsigned int factor)
   10725              : {
   10726            0 :   gcc_assert (nvectors != 0);
   10727            0 :   if (lens->length () < nvectors)
   10728            0 :     lens->safe_grow_cleared (nvectors, true);
   10729            0 :   rgroup_controls *rgl = &(*lens)[nvectors - 1];
   10730              : 
   10731              :   /* The number of scalars per iteration, scalar occupied bytes and
   10732              :      the number of vectors are both compile-time constants.  */
   10733            0 :   unsigned int nscalars_per_iter
   10734            0 :     = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
   10735            0 :                  LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
   10736              : 
   10737            0 :   if (rgl->max_nscalars_per_iter < nscalars_per_iter)
   10738              :     {
   10739              :       /* For now, we only support cases in which all loads and stores fall back
   10740              :          to VnQI or none do.  */
   10741            0 :       gcc_assert (!rgl->max_nscalars_per_iter
   10742              :                   || (rgl->factor == 1 && factor == 1)
   10743              :                   || (rgl->max_nscalars_per_iter * rgl->factor
   10744              :                       == nscalars_per_iter * factor));
   10745            0 :       rgl->max_nscalars_per_iter = nscalars_per_iter;
   10746            0 :       rgl->type = vectype;
   10747            0 :       rgl->factor = factor;
   10748              :     }
   10749            0 : }
   10750              : 
   10751              : /* Given a complete set of lengths LENS, extract length number INDEX
   10752              :    for an rgroup that operates on NVECTORS vectors of type VECTYPE,
   10753              :    where 0 <= INDEX < NVECTORS.  Return a value that contains FACTOR
   10754              :    multiplied by the number of elements that should be processed.
   10755              :    Insert any set-up statements before GSI.  */
   10756              : 
   10757              : tree
   10758            0 : vect_get_loop_len (loop_vec_info loop_vinfo, gimple_stmt_iterator *gsi,
   10759              :                    vec_loop_lens *lens, unsigned int nvectors, tree vectype,
   10760              :                    unsigned int index, unsigned int factor, bool adjusted)
   10761              : {
   10762            0 :   rgroup_controls *rgl = &(*lens)[nvectors - 1];
   10763            0 :   bool use_bias_adjusted_len =
   10764            0 :     LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo) != 0;
   10765              : 
   10766              :   /* Populate the rgroup's len array, if this is the first time we've
   10767              :      used it.  */
   10768            0 :   if (rgl->controls.is_empty ())
   10769              :     {
   10770            0 :       rgl->controls.safe_grow_cleared (nvectors, true);
   10771            0 :       for (unsigned int i = 0; i < nvectors; ++i)
   10772              :         {
   10773            0 :           tree len_type = LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo);
   10774            0 :           gcc_assert (len_type != NULL_TREE);
   10775              : 
   10776            0 :           tree len = make_temp_ssa_name (len_type, NULL, "loop_len");
   10777              : 
   10778              :           /* Provide a dummy definition until the real one is available.  */
   10779            0 :           SSA_NAME_DEF_STMT (len) = gimple_build_nop ();
   10780            0 :           rgl->controls[i] = len;
   10781              : 
   10782            0 :           if (use_bias_adjusted_len)
   10783              :             {
   10784            0 :               gcc_assert (i == 0);
   10785            0 :               tree adjusted_len =
   10786            0 :                 make_temp_ssa_name (len_type, NULL, "adjusted_loop_len");
   10787            0 :               SSA_NAME_DEF_STMT (adjusted_len) = gimple_build_nop ();
   10788            0 :               rgl->bias_adjusted_ctrl = adjusted_len;
   10789              :             }
   10790              :         }
   10791              :     }
   10792              : 
   10793            0 :   if (use_bias_adjusted_len && adjusted)
   10794            0 :     return rgl->bias_adjusted_ctrl;
   10795              : 
   10796            0 :   tree loop_len = rgl->controls[index];
   10797            0 :   if (rgl->factor == 1 && factor == 1)
   10798              :     {
   10799            0 :       poly_int64 nunits1 = TYPE_VECTOR_SUBPARTS (rgl->type);
   10800            0 :       poly_int64 nunits2 = TYPE_VECTOR_SUBPARTS (vectype);
   10801            0 :       if (maybe_ne (nunits1, nunits2))
   10802              :         {
   10803              :           /* A loop len for data type X can be reused for data type Y
   10804              :              if X has N times more elements than Y and if Y's elements
   10805              :              are N times bigger than X's.  */
   10806            0 :           gcc_assert (multiple_p (nunits1, nunits2));
   10807            0 :           factor = exact_div (nunits1, nunits2).to_constant ();
   10808            0 :           tree iv_type = LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo);
   10809            0 :           gimple_seq seq = NULL;
   10810            0 :           loop_len = gimple_build (&seq, EXACT_DIV_EXPR, iv_type, loop_len,
   10811            0 :                                    build_int_cst (iv_type, factor));
   10812            0 :           if (seq)
   10813            0 :             gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
   10814              :         }
   10815            0 :     }
   10816            0 :   else if (factor && rgl->factor != factor)
   10817              :     {
   10818              :       /* The number of scalars per iteration, scalar occupied bytes and
   10819              :          the number of vectors are both compile-time constants.  */
   10820            0 :       unsigned int nscalars_per_iter
   10821            0 :         = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
   10822            0 :                      LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
   10823            0 :       unsigned int rglvecsize = rgl->factor * rgl->max_nscalars_per_iter;
   10824            0 :       unsigned int vecsize = nscalars_per_iter * factor;
   10825            0 :       if (rglvecsize > vecsize)
   10826              :         {
   10827            0 :           unsigned int fac = rglvecsize / vecsize;
   10828            0 :           tree iv_type = LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo);
   10829            0 :           gimple_seq seq = NULL;
   10830            0 :           loop_len = gimple_build (&seq, EXACT_DIV_EXPR, iv_type, loop_len,
   10831            0 :                                    build_int_cst (iv_type, fac));
   10832            0 :           if (seq)
   10833            0 :             gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
   10834              :         }
   10835            0 :       else if (rglvecsize < vecsize)
   10836              :         {
   10837            0 :           unsigned int fac = vecsize / rglvecsize;
   10838            0 :           tree iv_type = LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo);
   10839            0 :           gimple_seq seq = NULL;
   10840            0 :           loop_len = gimple_build (&seq, MULT_EXPR, iv_type, loop_len,
   10841            0 :                                    build_int_cst (iv_type, fac));
   10842            0 :           if (seq)
   10843            0 :             gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
   10844              :         }
   10845              :     }
   10846              :   return loop_len;
   10847              : }
   10848              : 
   10849              : /* Generate the tree for the loop len mask and return it.  Given the lens,
   10850              :    nvectors, vectype, index and factor to gen the len mask as below.
   10851              : 
   10852              :    tree len_mask = VCOND_MASK_LEN (compare_mask, ones, zero, len, bias)
   10853              : */
   10854              : tree
   10855            0 : vect_gen_loop_len_mask (loop_vec_info loop_vinfo, gimple_stmt_iterator *gsi,
   10856              :                         gimple_stmt_iterator *cond_gsi, vec_loop_lens *lens,
   10857              :                         unsigned int nvectors, tree vectype, tree stmt,
   10858              :                         unsigned int index, unsigned int factor)
   10859              : {
   10860            0 :   tree all_one_mask = build_all_ones_cst (vectype);
   10861            0 :   tree all_zero_mask = build_zero_cst (vectype);
   10862            0 :   tree len = vect_get_loop_len (loop_vinfo, gsi, lens, nvectors, vectype, index,
   10863              :                                 factor, true);
   10864            0 :   tree bias = build_int_cst (intQI_type_node,
   10865            0 :                              LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo));
   10866            0 :   tree len_mask = make_temp_ssa_name (TREE_TYPE (stmt), NULL, "vec_len_mask");
   10867            0 :   gcall *call = gimple_build_call_internal (IFN_VCOND_MASK_LEN, 5, stmt,
   10868              :                                             all_one_mask, all_zero_mask, len,
   10869              :                                             bias);
   10870            0 :   gimple_call_set_lhs (call, len_mask);
   10871            0 :   gsi_insert_before (cond_gsi, call, GSI_SAME_STMT);
   10872              : 
   10873            0 :   return len_mask;
   10874              : }
   10875              : 
   10876              : /* Scale profiling counters by estimation for LOOP which is vectorized
   10877              :    by factor VF.
   10878              :    If FLAT is true, the loop we started with had unrealistically flat
   10879              :    profile.  */
   10880              : 
   10881              : static void
   10882        62300 : scale_profile_for_vect_loop (class loop *loop, edge exit_e, unsigned vf, bool flat)
   10883              : {
   10884              :   /* For flat profiles do not scale down proportionally by VF and only
   10885              :      cap by known iteration count bounds.  */
   10886        62300 :   if (flat)
   10887              :     {
   10888        34966 :       if (dump_file && (dump_flags & TDF_DETAILS))
   10889         5354 :         fprintf (dump_file,
   10890              :                  "Vectorized loop profile seems flat; not scaling iteration "
   10891              :                  "count down by the vectorization factor %i\n", vf);
   10892        34966 :       scale_loop_profile (loop, profile_probability::always (),
   10893              :                           get_likely_max_loop_iterations_int (loop));
   10894        34966 :       return;
   10895              :     }
   10896              :   /* Loop body executes VF fewer times and exit increases VF times.  */
   10897        27334 :   profile_count entry_count = loop_preheader_edge (loop)->count ();
   10898              : 
   10899              :   /* If we have unreliable loop profile avoid dropping entry
   10900              :      count below header count.  This can happen since loops
   10901              :      has unrealistically low trip counts.  */
   10902        27334 :   while (vf > 1
   10903        28402 :          && loop->header->count > entry_count
   10904        57851 :          && loop->header->count < entry_count * vf)
   10905              :     {
   10906         2115 :       if (dump_file && (dump_flags & TDF_DETAILS))
   10907          158 :         fprintf (dump_file,
   10908              :                  "Vectorization factor %i seems too large for profile "
   10909              :                  "previously believed to be consistent; reducing.\n", vf);
   10910         2115 :       vf /= 2;
   10911              :     }
   10912              : 
   10913        27334 :   if (entry_count.nonzero_p ())
   10914        27334 :     set_edge_probability_and_rescale_others
   10915        27334 :             (exit_e,
   10916        27334 :              entry_count.probability_in (loop->header->count / vf));
   10917              :   /* Avoid producing very large exit probability when we do not have
   10918              :      sensible profile.  */
   10919            0 :   else if (exit_e->probability < profile_probability::always () / (vf * 2))
   10920            0 :     set_edge_probability_and_rescale_others (exit_e, exit_e->probability * vf);
   10921        27334 :   loop->latch->count = single_pred_edge (loop->latch)->count ();
   10922              : 
   10923        27334 :   scale_loop_profile (loop, profile_probability::always () / vf,
   10924              :                       get_likely_max_loop_iterations_int (loop));
   10925              : }
   10926              : 
   10927              : /* Update EPILOGUE's loop_vec_info.  EPILOGUE was constructed as a copy of the
   10928              :    original loop that has now been vectorized.
   10929              : 
   10930              :    The inits of the data_references need to be advanced with the number of
   10931              :    iterations of the main loop.  This has been computed in vect_do_peeling and
   10932              :    is stored in parameter ADVANCE.
   10933              : 
   10934              :    Since the loop_vec_info of this EPILOGUE was constructed for the original
   10935              :    loop, its stmt_vec_infos all point to the original statements.  These need
   10936              :    to be updated to point to their corresponding copies.
   10937              : 
   10938              :    The data_reference's connections also need to be updated.  Their
   10939              :    corresponding dr_vec_info need to be reconnected to the EPILOGUE's
   10940              :    stmt_vec_infos, their statements need to point to their corresponding
   10941              :    copy.  */
   10942              : 
   10943              : static void
   10944         6883 : update_epilogue_loop_vinfo (class loop *epilogue, tree advance)
   10945              : {
   10946         6883 :   loop_vec_info epilogue_vinfo = loop_vec_info_for_loop (epilogue);
   10947         6883 :   hash_map<tree,tree> mapping;
   10948         6883 :   gimple *orig_stmt, *new_stmt;
   10949         6883 :   gimple_stmt_iterator epilogue_gsi;
   10950         6883 :   gphi_iterator epilogue_phi_gsi;
   10951         6883 :   stmt_vec_info stmt_vinfo = NULL, related_vinfo;
   10952         6883 :   basic_block *epilogue_bbs = get_loop_body (epilogue);
   10953         6883 :   unsigned i;
   10954              : 
   10955         6883 :   free (LOOP_VINFO_BBS (epilogue_vinfo));
   10956         6883 :   LOOP_VINFO_BBS (epilogue_vinfo) = epilogue_bbs;
   10957         6883 :   LOOP_VINFO_NBBS (epilogue_vinfo) = epilogue->num_nodes;
   10958              : 
   10959              :   /* The EPILOGUE loop is a copy of the original loop so they share the same
   10960              :      gimple UIDs.  In this loop we update the loop_vec_info of the EPILOGUE to
   10961              :      point to the copied statements.  */
   10962        20649 :   for (unsigned i = 0; i < epilogue->num_nodes; ++i)
   10963              :     {
   10964        13766 :       for (epilogue_phi_gsi = gsi_start_phis (epilogue_bbs[i]);
   10965        35494 :            !gsi_end_p (epilogue_phi_gsi); gsi_next (&epilogue_phi_gsi))
   10966              :         {
   10967        21728 :           new_stmt = epilogue_phi_gsi.phi ();
   10968              : 
   10969        21728 :           gcc_assert (gimple_uid (new_stmt) > 0);
   10970        21728 :           stmt_vinfo
   10971        21728 :             = epilogue_vinfo->stmt_vec_infos[gimple_uid (new_stmt) - 1];
   10972              : 
   10973        21728 :           STMT_VINFO_STMT (stmt_vinfo) = new_stmt;
   10974              :         }
   10975              : 
   10976        27532 :       for (epilogue_gsi = gsi_start_bb (epilogue_bbs[i]);
   10977       138530 :            !gsi_end_p (epilogue_gsi); gsi_next (&epilogue_gsi))
   10978              :         {
   10979       124764 :           new_stmt = gsi_stmt (epilogue_gsi);
   10980       124764 :           if (is_gimple_debug (new_stmt))
   10981        20733 :             continue;
   10982              : 
   10983       104031 :           gcc_assert (gimple_uid (new_stmt) > 0);
   10984       104031 :           stmt_vinfo
   10985       104031 :             = epilogue_vinfo->stmt_vec_infos[gimple_uid (new_stmt) - 1];
   10986              : 
   10987       104031 :           STMT_VINFO_STMT (stmt_vinfo) = new_stmt;
   10988              : 
   10989       104031 :           related_vinfo = STMT_VINFO_RELATED_STMT (stmt_vinfo);
   10990       104031 :           if (related_vinfo != NULL && related_vinfo != stmt_vinfo)
   10991              :             {
   10992         2181 :               gimple *stmt = STMT_VINFO_STMT (related_vinfo);
   10993              :               /* Set BB such that the assert in
   10994              :                 'get_initial_defs_for_reduction' is able to determine that
   10995              :                 the BB of the related stmt is inside this loop.  */
   10996         2181 :               gimple_set_bb (stmt,
   10997              :                              gimple_bb (new_stmt));
   10998         2181 :               related_vinfo = STMT_VINFO_RELATED_STMT (related_vinfo);
   10999         2181 :               gcc_assert (related_vinfo == NULL
   11000              :                           || related_vinfo == stmt_vinfo);
   11001              :             }
   11002              :         }
   11003              :     }
   11004              : 
   11005         6883 :   struct data_reference *dr;
   11006         6883 :   vec<data_reference_p> datarefs = LOOP_VINFO_DATAREFS (epilogue_vinfo);
   11007        31199 :   FOR_EACH_VEC_ELT (datarefs, i, dr)
   11008              :     {
   11009        24316 :       orig_stmt = DR_STMT (dr);
   11010        24316 :       gcc_assert (gimple_uid (orig_stmt) > 0);
   11011        24316 :       stmt_vinfo = epilogue_vinfo->stmt_vec_infos[gimple_uid (orig_stmt) - 1];
   11012        24316 :       DR_STMT (dr) = STMT_VINFO_STMT (stmt_vinfo);
   11013              :     }
   11014              : 
   11015              :   /* Advance data_reference's with the number of iterations of the previous
   11016              :      loop and its prologue.  */
   11017         6883 :   vect_update_inits_of_drs (epilogue_vinfo, advance, PLUS_EXPR);
   11018              : 
   11019              :   /* Remember the advancement made.  */
   11020         6883 :   LOOP_VINFO_DRS_ADVANCED_BY (epilogue_vinfo) = advance;
   11021         6883 : }
   11022              : 
   11023              : /*  When vectorizing early break statements instructions that happen before
   11024              :     the early break in the current BB need to be moved to after the early
   11025              :     break.  This function deals with that and assumes that any validity
   11026              :     checks has already been performed.
   11027              : 
   11028              :     While moving the instructions if it encounters a VUSE or VDEF it then
   11029              :     corrects the VUSES as it moves the statements along.  GDEST is the location
   11030              :     in which to insert the new statements.  */
   11031              : 
   11032              : static void
   11033         1469 : move_early_exit_stmts (loop_vec_info loop_vinfo)
   11034              : {
   11035         1469 :   DUMP_VECT_SCOPE ("move_early_exit_stmts");
   11036              : 
   11037         1469 :   if (LOOP_VINFO_EARLY_BRK_STORES (loop_vinfo).is_empty ())
   11038         1209 :     return;
   11039              : 
   11040              :   /* Move all stmts that need moving.  */
   11041          260 :   basic_block dest_bb = LOOP_VINFO_EARLY_BRK_DEST_BB (loop_vinfo);
   11042          260 :   gimple_stmt_iterator dest_gsi = gsi_after_labels (dest_bb);
   11043              : 
   11044          260 :   tree last_seen_vuse = NULL_TREE;
   11045          627 :   for (gimple *stmt : LOOP_VINFO_EARLY_BRK_STORES (loop_vinfo))
   11046              :     {
   11047              :       /* We have to update crossed degenerate virtual PHIs.  Simply
   11048              :          elide them.  */
   11049          367 :       if (gphi *vphi = dyn_cast <gphi *> (stmt))
   11050              :         {
   11051            7 :           tree vdef = gimple_phi_result (vphi);
   11052            7 :           tree vuse = gimple_phi_arg_def (vphi, 0);
   11053            7 :           imm_use_iterator iter;
   11054            7 :           use_operand_p use_p;
   11055            7 :           gimple *use_stmt;
   11056           23 :           FOR_EACH_IMM_USE_STMT (use_stmt, iter, vdef)
   11057              :             {
   11058           32 :               FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
   11059           16 :                 SET_USE (use_p, vuse);
   11060            7 :             }
   11061            7 :           auto gsi = gsi_for_stmt (stmt);
   11062            7 :           remove_phi_node (&gsi, true);
   11063            7 :           last_seen_vuse = vuse;
   11064            7 :           continue;
   11065            7 :         }
   11066              : 
   11067              :       /* Check to see if statement is still required for vect or has been
   11068              :          elided.  */
   11069          360 :       auto stmt_info = loop_vinfo->lookup_stmt (stmt);
   11070          360 :       if (!stmt_info)
   11071            0 :         continue;
   11072              : 
   11073          360 :       if (dump_enabled_p ())
   11074          165 :         dump_printf_loc (MSG_NOTE, vect_location, "moving stmt %G", stmt);
   11075              : 
   11076          360 :       gimple_stmt_iterator stmt_gsi = gsi_for_stmt (stmt);
   11077          360 :       gsi_move_before (&stmt_gsi, &dest_gsi, GSI_NEW_STMT);
   11078          720 :       last_seen_vuse = gimple_vuse (stmt);
   11079              :     }
   11080              : 
   11081              :   /* Update all the stmts with their new reaching VUSES.  */
   11082          815 :   for (auto p : LOOP_VINFO_EARLY_BRK_VUSES (loop_vinfo))
   11083              :     {
   11084          245 :       if (dump_enabled_p ())
   11085          167 :           dump_printf_loc (MSG_NOTE, vect_location,
   11086              :                            "updating vuse to %T for load %G",
   11087              :                            last_seen_vuse, p);
   11088          245 :       gimple_set_vuse (p, last_seen_vuse);
   11089          245 :       update_stmt (p);
   11090              :     }
   11091              : 
   11092              :   /* And update the LC PHIs on exits.  */
   11093         1313 :   for (edge e : get_loop_exit_edges (LOOP_VINFO_LOOP  (loop_vinfo)))
   11094          533 :     if (!dominated_by_p (CDI_DOMINATORS, e->src, dest_bb))
   11095          291 :       if (gphi *phi = get_virtual_phi (e->dest))
   11096          551 :         SET_PHI_ARG_DEF_ON_EDGE (phi, e, last_seen_vuse);
   11097              : }
   11098              : 
   11099              : /* Generate adjustment code for early break scalar IVs filling in the value
   11100              :    we created earlier on for LOOP_VINFO_EARLY_BRK_NITERS_VAR.  */
   11101              : 
   11102              : static void
   11103         1469 : vect_update_ivs_after_vectorizer_for_early_breaks (loop_vec_info loop_vinfo)
   11104              : {
   11105         1469 :   DUMP_VECT_SCOPE ("vect_update_ivs_after_vectorizer_for_early_breaks");
   11106              : 
   11107         1469 :   if (!LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
   11108              :       /* If no peeling was done then we have no IV to update.  */
   11109         1469 :       || !LOOP_VINFO_EARLY_BRK_NITERS_VAR (loop_vinfo))
   11110          590 :     return;
   11111              : 
   11112          879 :   tree phi_var = LOOP_VINFO_EARLY_BRK_NITERS_VAR (loop_vinfo);
   11113          879 :   tree niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
   11114          879 :   tree ty_var = TREE_TYPE (phi_var);
   11115          879 :   auto loop = LOOP_VINFO_LOOP (loop_vinfo);
   11116          879 :   tree induc_var = niters_skip ? copy_ssa_name (phi_var) : phi_var;
   11117              : 
   11118              :   /* Remove the existing dummy GIMPLE statement and just keep the def.  */
   11119          879 :   gimple *def = SSA_NAME_DEF_STMT (phi_var);
   11120          879 :   auto def_gsi = gsi_for_stmt (def);
   11121          879 :   gsi_remove (&def_gsi, true);
   11122              : 
   11123          879 :   auto induction_phi = create_phi_node (induc_var, loop->header);
   11124          879 :   tree induc_def = PHI_RESULT (induction_phi);
   11125              : 
   11126              :   /* Create the iv update inside the loop.  */
   11127          879 :   gimple_seq init_stmts = NULL;
   11128          879 :   gimple_seq stmts = NULL;
   11129          879 :   gimple_seq iv_stmts = NULL;
   11130          879 :   tree tree_iv_incr = LOOP_VINFO_IV_INCREMENT (loop_vinfo);
   11131              : 
   11132          879 :   tree iter_var;
   11133          879 :   if (POINTER_TYPE_P (ty_var))
   11134            0 :     iter_var = gimple_build (&stmts, POINTER_PLUS_EXPR, ty_var, induc_def,
   11135              :                              tree_iv_incr);
   11136              :   else
   11137              :     {
   11138          879 :       tree offset = gimple_convert (&stmts, ty_var, tree_iv_incr);
   11139          879 :       iter_var = gimple_build (&stmts, PLUS_EXPR, ty_var, induc_def, offset);
   11140              :     }
   11141              : 
   11142          879 :   tree init_var = build_zero_cst (ty_var);
   11143          879 :   if (niters_skip)
   11144            0 :     init_var = gimple_build (&init_stmts, MINUS_EXPR, ty_var, init_var,
   11145              :                              gimple_convert (&init_stmts, ty_var, niters_skip));
   11146              : 
   11147          879 :   add_phi_arg (induction_phi, iter_var,
   11148              :                loop_latch_edge (loop), UNKNOWN_LOCATION);
   11149          879 :   add_phi_arg (induction_phi, init_var,
   11150              :                loop_preheader_edge (loop), UNKNOWN_LOCATION);
   11151              : 
   11152              :   /* Find the first insertion point in the BB.  */
   11153          879 :   auto pe = loop_preheader_edge (loop);
   11154              : 
   11155              :   /* If we've done any peeling, calculate the peeling adjustment needed to the
   11156              :      final IV.  */
   11157          879 :   if (niters_skip)
   11158              :     {
   11159            0 :       tree induc_type = TREE_TYPE (induc_def);
   11160            0 :       tree s_induc_type = signed_type_for (induc_type);
   11161            0 :       induc_def = gimple_build (&iv_stmts, MAX_EXPR, s_induc_type,
   11162              :                                 gimple_convert (&iv_stmts, s_induc_type,
   11163              :                                                 induc_def),
   11164              :                                 build_zero_cst (s_induc_type));
   11165            0 :       auto stmt = gimple_build_assign (phi_var,
   11166              :                                        gimple_convert (&iv_stmts, induc_type,
   11167              :                                                        induc_def));
   11168            0 :       gimple_seq_add_stmt_without_update (&iv_stmts, stmt);
   11169            0 :       basic_block exit_bb = NULL;
   11170              :       /* Identify the early exit merge block.  I wish we had stored this.  */
   11171            0 :       for (auto e : get_loop_exit_edges (loop))
   11172            0 :         if (e != LOOP_VINFO_MAIN_EXIT (loop_vinfo))
   11173              :           {
   11174            0 :             exit_bb = e->dest;
   11175            0 :             break;
   11176            0 :           }
   11177              : 
   11178            0 :       gcc_assert (exit_bb);
   11179            0 :       auto exit_gsi = gsi_after_labels (exit_bb);
   11180            0 :       gsi_insert_seq_before (&exit_gsi, iv_stmts, GSI_SAME_STMT);
   11181              :     }
   11182              :   /* Write the init_stmts in the loop-preheader block.  */
   11183          879 :   auto psi = gsi_last_nondebug_bb (pe->src);
   11184          879 :   gsi_insert_seq_after (&psi, init_stmts, GSI_LAST_NEW_STMT);
   11185              : 
   11186              :   /* Write the adjustments at the end of the iv increment.  */
   11187          879 :   bool insert_after;
   11188          879 :   gimple_stmt_iterator incr_gsi;
   11189          879 :   vect_iv_increment_position (LOOP_VINFO_MAIN_EXIT (loop_vinfo), &incr_gsi,
   11190              :                               &insert_after);
   11191              : 
   11192          879 :   if (insert_after)
   11193            0 :     gsi_insert_seq_after (&incr_gsi, stmts, GSI_NEW_STMT);
   11194              :   else
   11195          879 :     gsi_insert_seq_before (&incr_gsi, stmts, GSI_NEW_STMT);
   11196              : }
   11197              : 
   11198              : /* Function vect_transform_loop.
   11199              : 
   11200              :    The analysis phase has determined that the loop is vectorizable.
   11201              :    Vectorize the loop - created vectorized stmts to replace the scalar
   11202              :    stmts in the loop, and update the loop exit condition.
   11203              :    Returns scalar epilogue loop if any.  */
   11204              : 
   11205              : class loop *
   11206        62300 : vect_transform_loop (loop_vec_info loop_vinfo, gimple *loop_vectorized_call)
   11207              : {
   11208        62300 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
   11209        62300 :   class loop *epilogue = NULL;
   11210        62300 :   basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
   11211        62300 :   int nbbs = loop->num_nodes;
   11212        62300 :   int i;
   11213        62300 :   tree niters_vector = NULL_TREE;
   11214        62300 :   tree step_vector = NULL_TREE;
   11215        62300 :   tree niters_vector_mult_vf = NULL_TREE;
   11216        62300 :   poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
   11217        62300 :   unsigned int lowest_vf = constant_lower_bound (vf);
   11218        62300 :   gimple *stmt;
   11219        62300 :   bool check_profitability = false;
   11220        62300 :   unsigned int th;
   11221        62300 :   bool flat = maybe_flat_loop_profile (loop);
   11222        62300 :   bool uncounted_p = LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo);
   11223              : 
   11224        62300 :   DUMP_VECT_SCOPE ("vec_transform_loop");
   11225              : 
   11226        62300 :   if (! LOOP_VINFO_EPILOGUE_P (loop_vinfo))
   11227        55417 :     loop_vinfo->shared->check_datarefs ();
   11228              : 
   11229              :   /* Use the more conservative vectorization threshold.  If the number
   11230              :      of iterations is constant assume the cost check has been performed
   11231              :      by our caller.  If the threshold makes all loops profitable that
   11232              :      run at least the (estimated) vectorization factor number of times
   11233              :      checking is pointless, too.  */
   11234        62300 :   th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
   11235        62300 :   if (vect_apply_runtime_profitability_check_p (loop_vinfo))
   11236              :     {
   11237        18914 :       if (dump_enabled_p ())
   11238          178 :         dump_printf_loc (MSG_NOTE, vect_location,
   11239              :                          "Profitability threshold is %d loop iterations.\n",
   11240              :                          th);
   11241              :       check_profitability = true;
   11242              :     }
   11243              : 
   11244              :   /* Make sure there exists a single-predecessor exit bb.  Do this before
   11245              :      versioning.   */
   11246        62300 :   edge e = LOOP_VINFO_MAIN_EXIT (loop_vinfo);
   11247        62300 :   if (! single_pred_p (e->dest) && !LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
   11248              :     {
   11249        18640 :       split_loop_exit_edge (e, true);
   11250        18640 :       if (dump_enabled_p ())
   11251         2320 :         dump_printf (MSG_NOTE, "split exit edge\n");
   11252              :     }
   11253              : 
   11254              :   /* Version the loop first, if required, so the profitability check
   11255              :      comes first.  */
   11256              : 
   11257        62300 :   if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
   11258              :     {
   11259         3790 :       class loop *sloop
   11260         3790 :         = vect_loop_versioning (loop_vinfo, loop_vectorized_call);
   11261         3790 :       sloop->force_vectorize = false;
   11262         3790 :       check_profitability = false;
   11263              :     }
   11264              : 
   11265              :   /* Make sure there exists a single-predecessor exit bb also on the
   11266              :      scalar loop copy.  Do this after versioning but before peeling
   11267              :      so CFG structure is fine for both scalar and if-converted loop
   11268              :      to make slpeel_duplicate_current_defs_from_edges face matched
   11269              :      loop closed PHI nodes on the exit.  */
   11270        62300 :   if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))
   11271              :     {
   11272         6939 :       e = LOOP_VINFO_SCALAR_MAIN_EXIT (loop_vinfo);
   11273         6939 :       if (! single_pred_p (e->dest))
   11274              :         {
   11275         6665 :           split_loop_exit_edge (e, true);
   11276         6665 :           if (dump_enabled_p ())
   11277         1170 :             dump_printf (MSG_NOTE, "split exit edge of scalar loop\n");
   11278              :         }
   11279              :     }
   11280              : 
   11281        62300 :   tree niters = vect_build_loop_niters (loop_vinfo);
   11282        62300 :   LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = niters;
   11283        62300 :   tree nitersm1 = unshare_expr (LOOP_VINFO_NITERSM1 (loop_vinfo));
   11284        62300 :   tree advance;
   11285        62300 :   drs_init_vec orig_drs_init;
   11286        62300 :   bool niters_no_overflow = uncounted_p ? false /* Not known.  */
   11287        62257 :                                         : loop_niters_no_overflow (loop_vinfo);
   11288              : 
   11289        62300 :   epilogue = vect_do_peeling (loop_vinfo, niters, nitersm1, &niters_vector,
   11290              :                               &step_vector, &niters_vector_mult_vf, th,
   11291              :                               check_profitability, niters_no_overflow,
   11292              :                               &advance);
   11293              : 
   11294        62300 :   LOOP_VINFO_IV_INCREMENT (loop_vinfo)
   11295        62300 :     = vect_get_loop_iv_increment (loop_vinfo);
   11296              : 
   11297              :   /* Assign hierarchical discriminators to the vectorized loop.  */
   11298        62300 :   poly_uint64 vf_val = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
   11299        62300 :   unsigned int vf_int = constant_lower_bound (vf_val);
   11300        62300 :   if (vf_int > DISCR_MULTIPLICITY_MAX)
   11301              :     vf_int = DISCR_MULTIPLICITY_MAX;
   11302              : 
   11303              :   /* Assign unique copy_id dynamically instead of using hardcoded constants.
   11304              :      Epilogue and main vectorized loops get different copy_ids.  */
   11305        62300 :   gimple *loop_last = last_nondebug_stmt (loop->header);
   11306        62300 :   location_t loop_loc
   11307        62300 :     = loop_last ? gimple_location (loop_last) : UNKNOWN_LOCATION;
   11308        62020 :   if (loop_loc != UNKNOWN_LOCATION)
   11309              :     {
   11310        51376 :       unsigned int copyid = allocate_copyid_base (loop_loc, 1);
   11311        51376 :       assign_discriminators_to_loop (loop, vf_int, copyid);
   11312              :     }
   11313        62300 :   if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo)
   11314        62300 :       && LOOP_VINFO_SCALAR_LOOP_SCALING (loop_vinfo).initialized_p ())
   11315              :     {
   11316              :       /* Ifcvt duplicates loop preheader, loop body and produces an basic
   11317              :          block after loop exit.  We need to scale all that.  */
   11318           90 :       basic_block preheader
   11319           90 :         = loop_preheader_edge (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))->src;
   11320           90 :       preheader->count
   11321              :         = preheader->count.apply_probability
   11322           90 :               (LOOP_VINFO_SCALAR_LOOP_SCALING (loop_vinfo));
   11323           90 :       scale_loop_frequencies (LOOP_VINFO_SCALAR_LOOP (loop_vinfo),
   11324              :                               LOOP_VINFO_SCALAR_LOOP_SCALING (loop_vinfo));
   11325           90 :       LOOP_VINFO_SCALAR_MAIN_EXIT (loop_vinfo)->dest->count = preheader->count;
   11326              :     }
   11327              : 
   11328        62300 :   if (niters_vector == NULL_TREE && !uncounted_p)
   11329              :     {
   11330        28318 :       if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
   11331        28318 :           && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
   11332        57440 :           && known_eq (lowest_vf, vf))
   11333              :         {
   11334        28313 :           niters_vector
   11335        28313 :             = build_int_cst (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)),
   11336        28313 :                              LOOP_VINFO_INT_NITERS (loop_vinfo) / lowest_vf);
   11337        28313 :           step_vector = build_one_cst (TREE_TYPE (niters));
   11338              :         }
   11339          814 :       else if (vect_use_loop_mask_for_alignment_p (loop_vinfo))
   11340            2 :         vect_gen_vector_loop_niters (loop_vinfo, niters, &niters_vector,
   11341              :                                      &step_vector, niters_no_overflow);
   11342              :       else
   11343              :         /* vect_do_peeling subtracted the number of peeled prologue
   11344              :            iterations from LOOP_VINFO_NITERS.  */
   11345          812 :         vect_gen_vector_loop_niters (loop_vinfo, LOOP_VINFO_NITERS (loop_vinfo),
   11346              :                                      &niters_vector, &step_vector,
   11347              :                                      niters_no_overflow);
   11348              :     }
   11349              : 
   11350              :   /* 1) Make sure the loop header has exactly two entries
   11351              :      2) Make sure we have a preheader basic block.  */
   11352              : 
   11353        62300 :   gcc_assert (EDGE_COUNT (loop->header->preds) == 2);
   11354              : 
   11355        62300 :   split_edge (loop_preheader_edge (loop));
   11356              : 
   11357        62300 :   if (vect_use_loop_mask_for_alignment_p (loop_vinfo))
   11358              :     /* This will deal with any possible peeling.  */
   11359            2 :     vect_prepare_for_masked_peels (loop_vinfo);
   11360              : 
   11361              :   /* Handle any code motion that we need to for early-break vectorization after
   11362              :      we've done peeling but just before we start vectorizing.  */
   11363        62300 :   if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
   11364              :     {
   11365         1469 :       vect_update_ivs_after_vectorizer_for_early_breaks (loop_vinfo);
   11366         1469 :       move_early_exit_stmts (loop_vinfo);
   11367              :     }
   11368              : 
   11369              :   /* Remove existing clobber stmts and prefetches.  */
   11370       190240 :   for (i = 0; i < nbbs; i++)
   11371              :     {
   11372       127940 :       basic_block bb = bbs[i];
   11373      1109735 :       for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);)
   11374              :         {
   11375       853855 :           stmt = gsi_stmt (si);
   11376       853855 :           if (gimple_clobber_p (stmt)
   11377       853855 :               || gimple_call_builtin_p (stmt, BUILT_IN_PREFETCH))
   11378              :             {
   11379           95 :               unlink_stmt_vdef (stmt);
   11380           95 :               gsi_remove (&si, true);
   11381           95 :               release_defs (stmt);
   11382              :             }
   11383              :           else
   11384       853760 :             gsi_next (&si);
   11385              :         }
   11386              :     }
   11387              : 
   11388              :   /* Schedule the SLP instances.  */
   11389        62300 :   if (!loop_vinfo->slp_instances.is_empty ())
   11390              :     {
   11391        62300 :       DUMP_VECT_SCOPE ("scheduling SLP instances");
   11392        62300 :       vect_schedule_slp (loop_vinfo, LOOP_VINFO_SLP_INSTANCES (loop_vinfo),
   11393              :                          false);
   11394              :     }
   11395              : 
   11396              :   /* Generate the loop invariant statements.  */
   11397        62300 :   if (!gimple_seq_empty_p (LOOP_VINFO_INV_PATTERN_DEF_SEQ (loop_vinfo)))
   11398              :     {
   11399           70 :       if (dump_enabled_p ())
   11400           26 :         dump_printf_loc (MSG_NOTE, vect_location,
   11401              :                          "------>generating loop invariant statements\n");
   11402           70 :       gimple_stmt_iterator gsi;
   11403           70 :       gsi = gsi_after_labels (loop_preheader_edge (loop)->src);
   11404           70 :       gsi_insert_seq_before (&gsi, LOOP_VINFO_INV_PATTERN_DEF_SEQ (loop_vinfo),
   11405              :                              GSI_CONTINUE_LINKING);
   11406              :     }
   11407              : 
   11408              :   /* Stub out scalar statements that must not survive vectorization and
   11409              :      were not picked as relevant in any SLP instance.
   11410              :      Doing this here helps with grouped statements, or statements that
   11411              :      are involved in patterns.  */
   11412       190240 :   for (i = 0; i < nbbs; i++)
   11413              :     {
   11414       127940 :       basic_block bb = bbs[i];
   11415       127940 :       stmt_vec_info stmt_info;
   11416       255880 :       for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
   11417      1696136 :            !gsi_end_p (gsi); gsi_next (&gsi))
   11418              :         {
   11419      1568196 :           gcall *call = dyn_cast <gcall *> (gsi_stmt (gsi));
   11420         6348 :           if (!call || !gimple_call_internal_p (call))
   11421      1563000 :             continue;
   11422         5196 :           internal_fn ifn = gimple_call_internal_fn (call);
   11423         5196 :           if (ifn == IFN_MASK_LOAD)
   11424              :             {
   11425          682 :               tree lhs = gimple_get_lhs (call);
   11426          682 :               if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
   11427              :                 {
   11428            0 :                   tree zero = build_zero_cst (TREE_TYPE (lhs));
   11429            0 :                   gimple *new_stmt = gimple_build_assign (lhs, zero);
   11430            0 :                   gsi_replace (&gsi, new_stmt, true);
   11431              :                 }
   11432              :             }
   11433         4514 :           else if (conditional_internal_fn_code (ifn) != ERROR_MARK)
   11434              :             {
   11435         2297 :               tree lhs = gimple_get_lhs (call);
   11436         2297 :               if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
   11437              :                 {
   11438            0 :                   tree else_arg
   11439            0 :                     = gimple_call_arg (call, gimple_call_num_args (call) - 1);
   11440            0 :                   gimple *new_stmt = gimple_build_assign (lhs, else_arg);
   11441            0 :                   gsi_replace (&gsi, new_stmt, true);
   11442              :                 }
   11443              :             }
   11444         2217 :           else if (ifn == IFN_MASK_CALL
   11445            4 :                    && (stmt_info = loop_vinfo->lookup_stmt (call))
   11446            4 :                    && !STMT_VINFO_RELEVANT_P (stmt_info)
   11447         2221 :                    && !STMT_VINFO_LIVE_P (stmt_info))
   11448              :             {
   11449            4 :               gcc_assert (!gimple_call_lhs (stmt_info->stmt));
   11450            4 :               loop_vinfo->remove_stmt (stmt_info);
   11451              :             }
   11452              :         }
   11453              :     }
   11454              : 
   11455        62300 :   if (!uncounted_p)
   11456              :     {
   11457              :       /* The vectorization factor is always > 1, so if we use an IV increment of
   11458              :          1.  A zero NITERS becomes a nonzero NITERS_VECTOR.  */
   11459        62257 :       if (integer_onep (step_vector))
   11460        62236 :         niters_no_overflow = true;
   11461              : 
   11462        62257 :       vect_set_loop_condition (loop, LOOP_VINFO_MAIN_EXIT (loop_vinfo),
   11463              :                                loop_vinfo, niters_vector, step_vector,
   11464              :                                niters_vector_mult_vf, !niters_no_overflow);
   11465              :     }
   11466              : 
   11467        62300 :   unsigned int assumed_vf = vect_vf_for_cost (loop_vinfo);
   11468              : 
   11469              :   /* True if the final iteration might not handle a full vector's
   11470              :      worth of scalar iterations.  */
   11471       124600 :   bool final_iter_may_be_partial
   11472        62300 :     = LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
   11473        62300 :       || LOOP_VINFO_EARLY_BREAKS (loop_vinfo);
   11474              : 
   11475              :   /* +1 to convert latch counts to loop iteration counts.  */
   11476        62300 :   int bias_for_lowest = 1;
   11477              : 
   11478              :   /* When we are peeling for gaps then we take away one scalar iteration
   11479              :      from the vector loop.  Thus we can adjust the upper bound by one
   11480              :      scalar iteration.  But only when we know the bound applies to the
   11481              :      IV exit test which might not be true when we have multiple exits.  */
   11482        62300 :   if (!LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
   11483       121256 :     bias_for_lowest -= LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) ? 1 : 0;
   11484              : 
   11485        62300 :   int bias_for_assumed = bias_for_lowest;
   11486        62300 :   int alignment_npeels = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
   11487        62300 :   if (alignment_npeels && LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
   11488              :     {
   11489              :       /* When the amount of peeling is known at compile time, the first
   11490              :          iteration will have exactly alignment_npeels active elements.
   11491              :          In the worst case it will have at least one.  */
   11492            2 :       int min_first_active = (alignment_npeels > 0 ? alignment_npeels : 1);
   11493            2 :       bias_for_lowest += lowest_vf - min_first_active;
   11494            2 :       bias_for_assumed += assumed_vf - min_first_active;
   11495              :     }
   11496              :   /* In these calculations the "- 1" converts loop iteration counts
   11497              :      back to latch counts.  */
   11498        62300 :   if (loop->any_upper_bound)
   11499              :     {
   11500        62284 :       loop_vec_info main_vinfo = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
   11501        62284 :       loop->nb_iterations_upper_bound
   11502        62284 :         = (final_iter_may_be_partial
   11503        63756 :            ? wi::udiv_ceil (loop->nb_iterations_upper_bound + bias_for_lowest,
   11504         2944 :                             lowest_vf) - 1
   11505        60812 :            : wi::udiv_floor (loop->nb_iterations_upper_bound + bias_for_lowest,
   11506       121624 :                              lowest_vf) - 1);
   11507        62284 :       if (main_vinfo
   11508              :           /* Both peeling for alignment and peeling for gaps can end up
   11509              :              with the scalar epilogue running for more than VF-1 iterations.  */
   11510         6883 :           && !main_vinfo->peeling_for_alignment
   11511         6835 :           && !main_vinfo->peeling_for_gaps)
   11512              :         {
   11513         6653 :           unsigned int bound;
   11514         6653 :           poly_uint64 main_iters
   11515         6653 :             = upper_bound (LOOP_VINFO_VECT_FACTOR (main_vinfo),
   11516              :                            LOOP_VINFO_COST_MODEL_THRESHOLD (main_vinfo));
   11517         6653 :           main_iters
   11518         6653 :             = upper_bound (main_iters,
   11519         6653 :                            LOOP_VINFO_VERSIONING_THRESHOLD (main_vinfo));
   11520         6653 :           if (can_div_away_from_zero_p (main_iters,
   11521         6653 :                                         LOOP_VINFO_VECT_FACTOR (loop_vinfo),
   11522              :                                         &bound))
   11523         6653 :             loop->nb_iterations_upper_bound
   11524         6653 :               = wi::umin ((bound_wide_int) (bound - 1),
   11525         6653 :                           loop->nb_iterations_upper_bound);
   11526              :       }
   11527              :   }
   11528        62300 :   if (loop->any_likely_upper_bound)
   11529        62284 :     loop->nb_iterations_likely_upper_bound
   11530        62284 :       = (final_iter_may_be_partial
   11531        63756 :          ? wi::udiv_ceil (loop->nb_iterations_likely_upper_bound
   11532         1472 :                           + bias_for_lowest, lowest_vf) - 1
   11533        60812 :          : wi::udiv_floor (loop->nb_iterations_likely_upper_bound
   11534        62284 :                            + bias_for_lowest, lowest_vf) - 1);
   11535        62300 :   if (loop->any_estimate)
   11536        35860 :     loop->nb_iterations_estimate
   11537        35860 :       = (final_iter_may_be_partial
   11538        36557 :          ? wi::udiv_ceil (loop->nb_iterations_estimate + bias_for_assumed,
   11539         1394 :                           assumed_vf) - 1
   11540        35163 :          : wi::udiv_floor (loop->nb_iterations_estimate + bias_for_assumed,
   11541        71023 :                            assumed_vf) - 1);
   11542        62300 :   scale_profile_for_vect_loop (loop, LOOP_VINFO_MAIN_EXIT (loop_vinfo),
   11543              :                                assumed_vf, flat);
   11544              : 
   11545        62300 :   if (dump_enabled_p ())
   11546              :     {
   11547        11127 :       if (!LOOP_VINFO_EPILOGUE_P (loop_vinfo))
   11548              :         {
   11549         9652 :           dump_printf_loc (MSG_NOTE, vect_location,
   11550              :                            "LOOP VECTORIZED\n");
   11551         9652 :           if (loop->inner)
   11552          345 :             dump_printf_loc (MSG_NOTE, vect_location,
   11553              :                              "OUTER LOOP VECTORIZED\n");
   11554         9652 :           dump_printf (MSG_NOTE, "\n");
   11555              :         }
   11556              :       else
   11557         1475 :         dump_printf_loc (MSG_NOTE, vect_location,
   11558              :                          "LOOP EPILOGUE VECTORIZED (MODE=%s)\n",
   11559         1475 :                          GET_MODE_NAME (loop_vinfo->vector_mode));
   11560              :     }
   11561              : 
   11562              :   /* Loops vectorized with a variable factor won't benefit from
   11563              :      unrolling/peeling.  */
   11564        62300 :   if (!vf.is_constant ())
   11565              :     {
   11566              :       loop->unroll = 1;
   11567              :       if (dump_enabled_p ())
   11568              :         dump_printf_loc (MSG_NOTE, vect_location, "Disabling unrolling due to"
   11569              :                          " variable-length vectorization factor\n");
   11570              :     }
   11571              : 
   11572              :   /* When we have unrolled the loop due to a user requested value we should
   11573              :      leave it up to the RTL unroll heuristics to determine if it's still worth
   11574              :      while to unroll more.  */
   11575        62300 :   if (LOOP_VINFO_USER_UNROLL (loop_vinfo))
   11576           44 :     loop->unroll = 0;
   11577              : 
   11578              :   /* Free SLP instances here because otherwise stmt reference counting
   11579              :      won't work.  */
   11580        62300 :   slp_instance instance;
   11581       152985 :   FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
   11582        90685 :     vect_free_slp_instance (instance);
   11583        62300 :   LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
   11584              :   /* Clear-up safelen field since its value is invalid after vectorization
   11585              :      since vectorized loop can have loop-carried dependencies.  */
   11586        62300 :   loop->safelen = 0;
   11587              : 
   11588        62300 :   if (epilogue)
   11589              :     {
   11590              :       /* Accumulate past advancements made.  */
   11591         6883 :       if (LOOP_VINFO_DRS_ADVANCED_BY (loop_vinfo))
   11592           75 :         advance = fold_build2 (PLUS_EXPR, TREE_TYPE (advance),
   11593              :                                LOOP_VINFO_DRS_ADVANCED_BY (loop_vinfo),
   11594              :                                advance);
   11595         6883 :       update_epilogue_loop_vinfo (epilogue, advance);
   11596              : 
   11597         6883 :       epilogue->simduid = loop->simduid;
   11598         6883 :       epilogue->force_vectorize = loop->force_vectorize;
   11599         6883 :       epilogue->dont_vectorize = false;
   11600              :     }
   11601              : 
   11602        62300 :   return epilogue;
   11603        62300 : }
   11604              : 
   11605              : /* The code below is trying to perform simple optimization - revert
   11606              :    if-conversion for masked stores, i.e. if the mask of a store is zero
   11607              :    do not perform it and all stored value producers also if possible.
   11608              :    For example,
   11609              :      for (i=0; i<n; i++)
   11610              :        if (c[i])
   11611              :         {
   11612              :           p1[i] += 1;
   11613              :           p2[i] = p3[i] +2;
   11614              :         }
   11615              :    this transformation will produce the following semi-hammock:
   11616              : 
   11617              :    if (!mask__ifc__42.18_165 == { 0, 0, 0, 0, 0, 0, 0, 0 })
   11618              :      {
   11619              :        vect__11.19_170 = MASK_LOAD (vectp_p1.20_168, 0B, mask__ifc__42.18_165);
   11620              :        vect__12.22_172 = vect__11.19_170 + vect_cst__171;
   11621              :        MASK_STORE (vectp_p1.23_175, 0B, mask__ifc__42.18_165, vect__12.22_172);
   11622              :        vect__18.25_182 = MASK_LOAD (vectp_p3.26_180, 0B, mask__ifc__42.18_165);
   11623              :        vect__19.28_184 = vect__18.25_182 + vect_cst__183;
   11624              :        MASK_STORE (vectp_p2.29_187, 0B, mask__ifc__42.18_165, vect__19.28_184);
   11625              :      }
   11626              : */
   11627              : 
   11628              : void
   11629          486 : optimize_mask_stores (class loop *loop)
   11630              : {
   11631          486 :   basic_block *bbs = get_loop_body (loop);
   11632          486 :   unsigned nbbs = loop->num_nodes;
   11633          486 :   unsigned i;
   11634          486 :   basic_block bb;
   11635          486 :   class loop *bb_loop;
   11636          486 :   gimple_stmt_iterator gsi;
   11637          486 :   gimple *stmt;
   11638          486 :   auto_vec<gimple *> worklist;
   11639          486 :   auto_purge_vect_location sentinel;
   11640              : 
   11641          486 :   vect_location = find_loop_location (loop);
   11642              :   /* Pick up all masked stores in loop if any.  */
   11643         1944 :   for (i = 0; i < nbbs; i++)
   11644              :     {
   11645          972 :       bb = bbs[i];
   11646        16527 :       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
   11647        14583 :            gsi_next (&gsi))
   11648              :         {
   11649        14583 :           stmt = gsi_stmt (gsi);
   11650        14583 :           if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
   11651          658 :             worklist.safe_push (stmt);
   11652              :         }
   11653              :     }
   11654              : 
   11655          486 :   free (bbs);
   11656          486 :   if (worklist.is_empty ())
   11657           68 :     return;
   11658              : 
   11659              :   /* Loop has masked stores.  */
   11660         1059 :   while (!worklist.is_empty ())
   11661              :     {
   11662          641 :       gimple *last, *last_store;
   11663          641 :       edge e, efalse;
   11664          641 :       tree mask;
   11665          641 :       basic_block store_bb, join_bb;
   11666          641 :       gimple_stmt_iterator gsi_to;
   11667          641 :       tree vdef, new_vdef;
   11668          641 :       gphi *phi;
   11669          641 :       tree vectype;
   11670          641 :       tree zero;
   11671              : 
   11672          641 :       last = worklist.pop ();
   11673          641 :       mask = gimple_call_arg (last, 2);
   11674          641 :       bb = gimple_bb (last);
   11675              :       /* Create then_bb and if-then structure in CFG, then_bb belongs to
   11676              :          the same loop as if_bb.  It could be different to LOOP when two
   11677              :          level loop-nest is vectorized and mask_store belongs to the inner
   11678              :          one.  */
   11679          641 :       e = split_block (bb, last);
   11680          641 :       bb_loop = bb->loop_father;
   11681          641 :       gcc_assert (loop == bb_loop || flow_loop_nested_p (loop, bb_loop));
   11682          641 :       join_bb = e->dest;
   11683          641 :       store_bb = create_empty_bb (bb);
   11684          641 :       add_bb_to_loop (store_bb, bb_loop);
   11685          641 :       e->flags = EDGE_TRUE_VALUE;
   11686          641 :       efalse = make_edge (bb, store_bb, EDGE_FALSE_VALUE);
   11687              :       /* Put STORE_BB to likely part.  */
   11688          641 :       efalse->probability = profile_probability::likely ();
   11689          641 :       e->probability = efalse->probability.invert ();
   11690          641 :       store_bb->count = efalse->count ();
   11691          641 :       make_single_succ_edge (store_bb, join_bb, EDGE_FALLTHRU);
   11692          641 :       if (dom_info_available_p (CDI_DOMINATORS))
   11693          641 :         set_immediate_dominator (CDI_DOMINATORS, store_bb, bb);
   11694          641 :       if (dump_enabled_p ())
   11695          326 :         dump_printf_loc (MSG_NOTE, vect_location,
   11696              :                          "Create new block %d to sink mask stores.",
   11697              :                          store_bb->index);
   11698              :       /* Create vector comparison with boolean result.  */
   11699          641 :       vectype = TREE_TYPE (mask);
   11700          641 :       zero = build_zero_cst (vectype);
   11701          641 :       stmt = gimple_build_cond (EQ_EXPR, mask, zero, NULL_TREE, NULL_TREE);
   11702          641 :       gsi = gsi_last_bb (bb);
   11703          641 :       gsi_insert_after (&gsi, stmt, GSI_SAME_STMT);
   11704              :       /* Create new PHI node for vdef of the last masked store:
   11705              :          .MEM_2 = VDEF <.MEM_1>
   11706              :          will be converted to
   11707              :          .MEM.3 = VDEF <.MEM_1>
   11708              :          and new PHI node will be created in join bb
   11709              :          .MEM_2 = PHI <.MEM_1, .MEM_3>
   11710              :       */
   11711          641 :       vdef = gimple_vdef (last);
   11712          641 :       new_vdef = make_ssa_name (gimple_vop (cfun), last);
   11713          641 :       gimple_set_vdef (last, new_vdef);
   11714          641 :       phi = create_phi_node (vdef, join_bb);
   11715          641 :       add_phi_arg (phi, new_vdef, EDGE_SUCC (store_bb, 0), UNKNOWN_LOCATION);
   11716              : 
   11717              :       /* Put all masked stores with the same mask to STORE_BB if possible.  */
   11718          675 :       while (true)
   11719              :         {
   11720          658 :           gimple_stmt_iterator gsi_from;
   11721          658 :           gimple *stmt1 = NULL;
   11722              : 
   11723              :           /* Move masked store to STORE_BB.  */
   11724          658 :           last_store = last;
   11725          658 :           gsi = gsi_for_stmt (last);
   11726          658 :           gsi_from = gsi;
   11727              :           /* Shift GSI to the previous stmt for further traversal.  */
   11728          658 :           gsi_prev (&gsi);
   11729          658 :           gsi_to = gsi_start_bb (store_bb);
   11730          658 :           gsi_move_before (&gsi_from, &gsi_to);
   11731              :           /* Setup GSI_TO to the non-empty block start.  */
   11732          658 :           gsi_to = gsi_start_bb (store_bb);
   11733          658 :           if (dump_enabled_p ())
   11734          342 :             dump_printf_loc (MSG_NOTE, vect_location,
   11735              :                              "Move stmt to created bb\n%G", last);
   11736              :           /* Move all stored value producers if possible.  */
   11737         4929 :           while (!gsi_end_p (gsi))
   11738              :             {
   11739         4928 :               tree lhs;
   11740         4928 :               imm_use_iterator imm_iter;
   11741         4928 :               use_operand_p use_p;
   11742         4928 :               bool res;
   11743              : 
   11744              :               /* Skip debug statements.  */
   11745         4928 :               if (is_gimple_debug (gsi_stmt (gsi)))
   11746              :                 {
   11747            1 :                   gsi_prev (&gsi);
   11748         3088 :                   continue;
   11749              :                 }
   11750         4927 :               stmt1 = gsi_stmt (gsi);
   11751              :               /* Do not consider statements writing to memory or having
   11752              :                  volatile operand.  */
   11753         9679 :               if (gimple_vdef (stmt1)
   11754         9679 :                   || gimple_has_volatile_ops (stmt1))
   11755              :                 break;
   11756         4752 :               gsi_from = gsi;
   11757         4752 :               gsi_prev (&gsi);
   11758         4752 :               lhs = gimple_get_lhs (stmt1);
   11759         4752 :               if (!lhs)
   11760              :                 break;
   11761              : 
   11762              :               /* LHS of vectorized stmt must be SSA_NAME.  */
   11763         4752 :               if (TREE_CODE (lhs) != SSA_NAME)
   11764              :                 break;
   11765              : 
   11766         4752 :               if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
   11767              :                 {
   11768              :                   /* Remove dead scalar statement.  */
   11769         3403 :                   if (has_zero_uses (lhs))
   11770              :                     {
   11771         3087 :                       gsi_remove (&gsi_from, true);
   11772         3087 :                       release_defs (stmt1);
   11773         3087 :                       continue;
   11774              :                     }
   11775              :                 }
   11776              : 
   11777              :               /* Check that LHS does not have uses outside of STORE_BB.  */
   11778         1665 :               res = true;
   11779         2872 :               FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
   11780              :                 {
   11781         1689 :                   gimple *use_stmt;
   11782         1689 :                   use_stmt = USE_STMT (use_p);
   11783         1689 :                   if (is_gimple_debug (use_stmt))
   11784            0 :                     continue;
   11785         1689 :                   if (gimple_bb (use_stmt) != store_bb)
   11786              :                     {
   11787              :                       res = false;
   11788              :                       break;
   11789              :                     }
   11790         1665 :                 }
   11791         1665 :               if (!res)
   11792              :                 break;
   11793              : 
   11794         1183 :               if (gimple_vuse (stmt1)
   11795         1645 :                   && gimple_vuse (stmt1) != gimple_vuse (last_store))
   11796              :                 break;
   11797              : 
   11798              :               /* Can move STMT1 to STORE_BB.  */
   11799         1183 :               if (dump_enabled_p ())
   11800          618 :                 dump_printf_loc (MSG_NOTE, vect_location,
   11801              :                                  "Move stmt to created bb\n%G", stmt1);
   11802         1183 :               gsi_move_before (&gsi_from, &gsi_to);
   11803              :               /* Shift GSI_TO for further insertion.  */
   11804         1183 :               gsi_prev (&gsi_to);
   11805              :             }
   11806              :           /* Put other masked stores with the same mask to STORE_BB.  */
   11807          658 :           if (worklist.is_empty ()
   11808          240 :               || gimple_call_arg (worklist.last (), 2) != mask
   11809           17 :               || worklist.last () != stmt1)
   11810              :             break;
   11811           17 :           last = worklist.pop ();
   11812           17 :         }
   11813         1282 :       add_phi_arg (phi, gimple_vuse (last_store), e, UNKNOWN_LOCATION);
   11814              :     }
   11815          486 : }
   11816              : 
   11817              : /* Decide whether it is possible to use a zero-based induction variable
   11818              :    when vectorizing LOOP_VINFO with partial vectors.  If it is, return
   11819              :    the value that the induction variable must be able to hold in order
   11820              :    to ensure that the rgroups eventually have no active vector elements.
   11821              :    Return -1 otherwise.  */
   11822              : 
   11823              : widest_int
   11824        47048 : vect_iv_limit_for_partial_vectors (loop_vec_info loop_vinfo)
   11825              : {
   11826        47048 :   tree niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
   11827        47048 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
   11828        47048 :   unsigned HOST_WIDE_INT max_vf = vect_max_vf (loop_vinfo);
   11829              : 
   11830              :   /* Calculate the value that the induction variable must be able
   11831              :      to hit in order to ensure that we end the loop with an all-false mask.
   11832              :      This involves adding the maximum number of inactive trailing scalar
   11833              :      iterations.  */
   11834        47048 :   widest_int iv_limit = -1;
   11835        47048 :   if (max_loop_iterations (loop, &iv_limit))
   11836              :     {
   11837        47048 :       if (niters_skip)
   11838              :         {
   11839              :           /* Add the maximum number of skipped iterations to the
   11840              :              maximum iteration count.  */
   11841            0 :           if (TREE_CODE (niters_skip) == INTEGER_CST)
   11842            0 :             iv_limit += wi::to_widest (niters_skip);
   11843              :           else
   11844            0 :             iv_limit += max_vf - 1;
   11845              :         }
   11846        47048 :       else if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo))
   11847              :         /* Make a conservatively-correct assumption.  */
   11848          326 :         iv_limit += max_vf - 1;
   11849              : 
   11850              :       /* IV_LIMIT is the maximum number of latch iterations, which is also
   11851              :          the maximum in-range IV value.  Round this value down to the previous
   11852              :          vector alignment boundary and then add an extra full iteration.  */
   11853        47048 :       poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
   11854        47048 :       iv_limit = (iv_limit & -(int) known_alignment (vf)) + max_vf;
   11855              :     }
   11856        47048 :   return iv_limit;
   11857              : }
   11858              : 
   11859              : /* For the given rgroup_controls RGC, check whether an induction variable
   11860              :    would ever hit a value that produces a set of all-false masks or zero
   11861              :    lengths before wrapping around.  Return true if it's possible to wrap
   11862              :    around before hitting the desirable value, otherwise return false.  */
   11863              : 
   11864              : bool
   11865            0 : vect_rgroup_iv_might_wrap_p (loop_vec_info loop_vinfo, rgroup_controls *rgc)
   11866              : {
   11867            0 :   widest_int iv_limit = vect_iv_limit_for_partial_vectors (loop_vinfo);
   11868              : 
   11869            0 :   if (iv_limit == -1)
   11870              :     return true;
   11871              : 
   11872            0 :   tree compare_type = LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo);
   11873            0 :   unsigned int compare_precision = TYPE_PRECISION (compare_type);
   11874            0 :   unsigned nitems = rgc->max_nscalars_per_iter * rgc->factor;
   11875              : 
   11876            0 :   if (wi::min_precision (iv_limit * nitems, UNSIGNED) > compare_precision)
   11877            0 :     return true;
   11878              : 
   11879              :   return false;
   11880            0 : }
        

Generated by: LCOV version 2.4-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.