Debian Codegraph @

gcc/tree-vect-loop.cc

raw
1 /* Loop Vectorization
2 Copyright (C) 2003-2025 Free Software Foundation, Inc.
3 Contributed by Dorit Naishlos <[email protected]> and
4 Ira Rosen <[email protected]>
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
62 /* Loop Vectorization Pass.
63
64 This pass tries to vectorize loops.
65
66 For example, the vectorizer transforms the following simple loop:
67
68 short a[N]; short b[N]; short c[N]; int i;
69
70 for (i=0; i<N; i++){
71 a[i] = b[i] + c[i];
72 }
73
74 as if it was manually vectorized by rewriting the source code into:
75
76 typedef int __attribute__((mode(V8HI))) v8hi;
77 short a[N]; short b[N]; short c[N]; int i;
78 v8hi *pa = (v8hi*)a, *pb = (v8hi*)b, *pc = (v8hi*)c;
79 v8hi va, vb, vc;
80
81 for (i=0; i<N/8; i++){
82 vb = pb[i];
83 vc = pc[i];
84 va = vb + vc;
85 pa[i] = va;
86 }
87
88 The main entry to this pass is vectorize_loops(), in which
89 the vectorizer applies a set of analyses on a given set of loops,
90 followed by the actual vectorization transformation for the loops that
91 had successfully passed the analysis phase.
92 Throughout this pass we make a distinction between two types of
93 data: scalars (which are represented by SSA_NAMES), and memory references
94 ("data-refs"). These two types of data require different handling both
95 during analysis and transformation. The types of data-refs that the
96 vectorizer currently supports are ARRAY_REFS which base is an array DECL
97 (not a pointer), and INDIRECT_REFS through pointers; both array and pointer
98 accesses are required to have a simple (consecutive) access pattern.
99
100 Analysis phase:
101 ===============
102 The driver for the analysis phase is vect_analyze_loop().
103 It applies a set of analyses, some of which rely on the scalar evolution
104 analyzer (scev) developed by Sebastian Pop.
105
106 During the analysis phase the vectorizer records some information
107 per stmt in a "stmt_vec_info" struct which is attached to each stmt in the
108 loop, as well as general information about the loop as a whole, which is
109 recorded in a "loop_vec_info" struct attached to each loop.
110
111 Transformation phase:
112 =====================
113 The loop transformation phase scans all the stmts in the loop, and
114 creates a vector stmt (or a sequence of stmts) for each scalar stmt S in
115 the loop that needs to be vectorized. It inserts the vector code sequence
116 just before the scalar stmt S, and records a pointer to the vector code
117 in STMT_VINFO_VEC_STMT (stmt_info) (stmt_info is the stmt_vec_info struct
118 attached to S). This pointer will be used for the vectorization of following
119 stmts which use the def of stmt S. Stmt S is removed if it writes to memory;
120 otherwise, we rely on dead code elimination for removing it.
121
122 For example, say stmt S1 was vectorized into stmt VS1:
123
124 VS1: vb = px[i];
125 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
126 S2: a = b;
127
128 To vectorize stmt S2, the vectorizer first finds the stmt that defines
129 the operand 'b' (S1), and gets the relevant vector def 'vb' from the
130 vector stmt VS1 pointed to by STMT_VINFO_VEC_STMT (stmt_info (S1)). The
131 resulting sequence would be:
132
133 VS1: vb = px[i];
134 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
135 VS2: va = vb;
136 S2: a = b; STMT_VINFO_VEC_STMT (stmt_info (S2)) = VS2
137
138 Operands that are not SSA_NAMEs, are data-refs that appear in
139 load/store operations (like 'x[i]' in S1), and are handled differently.
140
141 Target modeling:
142 =================
143 Currently the only target specific information that is used is the
144 size of the vector (in bytes) - "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD".
145 Targets that can support different sizes of vectors, for now will need
146 to specify one value for "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD". More
147 flexibility will be added in the future.
148
149 Since we only vectorize operations which vector form can be
150 expressed using existing tree codes, to verify that an operation is
151 supported, the vectorizer checks the relevant optab at the relevant
152 machine_mode (e.g, optab_handler (add_optab, V8HImode)). If
153 the value found is CODE_FOR_nothing, then there's no target support, and
154 we can't vectorize the stmt.
155
156 For additional information on this project see:
157 http://gcc.gnu.org/projects/tree-ssa/vectorization.html
158 */
159
160 static void vect_estimate_min_profitable_iters (loop_vec_info, int *, int *,
161 unsigned *);
162 static stmt_vec_info vect_is_simple_reduction (loop_vec_info, stmt_vec_info,
163 bool *, bool *, bool);
164
165 /* Subroutine of vect_determine_vf_for_stmt that handles only one
166 statement. VECTYPE_MAYBE_SET_P is true if STMT_VINFO_VECTYPE
167 may already be set for general statements (not just data refs). */
168
169 static opt_result
170 vect_determine_vf_for_stmt_1 (vec_info *vinfo, stmt_vec_info stmt_info,
171 bool vectype_maybe_set_p,
172 poly_uint64 *vf)
173 {
174 gimple *stmt = stmt_info->stmt;
175
176 if ((!STMT_VINFO_RELEVANT_P (stmt_info)
177 && !STMT_VINFO_LIVE_P (stmt_info))
178 || gimple_clobber_p (stmt))
179 {
180 if (dump_enabled_p ())
181 dump_printf_loc (MSG_NOTE, vect_location, "skip.\n");
182 return opt_result::success ();
183 }
184
185 tree stmt_vectype, nunits_vectype;
186 opt_result res = vect_get_vector_types_for_stmt (vinfo, stmt_info,
187 &stmt_vectype,
188 &nunits_vectype);
189 if (!res)
190 return res;
191
192 if (stmt_vectype)
193 {
194 if (STMT_VINFO_VECTYPE (stmt_info))
195 /* The only case when a vectype had been already set is for stmts
196 that contain a data ref, or for "pattern-stmts" (stmts generated
197 by the vectorizer to represent/replace a certain idiom). */
198 gcc_assert ((STMT_VINFO_DATA_REF (stmt_info)
199 || vectype_maybe_set_p)
200 && STMT_VINFO_VECTYPE (stmt_info) == stmt_vectype);
201 else
202 STMT_VINFO_VECTYPE (stmt_info) = stmt_vectype;
203 }
204
205 if (nunits_vectype)
206 vect_update_max_nunits (vf, nunits_vectype);
207
208 return opt_result::success ();
209 }
210
211 /* Subroutine of vect_determine_vectorization_factor. Set the vector
212 types of STMT_INFO and all attached pattern statements and update
213 the vectorization factor VF accordingly. Return true on success
214 or false if something prevented vectorization. */
215
216 static opt_result
217 vect_determine_vf_for_stmt (vec_info *vinfo,
218 stmt_vec_info stmt_info, poly_uint64 *vf)
219 {
220 if (dump_enabled_p ())
221 dump_printf_loc (MSG_NOTE, vect_location, "==> examining statement: %G",
222 stmt_info->stmt);
223 opt_result res = vect_determine_vf_for_stmt_1 (vinfo, stmt_info, false, vf);
224 if (!res)
225 return res;
226
227 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
228 && STMT_VINFO_RELATED_STMT (stmt_info))
229 {
230 gimple *pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
231 stmt_info = STMT_VINFO_RELATED_STMT (stmt_info);
232
233 /* If a pattern statement has def stmts, analyze them too. */
234 for (gimple_stmt_iterator si = gsi_start (pattern_def_seq);
235 !gsi_end_p (si); gsi_next (&si))
236 {
237 stmt_vec_info def_stmt_info = vinfo->lookup_stmt (gsi_stmt (si));
238 if (dump_enabled_p ())
239 dump_printf_loc (MSG_NOTE, vect_location,
240 "==> examining pattern def stmt: %G",
241 def_stmt_info->stmt);
242 res = vect_determine_vf_for_stmt_1 (vinfo, def_stmt_info, true, vf);
243 if (!res)
244 return res;
245 }
246
247 if (dump_enabled_p ())
248 dump_printf_loc (MSG_NOTE, vect_location,
249 "==> examining pattern statement: %G",
250 stmt_info->stmt);
251 res = vect_determine_vf_for_stmt_1 (vinfo, stmt_info, true, vf);
252 if (!res)
253 return res;
254 }
255
256 return opt_result::success ();
257 }
258
259 /* Function vect_determine_vectorization_factor
260
261 Determine the vectorization factor (VF). VF is the number of data elements
262 that are operated upon in parallel in a single iteration of the vectorized
263 loop. For example, when vectorizing a loop that operates on 4byte elements,
264 on a target with vector size (VS) 16byte, the VF is set to 4, since 4
265 elements can fit in a single vector register.
266
267 We currently support vectorization of loops in which all types operated upon
268 are of the same size. Therefore this function currently sets VF according to
269 the size of the types operated upon, and fails if there are multiple sizes
270 in the loop.
271
272 VF is also the factor by which the loop iterations are strip-mined, e.g.:
273 original loop:
274 for (i=0; i<N; i++){
275 a[i] = b[i] + c[i];
276 }
277
278 vectorized loop:
279 for (i=0; i<N; i+=VF){
280 a[i:VF] = b[i:VF] + c[i:VF];
281 }
282 */
283
284 static opt_result
285 vect_determine_vectorization_factor (loop_vec_info loop_vinfo)
286 {
287 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
288 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
289 unsigned nbbs = loop->num_nodes;
290 poly_uint64 vectorization_factor = 1;
291 tree scalar_type = NULL_TREE;
292 gphi *phi;
293 tree vectype;
294 stmt_vec_info stmt_info;
295 unsigned i;
296
297 DUMP_VECT_SCOPE ("vect_determine_vectorization_factor");
298
299 for (i = 0; i < nbbs; i++)
300 {
301 basic_block bb = bbs[i];
302
303 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
304 gsi_next (&si))
305 {
306 phi = si.phi ();
307 stmt_info = loop_vinfo->lookup_stmt (phi);
308 if (dump_enabled_p ())
309 dump_printf_loc (MSG_NOTE, vect_location, "==> examining phi: %G",
310 (gimple *) phi);
311
312 gcc_assert (stmt_info);
313
314 if (STMT_VINFO_RELEVANT_P (stmt_info)
315 || STMT_VINFO_LIVE_P (stmt_info))
316 {
317 gcc_assert (!STMT_VINFO_VECTYPE (stmt_info));
318 scalar_type = TREE_TYPE (PHI_RESULT (phi));
319
320 if (dump_enabled_p ())
321 dump_printf_loc (MSG_NOTE, vect_location,
322 "get vectype for scalar type: %T\n",
323 scalar_type);
324
325 vectype = get_vectype_for_scalar_type (loop_vinfo, scalar_type);
326 if (!vectype)
327 return opt_result::failure_at (phi,
328 "not vectorized: unsupported "
329 "data-type %T\n",
330 scalar_type);
331 STMT_VINFO_VECTYPE (stmt_info) = vectype;
332
333 if (dump_enabled_p ())
334 dump_printf_loc (MSG_NOTE, vect_location, "vectype: %T\n",
335 vectype);
336
337 if (dump_enabled_p ())
338 {
339 dump_printf_loc (MSG_NOTE, vect_location, "nunits = ");
340 dump_dec (MSG_NOTE, TYPE_VECTOR_SUBPARTS (vectype));
341 dump_printf (MSG_NOTE, "\n");
342 }
343
344 vect_update_max_nunits (&vectorization_factor, vectype);
345 }
346 }
347
348 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
349 gsi_next (&si))
350 {
351 if (is_gimple_debug (gsi_stmt (si)))
352 continue;
353 stmt_info = loop_vinfo->lookup_stmt (gsi_stmt (si));
354 opt_result res
355 = vect_determine_vf_for_stmt (loop_vinfo,
356 stmt_info, &vectorization_factor);
357 if (!res)
358 return res;
359 }
360 }
361
362 /* TODO: Analyze cost. Decide if worth while to vectorize. */
363 if (dump_enabled_p ())
364 {
365 dump_printf_loc (MSG_NOTE, vect_location, "vectorization factor = ");
366 dump_dec (MSG_NOTE, vectorization_factor);
367 dump_printf (MSG_NOTE, "\n");
368 }
369
370 if (known_le (vectorization_factor, 1U))
371 return opt_result::failure_at (vect_location,
372 "not vectorized: unsupported data-type\n");
373 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
374 return opt_result::success ();
375 }
376
377
378 /* Function vect_is_simple_iv_evolution.
379
380 FORNOW: A simple evolution of an induction variables in the loop is
381 considered a polynomial evolution. */
382
383 static bool
384 vect_is_simple_iv_evolution (unsigned loop_nb, tree access_fn, tree * init,
385 tree * step)
386 {
387 tree init_expr;
388 tree step_expr;
389 tree evolution_part = evolution_part_in_loop_num (access_fn, loop_nb);
390 basic_block bb;
391
392 /* When there is no evolution in this loop, the evolution function
393 is not "simple". */
394 if (evolution_part == NULL_TREE)
395 return false;
396
397 /* When the evolution is a polynomial of degree >= 2
398 the evolution function is not "simple". */
399 if (tree_is_chrec (evolution_part))
400 return false;
401
402 step_expr = evolution_part;
403 init_expr = unshare_expr (initial_condition_in_loop_num (access_fn, loop_nb));
404
405 if (dump_enabled_p ())
406 dump_printf_loc (MSG_NOTE, vect_location, "step: %T, init: %T\n",
407 step_expr, init_expr);
408
409 *init = init_expr;
410 *step = step_expr;
411
412 if (TREE_CODE (step_expr) != INTEGER_CST
413 && (TREE_CODE (step_expr) != SSA_NAME
414 || ((bb = gimple_bb (SSA_NAME_DEF_STMT (step_expr)))
415 && flow_bb_inside_loop_p (get_loop (cfun, loop_nb), bb))
416 || (!INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
417 && (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr))
418 || !flag_associative_math)))
419 && (TREE_CODE (step_expr) != REAL_CST
420 || !flag_associative_math))
421 {
422 if (dump_enabled_p ())
423 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
424 "step unknown.\n");
425 return false;
426 }
427
428 return true;
429 }
430
431 /* Function vect_is_nonlinear_iv_evolution
432
433 Only support nonlinear induction for integer type
434 1. neg
435 2. mul by constant
436 3. lshift/rshift by constant.
437
438 For neg induction, return a fake step as integer -1. */
439 static bool
440 vect_is_nonlinear_iv_evolution (class loop* loop, stmt_vec_info stmt_info,
441 gphi* loop_phi_node, tree *init, tree *step)
442 {
443 tree init_expr, ev_expr, result, op1, op2;
444 gimple* def;
445
446 if (gimple_phi_num_args (loop_phi_node) != 2)
447 return false;
448
449 init_expr = PHI_ARG_DEF_FROM_EDGE (loop_phi_node, loop_preheader_edge (loop));
450 ev_expr = PHI_ARG_DEF_FROM_EDGE (loop_phi_node, loop_latch_edge (loop));
451
452 /* Support nonlinear induction only for integer type. */
453 if (!INTEGRAL_TYPE_P (TREE_TYPE (init_expr)))
454 return false;
455
456 *init = init_expr;
457 result = PHI_RESULT (loop_phi_node);
458
459 if (TREE_CODE (ev_expr) != SSA_NAME
460 || ((def = SSA_NAME_DEF_STMT (ev_expr)), false)
461 || !is_gimple_assign (def))
462 return false;
463
464 enum tree_code t_code = gimple_assign_rhs_code (def);
465 switch (t_code)
466 {
467 case NEGATE_EXPR:
468 if (gimple_assign_rhs1 (def) != result)
469 return false;
470 *step = build_int_cst (TREE_TYPE (init_expr), -1);
471 STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_neg;
472 break;
473
474 case RSHIFT_EXPR:
475 case LSHIFT_EXPR:
476 case MULT_EXPR:
477 op1 = gimple_assign_rhs1 (def);
478 op2 = gimple_assign_rhs2 (def);
479 if (TREE_CODE (op2) != INTEGER_CST
480 || op1 != result)
481 return false;
482 *step = op2;
483 if (t_code == LSHIFT_EXPR)
484 STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_shl;
485 else if (t_code == RSHIFT_EXPR)
486 STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_shr;
487 /* NEGATE_EXPR and MULT_EXPR are both vect_step_op_mul. */
488 else
489 STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_mul;
490 break;
491
492 default:
493 return false;
494 }
495
496 STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_info) = *init;
497 STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info) = *step;
498
499 return true;
500 }
501
502 /* Return true if PHI, described by STMT_INFO, is the inner PHI in
503 what we are assuming is a double reduction. For example, given
504 a structure like this:
505
506 outer1:
507 x_1 = PHI <x_4(outer2), ...>;
508 ...
509
510 inner:
511 x_2 = PHI <x_1(outer1), ...>;
512 ...
513 x_3 = ...;
514 ...
515
516 outer2:
517 x_4 = PHI <x_3(inner)>;
518 ...
519
520 outer loop analysis would treat x_1 as a double reduction phi and
521 this function would then return true for x_2. */
522
523 static bool
524 vect_inner_phi_in_double_reduction_p (loop_vec_info loop_vinfo, gphi *phi)
525 {
526 use_operand_p use_p;
527 ssa_op_iter op_iter;
528 FOR_EACH_PHI_ARG (use_p, phi, op_iter, SSA_OP_USE)
529 if (stmt_vec_info def_info = loop_vinfo->lookup_def (USE_FROM_PTR (use_p)))
530 if (STMT_VINFO_DEF_TYPE (def_info) == vect_double_reduction_def)
531 return true;
532 return false;
533 }
534
535 /* Returns true if Phi is a first-order recurrence. A first-order
536 recurrence is a non-reduction recurrence relation in which the value of
537 the recurrence in the current loop iteration equals a value defined in
538 the previous iteration. */
539
540 static bool
541 vect_phi_first_order_recurrence_p (loop_vec_info loop_vinfo, class loop *loop,
542 gphi *phi)
543 {
544 /* A nested cycle isn't vectorizable as first order recurrence. */
545 if (LOOP_VINFO_LOOP (loop_vinfo) != loop)
546 return false;
547
548 /* Ensure the loop latch definition is from within the loop. */
549 edge latch = loop_latch_edge (loop);
550 tree ldef = PHI_ARG_DEF_FROM_EDGE (phi, latch);
551 if (TREE_CODE (ldef) != SSA_NAME
552 || SSA_NAME_IS_DEFAULT_DEF (ldef)
553 || is_a <gphi *> (SSA_NAME_DEF_STMT (ldef))
554 || !flow_bb_inside_loop_p (loop, gimple_bb (SSA_NAME_DEF_STMT (ldef))))
555 return false;
556
557 tree def = gimple_phi_result (phi);
558
559 /* Ensure every use_stmt of the phi node is dominated by the latch
560 definition. */
561 imm_use_iterator imm_iter;
562 use_operand_p use_p;
563 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, def)
564 if (!is_gimple_debug (USE_STMT (use_p))
565 && (SSA_NAME_DEF_STMT (ldef) == USE_STMT (use_p)
566 || !vect_stmt_dominates_stmt_p (SSA_NAME_DEF_STMT (ldef),
567 USE_STMT (use_p))))
568 return false;
569
570 /* First-order recurrence autovectorization needs shuffle vector. */
571 tree scalar_type = TREE_TYPE (def);
572 tree vectype = get_vectype_for_scalar_type (loop_vinfo, scalar_type);
573 if (!vectype)
574 return false;
575
576 return true;
577 }
578
579 /* Function vect_analyze_scalar_cycles_1.
580
581 Examine the cross iteration def-use cycles of scalar variables
582 in LOOP. LOOP_VINFO represents the loop that is now being
583 considered for vectorization (can be LOOP, or an outer-loop
584 enclosing LOOP). SLP indicates there will be some subsequent
585 slp analyses or not. */
586
587 static void
588 vect_analyze_scalar_cycles_1 (loop_vec_info loop_vinfo, class loop *loop,
589 bool slp)
590 {
591 basic_block bb = loop->header;
592 tree init, step;
593 auto_vec<stmt_vec_info, 64> worklist;
594 gphi_iterator gsi;
595 bool double_reduc, reduc_chain;
596
597 DUMP_VECT_SCOPE ("vect_analyze_scalar_cycles");
598
599 /* First - identify all inductions. Reduction detection assumes that all the
600 inductions have been identified, therefore, this order must not be
601 changed. */
602 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
603 {
604 gphi *phi = gsi.phi ();
605 tree access_fn = NULL;
606 tree def = PHI_RESULT (phi);
607 stmt_vec_info stmt_vinfo = loop_vinfo->lookup_stmt (phi);
608
609 if (dump_enabled_p ())
610 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: %G",
611 (gimple *) phi);
612
613 /* Skip virtual phi's. The data dependences that are associated with
614 virtual defs/uses (i.e., memory accesses) are analyzed elsewhere. */
615 if (virtual_operand_p (def))
616 continue;
617
618 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_unknown_def_type;
619
620 /* Analyze the evolution function. */
621 access_fn = analyze_scalar_evolution (loop, def);
622 if (access_fn)
623 {
624 STRIP_NOPS (access_fn);
625 if (dump_enabled_p ())
626 dump_printf_loc (MSG_NOTE, vect_location,
627 "Access function of PHI: %T\n", access_fn);
628 STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
629 = initial_condition_in_loop_num (access_fn, loop->num);
630 STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo)
631 = evolution_part_in_loop_num (access_fn, loop->num);
632 }
633
634 if ((!access_fn
635 || vect_inner_phi_in_double_reduction_p (loop_vinfo, phi)
636 || !vect_is_simple_iv_evolution (loop->num, access_fn,
637 &init, &step)
638 || (LOOP_VINFO_LOOP (loop_vinfo) != loop
639 && TREE_CODE (step) != INTEGER_CST))
640 /* Only handle nonlinear iv for same loop. */
641 && (LOOP_VINFO_LOOP (loop_vinfo) != loop
642 || !vect_is_nonlinear_iv_evolution (loop, stmt_vinfo,
643 phi, &init, &step)))
644 {
645 worklist.safe_push (stmt_vinfo);
646 continue;
647 }
648
649 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
650 != NULL_TREE);
651 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo) != NULL_TREE);
652
653 if (dump_enabled_p ())
654 dump_printf_loc (MSG_NOTE, vect_location, "Detected induction.\n");
655 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_induction_def;
656
657 /* Mark if we have a non-linear IV. */
658 LOOP_VINFO_NON_LINEAR_IV (loop_vinfo)
659 = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_vinfo) != vect_step_op_add;
660 }
661
662
663 /* Second - identify all reductions and nested cycles. */
664 while (worklist.length () > 0)
665 {
666 stmt_vec_info stmt_vinfo = worklist.pop ();
667 gphi *phi = as_a <gphi *> (stmt_vinfo->stmt);
668 tree def = PHI_RESULT (phi);
669
670 if (dump_enabled_p ())
671 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: %G",
672 (gimple *) phi);
673
674 gcc_assert (!virtual_operand_p (def)
675 && STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_unknown_def_type);
676
677 stmt_vec_info reduc_stmt_info
678 = vect_is_simple_reduction (loop_vinfo, stmt_vinfo, &double_reduc,
679 &reduc_chain, slp);
680 if (reduc_stmt_info)
681 {
682 STMT_VINFO_REDUC_DEF (stmt_vinfo) = reduc_stmt_info;
683 STMT_VINFO_REDUC_DEF (reduc_stmt_info) = stmt_vinfo;
684 if (double_reduc)
685 {
686 if (dump_enabled_p ())
687 dump_printf_loc (MSG_NOTE, vect_location,
688 "Detected double reduction.\n");
689
690 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_double_reduction_def;
691 STMT_VINFO_DEF_TYPE (reduc_stmt_info) = vect_double_reduction_def;
692 /* Make it accessible for SLP vectorization. */
693 LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push (reduc_stmt_info);
694 }
695 else
696 {
697 if (loop != LOOP_VINFO_LOOP (loop_vinfo))
698 {
699 if (dump_enabled_p ())
700 dump_printf_loc (MSG_NOTE, vect_location,
701 "Detected vectorizable nested cycle.\n");
702
703 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_nested_cycle;
704 }
705 else
706 {
707 if (dump_enabled_p ())
708 dump_printf_loc (MSG_NOTE, vect_location,
709 "Detected reduction.\n");
710
711 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_reduction_def;
712 STMT_VINFO_DEF_TYPE (reduc_stmt_info) = vect_reduction_def;
713 /* Store the reduction cycles for possible vectorization in
714 loop-aware SLP if it was not detected as reduction
715 chain. */
716 if (! reduc_chain)
717 LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push
718 (reduc_stmt_info);
719 }
720 }
721 }
722 else if (vect_phi_first_order_recurrence_p (loop_vinfo, loop, phi))
723 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_first_order_recurrence;
724 else
725 if (dump_enabled_p ())
726 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
727 "Unknown def-use cycle pattern.\n");
728 }
729 }
730
731
732 /* Function vect_analyze_scalar_cycles.
733
734 Examine the cross iteration def-use cycles of scalar variables, by
735 analyzing the loop-header PHIs of scalar variables. Classify each
736 cycle as one of the following: invariant, induction, reduction, unknown.
737 We do that for the loop represented by LOOP_VINFO, and also to its
738 inner-loop, if exists.
739 Examples for scalar cycles:
740
741 Example1: reduction:
742
743 loop1:
744 for (i=0; i<N; i++)
745 sum += a[i];
746
747 Example2: induction:
748
749 loop2:
750 for (i=0; i<N; i++)
751 a[i] = i; */
752
753 static void
754 vect_analyze_scalar_cycles (loop_vec_info loop_vinfo, bool slp)
755 {
756 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
757
758 vect_analyze_scalar_cycles_1 (loop_vinfo, loop, slp);
759
760 /* When vectorizing an outer-loop, the inner-loop is executed sequentially.
761 Reductions in such inner-loop therefore have different properties than
762 the reductions in the nest that gets vectorized:
763 1. When vectorized, they are executed in the same order as in the original
764 scalar loop, so we can't change the order of computation when
765 vectorizing them.
766 2. FIXME: Inner-loop reductions can be used in the inner-loop, so the
767 current checks are too strict. */
768
769 if (loop->inner)
770 vect_analyze_scalar_cycles_1 (loop_vinfo, loop->inner, slp);
771 }
772
773 /* Transfer group and reduction information from STMT_INFO to its
774 pattern stmt. */
775
776 static void
777 vect_fixup_reduc_chain (stmt_vec_info stmt_info)
778 {
779 stmt_vec_info firstp = STMT_VINFO_RELATED_STMT (stmt_info);
780 stmt_vec_info stmtp;
781 gcc_assert (!REDUC_GROUP_FIRST_ELEMENT (firstp)
782 && REDUC_GROUP_FIRST_ELEMENT (stmt_info));
783 REDUC_GROUP_SIZE (firstp) = REDUC_GROUP_SIZE (stmt_info);
784 do
785 {
786 stmtp = STMT_VINFO_RELATED_STMT (stmt_info);
787 gcc_checking_assert (STMT_VINFO_DEF_TYPE (stmtp)
788 == STMT_VINFO_DEF_TYPE (stmt_info));
789 REDUC_GROUP_FIRST_ELEMENT (stmtp) = firstp;
790 stmt_info = REDUC_GROUP_NEXT_ELEMENT (stmt_info);
791 if (stmt_info)
792 REDUC_GROUP_NEXT_ELEMENT (stmtp)
793 = STMT_VINFO_RELATED_STMT (stmt_info);
794 }
795 while (stmt_info);
796 }
797
798 /* Fixup scalar cycles that now have their stmts detected as patterns. */
799
800 static void
801 vect_fixup_scalar_cycles_with_patterns (loop_vec_info loop_vinfo)
802 {
803 stmt_vec_info first;
804 unsigned i;
805
806 FOR_EACH_VEC_ELT (LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo), i, first)
807 {
808 stmt_vec_info next = REDUC_GROUP_NEXT_ELEMENT (first);
809 while (next)
810 {
811 if ((STMT_VINFO_IN_PATTERN_P (next)
812 != STMT_VINFO_IN_PATTERN_P (first))
813 || STMT_VINFO_REDUC_IDX (vect_stmt_to_vectorize (next)) == -1)
814 break;
815 next = REDUC_GROUP_NEXT_ELEMENT (next);
816 }
817 /* If all reduction chain members are well-formed patterns adjust
818 the group to group the pattern stmts instead. */
819 if (! next
820 && STMT_VINFO_REDUC_IDX (vect_stmt_to_vectorize (first)) != -1)
821 {
822 if (STMT_VINFO_IN_PATTERN_P (first))
823 {
824 vect_fixup_reduc_chain (first);
825 LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo)[i]
826 = STMT_VINFO_RELATED_STMT (first);
827 }
828 }
829 /* If not all stmt in the chain are patterns or if we failed
830 to update STMT_VINFO_REDUC_IDX dissolve the chain and handle
831 it as regular reduction instead. */
832 else
833 {
834 stmt_vec_info vinfo = first;
835 stmt_vec_info last = NULL;
836 while (vinfo)
837 {
838 next = REDUC_GROUP_NEXT_ELEMENT (vinfo);
839 REDUC_GROUP_FIRST_ELEMENT (vinfo) = NULL;
840 REDUC_GROUP_NEXT_ELEMENT (vinfo) = NULL;
841 last = vinfo;
842 vinfo = next;
843 }
844 STMT_VINFO_DEF_TYPE (vect_stmt_to_vectorize (first))
845 = vect_internal_def;
846 loop_vinfo->reductions.safe_push (vect_stmt_to_vectorize (last));
847 LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo).unordered_remove (i);
848 --i;
849 }
850 }
851 }
852
853 /* Function vect_get_loop_niters.
854
855 Determine how many iterations the loop is executed and place it
856 in NUMBER_OF_ITERATIONS. Place the number of latch iterations
857 in NUMBER_OF_ITERATIONSM1. Place the condition under which the
858 niter information holds in ASSUMPTIONS.
859
860 Return the loop exit conditions. */
861
862
863 static vec<gcond *>
864 vect_get_loop_niters (class loop *loop, const_edge main_exit, tree *assumptions,
865 tree *number_of_iterations, tree *number_of_iterationsm1)
866 {
867 auto_vec<edge> exits = get_loop_exit_edges (loop);
868 vec<gcond *> conds;
869 conds.create (exits.length ());
870 class tree_niter_desc niter_desc;
871 tree niter_assumptions, niter, may_be_zero;
872
873 *assumptions = boolean_true_node;
874 *number_of_iterationsm1 = chrec_dont_know;
875 *number_of_iterations = chrec_dont_know;
876
877 DUMP_VECT_SCOPE ("get_loop_niters");
878
879 if (exits.is_empty ())
880 return conds;
881
882 if (dump_enabled_p ())
883 dump_printf_loc (MSG_NOTE, vect_location, "Loop has %d exits.\n",
884 exits.length ());
885
886 edge exit;
887 unsigned int i;
888 FOR_EACH_VEC_ELT (exits, i, exit)
889 {
890 gcond *cond = get_loop_exit_condition (exit);
891 if (cond)
892 conds.safe_push (cond);
893
894 if (dump_enabled_p ())
895 dump_printf_loc (MSG_NOTE, vect_location, "Analyzing exit %d...\n", i);
896
897 if (exit != main_exit)
898 continue;
899
900 may_be_zero = NULL_TREE;
901 if (!number_of_iterations_exit_assumptions (loop, exit, &niter_desc, NULL)
902 || chrec_contains_undetermined (niter_desc.niter))
903 continue;
904
905 niter_assumptions = niter_desc.assumptions;
906 may_be_zero = niter_desc.may_be_zero;
907 niter = niter_desc.niter;
908
909 if (may_be_zero && integer_zerop (may_be_zero))
910 may_be_zero = NULL_TREE;
911
912 if (may_be_zero)
913 {
914 if (COMPARISON_CLASS_P (may_be_zero))
915 {
916 /* Try to combine may_be_zero with assumptions, this can simplify
917 computation of niter expression. */
918 if (niter_assumptions && !integer_nonzerop (niter_assumptions))
919 niter_assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
920 niter_assumptions,
921 fold_build1 (TRUTH_NOT_EXPR,
922 boolean_type_node,
923 may_be_zero));
924 else
925 niter = fold_build3 (COND_EXPR, TREE_TYPE (niter), may_be_zero,
926 build_int_cst (TREE_TYPE (niter), 0),
927 rewrite_to_non_trapping_overflow (niter));
928
929 may_be_zero = NULL_TREE;
930 }
931 else if (integer_nonzerop (may_be_zero))
932 {
933 *number_of_iterationsm1 = build_int_cst (TREE_TYPE (niter), 0);
934 *number_of_iterations = build_int_cst (TREE_TYPE (niter), 1);
935 continue;
936 }
937 else
938 continue;
939 }
940
941 /* Loop assumptions are based off the normal exit. */
942 *assumptions = niter_assumptions;
943 *number_of_iterationsm1 = niter;
944
945 /* We want the number of loop header executions which is the number
946 of latch executions plus one.
947 ??? For UINT_MAX latch executions this number overflows to zero
948 for loops like do { n++; } while (n != 0); */
949 if (niter && !chrec_contains_undetermined (niter))
950 {
951 niter = fold_build2 (PLUS_EXPR, TREE_TYPE (niter),
952 unshare_expr (niter),
953 build_int_cst (TREE_TYPE (niter), 1));
954 if (TREE_CODE (niter) == INTEGER_CST
955 && TREE_CODE (*number_of_iterationsm1) != INTEGER_CST)
956 {
957 /* If we manage to fold niter + 1 into INTEGER_CST even when
958 niter is some complex expression, ensure back
959 *number_of_iterationsm1 is an INTEGER_CST as well. See
960 PR113210. */
961 *number_of_iterationsm1
962 = fold_build2 (PLUS_EXPR, TREE_TYPE (niter), niter,
963 build_minus_one_cst (TREE_TYPE (niter)));
964 }
965 }
966 *number_of_iterations = niter;
967 }
968
969 if (dump_enabled_p ())
970 dump_printf_loc (MSG_NOTE, vect_location, "All loop exits successfully analyzed.\n");
971
972 return conds;
973 }
974
975 /* Determine the main loop exit for the vectorizer. */
976
977 edge
978 vec_init_loop_exit_info (class loop *loop)
979 {
980 /* Before we begin we must first determine which exit is the main one and
981 which are auxilary exits. */
982 auto_vec<edge> exits = get_loop_exit_edges (loop);
983 if (exits.length () == 1)
984 return exits[0];
985
986 /* If we have multiple exits we only support counting IV at the moment.
987 Analyze all exits and return the last one we can analyze. */
988 class tree_niter_desc niter_desc;
989 edge candidate = NULL;
990 for (edge exit : exits)
991 {
992 if (!get_loop_exit_condition (exit))
993 continue;
994
995 if (number_of_iterations_exit_assumptions (loop, exit, &niter_desc, NULL)
996 && !chrec_contains_undetermined (niter_desc.niter))
997 {
998 tree may_be_zero = niter_desc.may_be_zero;
999 if ((integer_zerop (may_be_zero)
1000 /* As we are handling may_be_zero that's not false by
1001 rewriting niter to may_be_zero ? 0 : niter we require
1002 an empty latch. */
1003 || (single_pred_p (loop->latch)
1004 && exit->src == single_pred (loop->latch)
1005 && (integer_nonzerop (may_be_zero)
1006 || COMPARISON_CLASS_P (may_be_zero))))
1007 && (!candidate
1008 || dominated_by_p (CDI_DOMINATORS, exit->src,
1009 candidate->src)))
1010 candidate = exit;
1011 }
1012 }
1013
1014 return candidate;
1015 }
1016
1017 /* Function bb_in_loop_p
1018
1019 Used as predicate for dfs order traversal of the loop bbs. */
1020
1021 static bool
1022 bb_in_loop_p (const_basic_block bb, const void *data)
1023 {
1024 const class loop *const loop = (const class loop *)data;
1025 if (flow_bb_inside_loop_p (loop, bb))
1026 return true;
1027 return false;
1028 }
1029
1030
1031 /* Create and initialize a new loop_vec_info struct for LOOP_IN, as well as
1032 stmt_vec_info structs for all the stmts in LOOP_IN. */
1033
1034 _loop_vec_info::_loop_vec_info (class loop *loop_in, vec_info_shared *shared)
1035 : vec_info (vec_info::loop, shared),
1036 loop (loop_in),
1037 num_itersm1 (NULL_TREE),
1038 num_iters (NULL_TREE),
1039 num_iters_unchanged (NULL_TREE),
1040 num_iters_assumptions (NULL_TREE),
1041 vector_costs (nullptr),
1042 scalar_costs (nullptr),
1043 th (0),
1044 versioning_threshold (0),
1045 vectorization_factor (0),
1046 main_loop_edge (nullptr),
1047 skip_main_loop_edge (nullptr),
1048 skip_this_loop_edge (nullptr),
1049 reusable_accumulators (),
1050 suggested_unroll_factor (1),
1051 max_vectorization_factor (0),
1052 mask_skip_niters (NULL_TREE),
1053 mask_skip_niters_pfa_offset (NULL_TREE),
1054 rgroup_compare_type (NULL_TREE),
1055 simd_if_cond (NULL_TREE),
1056 partial_vector_style (vect_partial_vectors_none),
1057 unaligned_dr (NULL),
1058 peeling_for_alignment (0),
1059 ptr_mask (0),
1060 nonlinear_iv (false),
1061 ivexpr_map (NULL),
1062 scan_map (NULL),
1063 slp_unrolling_factor (1),
1064 inner_loop_cost_factor (param_vect_inner_loop_cost_factor),
1065 vectorizable (false),
1066 can_use_partial_vectors_p (param_vect_partial_vector_usage != 0),
1067 must_use_partial_vectors_p (false),
1068 using_partial_vectors_p (false),
1069 using_decrementing_iv_p (false),
1070 using_select_vl_p (false),
1071 epil_using_partial_vectors_p (false),
1072 partial_load_store_bias (0),
1073 peeling_for_gaps (false),
1074 peeling_for_niter (false),
1075 early_breaks (false),
1076 no_data_dependencies (false),
1077 has_mask_store (false),
1078 scalar_loop_scaling (profile_probability::uninitialized ()),
1079 scalar_loop (NULL),
1080 main_loop_info (NULL),
1081 orig_loop_info (NULL),
1082 epilogue_vinfo (NULL),
1083 drs_advanced_by (NULL_TREE),
1084 vec_loop_iv_exit (NULL),
1085 vec_epilogue_loop_iv_exit (NULL),
1086 scalar_loop_iv_exit (NULL)
1087 {
1088 /* CHECKME: We want to visit all BBs before their successors (except for
1089 latch blocks, for which this assertion wouldn't hold). In the simple
1090 case of the loop forms we allow, a dfs order of the BBs would the same
1091 as reversed postorder traversal, so we are safe. */
1092
1093 bbs = XCNEWVEC (basic_block, loop->num_nodes);
1094 nbbs = dfs_enumerate_from (loop->header, 0, bb_in_loop_p, bbs,
1095 loop->num_nodes, loop);
1096 gcc_assert (nbbs == loop->num_nodes);
1097
1098 for (unsigned int i = 0; i < nbbs; i++)
1099 {
1100 basic_block bb = bbs[i];
1101 gimple_stmt_iterator si;
1102
1103 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
1104 {
1105 gimple *phi = gsi_stmt (si);
1106 gimple_set_uid (phi, 0);
1107 add_stmt (phi);
1108 }
1109
1110 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1111 {
1112 gimple *stmt = gsi_stmt (si);
1113 gimple_set_uid (stmt, 0);
1114 if (is_gimple_debug (stmt))
1115 continue;
1116 add_stmt (stmt);
1117 /* If .GOMP_SIMD_LANE call for the current loop has 3 arguments, the
1118 third argument is the #pragma omp simd if (x) condition, when 0,
1119 loop shouldn't be vectorized, when non-zero constant, it should
1120 be vectorized normally, otherwise versioned with vectorized loop
1121 done if the condition is non-zero at runtime. */
1122 if (loop_in->simduid
1123 && is_gimple_call (stmt)
1124 && gimple_call_internal_p (stmt)
1125 && gimple_call_internal_fn (stmt) == IFN_GOMP_SIMD_LANE
1126 && gimple_call_num_args (stmt) >= 3
1127 && TREE_CODE (gimple_call_arg (stmt, 0)) == SSA_NAME
1128 && (loop_in->simduid
1129 == SSA_NAME_VAR (gimple_call_arg (stmt, 0))))
1130 {
1131 tree arg = gimple_call_arg (stmt, 2);
1132 if (integer_zerop (arg) || TREE_CODE (arg) == SSA_NAME)
1133 simd_if_cond = arg;
1134 else
1135 gcc_assert (integer_nonzerop (arg));
1136 }
1137 }
1138 }
1139 }
1140
1141 /* Free all levels of rgroup CONTROLS. */
1142
1143 void
1144 release_vec_loop_controls (vec<rgroup_controls> *controls)
1145 {
1146 rgroup_controls *rgc;
1147 unsigned int i;
1148 FOR_EACH_VEC_ELT (*controls, i, rgc)
1149 rgc->controls.release ();
1150 controls->release ();
1151 }
1152
1153 /* Free all memory used by the _loop_vec_info, as well as all the
1154 stmt_vec_info structs of all the stmts in the loop. */
1155
1156 _loop_vec_info::~_loop_vec_info ()
1157 {
1158 free (bbs);
1159
1160 release_vec_loop_controls (&masks.rgc_vec);
1161 release_vec_loop_controls (&lens);
1162 delete ivexpr_map;
1163 delete scan_map;
1164 delete scalar_costs;
1165 delete vector_costs;
1166
1167 /* When we release an epiloge vinfo that we do not intend to use
1168 avoid clearing AUX of the main loop which should continue to
1169 point to the main loop vinfo since otherwise we'll leak that. */
1170 if (loop->aux == this)
1171 loop->aux = NULL;
1172 }
1173
1174 /* Return an invariant or register for EXPR and emit necessary
1175 computations in the LOOP_VINFO loop preheader. */
1176
1177 tree
1178 cse_and_gimplify_to_preheader (loop_vec_info loop_vinfo, tree expr)
1179 {
1180 if (is_gimple_reg (expr)
1181 || is_gimple_min_invariant (expr))
1182 return expr;
1183
1184 if (! loop_vinfo->ivexpr_map)
1185 loop_vinfo->ivexpr_map = new hash_map<tree_operand_hash, tree>;
1186 tree &cached = loop_vinfo->ivexpr_map->get_or_insert (expr);
1187 if (! cached)
1188 {
1189 gimple_seq stmts = NULL;
1190 cached = force_gimple_operand (unshare_expr (expr),
1191 &stmts, true, NULL_TREE);
1192 if (stmts)
1193 {
1194 edge e = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
1195 gsi_insert_seq_on_edge_immediate (e, stmts);
1196 }
1197 }
1198 return cached;
1199 }
1200
1201 /* Return true if we can use CMP_TYPE as the comparison type to produce
1202 all masks required to mask LOOP_VINFO. */
1203
1204 static bool
1205 can_produce_all_loop_masks_p (loop_vec_info loop_vinfo, tree cmp_type)
1206 {
1207 rgroup_controls *rgm;
1208 unsigned int i;
1209 FOR_EACH_VEC_ELT (LOOP_VINFO_MASKS (loop_vinfo).rgc_vec, i, rgm)
1210 if (rgm->type != NULL_TREE
1211 && !direct_internal_fn_supported_p (IFN_WHILE_ULT,
1212 cmp_type, rgm->type,
1213 OPTIMIZE_FOR_SPEED))
1214 return false;
1215 return true;
1216 }
1217
1218 /* Calculate the maximum number of scalars per iteration for every
1219 rgroup in LOOP_VINFO. */
1220
1221 static unsigned int
1222 vect_get_max_nscalars_per_iter (loop_vec_info loop_vinfo)
1223 {
1224 unsigned int res = 1;
1225 unsigned int i;
1226 rgroup_controls *rgm;
1227 FOR_EACH_VEC_ELT (LOOP_VINFO_MASKS (loop_vinfo).rgc_vec, i, rgm)
1228 res = MAX (res, rgm->max_nscalars_per_iter);
1229 return res;
1230 }
1231
1232 /* Calculate the minimum precision necessary to represent:
1233
1234 MAX_NITERS * FACTOR
1235
1236 as an unsigned integer, where MAX_NITERS is the maximum number of
1237 loop header iterations for the original scalar form of LOOP_VINFO. */
1238
1239 static unsigned
1240 vect_min_prec_for_max_niters (loop_vec_info loop_vinfo, unsigned int factor)
1241 {
1242 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1243
1244 /* Get the maximum number of iterations that is representable
1245 in the counter type. */
1246 tree ni_type = TREE_TYPE (LOOP_VINFO_NITERSM1 (loop_vinfo));
1247 widest_int max_ni = wi::to_widest (TYPE_MAX_VALUE (ni_type)) + 1;
1248
1249 /* Get a more refined estimate for the number of iterations. */
1250 widest_int max_back_edges;
1251 if (max_loop_iterations (loop, &max_back_edges))
1252 max_ni = wi::smin (max_ni, max_back_edges + 1);
1253
1254 /* Work out how many bits we need to represent the limit. */
1255 return wi::min_precision (max_ni * factor, UNSIGNED);
1256 }
1257
1258 /* True if the loop needs peeling or partial vectors when vectorized. */
1259
1260 static bool
1261 vect_need_peeling_or_partial_vectors_p (loop_vec_info loop_vinfo)
1262 {
1263 unsigned HOST_WIDE_INT const_vf;
1264 HOST_WIDE_INT max_niter
1265 = likely_max_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
1266
1267 unsigned th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
1268 if (!th && LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo))
1269 th = LOOP_VINFO_COST_MODEL_THRESHOLD (LOOP_VINFO_ORIG_LOOP_INFO
1270 (loop_vinfo));
1271
1272 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
1273 && LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) >= 0)
1274 {
1275 /* Work out the (constant) number of iterations that need to be
1276 peeled for reasons other than niters. */
1277 unsigned int peel_niter = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
1278 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
1279 peel_niter += 1;
1280 if (!multiple_p (LOOP_VINFO_INT_NITERS (loop_vinfo) - peel_niter,
1281 LOOP_VINFO_VECT_FACTOR (loop_vinfo)))
1282 return true;
1283 }
1284 else if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
1285 /* ??? When peeling for gaps but not alignment, we could
1286 try to check whether the (variable) niters is known to be
1287 VF * N + 1. That's something of a niche case though. */
1288 || LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
1289 || !LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant (&const_vf)
1290 || ((tree_ctz (LOOP_VINFO_NITERS (loop_vinfo))
1291 < (unsigned) exact_log2 (const_vf))
1292 /* In case of versioning, check if the maximum number of
1293 iterations is greater than th. If they are identical,
1294 the epilogue is unnecessary. */
1295 && (!LOOP_REQUIRES_VERSIONING (loop_vinfo)
1296 || ((unsigned HOST_WIDE_INT) max_niter
1297 /* We'd like to use LOOP_VINFO_VERSIONING_THRESHOLD
1298 but that's only computed later based on our result.
1299 The following is the most conservative approximation. */
1300 > (std::max ((unsigned HOST_WIDE_INT) th,
1301 const_vf) / const_vf) * const_vf))))
1302 return true;
1303
1304 return false;
1305 }
1306
1307 /* Each statement in LOOP_VINFO can be masked where necessary. Check
1308 whether we can actually generate the masks required. Return true if so,
1309 storing the type of the scalar IV in LOOP_VINFO_RGROUP_COMPARE_TYPE. */
1310
1311 static bool
1312 vect_verify_full_masking (loop_vec_info loop_vinfo)
1313 {
1314 unsigned int min_ni_width;
1315
1316 /* Use a normal loop if there are no statements that need masking.
1317 This only happens in rare degenerate cases: it means that the loop
1318 has no loads, no stores, and no live-out values. */
1319 if (LOOP_VINFO_MASKS (loop_vinfo).is_empty ())
1320 return false;
1321
1322 /* Produce the rgroup controls. */
1323 for (auto mask : LOOP_VINFO_MASKS (loop_vinfo).mask_set)
1324 {
1325 vec_loop_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
1326 tree vectype = mask.first;
1327 unsigned nvectors = mask.second;
1328
1329 if (masks->rgc_vec.length () < nvectors)
1330 masks->rgc_vec.safe_grow_cleared (nvectors, true);
1331 rgroup_controls *rgm = &(*masks).rgc_vec[nvectors - 1];
1332 /* The number of scalars per iteration and the number of vectors are
1333 both compile-time constants. */
1334 unsigned int nscalars_per_iter
1335 = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
1336 LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
1337
1338 if (rgm->max_nscalars_per_iter < nscalars_per_iter)
1339 {
1340 rgm->max_nscalars_per_iter = nscalars_per_iter;
1341 rgm->type = truth_type_for (vectype);
1342 rgm->factor = 1;
1343 }
1344 }
1345
1346 unsigned int max_nscalars_per_iter
1347 = vect_get_max_nscalars_per_iter (loop_vinfo);
1348
1349 /* Work out how many bits we need to represent the limit. */
1350 min_ni_width
1351 = vect_min_prec_for_max_niters (loop_vinfo, max_nscalars_per_iter);
1352
1353 /* Find a scalar mode for which WHILE_ULT is supported. */
1354 opt_scalar_int_mode cmp_mode_iter;
1355 tree cmp_type = NULL_TREE;
1356 tree iv_type = NULL_TREE;
1357 widest_int iv_limit = vect_iv_limit_for_partial_vectors (loop_vinfo);
1358 unsigned int iv_precision = UINT_MAX;
1359
1360 if (iv_limit != -1)
1361 iv_precision = wi::min_precision (iv_limit * max_nscalars_per_iter,
1362 UNSIGNED);
1363
1364 FOR_EACH_MODE_IN_CLASS (cmp_mode_iter, MODE_INT)
1365 {
1366 unsigned int cmp_bits = GET_MODE_BITSIZE (cmp_mode_iter.require ());
1367 if (cmp_bits >= min_ni_width
1368 && targetm.scalar_mode_supported_p (cmp_mode_iter.require ()))
1369 {
1370 tree this_type = build_nonstandard_integer_type (cmp_bits, true);
1371 if (this_type
1372 && can_produce_all_loop_masks_p (loop_vinfo, this_type))
1373 {
1374 /* Although we could stop as soon as we find a valid mode,
1375 there are at least two reasons why that's not always the
1376 best choice:
1377
1378 - An IV that's Pmode or wider is more likely to be reusable
1379 in address calculations than an IV that's narrower than
1380 Pmode.
1381
1382 - Doing the comparison in IV_PRECISION or wider allows
1383 a natural 0-based IV, whereas using a narrower comparison
1384 type requires mitigations against wrap-around.
1385
1386 Conversely, if the IV limit is variable, doing the comparison
1387 in a wider type than the original type can introduce
1388 unnecessary extensions, so picking the widest valid mode
1389 is not always a good choice either.
1390
1391 Here we prefer the first IV type that's Pmode or wider,
1392 and the first comparison type that's IV_PRECISION or wider.
1393 (The comparison type must be no wider than the IV type,
1394 to avoid extensions in the vector loop.)
1395
1396 ??? We might want to try continuing beyond Pmode for ILP32
1397 targets if CMP_BITS < IV_PRECISION. */
1398 iv_type = this_type;
1399 if (!cmp_type || iv_precision > TYPE_PRECISION (cmp_type))
1400 cmp_type = this_type;
1401 if (cmp_bits >= GET_MODE_BITSIZE (Pmode))
1402 break;
1403 }
1404 }
1405 }
1406
1407 if (!cmp_type)
1408 {
1409 LOOP_VINFO_MASKS (loop_vinfo).rgc_vec.release ();
1410 return false;
1411 }
1412
1413 LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo) = cmp_type;
1414 LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo) = iv_type;
1415 LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) = vect_partial_vectors_while_ult;
1416 return true;
1417 }
1418
1419 /* Each statement in LOOP_VINFO can be masked where necessary. Check
1420 whether we can actually generate AVX512 style masks. Return true if so,
1421 storing the type of the scalar IV in LOOP_VINFO_RGROUP_IV_TYPE. */
1422
1423 static bool
1424 vect_verify_full_masking_avx512 (loop_vec_info loop_vinfo)
1425 {
1426 /* Produce differently organized rgc_vec and differently check
1427 we can produce masks. */
1428
1429 /* Use a normal loop if there are no statements that need masking.
1430 This only happens in rare degenerate cases: it means that the loop
1431 has no loads, no stores, and no live-out values. */
1432 if (LOOP_VINFO_MASKS (loop_vinfo).is_empty ())
1433 return false;
1434
1435 /* For the decrementing IV we need to represent all values in
1436 [0, niter + niter_skip] where niter_skip is the elements we
1437 skip in the first iteration for prologue peeling. */
1438 tree iv_type = NULL_TREE;
1439 widest_int iv_limit = vect_iv_limit_for_partial_vectors (loop_vinfo);
1440 unsigned int iv_precision = UINT_MAX;
1441 if (iv_limit != -1)
1442 iv_precision = wi::min_precision (iv_limit, UNSIGNED);
1443
1444 /* First compute the type for the IV we use to track the remaining
1445 scalar iterations. */
1446 opt_scalar_int_mode cmp_mode_iter;
1447 FOR_EACH_MODE_IN_CLASS (cmp_mode_iter, MODE_INT)
1448 {
1449 unsigned int cmp_bits = GET_MODE_BITSIZE (cmp_mode_iter.require ());
1450 if (cmp_bits >= iv_precision
1451 && targetm.scalar_mode_supported_p (cmp_mode_iter.require ()))
1452 {
1453 iv_type = build_nonstandard_integer_type (cmp_bits, true);
1454 if (iv_type)
1455 break;
1456 }
1457 }
1458 if (!iv_type)
1459 return false;
1460
1461 /* Produce the rgroup controls. */
1462 for (auto const &mask : LOOP_VINFO_MASKS (loop_vinfo).mask_set)
1463 {
1464 vec_loop_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
1465 tree vectype = mask.first;
1466 unsigned nvectors = mask.second;
1467
1468 /* The number of scalars per iteration and the number of vectors are
1469 both compile-time constants. */
1470 unsigned int nscalars_per_iter
1471 = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
1472 LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
1473
1474 /* We index the rgroup_controls vector with nscalars_per_iter
1475 which we keep constant and instead have a varying nvectors,
1476 remembering the vector mask with the fewest nV. */
1477 if (masks->rgc_vec.length () < nscalars_per_iter)
1478 masks->rgc_vec.safe_grow_cleared (nscalars_per_iter, true);
1479 rgroup_controls *rgm = &(*masks).rgc_vec[nscalars_per_iter - 1];
1480
1481 if (!rgm->type || rgm->factor > nvectors)
1482 {
1483 rgm->type = truth_type_for (vectype);
1484 rgm->compare_type = NULL_TREE;
1485 rgm->max_nscalars_per_iter = nscalars_per_iter;
1486 rgm->factor = nvectors;
1487 rgm->bias_adjusted_ctrl = NULL_TREE;
1488 }
1489 }
1490
1491 /* There is no fixed compare type we are going to use but we have to
1492 be able to get at one for each mask group. */
1493 unsigned int min_ni_width
1494 = wi::min_precision (vect_max_vf (loop_vinfo), UNSIGNED);
1495
1496 bool ok = true;
1497 for (auto &rgc : LOOP_VINFO_MASKS (loop_vinfo).rgc_vec)
1498 {
1499 tree mask_type = rgc.type;
1500 if (!mask_type)
1501 continue;
1502
1503 /* For now vect_get_loop_mask only supports integer mode masks
1504 when we need to split it. */
1505 if (GET_MODE_CLASS (TYPE_MODE (mask_type)) != MODE_INT
1506 || TYPE_PRECISION (TREE_TYPE (mask_type)) != 1)
1507 {
1508 ok = false;
1509 break;
1510 }
1511
1512 /* If iv_type is usable as compare type use that - we can elide the
1513 saturation in that case. */
1514 if (TYPE_PRECISION (iv_type) >= min_ni_width)
1515 {
1516 tree cmp_vectype
1517 = build_vector_type (iv_type, TYPE_VECTOR_SUBPARTS (mask_type));
1518 if (expand_vec_cmp_expr_p (cmp_vectype, mask_type, LT_EXPR))
1519 rgc.compare_type = cmp_vectype;
1520 }
1521 if (!rgc.compare_type)
1522 FOR_EACH_MODE_IN_CLASS (cmp_mode_iter, MODE_INT)
1523 {
1524 unsigned int cmp_bits = GET_MODE_BITSIZE (cmp_mode_iter.require ());
1525 if (cmp_bits >= min_ni_width
1526 && targetm.scalar_mode_supported_p (cmp_mode_iter.require ()))
1527 {
1528 tree cmp_type = build_nonstandard_integer_type (cmp_bits, true);
1529 if (!cmp_type)
1530 continue;
1531
1532 /* Check whether we can produce the mask with cmp_type. */
1533 tree cmp_vectype
1534 = build_vector_type (cmp_type, TYPE_VECTOR_SUBPARTS (mask_type));
1535 if (expand_vec_cmp_expr_p (cmp_vectype, mask_type, LT_EXPR))
1536 {
1537 rgc.compare_type = cmp_vectype;
1538 break;
1539 }
1540 }
1541 }
1542 if (!rgc.compare_type)
1543 {
1544 ok = false;
1545 break;
1546 }
1547 }
1548 if (!ok)
1549 {
1550 release_vec_loop_controls (&LOOP_VINFO_MASKS (loop_vinfo).rgc_vec);
1551 return false;
1552 }
1553
1554 LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo) = error_mark_node;
1555 LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo) = iv_type;
1556 LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) = vect_partial_vectors_avx512;
1557 return true;
1558 }
1559
1560 /* Check whether we can use vector access with length based on precison
1561 comparison. So far, to keep it simple, we only allow the case that the
1562 precision of the target supported length is larger than the precision
1563 required by loop niters. */
1564
1565 static bool
1566 vect_verify_loop_lens (loop_vec_info loop_vinfo)
1567 {
1568 if (LOOP_VINFO_LENS (loop_vinfo).is_empty ())
1569 return false;
1570
1571 if (!VECTOR_MODE_P (loop_vinfo->vector_mode))
1572 return false;
1573
1574 machine_mode len_load_mode, len_store_mode;
1575 if (!get_len_load_store_mode (loop_vinfo->vector_mode, true)
1576 .exists (&len_load_mode))
1577 return false;
1578 if (!get_len_load_store_mode (loop_vinfo->vector_mode, false)
1579 .exists (&len_store_mode))
1580 return false;
1581
1582 signed char partial_load_bias = internal_len_load_store_bias
1583 (IFN_LEN_LOAD, len_load_mode);
1584
1585 signed char partial_store_bias = internal_len_load_store_bias
1586 (IFN_LEN_STORE, len_store_mode);
1587
1588 gcc_assert (partial_load_bias == partial_store_bias);
1589
1590 if (partial_load_bias == VECT_PARTIAL_BIAS_UNSUPPORTED)
1591 return false;
1592
1593 /* If the backend requires a bias of -1 for LEN_LOAD, we must not emit
1594 len_loads with a length of zero. In order to avoid that we prohibit
1595 more than one loop length here. */
1596 if (partial_load_bias == -1
1597 && LOOP_VINFO_LENS (loop_vinfo).length () > 1)
1598 return false;
1599
1600 LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo) = partial_load_bias;
1601
1602 unsigned int max_nitems_per_iter = 1;
1603 unsigned int i;
1604 rgroup_controls *rgl;
1605 /* Find the maximum number of items per iteration for every rgroup. */
1606 FOR_EACH_VEC_ELT (LOOP_VINFO_LENS (loop_vinfo), i, rgl)
1607 {
1608 unsigned nitems_per_iter = rgl->max_nscalars_per_iter * rgl->factor;
1609 max_nitems_per_iter = MAX (max_nitems_per_iter, nitems_per_iter);
1610 }
1611
1612 /* Work out how many bits we need to represent the length limit. */
1613 unsigned int min_ni_prec
1614 = vect_min_prec_for_max_niters (loop_vinfo, max_nitems_per_iter);
1615
1616 /* Now use the maximum of below precisions for one suitable IV type:
1617 - the IV's natural precision
1618 - the precision needed to hold: the maximum number of scalar
1619 iterations multiplied by the scale factor (min_ni_prec above)
1620 - the Pmode precision
1621
1622 If min_ni_prec is less than the precision of the current niters,
1623 we perfer to still use the niters type. Prefer to use Pmode and
1624 wider IV to avoid narrow conversions. */
1625
1626 unsigned int ni_prec
1627 = TYPE_PRECISION (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)));
1628 min_ni_prec = MAX (min_ni_prec, ni_prec);
1629 min_ni_prec = MAX (min_ni_prec, GET_MODE_BITSIZE (Pmode));
1630
1631 tree iv_type = NULL_TREE;
1632 opt_scalar_int_mode tmode_iter;
1633 FOR_EACH_MODE_IN_CLASS (tmode_iter, MODE_INT)
1634 {
1635 scalar_mode tmode = tmode_iter.require ();
1636 unsigned int tbits = GET_MODE_BITSIZE (tmode);
1637
1638 /* ??? Do we really want to construct one IV whose precision exceeds
1639 BITS_PER_WORD? */
1640 if (tbits > BITS_PER_WORD)
1641 break;
1642
1643 /* Find the first available standard integral type. */
1644 if (tbits >= min_ni_prec && targetm.scalar_mode_supported_p (tmode))
1645 {
1646 iv_type = build_nonstandard_integer_type (tbits, true);
1647 break;
1648 }
1649 }
1650
1651 if (!iv_type)
1652 {
1653 if (dump_enabled_p ())
1654 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1655 "can't vectorize with length-based partial vectors"
1656 " because there is no suitable iv type.\n");
1657 return false;
1658 }
1659
1660 LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo) = iv_type;
1661 LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo) = iv_type;
1662 LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) = vect_partial_vectors_len;
1663
1664 return true;
1665 }
1666
1667 /* Calculate the cost of one scalar iteration of the loop. */
1668 static void
1669 vect_compute_single_scalar_iteration_cost (loop_vec_info loop_vinfo)
1670 {
1671 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1672 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1673 int nbbs = loop->num_nodes, factor;
1674 int innerloop_iters, i;
1675
1676 DUMP_VECT_SCOPE ("vect_compute_single_scalar_iteration_cost");
1677
1678 /* Gather costs for statements in the scalar loop. */
1679
1680 /* FORNOW. */
1681 innerloop_iters = 1;
1682 if (loop->inner)
1683 innerloop_iters = LOOP_VINFO_INNER_LOOP_COST_FACTOR (loop_vinfo);
1684
1685 for (i = 0; i < nbbs; i++)
1686 {
1687 gimple_stmt_iterator si;
1688 basic_block bb = bbs[i];
1689
1690 if (bb->loop_father == loop->inner)
1691 factor = innerloop_iters;
1692 else
1693 factor = 1;
1694
1695 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1696 {
1697 gimple *stmt = gsi_stmt (si);
1698 stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (stmt);
1699
1700 if (!is_gimple_assign (stmt)
1701 && !is_gimple_call (stmt)
1702 && !is_a<gcond *> (stmt))
1703 continue;
1704
1705 /* Skip stmts that are not vectorized inside the loop. */
1706 stmt_vec_info vstmt_info = vect_stmt_to_vectorize (stmt_info);
1707 if (!STMT_VINFO_RELEVANT_P (vstmt_info)
1708 && (!STMT_VINFO_LIVE_P (vstmt_info)
1709 || !VECTORIZABLE_CYCLE_DEF
1710 (STMT_VINFO_DEF_TYPE (vstmt_info))))
1711 continue;
1712
1713 vect_cost_for_stmt kind;
1714 if (STMT_VINFO_DATA_REF (stmt_info))
1715 {
1716 if (DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)))
1717 kind = scalar_load;
1718 else
1719 kind = scalar_store;
1720 }
1721 else if (vect_nop_conversion_p (stmt_info))
1722 continue;
1723 else
1724 kind = scalar_stmt;
1725
1726 /* We are using vect_prologue here to avoid scaling twice
1727 by the inner loop factor. */
1728 record_stmt_cost (&LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo),
1729 factor, kind, stmt_info, 0, vect_prologue);
1730 }
1731 }
1732
1733 /* Now accumulate cost. */
1734 loop_vinfo->scalar_costs = init_cost (loop_vinfo, true);
1735 add_stmt_costs (loop_vinfo->scalar_costs,
1736 &LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo));
1737 loop_vinfo->scalar_costs->finish_cost (nullptr);
1738 }
1739
1740 /* Function vect_analyze_loop_form.
1741
1742 Verify that certain CFG restrictions hold, including:
1743 - the loop has a pre-header
1744 - the loop has a single entry
1745 - nested loops can have only a single exit.
1746 - the loop exit condition is simple enough
1747 - the number of iterations can be analyzed, i.e, a countable loop. The
1748 niter could be analyzed under some assumptions. */
1749
1750 opt_result
1751 vect_analyze_loop_form (class loop *loop, gimple *loop_vectorized_call,
1752 vect_loop_form_info *info)
1753 {
1754 DUMP_VECT_SCOPE ("vect_analyze_loop_form");
1755
1756 edge exit_e = vec_init_loop_exit_info (loop);
1757 if (!exit_e)
1758 return opt_result::failure_at (vect_location,
1759 "not vectorized:"
1760 " could not determine main exit from"
1761 " loop with multiple exits.\n");
1762 if (loop_vectorized_call)
1763 {
1764 tree arg = gimple_call_arg (loop_vectorized_call, 1);
1765 class loop *scalar_loop = get_loop (cfun, tree_to_shwi (arg));
1766 edge scalar_exit_e = vec_init_loop_exit_info (scalar_loop);
1767 if (!scalar_exit_e)
1768 return opt_result::failure_at (vect_location,
1769 "not vectorized:"
1770 " could not determine main exit from"
1771 " loop with multiple exits.\n");
1772 }
1773
1774 info->loop_exit = exit_e;
1775 if (dump_enabled_p ())
1776 dump_printf_loc (MSG_NOTE, vect_location,
1777 "using as main loop exit: %d -> %d [AUX: %p]\n",
1778 exit_e->src->index, exit_e->dest->index, exit_e->aux);
1779
1780 /* Check if we have any control flow that doesn't leave the loop. */
1781 basic_block *bbs = get_loop_body (loop);
1782 for (unsigned i = 0; i < loop->num_nodes; i++)
1783 if (EDGE_COUNT (bbs[i]->succs) != 1
1784 && (EDGE_COUNT (bbs[i]->succs) != 2
1785 || !loop_exits_from_bb_p (bbs[i]->loop_father, bbs[i])))
1786 {
1787 free (bbs);
1788 return opt_result::failure_at (vect_location,
1789 "not vectorized:"
1790 " unsupported control flow in loop.\n");
1791 }
1792 free (bbs);
1793
1794 /* Different restrictions apply when we are considering an inner-most loop,
1795 vs. an outer (nested) loop.
1796 (FORNOW. May want to relax some of these restrictions in the future). */
1797
1798 info->inner_loop_cond = NULL;
1799 if (!loop->inner)
1800 {
1801 /* Inner-most loop. */
1802
1803 if (empty_block_p (loop->header))
1804 return opt_result::failure_at (vect_location,
1805 "not vectorized: empty loop.\n");
1806 }
1807 else
1808 {
1809 class loop *innerloop = loop->inner;
1810 edge entryedge;
1811
1812 /* Nested loop. We currently require that the loop is doubly-nested,
1813 contains a single inner loop with a single exit to the block
1814 with the single exit condition in the outer loop.
1815 Vectorizable outer-loops look like this:
1816
1817 (pre-header)
1818 |
1819 header <---+
1820 | |
1821 inner-loop |
1822 | |
1823 tail ------+
1824 |
1825 (exit-bb)
1826
1827 The inner-loop also has the properties expected of inner-most loops
1828 as described above. */
1829
1830 if ((loop->inner)->inner || (loop->inner)->next)
1831 return opt_result::failure_at (vect_location,
1832 "not vectorized:"
1833 " multiple nested loops.\n");
1834
1835 entryedge = loop_preheader_edge (innerloop);
1836 if (entryedge->src != loop->header
1837 || !single_exit (innerloop)
1838 || single_exit (innerloop)->dest != EDGE_PRED (loop->latch, 0)->src)
1839 return opt_result::failure_at (vect_location,
1840 "not vectorized:"
1841 " unsupported outerloop form.\n");
1842
1843 /* Analyze the inner-loop. */
1844 vect_loop_form_info inner;
1845 opt_result res = vect_analyze_loop_form (loop->inner, NULL, &inner);
1846 if (!res)
1847 {
1848 if (dump_enabled_p ())
1849 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1850 "not vectorized: Bad inner loop.\n");
1851 return res;
1852 }
1853
1854 /* Don't support analyzing niter under assumptions for inner
1855 loop. */
1856 if (!integer_onep (inner.assumptions))
1857 return opt_result::failure_at (vect_location,
1858 "not vectorized: Bad inner loop.\n");
1859
1860 if (!expr_invariant_in_loop_p (loop, inner.number_of_iterations))
1861 return opt_result::failure_at (vect_location,
1862 "not vectorized: inner-loop count not"
1863 " invariant.\n");
1864
1865 if (dump_enabled_p ())
1866 dump_printf_loc (MSG_NOTE, vect_location,
1867 "Considering outer-loop vectorization.\n");
1868 info->inner_loop_cond = inner.conds[0];
1869 }
1870
1871 if (EDGE_COUNT (loop->header->preds) != 2)
1872 return opt_result::failure_at (vect_location,
1873 "not vectorized:"
1874 " too many incoming edges.\n");
1875
1876 /* We assume that the latch is empty. */
1877 basic_block latch = loop->latch;
1878 do
1879 {
1880 if (!empty_block_p (latch)
1881 || !gimple_seq_empty_p (phi_nodes (latch)))
1882 return opt_result::failure_at (vect_location,
1883 "not vectorized: latch block not "
1884 "empty.\n");
1885 latch = single_pred (latch);
1886 }
1887 while (single_succ_p (latch));
1888
1889 /* Make sure there is no abnormal exit. */
1890 auto_vec<edge> exits = get_loop_exit_edges (loop);
1891 for (edge e : exits)
1892 {
1893 if (e->flags & EDGE_ABNORMAL)
1894 return opt_result::failure_at (vect_location,
1895 "not vectorized:"
1896 " abnormal loop exit edge.\n");
1897 }
1898
1899 info->conds
1900 = vect_get_loop_niters (loop, exit_e, &info->assumptions,
1901 &info->number_of_iterations,
1902 &info->number_of_iterationsm1);
1903 if (info->conds.is_empty ())
1904 return opt_result::failure_at
1905 (vect_location,
1906 "not vectorized: complicated exit condition.\n");
1907
1908 /* Determine what the primary and alternate exit conds are. */
1909 for (unsigned i = 0; i < info->conds.length (); i++)
1910 {
1911 gcond *cond = info->conds[i];
1912 if (exit_e->src == gimple_bb (cond))
1913 std::swap (info->conds[0], info->conds[i]);
1914 }
1915
1916 if (integer_zerop (info->assumptions)
1917 || !info->number_of_iterations
1918 || chrec_contains_undetermined (info->number_of_iterations))
1919 return opt_result::failure_at
1920 (info->conds[0],
1921 "not vectorized: number of iterations cannot be computed.\n");
1922
1923 if (integer_zerop (info->number_of_iterations))
1924 return opt_result::failure_at
1925 (info->conds[0],
1926 "not vectorized: number of iterations = 0.\n");
1927
1928 if (!(tree_fits_shwi_p (info->number_of_iterations)
1929 && tree_to_shwi (info->number_of_iterations) > 0))
1930 {
1931 if (dump_enabled_p ())
1932 {
1933 dump_printf_loc (MSG_NOTE, vect_location,
1934 "Symbolic number of iterations is ");
1935 dump_generic_expr (MSG_NOTE, TDF_DETAILS, info->number_of_iterations);
1936 dump_printf (MSG_NOTE, "\n");
1937 }
1938 }
1939
1940 return opt_result::success ();
1941 }
1942
1943 /* Create a loop_vec_info for LOOP with SHARED and the
1944 vect_analyze_loop_form result. */
1945
1946 loop_vec_info
1947 vect_create_loop_vinfo (class loop *loop, vec_info_shared *shared,
1948 const vect_loop_form_info *info,
1949 loop_vec_info orig_loop_info)
1950 {
1951 loop_vec_info loop_vinfo = new _loop_vec_info (loop, shared);
1952 LOOP_VINFO_NITERSM1 (loop_vinfo) = info->number_of_iterationsm1;
1953 LOOP_VINFO_NITERS (loop_vinfo) = info->number_of_iterations;
1954 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = info->number_of_iterations;
1955 LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo) = orig_loop_info;
1956 if (orig_loop_info && LOOP_VINFO_EPILOGUE_P (orig_loop_info))
1957 LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo)
1958 = LOOP_VINFO_MAIN_LOOP_INFO (orig_loop_info);
1959 else
1960 LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo) = orig_loop_info;
1961 /* Also record the assumptions for versioning. */
1962 if (!integer_onep (info->assumptions) && !orig_loop_info)
1963 LOOP_VINFO_NITERS_ASSUMPTIONS (loop_vinfo) = info->assumptions;
1964
1965 for (gcond *cond : info->conds)
1966 {
1967 stmt_vec_info loop_cond_info = loop_vinfo->lookup_stmt (cond);
1968 STMT_VINFO_TYPE (loop_cond_info) = loop_exit_ctrl_vec_info_type;
1969 /* Mark the statement as a condition. */
1970 STMT_VINFO_DEF_TYPE (loop_cond_info) = vect_condition_def;
1971 }
1972
1973 for (unsigned i = 1; i < info->conds.length (); i ++)
1974 LOOP_VINFO_LOOP_CONDS (loop_vinfo).safe_push (info->conds[i]);
1975 LOOP_VINFO_LOOP_IV_COND (loop_vinfo) = info->conds[0];
1976
1977 LOOP_VINFO_IV_EXIT (loop_vinfo) = info->loop_exit;
1978
1979 /* Check to see if we're vectorizing multiple exits. */
1980 LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
1981 = !LOOP_VINFO_LOOP_CONDS (loop_vinfo).is_empty ();
1982
1983 if (info->inner_loop_cond)
1984 {
1985 stmt_vec_info inner_loop_cond_info
1986 = loop_vinfo->lookup_stmt (info->inner_loop_cond);
1987 STMT_VINFO_TYPE (inner_loop_cond_info) = loop_exit_ctrl_vec_info_type;
1988 /* If we have an estimate on the number of iterations of the inner
1989 loop use that to limit the scale for costing, otherwise use
1990 --param vect-inner-loop-cost-factor literally. */
1991 widest_int nit;
1992 if (estimated_stmt_executions (loop->inner, &nit))
1993 LOOP_VINFO_INNER_LOOP_COST_FACTOR (loop_vinfo)
1994 = wi::smin (nit, param_vect_inner_loop_cost_factor).to_uhwi ();
1995 }
1996
1997 return loop_vinfo;
1998 }
1999
2000
2001
2002 /* Scan the loop stmts and dependent on whether there are any (non-)SLP
2003 statements update the vectorization factor. */
2004
2005 static void
2006 vect_update_vf_for_slp (loop_vec_info loop_vinfo)
2007 {
2008 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
2009 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
2010 int nbbs = loop->num_nodes;
2011 poly_uint64 vectorization_factor;
2012 int i;
2013
2014 DUMP_VECT_SCOPE ("vect_update_vf_for_slp");
2015
2016 vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2017 gcc_assert (known_ne (vectorization_factor, 0U));
2018
2019 /* If all the stmts in the loop can be SLPed, we perform only SLP, and
2020 vectorization factor of the loop is the unrolling factor required by
2021 the SLP instances. If that unrolling factor is 1, we say, that we
2022 perform pure SLP on loop - cross iteration parallelism is not
2023 exploited. */
2024 bool only_slp_in_loop = true;
2025 for (i = 0; i < nbbs; i++)
2026 {
2027 basic_block bb = bbs[i];
2028 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
2029 gsi_next (&si))
2030 {
2031 stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (si.phi ());
2032 if (!stmt_info)
2033 continue;
2034 if ((STMT_VINFO_RELEVANT_P (stmt_info)
2035 || VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
2036 && !PURE_SLP_STMT (stmt_info))
2037 /* STMT needs both SLP and loop-based vectorization. */
2038 only_slp_in_loop = false;
2039 }
2040 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
2041 gsi_next (&si))
2042 {
2043 if (is_gimple_debug (gsi_stmt (si)))
2044 continue;
2045 stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (gsi_stmt (si));
2046 stmt_info = vect_stmt_to_vectorize (stmt_info);
2047 if ((STMT_VINFO_RELEVANT_P (stmt_info)
2048 || VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
2049 && !PURE_SLP_STMT (stmt_info))
2050 /* STMT needs both SLP and loop-based vectorization. */
2051 only_slp_in_loop = false;
2052 }
2053 }
2054
2055 if (only_slp_in_loop)
2056 {
2057 if (dump_enabled_p ())
2058 dump_printf_loc (MSG_NOTE, vect_location,
2059 "Loop contains only SLP stmts\n");
2060 vectorization_factor = LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo);
2061 }
2062 else
2063 {
2064 if (dump_enabled_p ())
2065 dump_printf_loc (MSG_NOTE, vect_location,
2066 "Loop contains SLP and non-SLP stmts\n");
2067 /* Both the vectorization factor and unroll factor have the form
2068 GET_MODE_SIZE (loop_vinfo->vector_mode) * X for some rational X,
2069 so they must have a common multiple. */
2070 vectorization_factor
2071 = force_common_multiple (vectorization_factor,
2072 LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo));
2073 }
2074
2075 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
2076 if (dump_enabled_p ())
2077 {
2078 dump_printf_loc (MSG_NOTE, vect_location,
2079 "Updating vectorization factor to ");
2080 dump_dec (MSG_NOTE, vectorization_factor);
2081 dump_printf (MSG_NOTE, ".\n");
2082 }
2083 }
2084
2085 /* Return true if STMT_INFO describes a double reduction phi and if
2086 the other phi in the reduction is also relevant for vectorization.
2087 This rejects cases such as:
2088
2089 outer1:
2090 x_1 = PHI <x_3(outer2), ...>;
2091 ...
2092
2093 inner:
2094 x_2 = ...;
2095 ...
2096
2097 outer2:
2098 x_3 = PHI <x_2(inner)>;
2099
2100 if nothing in x_2 or elsewhere makes x_1 relevant. */
2101
2102 static bool
2103 vect_active_double_reduction_p (stmt_vec_info stmt_info)
2104 {
2105 if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_double_reduction_def)
2106 return false;
2107
2108 return STMT_VINFO_RELEVANT_P (STMT_VINFO_REDUC_DEF (stmt_info));
2109 }
2110
2111 /* Function vect_analyze_loop_operations.
2112
2113 Scan the loop stmts and make sure they are all vectorizable. */
2114
2115 static opt_result
2116 vect_analyze_loop_operations (loop_vec_info loop_vinfo)
2117 {
2118 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
2119 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
2120 int nbbs = loop->num_nodes;
2121 int i;
2122 stmt_vec_info stmt_info;
2123 bool need_to_vectorize = false;
2124 bool ok;
2125
2126 DUMP_VECT_SCOPE ("vect_analyze_loop_operations");
2127
2128 auto_vec<stmt_info_for_cost> cost_vec;
2129
2130 for (i = 0; i < nbbs; i++)
2131 {
2132 basic_block bb = bbs[i];
2133
2134 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
2135 gsi_next (&si))
2136 {
2137 gphi *phi = si.phi ();
2138 ok = true;
2139
2140 stmt_info = loop_vinfo->lookup_stmt (phi);
2141 if (dump_enabled_p ())
2142 dump_printf_loc (MSG_NOTE, vect_location, "examining phi: %G",
2143 (gimple *) phi);
2144 if (virtual_operand_p (gimple_phi_result (phi)))
2145 continue;
2146
2147 /* Inner-loop loop-closed exit phi in outer-loop vectorization
2148 (i.e., a phi in the tail of the outer-loop). */
2149 if (! is_loop_header_bb_p (bb))
2150 {
2151 /* FORNOW: we currently don't support the case that these phis
2152 are not used in the outerloop (unless it is double reduction,
2153 i.e., this phi is vect_reduction_def), cause this case
2154 requires to actually do something here. */
2155 if (STMT_VINFO_LIVE_P (stmt_info)
2156 && !vect_active_double_reduction_p (stmt_info))
2157 return opt_result::failure_at (phi,
2158 "Unsupported loop-closed phi"
2159 " in outer-loop.\n");
2160
2161 /* If PHI is used in the outer loop, we check that its operand
2162 is defined in the inner loop. */
2163 if (STMT_VINFO_RELEVANT_P (stmt_info))
2164 {
2165 tree phi_op;
2166
2167 if (gimple_phi_num_args (phi) != 1)
2168 return opt_result::failure_at (phi, "unsupported phi");
2169
2170 phi_op = PHI_ARG_DEF (phi, 0);
2171 stmt_vec_info op_def_info = loop_vinfo->lookup_def (phi_op);
2172 if (!op_def_info)
2173 return opt_result::failure_at (phi, "unsupported phi\n");
2174
2175 if (STMT_VINFO_RELEVANT (op_def_info) != vect_used_in_outer
2176 && (STMT_VINFO_RELEVANT (op_def_info)
2177 != vect_used_in_outer_by_reduction))
2178 return opt_result::failure_at (phi, "unsupported phi\n");
2179
2180 if ((STMT_VINFO_DEF_TYPE (stmt_info) == vect_internal_def
2181 || (STMT_VINFO_DEF_TYPE (stmt_info)
2182 == vect_double_reduction_def))
2183 && ! PURE_SLP_STMT (stmt_info)
2184 && !vectorizable_lc_phi (loop_vinfo,
2185 stmt_info, NULL, NULL))
2186 return opt_result::failure_at (phi, "unsupported phi\n");
2187 }
2188
2189 continue;
2190 }
2191
2192 gcc_assert (stmt_info);
2193
2194 if ((STMT_VINFO_RELEVANT (stmt_info) == vect_used_in_scope
2195 || STMT_VINFO_LIVE_P (stmt_info))
2196 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_induction_def
2197 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_first_order_recurrence)
2198 /* A scalar-dependence cycle that we don't support. */
2199 return opt_result::failure_at (phi,
2200 "not vectorized:"
2201 " scalar dependence cycle.\n");
2202
2203 if (STMT_VINFO_RELEVANT_P (stmt_info))
2204 {
2205 need_to_vectorize = true;
2206 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def
2207 && ! PURE_SLP_STMT (stmt_info))
2208 ok = vectorizable_induction (loop_vinfo,
2209 stmt_info, NULL, NULL,
2210 &cost_vec);
2211 else if ((STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
2212 || (STMT_VINFO_DEF_TYPE (stmt_info)
2213 == vect_double_reduction_def)
2214 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle)
2215 && ! PURE_SLP_STMT (stmt_info))
2216 ok = vectorizable_reduction (loop_vinfo,
2217 stmt_info, NULL, NULL, &cost_vec);
2218 else if ((STMT_VINFO_DEF_TYPE (stmt_info)
2219 == vect_first_order_recurrence)
2220 && ! PURE_SLP_STMT (stmt_info))
2221 ok = vectorizable_recurr (loop_vinfo, stmt_info, NULL, NULL,
2222 &cost_vec);
2223 }
2224
2225 /* SLP PHIs are tested by vect_slp_analyze_node_operations. */
2226 if (ok
2227 && STMT_VINFO_LIVE_P (stmt_info)
2228 && !PURE_SLP_STMT (stmt_info))
2229 ok = vectorizable_live_operation (loop_vinfo, stmt_info, NULL, NULL,
2230 -1, false, &cost_vec);
2231
2232 if (!ok)
2233 return opt_result::failure_at (phi,
2234 "not vectorized: relevant phi not "
2235 "supported: %G",
2236 static_cast <gimple *> (phi));
2237 }
2238
2239 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
2240 gsi_next (&si))
2241 {
2242 gimple *stmt = gsi_stmt (si);
2243 if (!gimple_clobber_p (stmt)
2244 && !is_gimple_debug (stmt))
2245 {
2246 opt_result res
2247 = vect_analyze_stmt (loop_vinfo,
2248 loop_vinfo->lookup_stmt (stmt),
2249 &need_to_vectorize,
2250 NULL, NULL, &cost_vec);
2251 if (!res)
2252 return res;
2253 }
2254 }
2255 } /* bbs */
2256
2257 add_stmt_costs (loop_vinfo->vector_costs, &cost_vec);
2258
2259 /* All operations in the loop are either irrelevant (deal with loop
2260 control, or dead), or only used outside the loop and can be moved
2261 out of the loop (e.g. invariants, inductions). The loop can be
2262 optimized away by scalar optimizations. We're better off not
2263 touching this loop. */
2264 if (!need_to_vectorize)
2265 {
2266 if (dump_enabled_p ())
2267 dump_printf_loc (MSG_NOTE, vect_location,
2268 "All the computation can be taken out of the loop.\n");
2269 return opt_result::failure_at
2270 (vect_location,
2271 "not vectorized: redundant loop. no profit to vectorize.\n");
2272 }
2273
2274 return opt_result::success ();
2275 }
2276
2277 /* Return true if we know that the iteration count is smaller than the
2278 vectorization factor. Return false if it isn't, or if we can't be sure
2279 either way. */
2280
2281 static bool
2282 vect_known_niters_smaller_than_vf (loop_vec_info loop_vinfo)
2283 {
2284 unsigned int assumed_vf = vect_vf_for_cost (loop_vinfo);
2285
2286 HOST_WIDE_INT max_niter;
2287 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
2288 max_niter = LOOP_VINFO_INT_NITERS (loop_vinfo);
2289 else
2290 max_niter = max_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
2291
2292 if (max_niter != -1 && (unsigned HOST_WIDE_INT) max_niter < assumed_vf)
2293 return true;
2294
2295 return false;
2296 }
2297
2298 /* Analyze the cost of the loop described by LOOP_VINFO. Decide if it
2299 is worthwhile to vectorize. Return 1 if definitely yes, 0 if
2300 definitely no, or -1 if it's worth retrying. */
2301
2302 static int
2303 vect_analyze_loop_costing (loop_vec_info loop_vinfo,
2304 unsigned *suggested_unroll_factor)
2305 {
2306 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
2307 unsigned int assumed_vf = vect_vf_for_cost (loop_vinfo);
2308
2309 /* Only loops that can handle partially-populated vectors can have iteration
2310 counts less than the vectorization factor. */
2311 if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
2312 && vect_known_niters_smaller_than_vf (loop_vinfo))
2313 {
2314 if (dump_enabled_p ())
2315 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2316 "not vectorized: iteration count smaller than "
2317 "vectorization factor.\n");
2318 return 0;
2319 }
2320
2321 /* If we know the number of iterations we can do better, for the
2322 epilogue we can also decide whether the main loop leaves us
2323 with enough iterations, prefering a smaller vector epilog then
2324 also possibly used for the case we skip the vector loop. */
2325 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
2326 {
2327 widest_int scalar_niters
2328 = wi::to_widest (LOOP_VINFO_NITERSM1 (loop_vinfo)) + 1;
2329 if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
2330 {
2331 loop_vec_info orig_loop_vinfo
2332 = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
2333 loop_vec_info main_loop_vinfo
2334 = LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo);
2335 unsigned lowest_vf
2336 = constant_lower_bound (LOOP_VINFO_VECT_FACTOR (orig_loop_vinfo));
2337 int prolog_peeling = 0;
2338 if (!vect_use_loop_mask_for_alignment_p (main_loop_vinfo))
2339 prolog_peeling = LOOP_VINFO_PEELING_FOR_ALIGNMENT (main_loop_vinfo);
2340 if (prolog_peeling >= 0
2341 && known_eq (LOOP_VINFO_VECT_FACTOR (orig_loop_vinfo),
2342 lowest_vf))
2343 {
2344 unsigned gap
2345 = LOOP_VINFO_PEELING_FOR_GAPS (main_loop_vinfo) ? 1 : 0;
2346 scalar_niters = ((scalar_niters - gap - prolog_peeling)
2347 % lowest_vf + gap);
2348 }
2349 }
2350 /* Reject vectorizing for a single scalar iteration, even if
2351 we could in principle implement that using partial vectors. */
2352 unsigned peeling_gap = LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo);
2353 if (scalar_niters <= peeling_gap + 1)
2354 {
2355 if (dump_enabled_p ())
2356 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2357 "not vectorized: loop only has a single "
2358 "scalar iteration.\n");
2359 return 0;
2360 }
2361
2362 if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
2363 {
2364 /* Check that the loop processes at least one full vector. */
2365 poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2366 if (known_lt (scalar_niters, vf))
2367 {
2368 if (dump_enabled_p ())
2369 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2370 "loop does not have enough iterations "
2371 "to support vectorization.\n");
2372 return 0;
2373 }
2374
2375 /* If we need to peel an extra epilogue iteration to handle data
2376 accesses with gaps, check that there are enough scalar iterations
2377 available.
2378
2379 The check above is redundant with this one when peeling for gaps,
2380 but the distinction is useful for diagnostics. */
2381 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
2382 && known_le (scalar_niters, vf))
2383 {
2384 if (dump_enabled_p ())
2385 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2386 "loop does not have enough iterations "
2387 "to support peeling for gaps.\n");
2388 return 0;
2389 }
2390 }
2391 }
2392
2393 /* If using the "very cheap" model. reject cases in which we'd keep
2394 a copy of the scalar code (even if we might be able to vectorize it). */
2395 if (loop_cost_model (loop) == VECT_COST_MODEL_VERY_CHEAP
2396 && (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
2397 || LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)))
2398 {
2399 if (dump_enabled_p ())
2400 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2401 "some scalar iterations would need to be peeled\n");
2402 return 0;
2403 }
2404
2405 int min_profitable_iters, min_profitable_estimate;
2406 vect_estimate_min_profitable_iters (loop_vinfo, &min_profitable_iters,
2407 &min_profitable_estimate,
2408 suggested_unroll_factor);
2409
2410 if (min_profitable_iters < 0)
2411 {
2412 if (dump_enabled_p ())
2413 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2414 "not vectorized: vectorization not profitable.\n");
2415 if (dump_enabled_p ())
2416 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2417 "not vectorized: vector version will never be "
2418 "profitable.\n");
2419 return -1;
2420 }
2421
2422 int min_scalar_loop_bound = (param_min_vect_loop_bound
2423 * assumed_vf);
2424
2425 /* Use the cost model only if it is more conservative than user specified
2426 threshold. */
2427 unsigned int th = (unsigned) MAX (min_scalar_loop_bound,
2428 min_profitable_iters);
2429
2430 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = th;
2431
2432 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2433 && LOOP_VINFO_INT_NITERS (loop_vinfo) < th)
2434 {
2435 if (dump_enabled_p ())
2436 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2437 "not vectorized: vectorization not profitable.\n");
2438 if (dump_enabled_p ())
2439 dump_printf_loc (MSG_NOTE, vect_location,
2440 "not vectorized: iteration count smaller than user "
2441 "specified loop bound parameter or minimum profitable "
2442 "iterations (whichever is more conservative).\n");
2443 return 0;
2444 }
2445
2446 /* The static profitablity threshold min_profitable_estimate includes
2447 the cost of having to check at runtime whether the scalar loop
2448 should be used instead. If it turns out that we don't need or want
2449 such a check, the threshold we should use for the static estimate
2450 is simply the point at which the vector loop becomes more profitable
2451 than the scalar loop. */
2452 if (min_profitable_estimate > min_profitable_iters
2453 && !LOOP_REQUIRES_VERSIONING (loop_vinfo)
2454 && !LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
2455 && !LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
2456 && !vect_apply_runtime_profitability_check_p (loop_vinfo))
2457 {
2458 if (dump_enabled_p ())
2459 dump_printf_loc (MSG_NOTE, vect_location, "no need for a runtime"
2460 " choice between the scalar and vector loops\n");
2461 min_profitable_estimate = min_profitable_iters;
2462 }
2463
2464 /* If the vector loop needs multiple iterations to be beneficial then
2465 things are probably too close to call, and the conservative thing
2466 would be to stick with the scalar code. */
2467 if (loop_cost_model (loop) == VECT_COST_MODEL_VERY_CHEAP
2468 && min_profitable_estimate > (int) vect_vf_for_cost (loop_vinfo))
2469 {
2470 if (dump_enabled_p ())
2471 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2472 "one iteration of the vector loop would be"
2473 " more expensive than the equivalent number of"
2474 " iterations of the scalar loop\n");
2475 return 0;
2476 }
2477
2478 HOST_WIDE_INT estimated_niter;
2479
2480 /* If we are vectorizing an epilogue then we know the maximum number of
2481 scalar iterations it will cover is at least one lower than the
2482 vectorization factor of the main loop. */
2483 if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
2484 estimated_niter
2485 = vect_vf_for_cost (LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo)) - 1;
2486 else
2487 {
2488 estimated_niter = estimated_stmt_executions_int (loop);
2489 if (estimated_niter == -1)
2490 estimated_niter = likely_max_stmt_executions_int (loop);
2491 }
2492 if (estimated_niter != -1
2493 && ((unsigned HOST_WIDE_INT) estimated_niter
2494 < MAX (th, (unsigned) min_profitable_estimate)))
2495 {
2496 if (dump_enabled_p ())
2497 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2498 "not vectorized: estimated iteration count too "
2499 "small.\n");
2500 if (dump_enabled_p ())
2501 dump_printf_loc (MSG_NOTE, vect_location,
2502 "not vectorized: estimated iteration count smaller "
2503 "than specified loop bound parameter or minimum "
2504 "profitable iterations (whichever is more "
2505 "conservative).\n");
2506 return -1;
2507 }
2508
2509 return 1;
2510 }
2511
2512 static opt_result
2513 vect_get_datarefs_in_loop (loop_p loop, basic_block *bbs,
2514 vec<data_reference_p> *datarefs)
2515 {
2516 for (unsigned i = 0; i < loop->num_nodes; i++)
2517 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
2518 !gsi_end_p (gsi); gsi_next (&gsi))
2519 {
2520 gimple *stmt = gsi_stmt (gsi);
2521 if (is_gimple_debug (stmt))
2522 continue;
2523 opt_result res = vect_find_stmt_data_reference (loop, stmt, datarefs,
2524 NULL, 0);
2525 if (!res)
2526 {
2527 if (is_gimple_call (stmt) && loop->safelen)
2528 {
2529 tree fndecl = gimple_call_fndecl (stmt), op;
2530 if (fndecl == NULL_TREE
2531 && gimple_call_internal_p (stmt, IFN_MASK_CALL))
2532 {
2533 fndecl = gimple_call_arg (stmt, 0);
2534 gcc_checking_assert (TREE_CODE (fndecl) == ADDR_EXPR);
2535 fndecl = TREE_OPERAND (fndecl, 0);
2536 gcc_checking_assert (TREE_CODE (fndecl) == FUNCTION_DECL);
2537 }
2538 if (fndecl != NULL_TREE)
2539 {
2540 cgraph_node *node = cgraph_node::get (fndecl);
2541 if (node != NULL && node->simd_clones != NULL)
2542 {
2543 unsigned int j, n = gimple_call_num_args (stmt);
2544 for (j = 0; j < n; j++)
2545 {
2546 op = gimple_call_arg (stmt, j);
2547 if (DECL_P (op)
2548 || (REFERENCE_CLASS_P (op)
2549 && get_base_address (op)))
2550 break;
2551 }
2552 op = gimple_call_lhs (stmt);
2553 /* Ignore #pragma omp declare simd functions
2554 if they don't have data references in the
2555 call stmt itself. */
2556 if (j == n
2557 && !(op
2558 && (DECL_P (op)
2559 || (REFERENCE_CLASS_P (op)
2560 && get_base_address (op)))))
2561 continue;
2562 }
2563 }
2564 }
2565 return res;
2566 }
2567 /* If dependence analysis will give up due to the limit on the
2568 number of datarefs stop here and fail fatally. */
2569 if (datarefs->length ()
2570 > (unsigned)param_loop_max_datarefs_for_datadeps)
2571 return opt_result::failure_at (stmt, "exceeded param "
2572 "loop-max-datarefs-for-datadeps\n");
2573 }
2574 return opt_result::success ();
2575 }
2576
2577 /* Look for SLP-only access groups and turn each individual access into its own
2578 group. */
2579 static void
2580 vect_dissolve_slp_only_groups (loop_vec_info loop_vinfo)
2581 {
2582 unsigned int i;
2583 struct data_reference *dr;
2584
2585 DUMP_VECT_SCOPE ("vect_dissolve_slp_only_groups");
2586
2587 vec<data_reference_p> datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
2588 FOR_EACH_VEC_ELT (datarefs, i, dr)
2589 {
2590 gcc_assert (DR_REF (dr));
2591 stmt_vec_info stmt_info
2592 = vect_stmt_to_vectorize (loop_vinfo->lookup_stmt (DR_STMT (dr)));
2593
2594 /* Check if the load is a part of an interleaving chain. */
2595 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
2596 {
2597 stmt_vec_info first_element = DR_GROUP_FIRST_ELEMENT (stmt_info);
2598 dr_vec_info *dr_info = STMT_VINFO_DR_INFO (first_element);
2599 unsigned int group_size = DR_GROUP_SIZE (first_element);
2600
2601 /* Check if SLP-only groups. */
2602 if (!STMT_SLP_TYPE (stmt_info)
2603 && STMT_VINFO_SLP_VECT_ONLY (first_element))
2604 {
2605 /* Dissolve the group. */
2606 STMT_VINFO_SLP_VECT_ONLY (first_element) = false;
2607
2608 stmt_vec_info vinfo = first_element;
2609 while (vinfo)
2610 {
2611 stmt_vec_info next = DR_GROUP_NEXT_ELEMENT (vinfo);
2612 DR_GROUP_FIRST_ELEMENT (vinfo) = vinfo;
2613 DR_GROUP_NEXT_ELEMENT (vinfo) = NULL;
2614 DR_GROUP_SIZE (vinfo) = 1;
2615 if (STMT_VINFO_STRIDED_P (first_element)
2616 /* We cannot handle stores with gaps. */
2617 || DR_IS_WRITE (dr_info->dr))
2618 {
2619 STMT_VINFO_STRIDED_P (vinfo) = true;
2620 DR_GROUP_GAP (vinfo) = 0;
2621 }
2622 else
2623 DR_GROUP_GAP (vinfo) = group_size - 1;
2624 /* Duplicate and adjust alignment info, it needs to
2625 be present on each group leader, see dr_misalignment. */
2626 if (vinfo != first_element)
2627 {
2628 dr_vec_info *dr_info2 = STMT_VINFO_DR_INFO (vinfo);
2629 dr_info2->target_alignment = dr_info->target_alignment;
2630 int misalignment = dr_info->misalignment;
2631 if (misalignment != DR_MISALIGNMENT_UNKNOWN)
2632 {
2633 HOST_WIDE_INT diff
2634 = (TREE_INT_CST_LOW (DR_INIT (dr_info2->dr))
2635 - TREE_INT_CST_LOW (DR_INIT (dr_info->dr)));
2636 unsigned HOST_WIDE_INT align_c
2637 = dr_info->target_alignment.to_constant ();
2638 misalignment = (misalignment + diff) % align_c;
2639 }
2640 dr_info2->misalignment = misalignment;
2641 }
2642 vinfo = next;
2643 }
2644 }
2645 }
2646 }
2647 }
2648
2649 /* Determine if operating on full vectors for LOOP_VINFO might leave
2650 some scalar iterations still to do. If so, decide how we should
2651 handle those scalar iterations. The possibilities are:
2652
2653 (1) Make LOOP_VINFO operate on partial vectors instead of full vectors.
2654 In this case:
2655
2656 LOOP_VINFO_USING_PARTIAL_VECTORS_P == true
2657 LOOP_VINFO_EPIL_USING_PARTIAL_VECTORS_P == false
2658 LOOP_VINFO_PEELING_FOR_NITER == false
2659
2660 (2) Make LOOP_VINFO operate on full vectors and use an epilogue loop
2661 to handle the remaining scalar iterations. In this case:
2662
2663 LOOP_VINFO_USING_PARTIAL_VECTORS_P == false
2664 LOOP_VINFO_PEELING_FOR_NITER == true
2665
2666 There are two choices:
2667
2668 (2a) Consider vectorizing the epilogue loop at the same VF as the
2669 main loop, but using partial vectors instead of full vectors.
2670 In this case:
2671
2672 LOOP_VINFO_EPIL_USING_PARTIAL_VECTORS_P == true
2673
2674 (2b) Consider vectorizing the epilogue loop at lower VFs only.
2675 In this case:
2676
2677 LOOP_VINFO_EPIL_USING_PARTIAL_VECTORS_P == false
2678 */
2679
2680 opt_result
2681 vect_determine_partial_vectors_and_peeling (loop_vec_info loop_vinfo)
2682 {
2683 /* Determine whether there would be any scalar iterations left over. */
2684 bool need_peeling_or_partial_vectors_p
2685 = vect_need_peeling_or_partial_vectors_p (loop_vinfo);
2686
2687 /* Decide whether to vectorize the loop with partial vectors. */
2688 LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = false;
2689 LOOP_VINFO_EPIL_USING_PARTIAL_VECTORS_P (loop_vinfo) = false;
2690 if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
2691 && LOOP_VINFO_MUST_USE_PARTIAL_VECTORS_P (loop_vinfo))
2692 LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = true;
2693 else if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
2694 && need_peeling_or_partial_vectors_p)
2695 {
2696 /* For partial-vector-usage=1, try to push the handling of partial
2697 vectors to the epilogue, with the main loop continuing to operate
2698 on full vectors.
2699
2700 If we are unrolling we also do not want to use partial vectors. This
2701 is to avoid the overhead of generating multiple masks and also to
2702 avoid having to execute entire iterations of FALSE masked instructions
2703 when dealing with one or less full iterations.
2704
2705 ??? We could then end up failing to use partial vectors if we
2706 decide to peel iterations into a prologue, and if the main loop
2707 then ends up processing fewer than VF iterations. */
2708 if ((param_vect_partial_vector_usage == 1
2709 || loop_vinfo->suggested_unroll_factor > 1)
2710 && !LOOP_VINFO_EPILOGUE_P (loop_vinfo)
2711 && !vect_known_niters_smaller_than_vf (loop_vinfo))
2712 LOOP_VINFO_EPIL_USING_PARTIAL_VECTORS_P (loop_vinfo) = true;
2713 else
2714 LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = true;
2715 }
2716
2717 if (LOOP_VINFO_MUST_USE_PARTIAL_VECTORS_P (loop_vinfo)
2718 && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
2719 return opt_result::failure_at (vect_location,
2720 "not vectorized: loop needs but cannot "
2721 "use partial vectors\n");
2722
2723 if (dump_enabled_p ())
2724 dump_printf_loc (MSG_NOTE, vect_location,
2725 "operating on %s vectors%s.\n",
2726 LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
2727 ? "partial" : "full",
2728 LOOP_VINFO_EPILOGUE_P (loop_vinfo)
2729 ? " for epilogue loop" : "");
2730
2731 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
2732 = (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
2733 && need_peeling_or_partial_vectors_p);
2734
2735 /* We set LOOP_VINFO_USING_SELECT_VL_P as true before loop vectorization
2736 analysis that we don't know whether the loop is vectorized by partial
2737 vectors (More details see tree-vect-loop-manip.cc).
2738
2739 However, SELECT_VL vectorizaton style should only applied on partial
2740 vectorization since SELECT_VL is the GIMPLE IR that calculates the
2741 number of elements to be process for each iteration.
2742
2743 After loop vectorization analysis, Clear LOOP_VINFO_USING_SELECT_VL_P
2744 if it is not partial vectorized loop. */
2745 if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
2746 LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = false;
2747
2748 return opt_result::success ();
2749 }
2750
2751 /* Function vect_analyze_loop_2.
2752
2753 Apply a set of analyses on LOOP specified by LOOP_VINFO, the different
2754 analyses will record information in some members of LOOP_VINFO. FATAL
2755 indicates if some analysis meets fatal error. If one non-NULL pointer
2756 SUGGESTED_UNROLL_FACTOR is provided, it's intent to be filled with one
2757 worked out suggested unroll factor, while one NULL pointer shows it's
2758 going to apply the suggested unroll factor. SLP_DONE_FOR_SUGGESTED_UF
2759 is to hold the slp decision when the suggested unroll factor is worked
2760 out. */
2761 static opt_result
2762 vect_analyze_loop_2 (loop_vec_info loop_vinfo, bool &fatal,
2763 unsigned *suggested_unroll_factor,
2764 unsigned& slp_done_for_suggested_uf)
2765 {
2766 opt_result ok = opt_result::success ();
2767 int res;
2768 unsigned int max_vf = MAX_VECTORIZATION_FACTOR;
2769 poly_uint64 min_vf = 2;
2770 loop_vec_info orig_loop_vinfo = NULL;
2771
2772 /* If we are dealing with an epilogue then orig_loop_vinfo points to the
2773 loop_vec_info of the first vectorized loop. */
2774 if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
2775 orig_loop_vinfo = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
2776 else
2777 orig_loop_vinfo = loop_vinfo;
2778 gcc_assert (orig_loop_vinfo);
2779
2780 /* The first group of checks is independent of the vector size. */
2781 fatal = true;
2782
2783 if (LOOP_VINFO_SIMD_IF_COND (loop_vinfo)
2784 && integer_zerop (LOOP_VINFO_SIMD_IF_COND (loop_vinfo)))
2785 return opt_result::failure_at (vect_location,
2786 "not vectorized: simd if(0)\n");
2787
2788 /* Find all data references in the loop (which correspond to vdefs/vuses)
2789 and analyze their evolution in the loop. */
2790
2791 loop_p loop = LOOP_VINFO_LOOP (loop_vinfo);
2792
2793 /* Gather the data references and count stmts in the loop. */
2794 if (!LOOP_VINFO_DATAREFS (loop_vinfo).exists ())
2795 {
2796 opt_result res
2797 = vect_get_datarefs_in_loop (loop, LOOP_VINFO_BBS (loop_vinfo),
2798 &LOOP_VINFO_DATAREFS (loop_vinfo));
2799 if (!res)
2800 {
2801 if (dump_enabled_p ())
2802 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2803 "not vectorized: loop contains function "
2804 "calls or data references that cannot "
2805 "be analyzed\n");
2806 return res;
2807 }
2808 loop_vinfo->shared->save_datarefs ();
2809 }
2810 else
2811 loop_vinfo->shared->check_datarefs ();
2812
2813 /* Analyze the data references and also adjust the minimal
2814 vectorization factor according to the loads and stores. */
2815
2816 ok = vect_analyze_data_refs (loop_vinfo, &min_vf, &fatal);
2817 if (!ok)
2818 {
2819 if (dump_enabled_p ())
2820 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2821 "bad data references.\n");
2822 return ok;
2823 }
2824
2825 /* Check if we are applying unroll factor now. */
2826 bool applying_suggested_uf = loop_vinfo->suggested_unroll_factor > 1;
2827 gcc_assert (!applying_suggested_uf || !suggested_unroll_factor);
2828
2829 /* If the slp decision is false when suggested unroll factor is worked
2830 out, and we are applying suggested unroll factor, we can simply skip
2831 all slp related analyses this time. */
2832 unsigned slp = !applying_suggested_uf ? 2 : slp_done_for_suggested_uf;
2833
2834 /* Classify all cross-iteration scalar data-flow cycles.
2835 Cross-iteration cycles caused by virtual phis are analyzed separately. */
2836 vect_analyze_scalar_cycles (loop_vinfo, slp == 2);
2837
2838 vect_pattern_recog (loop_vinfo);
2839
2840 vect_fixup_scalar_cycles_with_patterns (loop_vinfo);
2841
2842 /* Analyze the access patterns of the data-refs in the loop (consecutive,
2843 complex, etc.). FORNOW: Only handle consecutive access pattern. */
2844
2845 ok = vect_analyze_data_ref_accesses (loop_vinfo, NULL);
2846 if (!ok)
2847 {
2848 if (dump_enabled_p ())
2849 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2850 "bad data access.\n");
2851 return ok;
2852 }
2853
2854 /* Data-flow analysis to detect stmts that do not need to be vectorized. */
2855
2856 ok = vect_mark_stmts_to_be_vectorized (loop_vinfo, &fatal);
2857 if (!ok)
2858 {
2859 if (dump_enabled_p ())
2860 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2861 "unexpected pattern.\n");
2862 return ok;
2863 }
2864
2865 /* While the rest of the analysis below depends on it in some way. */
2866 fatal = false;
2867
2868 /* Analyze data dependences between the data-refs in the loop
2869 and adjust the maximum vectorization factor according to
2870 the dependences.
2871 FORNOW: fail at the first data dependence that we encounter. */
2872
2873 ok = vect_analyze_data_ref_dependences (loop_vinfo, &max_vf);
2874 if (!ok)
2875 {
2876 if (dump_enabled_p ())
2877 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2878 "bad data dependence.\n");
2879 return ok;
2880 }
2881 if (max_vf != MAX_VECTORIZATION_FACTOR
2882 && maybe_lt (max_vf, min_vf))
2883 return opt_result::failure_at (vect_location, "bad data dependence.\n");
2884 LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo) = max_vf;
2885
2886 ok = vect_determine_vectorization_factor (loop_vinfo);
2887 if (!ok)
2888 {
2889 if (dump_enabled_p ())
2890 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2891 "can't determine vectorization factor.\n");
2892 return ok;
2893 }
2894
2895 /* Compute the scalar iteration cost. */
2896 vect_compute_single_scalar_iteration_cost (loop_vinfo);
2897
2898 poly_uint64 saved_vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2899 bool saved_can_use_partial_vectors_p
2900 = LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo);
2901
2902 /* This is the point where we can re-start analysis with SLP forced off. */
2903 start_over:
2904
2905 if (slp)
2906 {
2907 /* Check the SLP opportunities in the loop, analyze and build
2908 SLP trees. */
2909 ok = vect_analyze_slp (loop_vinfo, loop_vinfo->stmt_vec_infos.length (),
2910 slp == 1);
2911 if (!ok)
2912 return ok;
2913
2914 /* If there are any SLP instances mark them as pure_slp. */
2915 if (vect_make_slp_decision (loop_vinfo))
2916 {
2917 /* Find stmts that need to be both vectorized and SLPed. */
2918 vect_detect_hybrid_slp (loop_vinfo);
2919
2920 /* Update the vectorization factor based on the SLP decision. */
2921 vect_update_vf_for_slp (loop_vinfo);
2922
2923 /* Optimize the SLP graph with the vectorization factor fixed. */
2924 vect_optimize_slp (loop_vinfo);
2925
2926 /* Gather the loads reachable from the SLP graph entries. */
2927 vect_gather_slp_loads (loop_vinfo);
2928 }
2929 }
2930
2931 /* We don't expect to have to roll back to anything other than an empty
2932 set of rgroups. */
2933 gcc_assert (LOOP_VINFO_MASKS (loop_vinfo).is_empty ());
2934
2935 /* When we arrive here with SLP disabled and we are supposed
2936 to use SLP for everything fail vectorization. */
2937 if (!slp && param_vect_force_slp)
2938 return opt_result::failure_at (vect_location,
2939 "may need non-SLP handling\n");
2940
2941 /* Apply the suggested unrolling factor, this was determined by the backend
2942 during finish_cost the first time we ran the analyzis for this
2943 vector mode. */
2944 if (applying_suggested_uf)
2945 LOOP_VINFO_VECT_FACTOR (loop_vinfo) *= loop_vinfo->suggested_unroll_factor;
2946
2947 /* Now the vectorization factor is final. */
2948 poly_uint64 vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2949 gcc_assert (known_ne (vectorization_factor, 0U));
2950
2951 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && dump_enabled_p ())
2952 {
2953 dump_printf_loc (MSG_NOTE, vect_location,
2954 "vectorization_factor = ");
2955 dump_dec (MSG_NOTE, vectorization_factor);
2956 dump_printf (MSG_NOTE, ", niters = %wd\n",
2957 LOOP_VINFO_INT_NITERS (loop_vinfo));
2958 }
2959
2960 if (max_vf != MAX_VECTORIZATION_FACTOR
2961 && maybe_lt (max_vf, LOOP_VINFO_VECT_FACTOR (loop_vinfo)))
2962 return opt_result::failure_at (vect_location, "bad data dependence.\n");
2963
2964 loop_vinfo->vector_costs = init_cost (loop_vinfo, false);
2965
2966 /* Analyze the alignment of the data-refs in the loop.
2967 Fail if a data reference is found that cannot be vectorized. */
2968
2969 ok = vect_analyze_data_refs_alignment (loop_vinfo);
2970 if (!ok)
2971 {
2972 if (dump_enabled_p ())
2973 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2974 "bad data alignment.\n");
2975 return ok;
2976 }
2977
2978 /* Prune the list of ddrs to be tested at run-time by versioning for alias.
2979 It is important to call pruning after vect_analyze_data_ref_accesses,
2980 since we use grouping information gathered by interleaving analysis. */
2981 ok = vect_prune_runtime_alias_test_list (loop_vinfo);
2982 if (!ok)
2983 return ok;
2984
2985 /* Do not invoke vect_enhance_data_refs_alignment for epilogue
2986 vectorization, since we do not want to add extra peeling or
2987 add versioning for alignment. */
2988 if (!LOOP_VINFO_EPILOGUE_P (loop_vinfo))
2989 /* This pass will decide on using loop versioning and/or loop peeling in
2990 order to enhance the alignment of data references in the loop. */
2991 ok = vect_enhance_data_refs_alignment (loop_vinfo);
2992 if (!ok)
2993 return ok;
2994
2995 if (slp)
2996 {
2997 /* Analyze operations in the SLP instances. We can't simply
2998 remove unsupported SLP instances as this makes the above
2999 SLP kind detection invalid and might also affect the VF. */
3000 if (! vect_slp_analyze_operations (loop_vinfo))
3001 {
3002 ok = opt_result::failure_at (vect_location,
3003 "unsupported SLP instances\n");
3004 goto again;
3005 }
3006 }
3007
3008 /* Dissolve SLP-only groups. */
3009 vect_dissolve_slp_only_groups (loop_vinfo);
3010
3011 /* Scan all the remaining operations in the loop that are not subject
3012 to SLP and make sure they are vectorizable. */
3013 ok = vect_analyze_loop_operations (loop_vinfo);
3014 if (!ok)
3015 {
3016 ok = opt_result::failure_at (vect_location,
3017 "bad operation or unsupported loop bound\n");
3018 goto again;
3019 }
3020
3021 /* For now, we don't expect to mix both masking and length approaches for one
3022 loop, disable it if both are recorded. */
3023 if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
3024 && !LOOP_VINFO_MASKS (loop_vinfo).is_empty ()
3025 && !LOOP_VINFO_LENS (loop_vinfo).is_empty ())
3026 {
3027 if (dump_enabled_p ())
3028 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3029 "can't vectorize a loop with partial vectors"
3030 " because we don't expect to mix different"
3031 " approaches with partial vectors for the"
3032 " same loop.\n");
3033 LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
3034 }
3035
3036 /* If we still have the option of using partial vectors,
3037 check whether we can generate the necessary loop controls. */
3038 if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
3039 {
3040 if (!LOOP_VINFO_MASKS (loop_vinfo).is_empty ())
3041 {
3042 if (!vect_verify_full_masking (loop_vinfo)
3043 && !vect_verify_full_masking_avx512 (loop_vinfo))
3044 LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
3045 }
3046 else /* !LOOP_VINFO_LENS (loop_vinfo).is_empty () */
3047 if (!vect_verify_loop_lens (loop_vinfo))
3048 LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
3049 }
3050
3051 /* If we're vectorizing a loop that uses length "controls" and
3052 can iterate more than once, we apply decrementing IV approach
3053 in loop control. */
3054 if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
3055 && LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) == vect_partial_vectors_len
3056 && LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo) == 0
3057 && !(LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
3058 && known_le (LOOP_VINFO_INT_NITERS (loop_vinfo),
3059 LOOP_VINFO_VECT_FACTOR (loop_vinfo))))
3060 LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo) = true;
3061
3062 /* If a loop uses length controls and has a decrementing loop control IV,
3063 we will normally pass that IV through a MIN_EXPR to calcaluate the
3064 basis for the length controls. E.g. in a loop that processes one
3065 element per scalar iteration, the number of elements would be
3066 MIN_EXPR <N, VF>, where N is the number of scalar iterations left.
3067
3068 This MIN_EXPR approach allows us to use pointer IVs with an invariant
3069 step, since only the final iteration of the vector loop can have
3070 inactive lanes.
3071
3072 However, some targets have a dedicated instruction for calculating the
3073 preferred length, given the total number of elements that still need to
3074 be processed. This is encapsulated in the SELECT_VL internal function.
3075
3076 If the target supports SELECT_VL, we can use it instead of MIN_EXPR
3077 to determine the basis for the length controls. However, unlike the
3078 MIN_EXPR calculation, the SELECT_VL calculation can decide to make
3079 lanes inactive in any iteration of the vector loop, not just the last
3080 iteration. This SELECT_VL approach therefore requires us to use pointer
3081 IVs with variable steps.
3082
3083 Once we've decided how many elements should be processed by one
3084 iteration of the vector loop, we need to populate the rgroup controls.
3085 If a loop has multiple rgroups, we need to make sure that those rgroups
3086 "line up" (that is, they must be consistent about which elements are
3087 active and which aren't). This is done by vect_adjust_loop_lens_control.
3088
3089 In principle, it would be possible to use vect_adjust_loop_lens_control
3090 on either the result of a MIN_EXPR or the result of a SELECT_VL.
3091 However:
3092
3093 (1) In practice, it only makes sense to use SELECT_VL when a vector
3094 operation will be controlled directly by the result. It is not
3095 worth using SELECT_VL if it would only be the input to other
3096 calculations.
3097
3098 (2) If we use SELECT_VL for an rgroup that has N controls, each associated
3099 pointer IV will need N updates by a variable amount (N-1 updates
3100 within the iteration and 1 update to move to the next iteration).
3101
3102 Because of this, we prefer to use the MIN_EXPR approach whenever there
3103 is more than one length control.
3104
3105 In addition, SELECT_VL always operates to a granularity of 1 unit.
3106 If we wanted to use it to control an SLP operation on N consecutive
3107 elements, we would need to make the SELECT_VL inputs measure scalar
3108 iterations (rather than elements) and then multiply the SELECT_VL
3109 result by N. But using SELECT_VL this way is inefficient because
3110 of (1) above.
3111
3112 2. We don't apply SELECT_VL on single-rgroup when both (1) and (2) are
3113 satisfied:
3114
3115 (1). LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) is true.
3116 (2). LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant () is true.
3117
3118 Since SELECT_VL (variable step) will make SCEV analysis failed and then
3119 we will fail to gain benefits of following unroll optimizations. We prefer
3120 using the MIN_EXPR approach in this situation. */
3121 if (LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo))
3122 {
3123 tree iv_type = LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo);
3124 if (direct_internal_fn_supported_p (IFN_SELECT_VL, iv_type,
3125 OPTIMIZE_FOR_SPEED)
3126 && LOOP_VINFO_LENS (loop_vinfo).length () == 1
3127 && LOOP_VINFO_LENS (loop_vinfo)[0].factor == 1
3128 && (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
3129 || !LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant ()))
3130 LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = true;
3131
3132 /* If any of the SLP instances cover more than a single lane
3133 we cannot use .SELECT_VL at the moment, even if the number
3134 of lanes is uniform throughout the SLP graph. */
3135 if (LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo))
3136 for (slp_instance inst : LOOP_VINFO_SLP_INSTANCES (loop_vinfo))
3137 if (SLP_TREE_LANES (SLP_INSTANCE_TREE (inst)) != 1
3138 && !(SLP_INSTANCE_KIND (inst) == slp_inst_kind_store
3139 && SLP_INSTANCE_TREE (inst)->ldst_lanes))
3140 {
3141 LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = false;
3142 break;
3143 }
3144 }
3145
3146 /* Decide whether this loop_vinfo should use partial vectors or peeling,
3147 assuming that the loop will be used as a main loop. We will redo
3148 this analysis later if we instead decide to use the loop as an
3149 epilogue loop. */
3150 ok = vect_determine_partial_vectors_and_peeling (loop_vinfo);
3151 if (!ok)
3152 return ok;
3153
3154 /* If we're vectorizing an epilogue loop, the vectorized loop either needs
3155 to be able to handle fewer than VF scalars, or needs to have a lower VF
3156 than the main loop. */
3157 if (LOOP_VINFO_EPILOGUE_P (loop_vinfo)
3158 && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
3159 {
3160 poly_uint64 unscaled_vf
3161 = exact_div (LOOP_VINFO_VECT_FACTOR (orig_loop_vinfo),
3162 orig_loop_vinfo->suggested_unroll_factor);
3163 if (maybe_ge (LOOP_VINFO_VECT_FACTOR (loop_vinfo), unscaled_vf))
3164 return opt_result::failure_at (vect_location,
3165 "Vectorization factor too high for"
3166 " epilogue loop.\n");
3167 }
3168
3169 /* If the epilogue needs peeling for gaps but the main loop doesn't give
3170 up on the epilogue. */
3171 if (LOOP_VINFO_EPILOGUE_P (loop_vinfo)
3172 && LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
3173 && (LOOP_VINFO_PEELING_FOR_GAPS (orig_loop_vinfo)
3174 != LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)))
3175 return opt_result::failure_at (vect_location,
3176 "Epilogue loop requires peeling for gaps "
3177 "but main loop does not.\n");
3178
3179 /* If an epilogue loop is required make sure we can create one. */
3180 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
3181 || LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
3182 || LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
3183 {
3184 if (dump_enabled_p ())
3185 dump_printf_loc (MSG_NOTE, vect_location, "epilog loop required\n");
3186 if (!vect_can_advance_ivs_p (loop_vinfo)
3187 || !slpeel_can_duplicate_loop_p (loop,
3188 LOOP_VINFO_IV_EXIT (loop_vinfo),
3189 LOOP_VINFO_IV_EXIT (loop_vinfo)))
3190 {
3191 ok = opt_result::failure_at (vect_location,
3192 "not vectorized: can't create required "
3193 "epilog loop\n");
3194 goto again;
3195 }
3196 }
3197
3198 /* Check the costings of the loop make vectorizing worthwhile. */
3199 res = vect_analyze_loop_costing (loop_vinfo, suggested_unroll_factor);
3200 if (res < 0)
3201 {
3202 ok = opt_result::failure_at (vect_location,
3203 "Loop costings may not be worthwhile.\n");
3204 goto again;
3205 }
3206 if (!res)
3207 return opt_result::failure_at (vect_location,
3208 "Loop costings not worthwhile.\n");
3209
3210 /* During peeling, we need to check if number of loop iterations is
3211 enough for both peeled prolog loop and vector loop. This check
3212 can be merged along with threshold check of loop versioning, so
3213 increase threshold for this case if necessary.
3214
3215 If we are analyzing an epilogue we still want to check what its
3216 versioning threshold would be. If we decide to vectorize the epilogues we
3217 will want to use the lowest versioning threshold of all epilogues and main
3218 loop. This will enable us to enter a vectorized epilogue even when
3219 versioning the loop. We can't simply check whether the epilogue requires
3220 versioning though since we may have skipped some versioning checks when
3221 analyzing the epilogue. For instance, checks for alias versioning will be
3222 skipped when dealing with epilogues as we assume we already checked them
3223 for the main loop. So instead we always check the 'orig_loop_vinfo'. */
3224 if (LOOP_REQUIRES_VERSIONING (orig_loop_vinfo))
3225 {
3226 poly_uint64 niters_th = 0;
3227 unsigned int th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
3228
3229 if (!vect_use_loop_mask_for_alignment_p (loop_vinfo))
3230 {
3231 /* Niters for peeled prolog loop. */
3232 if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
3233 {
3234 dr_vec_info *dr_info = LOOP_VINFO_UNALIGNED_DR (loop_vinfo);
3235 tree vectype = STMT_VINFO_VECTYPE (dr_info->stmt);
3236 niters_th += TYPE_VECTOR_SUBPARTS (vectype) - 1;
3237 }
3238 else
3239 niters_th += LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
3240 }
3241
3242 /* Niters for at least one iteration of vectorized loop. */
3243 if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
3244 niters_th += LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3245 /* One additional iteration because of peeling for gap. */
3246 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
3247 niters_th += 1;
3248
3249 /* Use the same condition as vect_transform_loop to decide when to use
3250 the cost to determine a versioning threshold. */
3251 if (vect_apply_runtime_profitability_check_p (loop_vinfo)
3252 && ordered_p (th, niters_th))
3253 niters_th = ordered_max (poly_uint64 (th), niters_th);
3254
3255 LOOP_VINFO_VERSIONING_THRESHOLD (loop_vinfo) = niters_th;
3256 }
3257
3258 gcc_assert (known_eq (vectorization_factor,
3259 LOOP_VINFO_VECT_FACTOR (loop_vinfo)));
3260
3261 slp_done_for_suggested_uf = slp;
3262
3263 /* Ok to vectorize! */
3264 LOOP_VINFO_VECTORIZABLE_P (loop_vinfo) = 1;
3265 return opt_result::success ();
3266
3267 again:
3268 /* Ensure that "ok" is false (with an opt_problem if dumping is enabled). */
3269 gcc_assert (!ok);
3270
3271 /* Try again with SLP degraded but if we didn't do any SLP there is
3272 no point in re-trying. */
3273 if (!slp)
3274 return ok;
3275
3276 /* If we are applying suggested unroll factor, we don't need to
3277 re-try any more as we want to keep the SLP mode fixed. */
3278 if (applying_suggested_uf)
3279 return ok;
3280
3281 /* If there are reduction chains re-trying will fail anyway. */
3282 if (! LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo).is_empty ())
3283 return ok;
3284
3285 /* Likewise if the grouped loads or stores in the SLP cannot be handled
3286 via interleaving or lane instructions. */
3287 slp_instance instance;
3288 slp_tree node;
3289 unsigned i, j;
3290 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
3291 {
3292 if (SLP_TREE_DEF_TYPE (SLP_INSTANCE_TREE (instance)) != vect_internal_def)
3293 continue;
3294
3295 stmt_vec_info vinfo;
3296 vinfo = SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (instance))[0];
3297 if (! STMT_VINFO_GROUPED_ACCESS (vinfo))
3298 continue;
3299 vinfo = DR_GROUP_FIRST_ELEMENT (vinfo);
3300 unsigned int size = DR_GROUP_SIZE (vinfo);
3301 tree vectype = STMT_VINFO_VECTYPE (vinfo);
3302 if (vect_store_lanes_supported (vectype, size, false) == IFN_LAST
3303 && ! known_eq (TYPE_VECTOR_SUBPARTS (vectype), 1U)
3304 && ! vect_grouped_store_supported (vectype, size))
3305 return opt_result::failure_at (vinfo->stmt,
3306 "unsupported grouped store\n");
3307 FOR_EACH_VEC_ELT (SLP_INSTANCE_LOADS (instance), j, node)
3308 {
3309 vinfo = SLP_TREE_REPRESENTATIVE (node);
3310 if (STMT_VINFO_GROUPED_ACCESS (vinfo))
3311 {
3312 vinfo = DR_GROUP_FIRST_ELEMENT (vinfo);
3313 bool single_element_p = !DR_GROUP_NEXT_ELEMENT (vinfo);
3314 size = DR_GROUP_SIZE (vinfo);
3315 vectype = STMT_VINFO_VECTYPE (vinfo);
3316 if (vect_load_lanes_supported (vectype, size, false) == IFN_LAST
3317 && ! vect_grouped_load_supported (vectype, single_element_p,
3318 size))
3319 return opt_result::failure_at (vinfo->stmt,
3320 "unsupported grouped load\n");
3321 }
3322 }
3323 }
3324
3325 /* Roll back state appropriately. Degrade SLP this time. From multi-
3326 to single-lane to disabled. */
3327 --slp;
3328 if (dump_enabled_p ())
3329 {
3330 if (slp)
3331 dump_printf_loc (MSG_NOTE, vect_location,
3332 "re-trying with single-lane SLP\n");
3333 else
3334 dump_printf_loc (MSG_NOTE, vect_location,
3335 "re-trying with SLP disabled\n");
3336 }
3337
3338 /* Restore vectorization factor as it were without SLP. */
3339 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = saved_vectorization_factor;
3340 /* Free the SLP instances. */
3341 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), j, instance)
3342 vect_free_slp_instance (instance);
3343 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
3344 /* Reset SLP type to loop_vect on all stmts. */
3345 for (i = 0; i < LOOP_VINFO_LOOP (loop_vinfo)->num_nodes; ++i)
3346 {
3347 basic_block bb = LOOP_VINFO_BBS (loop_vinfo)[i];
3348 for (gimple_stmt_iterator si = gsi_start_phis (bb);
3349 !gsi_end_p (si); gsi_next (&si))
3350 {
3351 stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (gsi_stmt (si));
3352 STMT_SLP_TYPE (stmt_info) = loop_vect;
3353 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
3354 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
3355 {
3356 /* vectorizable_reduction adjusts reduction stmt def-types,
3357 restore them to that of the PHI. */
3358 STMT_VINFO_DEF_TYPE (STMT_VINFO_REDUC_DEF (stmt_info))
3359 = STMT_VINFO_DEF_TYPE (stmt_info);
3360 STMT_VINFO_DEF_TYPE (vect_stmt_to_vectorize
3361 (STMT_VINFO_REDUC_DEF (stmt_info)))
3362 = STMT_VINFO_DEF_TYPE (stmt_info);
3363 }
3364 }
3365 for (gimple_stmt_iterator si = gsi_start_bb (bb);
3366 !gsi_end_p (si); gsi_next (&si))
3367 {
3368 if (is_gimple_debug (gsi_stmt (si)))
3369 continue;
3370 stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (gsi_stmt (si));
3371 STMT_SLP_TYPE (stmt_info) = loop_vect;
3372 if (STMT_VINFO_IN_PATTERN_P (stmt_info))
3373 {
3374 stmt_vec_info pattern_stmt_info
3375 = STMT_VINFO_RELATED_STMT (stmt_info);
3376 if (STMT_VINFO_SLP_VECT_ONLY_PATTERN (pattern_stmt_info))
3377 STMT_VINFO_IN_PATTERN_P (stmt_info) = false;
3378
3379 gimple *pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
3380 STMT_SLP_TYPE (pattern_stmt_info) = loop_vect;
3381 for (gimple_stmt_iterator pi = gsi_start (pattern_def_seq);
3382 !gsi_end_p (pi); gsi_next (&pi))
3383 STMT_SLP_TYPE (loop_vinfo->lookup_stmt (gsi_stmt (pi)))
3384 = loop_vect;
3385 }
3386 }
3387 }
3388 /* Free optimized alias test DDRS. */
3389 LOOP_VINFO_LOWER_BOUNDS (loop_vinfo).truncate (0);
3390 LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).release ();
3391 LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo).release ();
3392 /* Reset target cost data. */
3393 delete loop_vinfo->vector_costs;
3394 loop_vinfo->vector_costs = nullptr;
3395 /* Reset accumulated rgroup information. */
3396 LOOP_VINFO_MASKS (loop_vinfo).mask_set.empty ();
3397 release_vec_loop_controls (&LOOP_VINFO_MASKS (loop_vinfo).rgc_vec);
3398 release_vec_loop_controls (&LOOP_VINFO_LENS (loop_vinfo));
3399 /* Reset assorted flags. */
3400 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = false;
3401 LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) = false;
3402 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = 0;
3403 LOOP_VINFO_VERSIONING_THRESHOLD (loop_vinfo) = 0;
3404 LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
3405 = saved_can_use_partial_vectors_p;
3406 LOOP_VINFO_MUST_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
3407 LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = false;
3408 if (loop_vinfo->scan_map)
3409 loop_vinfo->scan_map->empty ();
3410
3411 goto start_over;
3412 }
3413
3414 /* Return true if vectorizing a loop using NEW_LOOP_VINFO appears
3415 to be better than vectorizing it using OLD_LOOP_VINFO. Assume that
3416 OLD_LOOP_VINFO is better unless something specifically indicates
3417 otherwise.
3418
3419 Note that this deliberately isn't a partial order. */
3420
3421 static bool
3422 vect_better_loop_vinfo_p (loop_vec_info new_loop_vinfo,
3423 loop_vec_info old_loop_vinfo)
3424 {
3425 struct loop *loop = LOOP_VINFO_LOOP (new_loop_vinfo);
3426 gcc_assert (LOOP_VINFO_LOOP (old_loop_vinfo) == loop);
3427
3428 poly_int64 new_vf = LOOP_VINFO_VECT_FACTOR (new_loop_vinfo);
3429 poly_int64 old_vf = LOOP_VINFO_VECT_FACTOR (old_loop_vinfo);
3430
3431 /* Always prefer a VF of loop->simdlen over any other VF. */
3432 if (loop->simdlen)
3433 {
3434 bool new_simdlen_p = known_eq (new_vf, loop->simdlen);
3435 bool old_simdlen_p = known_eq (old_vf, loop->simdlen);
3436 if (new_simdlen_p != old_simdlen_p)
3437 return new_simdlen_p;
3438 }
3439
3440 const auto *old_costs = old_loop_vinfo->vector_costs;
3441 const auto *new_costs = new_loop_vinfo->vector_costs;
3442 if (loop_vec_info main_loop = LOOP_VINFO_ORIG_LOOP_INFO (old_loop_vinfo))
3443 return new_costs->better_epilogue_loop_than_p (old_costs, main_loop);
3444
3445 return new_costs->better_main_loop_than_p (old_costs);
3446 }
3447
3448 /* Decide whether to replace OLD_LOOP_VINFO with NEW_LOOP_VINFO. Return
3449 true if we should. */
3450
3451 static bool
3452 vect_joust_loop_vinfos (loop_vec_info new_loop_vinfo,
3453 loop_vec_info old_loop_vinfo)
3454 {
3455 if (!vect_better_loop_vinfo_p (new_loop_vinfo, old_loop_vinfo))
3456 return false;
3457
3458 if (dump_enabled_p ())
3459 dump_printf_loc (MSG_NOTE, vect_location,
3460 "***** Preferring vector mode %s to vector mode %s\n",
3461 GET_MODE_NAME (new_loop_vinfo->vector_mode),
3462 GET_MODE_NAME (old_loop_vinfo->vector_mode));
3463 return true;
3464 }
3465
3466 /* Analyze LOOP with VECTOR_MODES[MODE_I] and as epilogue if ORIG_LOOP_VINFO is
3467 not NULL. Set AUTODETECTED_VECTOR_MODE if VOIDmode and advance
3468 MODE_I to the next mode useful to analyze.
3469 Return the loop_vinfo on success and wrapped null on failure. */
3470
3471 static opt_loop_vec_info
3472 vect_analyze_loop_1 (class loop *loop, vec_info_shared *shared,
3473 const vect_loop_form_info *loop_form_info,
3474 loop_vec_info orig_loop_vinfo,
3475 const vector_modes &vector_modes, unsigned &mode_i,
3476 machine_mode &autodetected_vector_mode,
3477 bool &fatal)
3478 {
3479 loop_vec_info loop_vinfo
3480 = vect_create_loop_vinfo (loop, shared, loop_form_info, orig_loop_vinfo);
3481
3482 machine_mode vector_mode = vector_modes[mode_i];
3483 loop_vinfo->vector_mode = vector_mode;
3484 unsigned int suggested_unroll_factor = 1;
3485 unsigned slp_done_for_suggested_uf = 0;
3486
3487 /* Run the main analysis. */
3488 opt_result res = vect_analyze_loop_2 (loop_vinfo, fatal,
3489 &suggested_unroll_factor,
3490 slp_done_for_suggested_uf);
3491 if (dump_enabled_p ())
3492 dump_printf_loc (MSG_NOTE, vect_location,
3493 "***** Analysis %s with vector mode %s\n",
3494 res ? "succeeded" : "failed",
3495 GET_MODE_NAME (loop_vinfo->vector_mode));
3496
3497 if (res && !LOOP_VINFO_EPILOGUE_P (loop_vinfo) && suggested_unroll_factor > 1)
3498 {
3499 if (dump_enabled_p ())
3500 dump_printf_loc (MSG_NOTE, vect_location,
3501 "***** Re-trying analysis for unrolling"
3502 " with unroll factor %d and slp %s.\n",
3503 suggested_unroll_factor,
3504 slp_done_for_suggested_uf ? "on" : "off");
3505 loop_vec_info unroll_vinfo
3506 = vect_create_loop_vinfo (loop, shared, loop_form_info, NULL);
3507 unroll_vinfo->vector_mode = vector_mode;
3508 unroll_vinfo->suggested_unroll_factor = suggested_unroll_factor;
3509 opt_result new_res = vect_analyze_loop_2 (unroll_vinfo, fatal, NULL,
3510 slp_done_for_suggested_uf);
3511 if (new_res)
3512 {
3513 delete loop_vinfo;
3514 loop_vinfo = unroll_vinfo;
3515 }
3516 else
3517 delete unroll_vinfo;
3518 }
3519
3520 /* Remember the autodetected vector mode. */
3521 if (vector_mode == VOIDmode)
3522 autodetected_vector_mode = loop_vinfo->vector_mode;
3523
3524 /* Advance mode_i, first skipping modes that would result in the
3525 same analysis result. */
3526 while (mode_i + 1 < vector_modes.length ()
3527 && vect_chooses_same_modes_p (loop_vinfo,
3528 vector_modes[mode_i + 1]))
3529 {
3530 if (dump_enabled_p ())
3531 dump_printf_loc (MSG_NOTE, vect_location,
3532 "***** The result for vector mode %s would"
3533 " be the same\n",
3534 GET_MODE_NAME (vector_modes[mode_i + 1]));
3535 mode_i += 1;
3536 }
3537 if (mode_i + 1 < vector_modes.length ()
3538 && VECTOR_MODE_P (autodetected_vector_mode)
3539 && (related_vector_mode (vector_modes[mode_i + 1],
3540 GET_MODE_INNER (autodetected_vector_mode))
3541 == autodetected_vector_mode)
3542 && (related_vector_mode (autodetected_vector_mode,
3543 GET_MODE_INNER (vector_modes[mode_i + 1]))
3544 == vector_modes[mode_i + 1]))
3545 {
3546 if (dump_enabled_p ())
3547 dump_printf_loc (MSG_NOTE, vect_location,
3548 "***** Skipping vector mode %s, which would"
3549 " repeat the analysis for %s\n",
3550 GET_MODE_NAME (vector_modes[mode_i + 1]),
3551 GET_MODE_NAME (autodetected_vector_mode));
3552 mode_i += 1;
3553 }
3554 mode_i++;
3555
3556 if (!res)
3557 {
3558 delete loop_vinfo;
3559 if (fatal)
3560 gcc_checking_assert (orig_loop_vinfo == NULL);
3561 return opt_loop_vec_info::propagate_failure (res);
3562 }
3563
3564 return opt_loop_vec_info::success (loop_vinfo);
3565 }
3566
3567 /* Function vect_analyze_loop.
3568
3569 Apply a set of analyses on LOOP, and create a loop_vec_info struct
3570 for it. The different analyses will record information in the
3571 loop_vec_info struct. */
3572 opt_loop_vec_info
3573 vect_analyze_loop (class loop *loop, gimple *loop_vectorized_call,
3574 vec_info_shared *shared)
3575 {
3576 DUMP_VECT_SCOPE ("analyze_loop_nest");
3577
3578 if (loop_outer (loop)
3579 && loop_vec_info_for_loop (loop_outer (loop))
3580 && LOOP_VINFO_VECTORIZABLE_P (loop_vec_info_for_loop (loop_outer (loop))))
3581 return opt_loop_vec_info::failure_at (vect_location,
3582 "outer-loop already vectorized.\n");
3583
3584 if (!find_loop_nest (loop, &shared->loop_nest))
3585 return opt_loop_vec_info::failure_at
3586 (vect_location,
3587 "not vectorized: loop nest containing two or more consecutive inner"
3588 " loops cannot be vectorized\n");
3589
3590 /* Analyze the loop form. */
3591 vect_loop_form_info loop_form_info;
3592 opt_result res = vect_analyze_loop_form (loop, loop_vectorized_call,
3593 &loop_form_info);
3594 if (!res)
3595 {
3596 if (dump_enabled_p ())
3597 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3598 "bad loop form.\n");
3599 return opt_loop_vec_info::propagate_failure (res);
3600 }
3601 if (!integer_onep (loop_form_info.assumptions))
3602 {
3603 /* We consider to vectorize this loop by versioning it under
3604 some assumptions. In order to do this, we need to clear
3605 existing information computed by scev and niter analyzer. */
3606 scev_reset_htab ();
3607 free_numbers_of_iterations_estimates (loop);
3608 /* Also set flag for this loop so that following scev and niter
3609 analysis are done under the assumptions. */
3610 loop_constraint_set (loop, LOOP_C_FINITE);
3611 }
3612 else
3613 /* Clear the existing niter information to make sure the nonwrapping flag
3614 will be calculated and set propriately. */
3615 free_numbers_of_iterations_estimates (loop);
3616
3617 auto_vector_modes vector_modes;
3618 /* Autodetect first vector size we try. */
3619 vector_modes.safe_push (VOIDmode);
3620 unsigned int autovec_flags
3621 = targetm.vectorize.autovectorize_vector_modes (&vector_modes,
3622 loop->simdlen != 0);
3623 bool pick_lowest_cost_p = ((autovec_flags & VECT_COMPARE_COSTS)
3624 && !unlimited_cost_model (loop));
3625 machine_mode autodetected_vector_mode = VOIDmode;
3626 opt_loop_vec_info first_loop_vinfo = opt_loop_vec_info::success (NULL);
3627 unsigned int mode_i = 0;
3628 unsigned HOST_WIDE_INT simdlen = loop->simdlen;
3629
3630 /* Keep track of the VF for each mode. Initialize all to 0 which indicates
3631 a mode has not been analyzed. */
3632 auto_vec<poly_uint64, 8> cached_vf_per_mode;
3633 for (unsigned i = 0; i < vector_modes.length (); ++i)
3634 cached_vf_per_mode.safe_push (0);
3635
3636 /* First determine the main loop vectorization mode, either the first
3637 one that works, starting with auto-detecting the vector mode and then
3638 following the targets order of preference, or the one with the
3639 lowest cost if pick_lowest_cost_p. */
3640 while (1)
3641 {
3642 bool fatal;
3643 unsigned int last_mode_i = mode_i;
3644 /* Set cached VF to -1 prior to analysis, which indicates a mode has
3645 failed. */
3646 cached_vf_per_mode[last_mode_i] = -1;
3647 opt_loop_vec_info loop_vinfo
3648 = vect_analyze_loop_1 (loop, shared, &loop_form_info,
3649 NULL, vector_modes, mode_i,
3650 autodetected_vector_mode, fatal);
3651 if (fatal)
3652 break;
3653
3654 if (loop_vinfo)
3655 {
3656 /* Analyzis has been successful so update the VF value. The
3657 VF should always be a multiple of unroll_factor and we want to
3658 capture the original VF here. */
3659 cached_vf_per_mode[last_mode_i]
3660 = exact_div (LOOP_VINFO_VECT_FACTOR (loop_vinfo),
3661 loop_vinfo->suggested_unroll_factor);
3662 /* Once we hit the desired simdlen for the first time,
3663 discard any previous attempts. */
3664 if (simdlen
3665 && known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), simdlen))
3666 {
3667 delete first_loop_vinfo;
3668 first_loop_vinfo = opt_loop_vec_info::success (NULL);
3669 simdlen = 0;
3670 }
3671 else if (pick_lowest_cost_p
3672 && first_loop_vinfo
3673 && vect_joust_loop_vinfos (loop_vinfo, first_loop_vinfo))
3674 {
3675 /* Pick loop_vinfo over first_loop_vinfo. */
3676 delete first_loop_vinfo;
3677 first_loop_vinfo = opt_loop_vec_info::success (NULL);
3678 }
3679 if (first_loop_vinfo == NULL)
3680 first_loop_vinfo = loop_vinfo;
3681 else
3682 {
3683 delete loop_vinfo;
3684 loop_vinfo = opt_loop_vec_info::success (NULL);
3685 }
3686
3687 /* Commit to first_loop_vinfo if we have no reason to try
3688 alternatives. */
3689 if (!simdlen && !pick_lowest_cost_p)
3690 break;
3691 }
3692 if (mode_i == vector_modes.length ()
3693 || autodetected_vector_mode == VOIDmode)
3694 break;
3695
3696 /* Try the next biggest vector size. */
3697 if (dump_enabled_p ())
3698 dump_printf_loc (MSG_NOTE, vect_location,
3699 "***** Re-trying analysis with vector mode %s\n",
3700 GET_MODE_NAME (vector_modes[mode_i]));
3701 }
3702 if (!first_loop_vinfo)
3703 return opt_loop_vec_info::propagate_failure (res);
3704
3705 if (dump_enabled_p ())
3706 dump_printf_loc (MSG_NOTE, vect_location,
3707 "***** Choosing vector mode %s\n",
3708 GET_MODE_NAME (first_loop_vinfo->vector_mode));
3709
3710 /* Only vectorize epilogues if PARAM_VECT_EPILOGUES_NOMASK is
3711 enabled, SIMDUID is not set, it is the innermost loop and we have
3712 either already found the loop's SIMDLEN or there was no SIMDLEN to
3713 begin with.
3714 TODO: Enable epilogue vectorization for loops with SIMDUID set. */
3715 bool vect_epilogues = (!simdlen
3716 && loop->inner == NULL
3717 && param_vect_epilogues_nomask
3718 && LOOP_VINFO_PEELING_FOR_NITER (first_loop_vinfo)
3719 /* No code motion support for multiple epilogues so for now
3720 not supported when multiple exits. */
3721 && !LOOP_VINFO_EARLY_BREAKS (first_loop_vinfo)
3722 && !loop->simduid
3723 && loop_cost_model (loop) > VECT_COST_MODEL_VERY_CHEAP);
3724 if (!vect_epilogues)
3725 return first_loop_vinfo;
3726
3727 /* Now analyze first_loop_vinfo for epilogue vectorization. */
3728
3729 /* For epilogues start the analysis from the first mode. The motivation
3730 behind starting from the beginning comes from cases where the VECTOR_MODES
3731 array may contain length-agnostic and length-specific modes. Their
3732 ordering is not guaranteed, so we could end up picking a mode for the main
3733 loop that is after the epilogue's optimal mode. */
3734 if (!unlimited_cost_model (loop)
3735 && first_loop_vinfo->vector_costs->suggested_epilogue_mode () != VOIDmode)
3736 {
3737 vector_modes[0]
3738 = first_loop_vinfo->vector_costs->suggested_epilogue_mode ();
3739 cached_vf_per_mode[0] = 0;
3740 }
3741 else
3742 vector_modes[0] = autodetected_vector_mode;
3743 mode_i = 0;
3744
3745 bool supports_partial_vectors =
3746 partial_vectors_supported_p () && param_vect_partial_vector_usage != 0;
3747 poly_uint64 first_vinfo_vf = LOOP_VINFO_VECT_FACTOR (first_loop_vinfo);
3748
3749 loop_vec_info orig_loop_vinfo = first_loop_vinfo;
3750 do
3751 {
3752 while (1)
3753 {
3754 /* If the target does not support partial vectors we can shorten the
3755 number of modes to analyze for the epilogue as we know we can't
3756 pick a mode that would lead to a VF at least as big as the
3757 FIRST_VINFO_VF. */
3758 if (!supports_partial_vectors
3759 && maybe_ge (cached_vf_per_mode[mode_i], first_vinfo_vf))
3760 {
3761 mode_i++;
3762 if (mode_i == vector_modes.length ())
3763 break;
3764 continue;
3765 }
3766
3767 if (dump_enabled_p ())
3768 dump_printf_loc (MSG_NOTE, vect_location,
3769 "***** Re-trying epilogue analysis with vector "
3770 "mode %s\n", GET_MODE_NAME (vector_modes[mode_i]));
3771
3772 bool fatal;
3773 opt_loop_vec_info loop_vinfo
3774 = vect_analyze_loop_1 (loop, shared, &loop_form_info,
3775 orig_loop_vinfo,
3776 vector_modes, mode_i,
3777 autodetected_vector_mode, fatal);
3778 if (fatal)
3779 break;
3780
3781 if (loop_vinfo)
3782 {
3783 if (pick_lowest_cost_p
3784 && orig_loop_vinfo->epilogue_vinfo
3785 && vect_joust_loop_vinfos (loop_vinfo,
3786 orig_loop_vinfo->epilogue_vinfo))
3787 {
3788 gcc_assert (vect_epilogues);
3789 delete orig_loop_vinfo->epilogue_vinfo;
3790 orig_loop_vinfo->epilogue_vinfo = nullptr;
3791 }
3792 if (!orig_loop_vinfo->epilogue_vinfo)
3793 orig_loop_vinfo->epilogue_vinfo = loop_vinfo;
3794 else
3795 {
3796 delete loop_vinfo;
3797 loop_vinfo = opt_loop_vec_info::success (NULL);
3798 }
3799
3800 /* For now only allow one epilogue loop, but allow
3801 pick_lowest_cost_p to replace it, so commit to the
3802 first epilogue if we have no reason to try alternatives. */
3803 if (!pick_lowest_cost_p)
3804 break;
3805 }
3806
3807 if (mode_i == vector_modes.length ())
3808 break;
3809 }
3810
3811 orig_loop_vinfo = orig_loop_vinfo->epilogue_vinfo;
3812 if (!orig_loop_vinfo)
3813 break;
3814
3815 /* When we selected a first vectorized epilogue, see if the target
3816 suggests to have another one. */
3817 if (!unlimited_cost_model (loop)
3818 && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (orig_loop_vinfo)
3819 && (orig_loop_vinfo->vector_costs->suggested_epilogue_mode ()
3820 != VOIDmode))
3821 {
3822 vector_modes[0]
3823 = orig_loop_vinfo->vector_costs->suggested_epilogue_mode ();
3824 cached_vf_per_mode[0] = 0;
3825 mode_i = 0;
3826 }
3827 else
3828 break;
3829 }
3830 while (1);
3831
3832 if (first_loop_vinfo->epilogue_vinfo)
3833 {
3834 poly_uint64 lowest_th
3835 = LOOP_VINFO_VERSIONING_THRESHOLD (first_loop_vinfo);
3836 loop_vec_info epilog_vinfo = first_loop_vinfo->epilogue_vinfo;
3837 do
3838 {
3839 poly_uint64 th = LOOP_VINFO_VERSIONING_THRESHOLD (epilog_vinfo);
3840 gcc_assert (!LOOP_REQUIRES_VERSIONING (epilog_vinfo)
3841 || maybe_ne (lowest_th, 0U));
3842 /* Keep track of the known smallest versioning threshold. */
3843 if (ordered_p (lowest_th, th))
3844 lowest_th = ordered_min (lowest_th, th);
3845 epilog_vinfo = epilog_vinfo->epilogue_vinfo;
3846 }
3847 while (epilog_vinfo);
3848 LOOP_VINFO_VERSIONING_THRESHOLD (first_loop_vinfo) = lowest_th;
3849 if (dump_enabled_p ())
3850 dump_printf_loc (MSG_NOTE, vect_location,
3851 "***** Choosing epilogue vector mode %s\n",
3852 GET_MODE_NAME
3853 (first_loop_vinfo->epilogue_vinfo->vector_mode));
3854 }
3855
3856 return first_loop_vinfo;
3857 }
3858
3859 /* Return true if there is an in-order reduction function for CODE, storing
3860 it in *REDUC_FN if so. */
3861
3862 static bool
3863 fold_left_reduction_fn (code_helper code, internal_fn *reduc_fn)
3864 {
3865 /* We support MINUS_EXPR by negating the operand. This also preserves an
3866 initial -0.0 since -0.0 - 0.0 (neutral op for MINUS_EXPR) == -0.0 +
3867 (-0.0) = -0.0. */
3868 if (code == PLUS_EXPR || code == MINUS_EXPR)
3869 {
3870 *reduc_fn = IFN_FOLD_LEFT_PLUS;
3871 return true;
3872 }
3873 return false;
3874 }
3875
3876 /* Function reduction_fn_for_scalar_code
3877
3878 Input:
3879 CODE - tree_code of a reduction operations.
3880
3881 Output:
3882 REDUC_FN - the corresponding internal function to be used to reduce the
3883 vector of partial results into a single scalar result, or IFN_LAST
3884 if the operation is a supported reduction operation, but does not have
3885 such an internal function.
3886
3887 Return FALSE if CODE currently cannot be vectorized as reduction. */
3888
3889 bool
3890 reduction_fn_for_scalar_code (code_helper code, internal_fn *reduc_fn)
3891 {
3892 if (code.is_tree_code ())
3893 switch (tree_code (code))
3894 {
3895 case MAX_EXPR:
3896 *reduc_fn = IFN_REDUC_MAX;
3897 return true;
3898
3899 case MIN_EXPR:
3900 *reduc_fn = IFN_REDUC_MIN;
3901 return true;
3902
3903 case PLUS_EXPR:
3904 *reduc_fn = IFN_REDUC_PLUS;
3905 return true;
3906
3907 case BIT_AND_EXPR:
3908 *reduc_fn = IFN_REDUC_AND;
3909 return true;
3910
3911 case BIT_IOR_EXPR:
3912 *reduc_fn = IFN_REDUC_IOR;
3913 return true;
3914
3915 case BIT_XOR_EXPR:
3916 *reduc_fn = IFN_REDUC_XOR;
3917 return true;
3918
3919 case MULT_EXPR:
3920 case MINUS_EXPR:
3921 *reduc_fn = IFN_LAST;
3922 return true;
3923
3924 default:
3925 return false;
3926 }
3927 else
3928 switch (combined_fn (code))
3929 {
3930 CASE_CFN_FMAX:
3931 *reduc_fn = IFN_REDUC_FMAX;
3932 return true;
3933
3934 CASE_CFN_FMIN:
3935 *reduc_fn = IFN_REDUC_FMIN;
3936 return true;
3937
3938 default:
3939 return false;
3940 }
3941 }
3942
3943 /* If there is a neutral value X such that a reduction would not be affected
3944 by the introduction of additional X elements, return that X, otherwise
3945 return null. CODE is the code of the reduction and SCALAR_TYPE is type
3946 of the scalar elements. If the reduction has just a single initial value
3947 then INITIAL_VALUE is that value, otherwise it is null.
3948 If AS_INITIAL is TRUE the value is supposed to be used as initial value.
3949 In that case no signed zero is returned. */
3950
3951 tree
3952 neutral_op_for_reduction (tree scalar_type, code_helper code,
3953 tree initial_value, bool as_initial)
3954 {
3955 if (code.is_tree_code ())
3956 switch (tree_code (code))
3957 {
3958 case DOT_PROD_EXPR:
3959 case SAD_EXPR:
3960 case MINUS_EXPR:
3961 case BIT_IOR_EXPR:
3962 case BIT_XOR_EXPR:
3963 return build_zero_cst (scalar_type);
3964 case WIDEN_SUM_EXPR:
3965 case PLUS_EXPR:
3966 if (!as_initial && HONOR_SIGNED_ZEROS (scalar_type))
3967 return build_real (scalar_type, dconstm0);
3968 else
3969 return build_zero_cst (scalar_type);
3970
3971 case MULT_EXPR:
3972 return build_one_cst (scalar_type);
3973
3974 case BIT_AND_EXPR:
3975 return build_all_ones_cst (scalar_type);
3976
3977 case MAX_EXPR:
3978 case MIN_EXPR:
3979 return initial_value;
3980
3981 default:
3982 return NULL_TREE;
3983 }
3984 else
3985 switch (combined_fn (code))
3986 {
3987 CASE_CFN_FMIN:
3988 CASE_CFN_FMAX:
3989 return initial_value;
3990
3991 default:
3992 return NULL_TREE;
3993 }
3994 }
3995
3996 /* Error reporting helper for vect_is_simple_reduction below. GIMPLE statement
3997 STMT is printed with a message MSG. */
3998
3999 static void
4000 report_vect_op (dump_flags_t msg_type, gimple *stmt, const char *msg)
4001 {
4002 dump_printf_loc (msg_type, vect_location, "%s%G", msg, stmt);
4003 }
4004
4005 /* Return true if we need an in-order reduction for operation CODE
4006 on type TYPE. NEED_WRAPPING_INTEGRAL_OVERFLOW is true if integer
4007 overflow must wrap. */
4008
4009 bool
4010 needs_fold_left_reduction_p (tree type, code_helper code)
4011 {
4012 /* CHECKME: check for !flag_finite_math_only too? */
4013 if (SCALAR_FLOAT_TYPE_P (type))
4014 {
4015 if (code.is_tree_code ())
4016 switch (tree_code (code))
4017 {
4018 case MIN_EXPR:
4019 case MAX_EXPR:
4020 return false;
4021
4022 default:
4023 return !flag_associative_math;
4024 }
4025 else
4026 switch (combined_fn (code))
4027 {
4028 CASE_CFN_FMIN:
4029 CASE_CFN_FMAX:
4030 return false;
4031
4032 default:
4033 return !flag_associative_math;
4034 }
4035 }
4036
4037 if (INTEGRAL_TYPE_P (type))
4038 return (!code.is_tree_code ()
4039 || !operation_no_trapping_overflow (type, tree_code (code)));
4040
4041 if (SAT_FIXED_POINT_TYPE_P (type))
4042 return true;
4043
4044 return false;
4045 }
4046
4047 /* Return true if the reduction PHI in LOOP with latch arg LOOP_ARG and
4048 has a handled computation expression. Store the main reduction
4049 operation in *CODE. */
4050
4051 static bool
4052 check_reduction_path (dump_user_location_t loc, loop_p loop, gphi *phi,
4053 tree loop_arg, code_helper *code,
4054 vec<std::pair<ssa_op_iter, use_operand_p> > &path,
4055 bool inner_loop_of_double_reduc)
4056 {
4057 auto_bitmap visited;
4058 tree lookfor = PHI_RESULT (phi);
4059 ssa_op_iter curri;
4060 use_operand_p curr = op_iter_init_phiuse (&curri, phi, SSA_OP_USE);
4061 while (USE_FROM_PTR (curr) != loop_arg)
4062 curr = op_iter_next_use (&curri);
4063 curri.i = curri.numops;
4064 do
4065 {
4066 path.safe_push (std::make_pair (curri, curr));
4067 tree use = USE_FROM_PTR (curr);
4068 if (use == lookfor)
4069 break;
4070 gimple *def = SSA_NAME_DEF_STMT (use);
4071 if (gimple_nop_p (def)
4072 || ! flow_bb_inside_loop_p (loop, gimple_bb (def)))
4073 {
4074 pop:
4075 do
4076 {
4077 std::pair<ssa_op_iter, use_operand_p> x = path.pop ();
4078 curri = x.first;
4079 curr = x.second;
4080 do
4081 curr = op_iter_next_use (&curri);
4082 /* Skip already visited or non-SSA operands (from iterating
4083 over PHI args). */
4084 while (curr != NULL_USE_OPERAND_P
4085 && (TREE_CODE (USE_FROM_PTR (curr)) != SSA_NAME
4086 || ! bitmap_set_bit (visited,
4087 SSA_NAME_VERSION
4088 (USE_FROM_PTR (curr)))));
4089 }
4090 while (curr == NULL_USE_OPERAND_P && ! path.is_empty ());
4091 if (curr == NULL_USE_OPERAND_P)
4092 break;
4093 }
4094 else
4095 {
4096 if (gimple_code (def) == GIMPLE_PHI)
4097 curr = op_iter_init_phiuse (&curri, as_a <gphi *>(def), SSA_OP_USE);
4098 else
4099 curr = op_iter_init_use (&curri, def, SSA_OP_USE);
4100 while (curr != NULL_USE_OPERAND_P
4101 && (TREE_CODE (USE_FROM_PTR (curr)) != SSA_NAME
4102 || ! bitmap_set_bit (visited,
4103 SSA_NAME_VERSION
4104 (USE_FROM_PTR (curr)))))
4105 curr = op_iter_next_use (&curri);
4106 if (curr == NULL_USE_OPERAND_P)
4107 goto pop;
4108 }
4109 }
4110 while (1);
4111 if (dump_file && (dump_flags & TDF_DETAILS))
4112 {
4113 dump_printf_loc (MSG_NOTE, loc, "reduction path: ");
4114 unsigned i;
4115 std::pair<ssa_op_iter, use_operand_p> *x;
4116 FOR_EACH_VEC_ELT (path, i, x)
4117 dump_printf (MSG_NOTE, "%T ", USE_FROM_PTR (x->second));
4118 dump_printf (MSG_NOTE, "\n");
4119 }
4120
4121 /* Check whether the reduction path detected is valid. */
4122 bool fail = path.length () == 0;
4123 bool neg = false;
4124 int sign = -1;
4125 *code = ERROR_MARK;
4126 for (unsigned i = 1; i < path.length (); ++i)
4127 {
4128 gimple *use_stmt = USE_STMT (path[i].second);
4129 gimple_match_op op;
4130 if (!gimple_extract_op (use_stmt, &op))
4131 {
4132 fail = true;
4133 break;
4134 }
4135 unsigned int opi = op.num_ops;
4136 if (gassign *assign = dyn_cast<gassign *> (use_stmt))
4137 {
4138 /* The following make sure we can compute the operand index
4139 easily plus it mostly disallows chaining via COND_EXPR condition
4140 operands. */
4141 for (opi = 0; opi < op.num_ops; ++opi)
4142 if (gimple_assign_rhs1_ptr (assign) + opi == path[i].second->use)
4143 break;
4144 }
4145 else if (gcall *call = dyn_cast<gcall *> (use_stmt))
4146 {
4147 for (opi = 0; opi < op.num_ops; ++opi)
4148 if (gimple_call_arg_ptr (call, opi) == path[i].second->use)
4149 break;
4150 }
4151 if (opi == op.num_ops)
4152 {
4153 fail = true;
4154 break;
4155 }
4156 op.code = canonicalize_code (op.code, op.type);
4157 if (op.code == MINUS_EXPR)
4158 {
4159 op.code = PLUS_EXPR;
4160 /* Track whether we negate the reduction value each iteration. */
4161 if (op.ops[1] == op.ops[opi])
4162 neg = ! neg;
4163 }
4164 else if (op.code == IFN_COND_SUB)
4165 {
4166 op.code = IFN_COND_ADD;
4167 /* Track whether we negate the reduction value each iteration. */
4168 if (op.ops[2] == op.ops[opi])
4169 neg = ! neg;
4170 }
4171 if (CONVERT_EXPR_CODE_P (op.code)
4172 && tree_nop_conversion_p (op.type, TREE_TYPE (op.ops[0])))
4173 ;
4174 else if (*code == ERROR_MARK)
4175 {
4176 *code = op.code;
4177 sign = TYPE_SIGN (op.type);
4178 }
4179 else if (op.code != *code)
4180 {
4181 fail = true;
4182 break;
4183 }
4184 else if ((op.code == MIN_EXPR
4185 || op.code == MAX_EXPR)
4186 && sign != TYPE_SIGN (op.type))
4187 {
4188 fail = true;
4189 break;
4190 }
4191 /* Check there's only a single stmt the op is used on. For the
4192 not value-changing tail and the last stmt allow out-of-loop uses,
4193 but not when this is the inner loop of a double reduction.
4194 ??? We could relax this and handle arbitrary live stmts by
4195 forcing a scalar epilogue for example. */
4196 imm_use_iterator imm_iter;
4197 use_operand_p use_p;
4198 gimple *op_use_stmt;
4199 unsigned cnt = 0;
4200 bool cond_fn_p = op.code.is_internal_fn ()
4201 && (conditional_internal_fn_code (internal_fn (op.code))
4202 != ERROR_MARK);
4203
4204 FOR_EACH_IMM_USE_STMT (op_use_stmt, imm_iter, op.ops[opi])
4205 {
4206 /* In case of a COND_OP (mask, op1, op2, op1) reduction we should
4207 have op1 twice (once as definition, once as else) in the same
4208 operation. Enforce this. */
4209 if (cond_fn_p && op_use_stmt == use_stmt)
4210 {
4211 gcall *call = as_a<gcall *> (use_stmt);
4212 unsigned else_pos
4213 = internal_fn_else_index (internal_fn (op.code));
4214 if (gimple_call_arg (call, else_pos) != op.ops[opi])
4215 {
4216 fail = true;
4217 break;
4218 }
4219 for (unsigned int j = 0; j < gimple_call_num_args (call); ++j)
4220 {
4221 if (j == else_pos)
4222 continue;
4223 if (gimple_call_arg (call, j) == op.ops[opi])
4224 cnt++;
4225 }
4226 }
4227 else if (!is_gimple_debug (op_use_stmt)
4228 && ((*code != ERROR_MARK || inner_loop_of_double_reduc)
4229 || flow_bb_inside_loop_p (loop,
4230 gimple_bb (op_use_stmt))))
4231 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
4232 cnt++;
4233 }
4234
4235 if (cnt != 1)
4236 {
4237 fail = true;
4238 break;
4239 }
4240 }
4241 return ! fail && ! neg && *code != ERROR_MARK;
4242 }
4243
4244 bool
4245 check_reduction_path (dump_user_location_t loc, loop_p loop, gphi *phi,
4246 tree loop_arg, enum tree_code code)
4247 {
4248 auto_vec<std::pair<ssa_op_iter, use_operand_p> > path;
4249 code_helper code_;
4250 return (check_reduction_path (loc, loop, phi, loop_arg, &code_, path, false)
4251 && code_ == code);
4252 }
4253
4254
4255
4256 /* Function vect_is_simple_reduction
4257
4258 (1) Detect a cross-iteration def-use cycle that represents a simple
4259 reduction computation. We look for the following pattern:
4260
4261 loop_header:
4262 a1 = phi < a0, a2 >
4263 a3 = ...
4264 a2 = operation (a3, a1)
4265
4266 or
4267
4268 a3 = ...
4269 loop_header:
4270 a1 = phi < a0, a2 >
4271 a2 = operation (a3, a1)
4272
4273 such that:
4274 1. operation is commutative and associative and it is safe to
4275 change the order of the computation
4276 2. no uses for a2 in the loop (a2 is used out of the loop)
4277 3. no uses of a1 in the loop besides the reduction operation
4278 4. no uses of a1 outside the loop.
4279
4280 Conditions 1,4 are tested here.
4281 Conditions 2,3 are tested in vect_mark_stmts_to_be_vectorized.
4282
4283 (2) Detect a cross-iteration def-use cycle in nested loops, i.e.,
4284 nested cycles.
4285
4286 (3) Detect cycles of phi nodes in outer-loop vectorization, i.e., double
4287 reductions:
4288
4289 a1 = phi < a0, a2 >
4290 inner loop (def of a3)
4291 a2 = phi < a3 >
4292
4293 (4) Detect condition expressions, ie:
4294 for (int i = 0; i < N; i++)
4295 if (a[i] < val)
4296 ret_val = a[i];
4297
4298 */
4299
4300 static stmt_vec_info
4301 vect_is_simple_reduction (loop_vec_info loop_info, stmt_vec_info phi_info,
4302 bool *double_reduc, bool *reduc_chain_p, bool slp)
4303 {
4304 gphi *phi = as_a <gphi *> (phi_info->stmt);
4305 gimple *phi_use_stmt = NULL;
4306 imm_use_iterator imm_iter;
4307 use_operand_p use_p;
4308
4309 *double_reduc = false;
4310 *reduc_chain_p = false;
4311 STMT_VINFO_REDUC_TYPE (phi_info) = TREE_CODE_REDUCTION;
4312
4313 tree phi_name = PHI_RESULT (phi);
4314 /* ??? If there are no uses of the PHI result the inner loop reduction
4315 won't be detected as possibly double-reduction by vectorizable_reduction
4316 because that tries to walk the PHI arg from the preheader edge which
4317 can be constant. See PR60382. */
4318 if (has_zero_uses (phi_name))
4319 return NULL;
4320 class loop *loop = (gimple_bb (phi))->loop_father;
4321 unsigned nphi_def_loop_uses = 0;
4322 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, phi_name)
4323 {
4324 gimple *use_stmt = USE_STMT (use_p);
4325 if (is_gimple_debug (use_stmt))
4326 continue;
4327
4328 if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
4329 {
4330 if (dump_enabled_p ())
4331 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4332 "intermediate value used outside loop.\n");
4333
4334 return NULL;
4335 }
4336
4337 /* In case of a COND_OP (mask, op1, op2, op1) reduction we might have
4338 op1 twice (once as definition, once as else) in the same operation.
4339 Only count it as one. */
4340 if (use_stmt != phi_use_stmt)
4341 {
4342 nphi_def_loop_uses++;
4343 phi_use_stmt = use_stmt;
4344 }
4345 }
4346
4347 tree latch_def = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
4348 if (TREE_CODE (latch_def) != SSA_NAME)
4349 {
4350 if (dump_enabled_p ())
4351 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4352 "reduction: not ssa_name: %T\n", latch_def);
4353 return NULL;
4354 }
4355
4356 stmt_vec_info def_stmt_info = loop_info->lookup_def (latch_def);
4357 if (!def_stmt_info
4358 || !flow_bb_inside_loop_p (loop, gimple_bb (def_stmt_info->stmt)))
4359 return NULL;
4360
4361 bool nested_in_vect_loop
4362 = flow_loop_nested_p (LOOP_VINFO_LOOP (loop_info), loop);
4363 unsigned nlatch_def_loop_uses = 0;
4364 auto_vec<gphi *, 3> lcphis;
4365 bool inner_loop_of_double_reduc = false;
4366 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, latch_def)
4367 {
4368 gimple *use_stmt = USE_STMT (use_p);
4369 if (is_gimple_debug (use_stmt))
4370 continue;
4371 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
4372 nlatch_def_loop_uses++;
4373 else
4374 {
4375 /* We can have more than one loop-closed PHI. */
4376 lcphis.safe_push (as_a <gphi *> (use_stmt));
4377 if (nested_in_vect_loop
4378 && (STMT_VINFO_DEF_TYPE (loop_info->lookup_stmt (use_stmt))
4379 == vect_double_reduction_def))
4380 inner_loop_of_double_reduc = true;
4381 }
4382 }
4383
4384 /* If we are vectorizing an inner reduction we are executing that
4385 in the original order only in case we are not dealing with a
4386 double reduction. */
4387 if (nested_in_vect_loop && !inner_loop_of_double_reduc)
4388 {
4389 if (dump_enabled_p ())
4390 report_vect_op (MSG_NOTE, def_stmt_info->stmt,
4391 "detected nested cycle: ");
4392 return def_stmt_info;
4393 }
4394
4395 /* When the inner loop of a double reduction ends up with more than
4396 one loop-closed PHI we have failed to classify alternate such
4397 PHIs as double reduction, leading to wrong code. See PR103237. */
4398 if (inner_loop_of_double_reduc && lcphis.length () != 1)
4399 {
4400 if (dump_enabled_p ())
4401 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4402 "unhandle double reduction\n");
4403 return NULL;
4404 }
4405
4406 /* If this isn't a nested cycle or if the nested cycle reduction value
4407 is used ouside of the inner loop we cannot handle uses of the reduction
4408 value. */
4409 if (nlatch_def_loop_uses > 1 || nphi_def_loop_uses > 1)
4410 {
4411 if (dump_enabled_p ())
4412 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4413 "reduction used in loop.\n");
4414 return NULL;
4415 }
4416
4417 /* If DEF_STMT is a phi node itself, we expect it to have a single argument
4418 defined in the inner loop. */
4419 if (gphi *def_stmt = dyn_cast <gphi *> (def_stmt_info->stmt))
4420 {
4421 tree op1 = PHI_ARG_DEF (def_stmt, 0);
4422 if (gimple_phi_num_args (def_stmt) != 1
4423 || TREE_CODE (op1) != SSA_NAME)
4424 {
4425 if (dump_enabled_p ())
4426 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4427 "unsupported phi node definition.\n");
4428
4429 return NULL;
4430 }
4431
4432 /* Verify there is an inner cycle composed of the PHI phi_use_stmt
4433 and the latch definition op1. */
4434 gimple *def1 = SSA_NAME_DEF_STMT (op1);
4435 if (gimple_bb (def1)
4436 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
4437 && loop->inner
4438 && flow_bb_inside_loop_p (loop->inner, gimple_bb (def1))
4439 && (is_gimple_assign (def1) || is_gimple_call (def1))
4440 && is_a <gphi *> (phi_use_stmt)
4441 && flow_bb_inside_loop_p (loop->inner, gimple_bb (phi_use_stmt))
4442 && (op1 == PHI_ARG_DEF_FROM_EDGE (phi_use_stmt,
4443 loop_latch_edge (loop->inner)))
4444 && lcphis.length () == 1)
4445 {
4446 if (dump_enabled_p ())
4447 report_vect_op (MSG_NOTE, def_stmt,
4448 "detected double reduction: ");
4449
4450 *double_reduc = true;
4451 return def_stmt_info;
4452 }
4453
4454 return NULL;
4455 }
4456
4457 /* Look for the expression computing latch_def from then loop PHI result. */
4458 auto_vec<std::pair<ssa_op_iter, use_operand_p> > path;
4459 code_helper code;
4460 if (check_reduction_path (vect_location, loop, phi, latch_def, &code,
4461 path, inner_loop_of_double_reduc))
4462 {
4463 STMT_VINFO_REDUC_CODE (phi_info) = code;
4464 if (code == COND_EXPR && !nested_in_vect_loop)
4465 STMT_VINFO_REDUC_TYPE (phi_info) = COND_REDUCTION;
4466
4467 /* Fill in STMT_VINFO_REDUC_IDX and gather stmts for an SLP
4468 reduction chain for which the additional restriction is that
4469 all operations in the chain are the same. */
4470 auto_vec<stmt_vec_info, 8> reduc_chain;
4471 unsigned i;
4472 bool is_slp_reduc = !nested_in_vect_loop && code != COND_EXPR;
4473 for (i = path.length () - 1; i >= 1; --i)
4474 {
4475 gimple *stmt = USE_STMT (path[i].second);
4476 stmt_vec_info stmt_info = loop_info->lookup_stmt (stmt);
4477 gimple_match_op op;
4478 if (!gimple_extract_op (stmt, &op))
4479 gcc_unreachable ();
4480 if (gassign *assign = dyn_cast<gassign *> (stmt))
4481 STMT_VINFO_REDUC_IDX (stmt_info)
4482 = path[i].second->use - gimple_assign_rhs1_ptr (assign);
4483 else
4484 {
4485 gcall *call = as_a<gcall *> (stmt);
4486 STMT_VINFO_REDUC_IDX (stmt_info)
4487 = path[i].second->use - gimple_call_arg_ptr (call, 0);
4488 }
4489 bool leading_conversion = (CONVERT_EXPR_CODE_P (op.code)
4490 && (i == 1 || i == path.length () - 1));
4491 if ((op.code != code && !leading_conversion)
4492 /* We can only handle the final value in epilogue
4493 generation for reduction chains. */
4494 || (i != 1 && !has_single_use (gimple_get_lhs (stmt))))
4495 is_slp_reduc = false;
4496 /* For reduction chains we support a trailing/leading
4497 conversions. We do not store those in the actual chain. */
4498 if (leading_conversion)
4499 continue;
4500 reduc_chain.safe_push (stmt_info);
4501 }
4502 if (slp && is_slp_reduc && reduc_chain.length () > 1)
4503 {
4504 for (unsigned i = 0; i < reduc_chain.length () - 1; ++i)
4505 {
4506 REDUC_GROUP_FIRST_ELEMENT (reduc_chain[i]) = reduc_chain[0];
4507 REDUC_GROUP_NEXT_ELEMENT (reduc_chain[i]) = reduc_chain[i+1];
4508 }
4509 REDUC_GROUP_FIRST_ELEMENT (reduc_chain.last ()) = reduc_chain[0];
4510 REDUC_GROUP_NEXT_ELEMENT (reduc_chain.last ()) = NULL;
4511
4512 /* Save the chain for further analysis in SLP detection. */
4513 LOOP_VINFO_REDUCTION_CHAINS (loop_info).safe_push (reduc_chain[0]);
4514 REDUC_GROUP_SIZE (reduc_chain[0]) = reduc_chain.length ();
4515
4516 *reduc_chain_p = true;
4517 if (dump_enabled_p ())
4518 dump_printf_loc (MSG_NOTE, vect_location,
4519 "reduction: detected reduction chain\n");
4520 }
4521 else if (dump_enabled_p ())
4522 dump_printf_loc (MSG_NOTE, vect_location,
4523 "reduction: detected reduction\n");
4524
4525 return def_stmt_info;
4526 }
4527
4528 if (dump_enabled_p ())
4529 dump_printf_loc (MSG_NOTE, vect_location,
4530 "reduction: unknown pattern\n");
4531
4532 return NULL;
4533 }
4534
4535 /* Estimate the number of peeled epilogue iterations for LOOP_VINFO.
4536 PEEL_ITERS_PROLOGUE is the number of peeled prologue iterations,
4537 or -1 if not known. */
4538
4539 static int
4540 vect_get_peel_iters_epilogue (loop_vec_info loop_vinfo, int peel_iters_prologue)
4541 {
4542 int assumed_vf = vect_vf_for_cost (loop_vinfo);
4543 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) || peel_iters_prologue == -1)
4544 {
4545 if (dump_enabled_p ())
4546 dump_printf_loc (MSG_NOTE, vect_location,
4547 "cost model: epilogue peel iters set to vf/2 "
4548 "because loop iterations are unknown .\n");
4549 return assumed_vf / 2;
4550 }
4551 else
4552 {
4553 int niters = LOOP_VINFO_INT_NITERS (loop_vinfo);
4554 peel_iters_prologue = MIN (niters, peel_iters_prologue);
4555 int peel_iters_epilogue = (niters - peel_iters_prologue) % assumed_vf;
4556 /* If we need to peel for gaps, but no peeling is required, we have to
4557 peel VF iterations. */
4558 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) && !peel_iters_epilogue)
4559 peel_iters_epilogue = assumed_vf;
4560 return peel_iters_epilogue;
4561 }
4562 }
4563
4564 /* Calculate cost of peeling the loop PEEL_ITERS_PROLOGUE times. */
4565 int
4566 vect_get_known_peeling_cost (loop_vec_info loop_vinfo, int peel_iters_prologue,
4567 int *peel_iters_epilogue,
4568 stmt_vector_for_cost *scalar_cost_vec,
4569 stmt_vector_for_cost *prologue_cost_vec,
4570 stmt_vector_for_cost *epilogue_cost_vec)
4571 {
4572 int retval = 0;
4573
4574 *peel_iters_epilogue
4575 = vect_get_peel_iters_epilogue (loop_vinfo, peel_iters_prologue);
4576
4577 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
4578 {
4579 /* If peeled iterations are known but number of scalar loop
4580 iterations are unknown, count a taken branch per peeled loop. */
4581 if (peel_iters_prologue > 0)
4582 retval = record_stmt_cost (prologue_cost_vec, 1, cond_branch_taken,
4583 vect_prologue);
4584 if (*peel_iters_epilogue > 0)
4585 retval += record_stmt_cost (epilogue_cost_vec, 1, cond_branch_taken,
4586 vect_epilogue);
4587 }
4588
4589 stmt_info_for_cost *si;
4590 int j;
4591 if (peel_iters_prologue)
4592 FOR_EACH_VEC_ELT (*scalar_cost_vec, j, si)
4593 retval += record_stmt_cost (prologue_cost_vec,
4594 si->count * peel_iters_prologue,
4595 si->kind, si->stmt_info, si->misalign,
4596 vect_prologue);
4597 if (*peel_iters_epilogue)
4598 FOR_EACH_VEC_ELT (*scalar_cost_vec, j, si)
4599 retval += record_stmt_cost (epilogue_cost_vec,
4600 si->count * *peel_iters_epilogue,
4601 si->kind, si->stmt_info, si->misalign,
4602 vect_epilogue);
4603
4604 return retval;
4605 }
4606
4607 /* Function vect_estimate_min_profitable_iters
4608
4609 Return the number of iterations required for the vector version of the
4610 loop to be profitable relative to the cost of the scalar version of the
4611 loop.
4612
4613 *RET_MIN_PROFITABLE_NITERS is a cost model profitability threshold
4614 of iterations for vectorization. -1 value means loop vectorization
4615 is not profitable. This returned value may be used for dynamic
4616 profitability check.
4617
4618 *RET_MIN_PROFITABLE_ESTIMATE is a profitability threshold to be used
4619 for static check against estimated number of iterations. */
4620
4621 static void
4622 vect_estimate_min_profitable_iters (loop_vec_info loop_vinfo,
4623 int *ret_min_profitable_niters,
4624 int *ret_min_profitable_estimate,
4625 unsigned *suggested_unroll_factor)
4626 {
4627 int min_profitable_iters;
4628 int min_profitable_estimate;
4629 int peel_iters_prologue;
4630 int peel_iters_epilogue;
4631 unsigned vec_inside_cost = 0;
4632 int vec_outside_cost = 0;
4633 unsigned vec_prologue_cost = 0;
4634 unsigned vec_epilogue_cost = 0;
4635 int scalar_single_iter_cost = 0;
4636 int scalar_outside_cost = 0;
4637 int assumed_vf = vect_vf_for_cost (loop_vinfo);
4638 int npeel = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
4639 vector_costs *target_cost_data = loop_vinfo->vector_costs;
4640
4641 /* Cost model disabled. */
4642 if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
4643 {
4644 if (dump_enabled_p ())
4645 dump_printf_loc (MSG_NOTE, vect_location, "cost model disabled.\n");
4646 *ret_min_profitable_niters = 0;
4647 *ret_min_profitable_estimate = 0;
4648 return;
4649 }
4650
4651 /* Requires loop versioning tests to handle misalignment. */
4652 if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo))
4653 {
4654 /* FIXME: Make cost depend on complexity of individual check. */
4655 unsigned len = LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).length ();
4656 (void) add_stmt_cost (target_cost_data, len, scalar_stmt, vect_prologue);
4657 if (dump_enabled_p ())
4658 dump_printf (MSG_NOTE,
4659 "cost model: Adding cost of checks for loop "
4660 "versioning to treat misalignment.\n");
4661 }
4662
4663 /* Requires loop versioning with alias checks. */
4664 if (LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
4665 {
4666 /* FIXME: Make cost depend on complexity of individual check. */
4667 unsigned len = LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).length ();
4668 (void) add_stmt_cost (target_cost_data, len, scalar_stmt, vect_prologue);
4669 len = LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo).length ();
4670 if (len)
4671 /* Count LEN - 1 ANDs and LEN comparisons. */
4672 (void) add_stmt_cost (target_cost_data, len * 2 - 1,
4673 scalar_stmt, vect_prologue);
4674 len = LOOP_VINFO_LOWER_BOUNDS (loop_vinfo).length ();
4675 if (len)
4676 {
4677 /* Count LEN - 1 ANDs and LEN comparisons. */
4678 unsigned int nstmts = len * 2 - 1;
4679 /* +1 for each bias that needs adding. */
4680 for (unsigned int i = 0; i < len; ++i)
4681 if (!LOOP_VINFO_LOWER_BOUNDS (loop_vinfo)[i].unsigned_p)
4682 nstmts += 1;
4683 (void) add_stmt_cost (target_cost_data, nstmts,
4684 scalar_stmt, vect_prologue);
4685 }
4686 if (dump_enabled_p ())
4687 dump_printf (MSG_NOTE,
4688 "cost model: Adding cost of checks for loop "
4689 "versioning aliasing.\n");
4690 }
4691
4692 /* Requires loop versioning with niter checks. */
4693 if (LOOP_REQUIRES_VERSIONING_FOR_NITERS (loop_vinfo))
4694 {
4695 /* FIXME: Make cost depend on complexity of individual check. */
4696 (void) add_stmt_cost (target_cost_data, 1, vector_stmt,
4697 NULL, NULL, NULL_TREE, 0, vect_prologue);
4698 if (dump_enabled_p ())
4699 dump_printf (MSG_NOTE,
4700 "cost model: Adding cost of checks for loop "
4701 "versioning niters.\n");
4702 }
4703
4704 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
4705 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
4706 vect_prologue);
4707
4708 /* Count statements in scalar loop. Using this as scalar cost for a single
4709 iteration for now.
4710
4711 TODO: Add outer loop support.
4712
4713 TODO: Consider assigning different costs to different scalar
4714 statements. */
4715
4716 scalar_single_iter_cost = loop_vinfo->scalar_costs->total_cost ();
4717
4718 /* Add additional cost for the peeled instructions in prologue and epilogue
4719 loop. (For fully-masked loops there will be no peeling.)
4720
4721 FORNOW: If we don't know the value of peel_iters for prologue or epilogue
4722 at compile-time - we assume it's vf/2 (the worst would be vf-1).
4723
4724 TODO: Build an expression that represents peel_iters for prologue and
4725 epilogue to be used in a run-time test. */
4726
4727 bool prologue_need_br_taken_cost = false;
4728 bool prologue_need_br_not_taken_cost = false;
4729
4730 /* Calculate peel_iters_prologue. */
4731 if (vect_use_loop_mask_for_alignment_p (loop_vinfo))
4732 peel_iters_prologue = 0;
4733 else if (npeel < 0)
4734 {
4735 peel_iters_prologue = assumed_vf / 2;
4736 if (dump_enabled_p ())
4737 dump_printf (MSG_NOTE, "cost model: "
4738 "prologue peel iters set to vf/2.\n");
4739
4740 /* If peeled iterations are unknown, count a taken branch and a not taken
4741 branch per peeled loop. Even if scalar loop iterations are known,
4742 vector iterations are not known since peeled prologue iterations are
4743 not known. Hence guards remain the same. */
4744 prologue_need_br_taken_cost = true;
4745 prologue_need_br_not_taken_cost = true;
4746 }
4747 else
4748 {
4749 peel_iters_prologue = npeel;
4750 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && peel_iters_prologue > 0)
4751 /* If peeled iterations are known but number of scalar loop
4752 iterations are unknown, count a taken branch per peeled loop. */
4753 prologue_need_br_taken_cost = true;
4754 }
4755
4756 bool epilogue_need_br_taken_cost = false;
4757 bool epilogue_need_br_not_taken_cost = false;
4758
4759 /* Calculate peel_iters_epilogue. */
4760 if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
4761 /* We need to peel exactly one iteration for gaps. */
4762 peel_iters_epilogue = LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) ? 1 : 0;
4763 else if (npeel < 0)
4764 {
4765 /* If peeling for alignment is unknown, loop bound of main loop
4766 becomes unknown. */
4767 peel_iters_epilogue = assumed_vf / 2;
4768 if (dump_enabled_p ())
4769 dump_printf (MSG_NOTE, "cost model: "
4770 "epilogue peel iters set to vf/2 because "
4771 "peeling for alignment is unknown.\n");
4772
4773 /* See the same reason above in peel_iters_prologue calculation. */
4774 epilogue_need_br_taken_cost = true;
4775 epilogue_need_br_not_taken_cost = true;
4776 }
4777 else
4778 {
4779 peel_iters_epilogue = vect_get_peel_iters_epilogue (loop_vinfo, npeel);
4780 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && peel_iters_epilogue > 0)
4781 /* If peeled iterations are known but number of scalar loop
4782 iterations are unknown, count a taken branch per peeled loop. */
4783 epilogue_need_br_taken_cost = true;
4784 }
4785
4786 stmt_info_for_cost *si;
4787 int j;
4788 /* Add costs associated with peel_iters_prologue. */
4789 if (peel_iters_prologue)
4790 FOR_EACH_VEC_ELT (LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo), j, si)
4791 {
4792 (void) add_stmt_cost (target_cost_data,
4793 si->count * peel_iters_prologue, si->kind,
4794 si->stmt_info, si->node, si->vectype,
4795 si->misalign, vect_prologue);
4796 }
4797
4798 /* Add costs associated with peel_iters_epilogue. */
4799 if (peel_iters_epilogue)
4800 FOR_EACH_VEC_ELT (LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo), j, si)
4801 {
4802 (void) add_stmt_cost (target_cost_data,
4803 si->count * peel_iters_epilogue, si->kind,
4804 si->stmt_info, si->node, si->vectype,
4805 si->misalign, vect_epilogue);
4806 }
4807
4808 /* Add possible cond_branch_taken/cond_branch_not_taken cost. */
4809
4810 if (prologue_need_br_taken_cost)
4811 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
4812 vect_prologue);
4813
4814 if (prologue_need_br_not_taken_cost)
4815 (void) add_stmt_cost (target_cost_data, 1,
4816 cond_branch_not_taken, vect_prologue);
4817
4818 if (epilogue_need_br_taken_cost)
4819 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
4820 vect_epilogue);
4821
4822 if (epilogue_need_br_not_taken_cost)
4823 (void) add_stmt_cost (target_cost_data, 1,
4824 cond_branch_not_taken, vect_epilogue);
4825
4826 /* Take care of special costs for rgroup controls of partial vectors. */
4827 if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
4828 && (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo)
4829 == vect_partial_vectors_avx512))
4830 {
4831 /* Calculate how many masks we need to generate. */
4832 unsigned int num_masks = 0;
4833 bool need_saturation = false;
4834 for (auto rgm : LOOP_VINFO_MASKS (loop_vinfo).rgc_vec)
4835 if (rgm.type)
4836 {
4837 unsigned nvectors = rgm.factor;
4838 num_masks += nvectors;
4839 if (TYPE_PRECISION (TREE_TYPE (rgm.compare_type))
4840 < TYPE_PRECISION (LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo)))
4841 need_saturation = true;
4842 }
4843
4844 /* ??? The target isn't able to identify the costs below as
4845 producing masks so it cannot penaltize cases where we'd run
4846 out of mask registers for example. */
4847
4848 /* ??? We are also failing to account for smaller vector masks
4849 we generate by splitting larger masks in vect_get_loop_mask. */
4850
4851 /* In the worst case, we need to generate each mask in the prologue
4852 and in the loop body. We need one splat per group and one
4853 compare per mask.
4854
4855 Sometimes the prologue mask will fold to a constant,
4856 so the actual prologue cost might be smaller. However, it's
4857 simpler and safer to use the worst-case cost; if this ends up
4858 being the tie-breaker between vectorizing or not, then it's
4859 probably better not to vectorize. */
4860 (void) add_stmt_cost (target_cost_data,
4861 num_masks
4862 + LOOP_VINFO_MASKS (loop_vinfo).rgc_vec.length (),
4863 vector_stmt, NULL, NULL, NULL_TREE, 0,
4864 vect_prologue);
4865 (void) add_stmt_cost (target_cost_data,
4866 num_masks
4867 + LOOP_VINFO_MASKS (loop_vinfo).rgc_vec.length (),
4868 vector_stmt, NULL, NULL, NULL_TREE, 0, vect_body);
4869
4870 /* When we need saturation we need it both in the prologue and
4871 the epilogue. */
4872 if (need_saturation)
4873 {
4874 (void) add_stmt_cost (target_cost_data, 1, scalar_stmt,
4875 NULL, NULL, NULL_TREE, 0, vect_prologue);
4876 (void) add_stmt_cost (target_cost_data, 1, scalar_stmt,
4877 NULL, NULL, NULL_TREE, 0, vect_body);
4878 }
4879 }
4880 else if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
4881 && (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo)
4882 == vect_partial_vectors_while_ult))
4883 {
4884 /* Calculate how many masks we need to generate. */
4885 unsigned int num_masks = 0;
4886 rgroup_controls *rgm;
4887 unsigned int num_vectors_m1;
4888 FOR_EACH_VEC_ELT (LOOP_VINFO_MASKS (loop_vinfo).rgc_vec,
4889 num_vectors_m1, rgm)
4890 if (rgm->type)
4891 num_masks += num_vectors_m1 + 1;
4892 gcc_assert (num_masks > 0);
4893
4894 /* In the worst case, we need to generate each mask in the prologue
4895 and in the loop body. One of the loop body mask instructions
4896 replaces the comparison in the scalar loop, and since we don't
4897 count the scalar comparison against the scalar body, we shouldn't
4898 count that vector instruction against the vector body either.
4899
4900 Sometimes we can use unpacks instead of generating prologue
4901 masks and sometimes the prologue mask will fold to a constant,
4902 so the actual prologue cost might be smaller. However, it's
4903 simpler and safer to use the worst-case cost; if this ends up
4904 being the tie-breaker between vectorizing or not, then it's
4905 probably better not to vectorize. */
4906 (void) add_stmt_cost (target_cost_data, num_masks,
4907 vector_stmt, NULL, NULL, NULL_TREE, 0,
4908 vect_prologue);
4909 (void) add_stmt_cost (target_cost_data, num_masks - 1,
4910 vector_stmt, NULL, NULL, NULL_TREE, 0,
4911 vect_body);
4912 }
4913 else if (LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
4914 {
4915 /* Referring to the functions vect_set_loop_condition_partial_vectors
4916 and vect_set_loop_controls_directly, we need to generate each
4917 length in the prologue and in the loop body if required. Although
4918 there are some possible optimizations, we consider the worst case
4919 here. */
4920
4921 bool niters_known_p = LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo);
4922 signed char partial_load_store_bias
4923 = LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo);
4924 bool need_iterate_p
4925 = (!LOOP_VINFO_EPILOGUE_P (loop_vinfo)
4926 && !vect_known_niters_smaller_than_vf (loop_vinfo));
4927
4928 /* Calculate how many statements to be added. */
4929 unsigned int prologue_stmts = 0;
4930 unsigned int body_stmts = 0;
4931
4932 rgroup_controls *rgc;
4933 unsigned int num_vectors_m1;
4934 FOR_EACH_VEC_ELT (LOOP_VINFO_LENS (loop_vinfo), num_vectors_m1, rgc)
4935 if (rgc->type)
4936 {
4937 /* May need one SHIFT for nitems_total computation. */
4938 unsigned nitems = rgc->max_nscalars_per_iter * rgc->factor;
4939 if (nitems != 1 && !niters_known_p)
4940 prologue_stmts += 1;
4941
4942 /* May need one MAX and one MINUS for wrap around. */
4943 if (vect_rgroup_iv_might_wrap_p (loop_vinfo, rgc))
4944 prologue_stmts += 2;
4945
4946 /* Need one MAX and one MINUS for each batch limit excepting for
4947 the 1st one. */
4948 prologue_stmts += num_vectors_m1 * 2;
4949
4950 unsigned int num_vectors = num_vectors_m1 + 1;
4951
4952 /* Need to set up lengths in prologue, only one MIN required
4953 for each since start index is zero. */
4954 prologue_stmts += num_vectors;
4955
4956 /* If we have a non-zero partial load bias, we need one PLUS
4957 to adjust the load length. */
4958 if (partial_load_store_bias != 0)
4959 body_stmts += 1;
4960
4961 unsigned int length_update_cost = 0;
4962 if (LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo))
4963 /* For decrement IV style, Each only need a single SELECT_VL
4964 or MIN since beginning to calculate the number of elements
4965 need to be processed in current iteration. */
4966 length_update_cost = 1;
4967 else
4968 /* For increment IV stype, Each may need two MINs and one MINUS to
4969 update lengths in body for next iteration. */
4970 length_update_cost = 3;
4971
4972 if (need_iterate_p)
4973 body_stmts += length_update_cost * num_vectors;
4974 }
4975
4976 (void) add_stmt_cost (target_cost_data, prologue_stmts,
4977 scalar_stmt, vect_prologue);
4978 (void) add_stmt_cost (target_cost_data, body_stmts,
4979 scalar_stmt, vect_body);
4980 }
4981
4982 /* FORNOW: The scalar outside cost is incremented in one of the
4983 following ways:
4984
4985 1. The vectorizer checks for alignment and aliasing and generates
4986 a condition that allows dynamic vectorization. A cost model
4987 check is ANDED with the versioning condition. Hence scalar code
4988 path now has the added cost of the versioning check.
4989
4990 if (cost > th & versioning_check)
4991 jmp to vector code
4992
4993 Hence run-time scalar is incremented by not-taken branch cost.
4994
4995 2. The vectorizer then checks if a prologue is required. If the
4996 cost model check was not done before during versioning, it has to
4997 be done before the prologue check.
4998
4999 if (cost <= th)
5000 prologue = scalar_iters
5001 if (prologue == 0)
5002 jmp to vector code
5003 else
5004 execute prologue
5005 if (prologue == num_iters)
5006 go to exit
5007
5008 Hence the run-time scalar cost is incremented by a taken branch,
5009 plus a not-taken branch, plus a taken branch cost.
5010
5011 3. The vectorizer then checks if an epilogue is required. If the
5012 cost model check was not done before during prologue check, it
5013 has to be done with the epilogue check.
5014
5015 if (prologue == 0)
5016 jmp to vector code
5017 else
5018 execute prologue
5019 if (prologue == num_iters)
5020 go to exit
5021 vector code:
5022 if ((cost <= th) | (scalar_iters-prologue-epilogue == 0))
5023 jmp to epilogue
5024
5025 Hence the run-time scalar cost should be incremented by 2 taken
5026 branches.
5027
5028 TODO: The back end may reorder the BBS's differently and reverse
5029 conditions/branch directions. Change the estimates below to
5030 something more reasonable. */
5031
5032 /* If the number of iterations is known and we do not do versioning, we can
5033 decide whether to vectorize at compile time. Hence the scalar version
5034 do not carry cost model guard costs. */
5035 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
5036 || LOOP_REQUIRES_VERSIONING (loop_vinfo))
5037 {
5038 /* Cost model check occurs at versioning. */
5039 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
5040 scalar_outside_cost += vect_get_stmt_cost (cond_branch_not_taken);
5041 else
5042 {
5043 /* Cost model check occurs at prologue generation. */
5044 if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
5045 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken)
5046 + vect_get_stmt_cost (cond_branch_not_taken);
5047 /* Cost model check occurs at epilogue generation. */
5048 else
5049 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken);
5050 }
5051 }
5052
5053 /* Complete the target-specific cost calculations. */
5054 loop_vinfo->vector_costs->finish_cost (loop_vinfo->scalar_costs);
5055 vec_prologue_cost = loop_vinfo->vector_costs->prologue_cost ();
5056 vec_inside_cost = loop_vinfo->vector_costs->body_cost ();
5057 vec_epilogue_cost = loop_vinfo->vector_costs->epilogue_cost ();
5058 if (suggested_unroll_factor)
5059 *suggested_unroll_factor
5060 = loop_vinfo->vector_costs->suggested_unroll_factor ();
5061
5062 if (suggested_unroll_factor && *suggested_unroll_factor > 1
5063 && LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo) != MAX_VECTORIZATION_FACTOR
5064 && !known_le (LOOP_VINFO_VECT_FACTOR (loop_vinfo) *
5065 *suggested_unroll_factor,
5066 LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo)))
5067 {
5068 if (dump_enabled_p ())
5069 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5070 "can't unroll as unrolled vectorization factor larger"
5071 " than maximum vectorization factor: "
5072 HOST_WIDE_INT_PRINT_UNSIGNED "\n",
5073 LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo));
5074 *suggested_unroll_factor = 1;
5075 }
5076
5077 vec_outside_cost = (int)(vec_prologue_cost + vec_epilogue_cost);
5078
5079 if (dump_enabled_p ())
5080 {
5081 dump_printf_loc (MSG_NOTE, vect_location, "Cost model analysis: \n");
5082 dump_printf (MSG_NOTE, " Vector inside of loop cost: %d\n",
5083 vec_inside_cost);
5084 dump_printf (MSG_NOTE, " Vector prologue cost: %d\n",
5085 vec_prologue_cost);
5086 dump_printf (MSG_NOTE, " Vector epilogue cost: %d\n",
5087 vec_epilogue_cost);
5088 dump_printf (MSG_NOTE, " Scalar iteration cost: %d\n",
5089 scalar_single_iter_cost);
5090 dump_printf (MSG_NOTE, " Scalar outside cost: %d\n",
5091 scalar_outside_cost);
5092 dump_printf (MSG_NOTE, " Vector outside cost: %d\n",
5093 vec_outside_cost);
5094 dump_printf (MSG_NOTE, " prologue iterations: %d\n",
5095 peel_iters_prologue);
5096 dump_printf (MSG_NOTE, " epilogue iterations: %d\n",
5097 peel_iters_epilogue);
5098 }
5099
5100 /* Calculate number of iterations required to make the vector version
5101 profitable, relative to the loop bodies only. The following condition
5102 must hold true:
5103 SIC * niters + SOC > VIC * ((niters - NPEEL) / VF) + VOC
5104 where
5105 SIC = scalar iteration cost, VIC = vector iteration cost,
5106 VOC = vector outside cost, VF = vectorization factor,
5107 NPEEL = prologue iterations + epilogue iterations,
5108 SOC = scalar outside cost for run time cost model check. */
5109
5110 int saving_per_viter = (scalar_single_iter_cost * assumed_vf
5111 - vec_inside_cost);
5112 if (saving_per_viter <= 0)
5113 {
5114 if (LOOP_VINFO_LOOP (loop_vinfo)->force_vectorize)
5115 warning_at (vect_location.get_location_t (), OPT_Wopenmp_simd,
5116 "vectorization did not happen for a simd loop");
5117
5118 if (dump_enabled_p ())
5119 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5120 "cost model: the vector iteration cost = %d "
5121 "divided by the scalar iteration cost = %d "
5122 "is greater or equal to the vectorization factor = %d"
5123 ".\n",
5124 vec_inside_cost, scalar_single_iter_cost, assumed_vf);
5125 *ret_min_profitable_niters = -1;
5126 *ret_min_profitable_estimate = -1;
5127 return;
5128 }
5129
5130 /* ??? The "if" arm is written to handle all cases; see below for what
5131 we would do for !LOOP_VINFO_USING_PARTIAL_VECTORS_P. */
5132 if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
5133 {
5134 /* Rewriting the condition above in terms of the number of
5135 vector iterations (vniters) rather than the number of
5136 scalar iterations (niters) gives:
5137
5138 SIC * (vniters * VF + NPEEL) + SOC > VIC * vniters + VOC
5139
5140 <==> vniters * (SIC * VF - VIC) > VOC - SIC * NPEEL - SOC
5141
5142 For integer N, X and Y when X > 0:
5143
5144 N * X > Y <==> N >= (Y /[floor] X) + 1. */
5145 int outside_overhead = (vec_outside_cost
5146 - scalar_single_iter_cost * peel_iters_prologue
5147 - scalar_single_iter_cost * peel_iters_epilogue
5148 - scalar_outside_cost);
5149 /* We're only interested in cases that require at least one
5150 vector iteration. */
5151 int min_vec_niters = 1;
5152 if (outside_overhead > 0)
5153 min_vec_niters = outside_overhead / saving_per_viter + 1;
5154
5155 if (dump_enabled_p ())
5156 dump_printf (MSG_NOTE, " Minimum number of vector iterations: %d\n",
5157 min_vec_niters);
5158
5159 if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
5160 {
5161 /* Now that we know the minimum number of vector iterations,
5162 find the minimum niters for which the scalar cost is larger:
5163
5164 SIC * niters > VIC * vniters + VOC - SOC
5165
5166 We know that the minimum niters is no more than
5167 vniters * VF + NPEEL, but it might be (and often is) less
5168 than that if a partial vector iteration is cheaper than the
5169 equivalent scalar code. */
5170 int threshold = (vec_inside_cost * min_vec_niters
5171 + vec_outside_cost
5172 - scalar_outside_cost);
5173 if (threshold <= 0)
5174 min_profitable_iters = 1;
5175 else
5176 min_profitable_iters = threshold / scalar_single_iter_cost + 1;
5177 }
5178 else
5179 /* Convert the number of vector iterations into a number of
5180 scalar iterations. */
5181 min_profitable_iters = (min_vec_niters * assumed_vf
5182 + peel_iters_prologue
5183 + peel_iters_epilogue);
5184 }
5185 else
5186 {
5187 min_profitable_iters = ((vec_outside_cost - scalar_outside_cost)
5188 * assumed_vf
5189 - vec_inside_cost * peel_iters_prologue
5190 - vec_inside_cost * peel_iters_epilogue);
5191 if (min_profitable_iters <= 0)
5192 min_profitable_iters = 0;
5193 else
5194 {
5195 min_profitable_iters /= saving_per_viter;
5196
5197 if ((scalar_single_iter_cost * assumed_vf * min_profitable_iters)
5198 <= (((int) vec_inside_cost * min_profitable_iters)
5199 + (((int) vec_outside_cost - scalar_outside_cost)
5200 * assumed_vf)))
5201 min_profitable_iters++;
5202 }
5203 }
5204
5205 if (dump_enabled_p ())
5206 dump_printf (MSG_NOTE,
5207 " Calculated minimum iters for profitability: %d\n",
5208 min_profitable_iters);
5209
5210 if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
5211 && min_profitable_iters < (assumed_vf + peel_iters_prologue))
5212 /* We want the vectorized loop to execute at least once. */
5213 min_profitable_iters = assumed_vf + peel_iters_prologue;
5214 else if (min_profitable_iters < peel_iters_prologue)
5215 /* For LOOP_VINFO_USING_PARTIAL_VECTORS_P, we need to ensure the
5216 vectorized loop executes at least once. */
5217 min_profitable_iters = peel_iters_prologue;
5218
5219 if (dump_enabled_p ())
5220 dump_printf_loc (MSG_NOTE, vect_location,
5221 " Runtime profitability threshold = %d\n",
5222 min_profitable_iters);
5223
5224 *ret_min_profitable_niters = min_profitable_iters;
5225
5226 /* Calculate number of iterations required to make the vector version
5227 profitable, relative to the loop bodies only.
5228
5229 Non-vectorized variant is SIC * niters and it must win over vector
5230 variant on the expected loop trip count. The following condition must hold true:
5231 SIC * niters > VIC * ((niters - NPEEL) / VF) + VOC + SOC */
5232
5233 if (vec_outside_cost <= 0)
5234 min_profitable_estimate = 0;
5235 /* ??? This "else if" arm is written to handle all cases; see below for
5236 what we would do for !LOOP_VINFO_USING_PARTIAL_VECTORS_P. */
5237 else if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
5238 {
5239 /* This is a repeat of the code above, but with + SOC rather
5240 than - SOC. */
5241 int outside_overhead = (vec_outside_cost
5242 - scalar_single_iter_cost * peel_iters_prologue
5243 - scalar_single_iter_cost * peel_iters_epilogue
5244 + scalar_outside_cost);
5245 int min_vec_niters = 1;
5246 if (outside_overhead > 0)
5247 min_vec_niters = outside_overhead / saving_per_viter + 1;
5248
5249 if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
5250 {
5251 int threshold = (vec_inside_cost * min_vec_niters
5252 + vec_outside_cost
5253 + scalar_outside_cost);
5254 min_profitable_estimate = threshold / scalar_single_iter_cost + 1;
5255 }
5256 else
5257 min_profitable_estimate = (min_vec_niters * assumed_vf
5258 + peel_iters_prologue
5259 + peel_iters_epilogue);
5260 }
5261 else
5262 {
5263 min_profitable_estimate = ((vec_outside_cost + scalar_outside_cost)
5264 * assumed_vf
5265 - vec_inside_cost * peel_iters_prologue
5266 - vec_inside_cost * peel_iters_epilogue)
5267 / ((scalar_single_iter_cost * assumed_vf)
5268 - vec_inside_cost);
5269 }
5270 min_profitable_estimate = MAX (min_profitable_estimate, min_profitable_iters);
5271 if (dump_enabled_p ())
5272 dump_printf_loc (MSG_NOTE, vect_location,
5273 " Static estimate profitability threshold = %d\n",
5274 min_profitable_estimate);
5275
5276 *ret_min_profitable_estimate = min_profitable_estimate;
5277 }
5278
5279 /* Writes into SEL a mask for a vec_perm, equivalent to a vec_shr by OFFSET
5280 vector elements (not bits) for a vector with NELT elements. */
5281 static void
5282 calc_vec_perm_mask_for_shift (unsigned int offset, unsigned int nelt,
5283 vec_perm_builder *sel)
5284 {
5285 /* The encoding is a single stepped pattern. Any wrap-around is handled
5286 by vec_perm_indices. */
5287 sel->new_vector (nelt, 1, 3);
5288 for (unsigned int i = 0; i < 3; i++)
5289 sel->quick_push (i + offset);
5290 }
5291
5292 /* Checks whether the target supports whole-vector shifts for vectors of mode
5293 MODE. This is the case if _either_ the platform handles vec_shr_optab, _or_
5294 it supports vec_perm_const with masks for all necessary shift amounts. */
5295 static bool
5296 have_whole_vector_shift (machine_mode mode)
5297 {
5298 if (can_implement_p (vec_shr_optab, mode))
5299 return true;
5300
5301 /* Variable-length vectors should be handled via the optab. */
5302 unsigned int nelt;
5303 if (!GET_MODE_NUNITS (mode).is_constant (&nelt))
5304 return false;
5305
5306 vec_perm_builder sel;
5307 vec_perm_indices indices;
5308 for (unsigned int i = nelt / 2; i >= 1; i /= 2)
5309 {
5310 calc_vec_perm_mask_for_shift (i, nelt, &sel);
5311 indices.new_vector (sel, 2, nelt);
5312 if (!can_vec_perm_const_p (mode, mode, indices, false))
5313 return false;
5314 }
5315 return true;
5316 }
5317
5318 /* Return true if (a) STMT_INFO is a DOT_PROD_EXPR reduction whose
5319 multiplication operands have differing signs and (b) we intend
5320 to emulate the operation using a series of signed DOT_PROD_EXPRs.
5321 See vect_emulate_mixed_dot_prod for the actual sequence used. */
5322
5323 static bool
5324 vect_is_emulated_mixed_dot_prod (stmt_vec_info stmt_info)
5325 {
5326 gassign *assign = dyn_cast<gassign *> (stmt_info->stmt);
5327 if (!assign || gimple_assign_rhs_code (assign) != DOT_PROD_EXPR)
5328 return false;
5329
5330 tree rhs1 = gimple_assign_rhs1 (assign);
5331 tree rhs2 = gimple_assign_rhs2 (assign);
5332 if (TYPE_SIGN (TREE_TYPE (rhs1)) == TYPE_SIGN (TREE_TYPE (rhs2)))
5333 return false;
5334
5335 gcc_assert (STMT_VINFO_REDUC_VECTYPE_IN (stmt_info));
5336 return !directly_supported_p (DOT_PROD_EXPR,
5337 STMT_VINFO_VECTYPE (stmt_info),
5338 STMT_VINFO_REDUC_VECTYPE_IN (stmt_info),
5339 optab_vector_mixed_sign);
5340 }
5341
5342 /* TODO: Close dependency between vect_model_*_cost and vectorizable_*
5343 functions. Design better to avoid maintenance issues. */
5344
5345 /* Function vect_model_reduction_cost.
5346
5347 Models cost for a reduction operation, including the vector ops
5348 generated within the strip-mine loop in some cases, the initial
5349 definition before the loop, and the epilogue code that must be generated. */
5350
5351 static void
5352 vect_model_reduction_cost (loop_vec_info loop_vinfo,
5353 stmt_vec_info stmt_info, internal_fn reduc_fn,
5354 vect_reduction_type reduction_type,
5355 int ncopies, stmt_vector_for_cost *cost_vec)
5356 {
5357 int prologue_cost = 0, epilogue_cost = 0, inside_cost = 0;
5358 tree vectype;
5359 machine_mode mode;
5360 class loop *loop = NULL;
5361
5362 if (loop_vinfo)
5363 loop = LOOP_VINFO_LOOP (loop_vinfo);
5364
5365 /* Condition reductions generate two reductions in the loop. */
5366 if (reduction_type == COND_REDUCTION)
5367 ncopies *= 2;
5368
5369 vectype = STMT_VINFO_VECTYPE (stmt_info);
5370 mode = TYPE_MODE (vectype);
5371 stmt_vec_info orig_stmt_info = vect_orig_stmt (stmt_info);
5372
5373 gimple_match_op op;
5374 if (!gimple_extract_op (orig_stmt_info->stmt, &op))
5375 gcc_unreachable ();
5376
5377 if (reduction_type == EXTRACT_LAST_REDUCTION)
5378 /* No extra instructions are needed in the prologue. The loop body
5379 operations are costed in vectorizable_condition. */
5380 inside_cost = 0;
5381 else if (reduction_type == FOLD_LEFT_REDUCTION)
5382 {
5383 /* No extra instructions needed in the prologue. */
5384 prologue_cost = 0;
5385
5386 if (reduc_fn != IFN_LAST)
5387 /* Count one reduction-like operation per vector. */
5388 inside_cost = record_stmt_cost (cost_vec, ncopies, vec_to_scalar,
5389 stmt_info, 0, vect_body);
5390 else
5391 {
5392 /* Use NELEMENTS extracts and NELEMENTS scalar ops. */
5393 unsigned int nelements = ncopies * vect_nunits_for_cost (vectype);
5394 inside_cost = record_stmt_cost (cost_vec, nelements,
5395 vec_to_scalar, stmt_info, 0,
5396 vect_body);
5397 inside_cost += record_stmt_cost (cost_vec, nelements,
5398 scalar_stmt, stmt_info, 0,
5399 vect_body);
5400 }
5401 }
5402 else
5403 {
5404 /* Add in the cost of the initial definitions. */
5405 int prologue_stmts;
5406 if (reduction_type == COND_REDUCTION)
5407 /* For cond reductions we have four vectors: initial index, step,
5408 initial result of the data reduction, initial value of the index
5409 reduction. */
5410 prologue_stmts = 4;
5411 else
5412 /* We need the initial reduction value. */
5413 prologue_stmts = 1;
5414 prologue_cost += record_stmt_cost (cost_vec, prologue_stmts,
5415 scalar_to_vec, stmt_info, 0,
5416 vect_prologue);
5417 }
5418
5419 /* Determine cost of epilogue code.
5420
5421 We have a reduction operator that will reduce the vector in one statement.
5422 Also requires scalar extract. */
5423
5424 if (!loop || !nested_in_vect_loop_p (loop, orig_stmt_info))
5425 {
5426 if (reduc_fn != IFN_LAST)
5427 {
5428 if (reduction_type == COND_REDUCTION)
5429 {
5430 /* An EQ stmt and an COND_EXPR stmt. */
5431 epilogue_cost += record_stmt_cost (cost_vec, 2,
5432 vector_stmt, stmt_info, 0,
5433 vect_epilogue);
5434 /* Reduction of the max index and a reduction of the found
5435 values. */
5436 epilogue_cost += record_stmt_cost (cost_vec, 2,
5437 vec_to_scalar, stmt_info, 0,
5438 vect_epilogue);
5439 /* A broadcast of the max value. */
5440 epilogue_cost += record_stmt_cost (cost_vec, 1,
5441 scalar_to_vec, stmt_info, 0,
5442 vect_epilogue);
5443 }
5444 else
5445 {
5446 epilogue_cost += record_stmt_cost (cost_vec, 1, vector_stmt,
5447 stmt_info, 0, vect_epilogue);
5448 epilogue_cost += record_stmt_cost (cost_vec, 1,
5449 vec_to_scalar, stmt_info, 0,
5450 vect_epilogue);
5451 }
5452 }
5453 else if (reduction_type == COND_REDUCTION)
5454 {
5455 unsigned estimated_nunits = vect_nunits_for_cost (vectype);
5456 /* Extraction of scalar elements. */
5457 epilogue_cost += record_stmt_cost (cost_vec,
5458 2 * estimated_nunits,
5459 vec_to_scalar, stmt_info, 0,
5460 vect_epilogue);
5461 /* Scalar max reductions via COND_EXPR / MAX_EXPR. */
5462 epilogue_cost += record_stmt_cost (cost_vec,
5463 2 * estimated_nunits - 3,
5464 scalar_stmt, stmt_info, 0,
5465 vect_epilogue);
5466 }
5467 else if (reduction_type == EXTRACT_LAST_REDUCTION
5468 || reduction_type == FOLD_LEFT_REDUCTION)
5469 /* No extra instructions need in the epilogue. */
5470 ;
5471 else
5472 {
5473 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
5474 tree bitsize = TYPE_SIZE (op.type);
5475 int element_bitsize = tree_to_uhwi (bitsize);
5476 int nelements = vec_size_in_bits / element_bitsize;
5477
5478 if (op.code == COND_EXPR)
5479 op.code = MAX_EXPR;
5480
5481 /* We have a whole vector shift available. */
5482 if (VECTOR_MODE_P (mode)
5483 && directly_supported_p (op.code, vectype)
5484 && have_whole_vector_shift (mode))
5485 {
5486 /* Final reduction via vector shifts and the reduction operator.
5487 Also requires scalar extract. */
5488 epilogue_cost += record_stmt_cost (cost_vec,
5489 exact_log2 (nelements) * 2,
5490 vector_stmt, stmt_info, 0,
5491 vect_epilogue);
5492 epilogue_cost += record_stmt_cost (cost_vec, 1,
5493 vec_to_scalar, stmt_info, 0,
5494 vect_epilogue);
5495 }
5496 else
5497 /* Use extracts and reduction op for final reduction. For N
5498 elements, we have N extracts and N-1 reduction ops. */
5499 epilogue_cost += record_stmt_cost (cost_vec,
5500 nelements + nelements - 1,
5501 vector_stmt, stmt_info, 0,
5502 vect_epilogue);
5503 }
5504 }
5505
5506 if (dump_enabled_p ())
5507 dump_printf (MSG_NOTE,
5508 "vect_model_reduction_cost: inside_cost = %d, "
5509 "prologue_cost = %d, epilogue_cost = %d .\n", inside_cost,
5510 prologue_cost, epilogue_cost);
5511 }
5512
5513 /* SEQ is a sequence of instructions that initialize the reduction
5514 described by REDUC_INFO. Emit them in the appropriate place. */
5515
5516 static void
5517 vect_emit_reduction_init_stmts (loop_vec_info loop_vinfo,
5518 stmt_vec_info reduc_info, gimple *seq)
5519 {
5520 if (reduc_info->reused_accumulator)
5521 {
5522 /* When reusing an accumulator from the main loop, we only need
5523 initialization instructions if the main loop can be skipped.
5524 In that case, emit the initialization instructions at the end
5525 of the guard block that does the skip. */
5526 edge skip_edge = loop_vinfo->skip_main_loop_edge;
5527 gcc_assert (skip_edge);
5528 gimple_stmt_iterator gsi = gsi_last_bb (skip_edge->src);
5529 gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
5530 }
5531 else
5532 {
5533 /* The normal case: emit the initialization instructions on the
5534 preheader edge. */
5535 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
5536 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), seq);
5537 }
5538 }
5539
5540 /* Function get_initial_def_for_reduction
5541
5542 Input:
5543 REDUC_INFO - the info_for_reduction
5544 INIT_VAL - the initial value of the reduction variable
5545 NEUTRAL_OP - a value that has no effect on the reduction, as per
5546 neutral_op_for_reduction
5547
5548 Output:
5549 Return a vector variable, initialized according to the operation that
5550 STMT_VINFO performs. This vector will be used as the initial value
5551 of the vector of partial results.
5552
5553 The value we need is a vector in which element 0 has value INIT_VAL
5554 and every other element has value NEUTRAL_OP. */
5555
5556 static tree
5557 get_initial_def_for_reduction (loop_vec_info loop_vinfo,
5558 stmt_vec_info reduc_info,
5559 tree init_val, tree neutral_op)
5560 {
5561 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
5562 tree scalar_type = TREE_TYPE (init_val);
5563 tree vectype = get_vectype_for_scalar_type (loop_vinfo, scalar_type);
5564 tree init_def;
5565 gimple_seq stmts = NULL;
5566
5567 gcc_assert (vectype);
5568
5569 gcc_assert (POINTER_TYPE_P (scalar_type) || INTEGRAL_TYPE_P (scalar_type)
5570 || SCALAR_FLOAT_TYPE_P (scalar_type));
5571
5572 gcc_assert (nested_in_vect_loop_p (loop, reduc_info)
5573 || loop == (gimple_bb (reduc_info->stmt))->loop_father);
5574
5575 if (operand_equal_p (init_val, neutral_op))
5576 {
5577 /* If both elements are equal then the vector described above is
5578 just a splat. */
5579 neutral_op = gimple_convert (&stmts, TREE_TYPE (vectype), neutral_op);
5580 init_def = gimple_build_vector_from_val (&stmts, vectype, neutral_op);
5581 }
5582 else
5583 {
5584 neutral_op = gimple_convert (&stmts, TREE_TYPE (vectype), neutral_op);
5585 init_val = gimple_convert (&stmts, TREE_TYPE (vectype), init_val);
5586 if (!TYPE_VECTOR_SUBPARTS (vectype).is_constant ())
5587 {
5588 /* Construct a splat of NEUTRAL_OP and insert INIT_VAL into
5589 element 0. */
5590 init_def = gimple_build_vector_from_val (&stmts, vectype,
5591 neutral_op);
5592 init_def = gimple_build (&stmts, CFN_VEC_SHL_INSERT,
5593 vectype, init_def, init_val);
5594 }
5595 else
5596 {
5597 /* Build {INIT_VAL, NEUTRAL_OP, NEUTRAL_OP, ...}. */
5598 tree_vector_builder elts (vectype, 1, 2);
5599 elts.quick_push (init_val);
5600 elts.quick_push (neutral_op);
5601 init_def = gimple_build_vector (&stmts, &elts);
5602 }
5603 }
5604
5605 if (stmts)
5606 vect_emit_reduction_init_stmts (loop_vinfo, reduc_info, stmts);
5607 return init_def;
5608 }
5609
5610 /* Get at the initial defs for the reduction PHIs for REDUC_INFO,
5611 which performs a reduction involving GROUP_SIZE scalar statements.
5612 NUMBER_OF_VECTORS is the number of vector defs to create. If NEUTRAL_OP
5613 is nonnull, introducing extra elements of that value will not change the
5614 result. */
5615
5616 static void
5617 get_initial_defs_for_reduction (loop_vec_info loop_vinfo,
5618 stmt_vec_info reduc_info,
5619 vec<tree> *vec_oprnds,
5620 unsigned int number_of_vectors,
5621 unsigned int group_size, tree neutral_op)
5622 {
5623 vec<tree> &initial_values = reduc_info->reduc_initial_values;
5624 unsigned HOST_WIDE_INT nunits;
5625 unsigned j, number_of_places_left_in_vector;
5626 tree vector_type = STMT_VINFO_VECTYPE (reduc_info);
5627 unsigned int i;
5628
5629 gcc_assert (group_size == initial_values.length () || neutral_op);
5630
5631 /* NUMBER_OF_COPIES is the number of times we need to use the same values in
5632 created vectors. It is greater than 1 if unrolling is performed.
5633
5634 For example, we have two scalar operands, s1 and s2 (e.g., group of
5635 strided accesses of size two), while NUNITS is four (i.e., four scalars
5636 of this type can be packed in a vector). The output vector will contain
5637 two copies of each scalar operand: {s1, s2, s1, s2}. (NUMBER_OF_COPIES
5638 will be 2).
5639
5640 If REDUC_GROUP_SIZE > NUNITS, the scalars will be split into several
5641 vectors containing the operands.
5642
5643 For example, NUNITS is four as before, and the group size is 8
5644 (s1, s2, ..., s8). We will create two vectors {s1, s2, s3, s4} and
5645 {s5, s6, s7, s8}. */
5646
5647 if (!TYPE_VECTOR_SUBPARTS (vector_type).is_constant (&nunits))
5648 nunits = group_size;
5649
5650 number_of_places_left_in_vector = nunits;
5651 bool constant_p = true;
5652 tree_vector_builder elts (vector_type, nunits, 1);
5653 elts.quick_grow (nunits);
5654 gimple_seq ctor_seq = NULL;
5655 if (neutral_op
5656 && !useless_type_conversion_p (TREE_TYPE (vector_type),
5657 TREE_TYPE (neutral_op)))
5658 neutral_op = gimple_convert (&ctor_seq,
5659 TREE_TYPE (vector_type),
5660 neutral_op);
5661 for (j = 0; j < nunits * number_of_vectors; ++j)
5662 {
5663 tree op;
5664 i = j % group_size;
5665
5666 /* Get the def before the loop. In reduction chain we have only
5667 one initial value. Else we have as many as PHIs in the group. */
5668 if (i >= initial_values.length () || (j > i && neutral_op))
5669 op = neutral_op;
5670 else
5671 {
5672 if (!useless_type_conversion_p (TREE_TYPE (vector_type),
5673 TREE_TYPE (initial_values[i])))
5674 initial_values[i] = gimple_convert (&ctor_seq,
5675 TREE_TYPE (vector_type),
5676 initial_values[i]);
5677 op = initial_values[i];
5678 }
5679
5680 /* Create 'vect_ = {op0,op1,...,opn}'. */
5681 number_of_places_left_in_vector--;
5682 elts[nunits - number_of_places_left_in_vector - 1] = op;
5683 if (!CONSTANT_CLASS_P (op))
5684 constant_p = false;
5685
5686 if (number_of_places_left_in_vector == 0)
5687 {
5688 tree init;
5689 if (constant_p && !neutral_op
5690 ? multiple_p (TYPE_VECTOR_SUBPARTS (vector_type), nunits)
5691 : known_eq (TYPE_VECTOR_SUBPARTS (vector_type), nunits))
5692 /* Build the vector directly from ELTS. */
5693 init = gimple_build_vector (&ctor_seq, &elts);
5694 else if (neutral_op)
5695 {
5696 /* Build a vector of the neutral value and shift the
5697 other elements into place. */
5698 init = gimple_build_vector_from_val (&ctor_seq, vector_type,
5699 neutral_op);
5700 int k = nunits;
5701 while (k > 0 && operand_equal_p (elts[k - 1], neutral_op))
5702 k -= 1;
5703 while (k > 0)
5704 {
5705 k -= 1;
5706 init = gimple_build (&ctor_seq, CFN_VEC_SHL_INSERT,
5707 vector_type, init, elts[k]);
5708 }
5709 }
5710 else
5711 {
5712 /* First time round, duplicate ELTS to fill the
5713 required number of vectors. */
5714 duplicate_and_interleave (loop_vinfo, &ctor_seq, vector_type,
5715 elts, number_of_vectors, *vec_oprnds);
5716 break;
5717 }
5718 vec_oprnds->quick_push (init);
5719
5720 number_of_places_left_in_vector = nunits;
5721 elts.new_vector (vector_type, nunits, 1);
5722 elts.quick_grow (nunits);
5723 constant_p = true;
5724 }
5725 }
5726 if (ctor_seq != NULL)
5727 vect_emit_reduction_init_stmts (loop_vinfo, reduc_info, ctor_seq);
5728 }
5729
5730 /* For a statement STMT_INFO taking part in a reduction operation return
5731 the stmt_vec_info the meta information is stored on. */
5732
5733 stmt_vec_info
5734 info_for_reduction (vec_info *vinfo, stmt_vec_info stmt_info)
5735 {
5736 stmt_info = vect_orig_stmt (stmt_info);
5737 gcc_assert (STMT_VINFO_REDUC_DEF (stmt_info));
5738 if (!is_a <gphi *> (stmt_info->stmt)
5739 || !VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
5740 stmt_info = STMT_VINFO_REDUC_DEF (stmt_info);
5741 gphi *phi = as_a <gphi *> (stmt_info->stmt);
5742 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
5743 {
5744 if (gimple_phi_num_args (phi) == 1)
5745 stmt_info = STMT_VINFO_REDUC_DEF (stmt_info);
5746 }
5747 else if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle)
5748 {
5749 stmt_vec_info info = vinfo->lookup_def (vect_phi_initial_value (phi));
5750 if (info && STMT_VINFO_DEF_TYPE (info) == vect_double_reduction_def)
5751 stmt_info = info;
5752 }
5753 return stmt_info;
5754 }
5755
5756 /* See if LOOP_VINFO is an epilogue loop whose main loop had a reduction that
5757 REDUC_INFO can build on. Adjust REDUC_INFO and return true if so, otherwise
5758 return false. */
5759
5760 static bool
5761 vect_find_reusable_accumulator (loop_vec_info loop_vinfo,
5762 stmt_vec_info reduc_info)
5763 {
5764 loop_vec_info main_loop_vinfo = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
5765 if (!main_loop_vinfo)
5766 return false;
5767
5768 if (STMT_VINFO_REDUC_TYPE (reduc_info) != TREE_CODE_REDUCTION)
5769 return false;
5770
5771 unsigned int num_phis = reduc_info->reduc_initial_values.length ();
5772 auto_vec<tree, 16> main_loop_results (num_phis);
5773 auto_vec<tree, 16> initial_values (num_phis);
5774 if (edge main_loop_edge = loop_vinfo->main_loop_edge)
5775 {
5776 /* The epilogue loop can be entered either from the main loop or
5777 from an earlier guard block. */
5778 edge skip_edge = loop_vinfo->skip_main_loop_edge;
5779 for (tree incoming_value : reduc_info->reduc_initial_values)
5780 {
5781 /* Look for:
5782
5783 INCOMING_VALUE = phi<MAIN_LOOP_RESULT(main loop),
5784 INITIAL_VALUE(guard block)>. */
5785 gcc_assert (TREE_CODE (incoming_value) == SSA_NAME);
5786
5787 gphi *phi = as_a <gphi *> (SSA_NAME_DEF_STMT (incoming_value));
5788 gcc_assert (gimple_bb (phi) == main_loop_edge->dest);
5789
5790 tree from_main_loop = PHI_ARG_DEF_FROM_EDGE (phi, main_loop_edge);
5791 tree from_skip = PHI_ARG_DEF_FROM_EDGE (phi, skip_edge);
5792
5793 main_loop_results.quick_push (from_main_loop);
5794 initial_values.quick_push (from_skip);
5795 }
5796 }
5797 else
5798 /* The main loop dominates the epilogue loop. */
5799 main_loop_results.splice (reduc_info->reduc_initial_values);
5800
5801 /* See if the main loop has the kind of accumulator we need. */
5802 vect_reusable_accumulator *accumulator
5803 = main_loop_vinfo->reusable_accumulators.get (main_loop_results[0]);
5804 if (!accumulator
5805 || num_phis != accumulator->reduc_info->reduc_scalar_results.length ()
5806 || !std::equal (main_loop_results.begin (), main_loop_results.end (),
5807 accumulator->reduc_info->reduc_scalar_results.begin ()))
5808 return false;
5809
5810 /* Handle the case where we can reduce wider vectors to narrower ones. */
5811 tree vectype = STMT_VINFO_VECTYPE (reduc_info);
5812 tree old_vectype = TREE_TYPE (accumulator->reduc_input);
5813 unsigned HOST_WIDE_INT m;
5814 if (!constant_multiple_p (TYPE_VECTOR_SUBPARTS (old_vectype),
5815 TYPE_VECTOR_SUBPARTS (vectype), &m))
5816 return false;
5817 /* Check the intermediate vector types and operations are available. */
5818 tree prev_vectype = old_vectype;
5819 poly_uint64 intermediate_nunits = TYPE_VECTOR_SUBPARTS (old_vectype);
5820 while (known_gt (intermediate_nunits, TYPE_VECTOR_SUBPARTS (vectype)))
5821 {
5822 intermediate_nunits = exact_div (intermediate_nunits, 2);
5823 tree intermediate_vectype = get_related_vectype_for_scalar_type
5824 (TYPE_MODE (vectype), TREE_TYPE (vectype), intermediate_nunits);
5825 if (!intermediate_vectype
5826 || !directly_supported_p (STMT_VINFO_REDUC_CODE (reduc_info),
5827 intermediate_vectype)
5828 || !can_vec_extract (TYPE_MODE (prev_vectype),
5829 TYPE_MODE (intermediate_vectype)))
5830 return false;
5831 prev_vectype = intermediate_vectype;
5832 }
5833
5834 /* Non-SLP reductions might apply an adjustment after the reduction
5835 operation, in order to simplify the initialization of the accumulator.
5836 If the epilogue loop carries on from where the main loop left off,
5837 it should apply the same adjustment to the final reduction result.
5838
5839 If the epilogue loop can also be entered directly (rather than via
5840 the main loop), we need to be able to handle that case in the same way,
5841 with the same adjustment. (In principle we could add a PHI node
5842 to select the correct adjustment, but in practice that shouldn't be
5843 necessary.) */
5844 tree main_adjustment
5845 = STMT_VINFO_REDUC_EPILOGUE_ADJUSTMENT (accumulator->reduc_info);
5846 if (loop_vinfo->main_loop_edge && main_adjustment)
5847 {
5848 gcc_assert (num_phis == 1);
5849 tree initial_value = initial_values[0];
5850 /* Check that we can use INITIAL_VALUE as the adjustment and
5851 initialize the accumulator with a neutral value instead. */
5852 if (!operand_equal_p (initial_value, main_adjustment))
5853 return false;
5854 code_helper code = STMT_VINFO_REDUC_CODE (reduc_info);
5855 initial_values[0] = neutral_op_for_reduction (TREE_TYPE (initial_value),
5856 code, initial_value);
5857 }
5858 STMT_VINFO_REDUC_EPILOGUE_ADJUSTMENT (reduc_info) = main_adjustment;
5859 reduc_info->reduc_initial_values.truncate (0);
5860 reduc_info->reduc_initial_values.splice (initial_values);
5861 reduc_info->reused_accumulator = accumulator;
5862 return true;
5863 }
5864
5865 /* Reduce the vector VEC_DEF down to VECTYPE with reduction operation
5866 CODE emitting stmts before GSI. Returns a vector def of VECTYPE. */
5867
5868 static tree
5869 vect_create_partial_epilog (tree vec_def, tree vectype, code_helper code,
5870 gimple_seq *seq)
5871 {
5872 unsigned nunits = TYPE_VECTOR_SUBPARTS (TREE_TYPE (vec_def)).to_constant ();
5873 unsigned nunits1 = TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
5874 tree stype = TREE_TYPE (vectype);
5875 tree new_temp = vec_def;
5876 while (nunits > nunits1)
5877 {
5878 nunits /= 2;
5879 tree vectype1 = get_related_vectype_for_scalar_type (TYPE_MODE (vectype),
5880 stype, nunits);
5881 unsigned int bitsize = tree_to_uhwi (TYPE_SIZE (vectype1));
5882
5883 /* The target has to make sure we support lowpart/highpart
5884 extraction, either via direct vector extract or through
5885 an integer mode punning. */
5886 tree dst1, dst2;
5887 gimple *epilog_stmt;
5888 if (convert_optab_handler (vec_extract_optab,
5889 TYPE_MODE (TREE_TYPE (new_temp)),
5890 TYPE_MODE (vectype1))
5891 != CODE_FOR_nothing)
5892 {
5893 /* Extract sub-vectors directly once vec_extract becomes
5894 a conversion optab. */
5895 dst1 = make_ssa_name (vectype1);
5896 epilog_stmt
5897 = gimple_build_assign (dst1, BIT_FIELD_REF,
5898 build3 (BIT_FIELD_REF, vectype1,
5899 new_temp, TYPE_SIZE (vectype1),
5900 bitsize_int (0)));
5901 gimple_seq_add_stmt_without_update (seq, epilog_stmt);
5902 dst2 = make_ssa_name (vectype1);
5903 epilog_stmt
5904 = gimple_build_assign (dst2, BIT_FIELD_REF,
5905 build3 (BIT_FIELD_REF, vectype1,
5906 new_temp, TYPE_SIZE (vectype1),
5907 bitsize_int (bitsize)));
5908 gimple_seq_add_stmt_without_update (seq, epilog_stmt);
5909 }
5910 else
5911 {
5912 /* Extract via punning to appropriately sized integer mode
5913 vector. */
5914 tree eltype = build_nonstandard_integer_type (bitsize, 1);
5915 tree etype = build_vector_type (eltype, 2);
5916 gcc_assert (convert_optab_handler (vec_extract_optab,
5917 TYPE_MODE (etype),
5918 TYPE_MODE (eltype))
5919 != CODE_FOR_nothing);
5920 tree tem = make_ssa_name (etype);
5921 epilog_stmt = gimple_build_assign (tem, VIEW_CONVERT_EXPR,
5922 build1 (VIEW_CONVERT_EXPR,
5923 etype, new_temp));
5924 gimple_seq_add_stmt_without_update (seq, epilog_stmt);
5925 new_temp = tem;
5926 tem = make_ssa_name (eltype);
5927 epilog_stmt
5928 = gimple_build_assign (tem, BIT_FIELD_REF,
5929 build3 (BIT_FIELD_REF, eltype,
5930 new_temp, TYPE_SIZE (eltype),
5931 bitsize_int (0)));
5932 gimple_seq_add_stmt_without_update (seq, epilog_stmt);
5933 dst1 = make_ssa_name (vectype1);
5934 epilog_stmt = gimple_build_assign (dst1, VIEW_CONVERT_EXPR,
5935 build1 (VIEW_CONVERT_EXPR,
5936 vectype1, tem));
5937 gimple_seq_add_stmt_without_update (seq, epilog_stmt);
5938 tem = make_ssa_name (eltype);
5939 epilog_stmt
5940 = gimple_build_assign (tem, BIT_FIELD_REF,
5941 build3 (BIT_FIELD_REF, eltype,
5942 new_temp, TYPE_SIZE (eltype),
5943 bitsize_int (bitsize)));
5944 gimple_seq_add_stmt_without_update (seq, epilog_stmt);
5945 dst2 = make_ssa_name (vectype1);
5946 epilog_stmt = gimple_build_assign (dst2, VIEW_CONVERT_EXPR,
5947 build1 (VIEW_CONVERT_EXPR,
5948 vectype1, tem));
5949 gimple_seq_add_stmt_without_update (seq, epilog_stmt);
5950 }
5951
5952 new_temp = gimple_build (seq, code, vectype1, dst1, dst2);
5953 }
5954
5955 return new_temp;
5956 }
5957
5958 /* Function vect_create_epilog_for_reduction
5959
5960 Create code at the loop-epilog to finalize the result of a reduction
5961 computation.
5962
5963 STMT_INFO is the scalar reduction stmt that is being vectorized.
5964 SLP_NODE is an SLP node containing a group of reduction statements. The
5965 first one in this group is STMT_INFO.
5966 SLP_NODE_INSTANCE is the SLP node instance containing SLP_NODE
5967 REDUC_INDEX says which rhs operand of the STMT_INFO is the reduction phi
5968 (counting from 0)
5969 LOOP_EXIT is the edge to update in the merge block. In the case of a single
5970 exit this edge is always the main loop exit.
5971
5972 This function:
5973 1. Completes the reduction def-use cycles.
5974 2. "Reduces" each vector of partial results VECT_DEFS into a single result,
5975 by calling the function specified by REDUC_FN if available, or by
5976 other means (whole-vector shifts or a scalar loop).
5977 The function also creates a new phi node at the loop exit to preserve
5978 loop-closed form, as illustrated below.
5979
5980 The flow at the entry to this function:
5981
5982 loop:
5983 vec_def = phi <vec_init, null> # REDUCTION_PHI
5984 VECT_DEF = vector_stmt # vectorized form of STMT_INFO
5985 s_loop = scalar_stmt # (scalar) STMT_INFO
5986 loop_exit:
5987 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
5988 use <s_out0>
5989 use <s_out0>
5990
5991 The above is transformed by this function into:
5992
5993 loop:
5994 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
5995 VECT_DEF = vector_stmt # vectorized form of STMT_INFO
5996 s_loop = scalar_stmt # (scalar) STMT_INFO
5997 loop_exit:
5998 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
5999 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
6000 v_out2 = reduce <v_out1>
6001 s_out3 = extract_field <v_out2, 0>
6002 s_out4 = adjust_result <s_out3>
6003 use <s_out4>
6004 use <s_out4>
6005 */
6006
6007 static void
6008 vect_create_epilog_for_reduction (loop_vec_info loop_vinfo,
6009 stmt_vec_info stmt_info,
6010 slp_tree slp_node,
6011 slp_instance slp_node_instance,
6012 edge loop_exit)
6013 {
6014 stmt_vec_info reduc_info = info_for_reduction (loop_vinfo, stmt_info);
6015 gcc_assert (reduc_info->is_reduc_info);
6016 /* For double reductions we need to get at the inner loop reduction
6017 stmt which has the meta info attached. Our stmt_info is that of the
6018 loop-closed PHI of the inner loop which we remember as
6019 def for the reduction PHI generation. */
6020 bool double_reduc = false;
6021 stmt_vec_info rdef_info = stmt_info;
6022 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
6023 {
6024 double_reduc = true;
6025 stmt_info = loop_vinfo->lookup_def (gimple_phi_arg_def
6026 (stmt_info->stmt, 0));
6027 stmt_info = vect_stmt_to_vectorize (stmt_info);
6028 }
6029 code_helper code = STMT_VINFO_REDUC_CODE (reduc_info);
6030 internal_fn reduc_fn = STMT_VINFO_REDUC_FN (reduc_info);
6031 tree vectype;
6032 machine_mode mode;
6033 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo), *outer_loop = NULL;
6034 basic_block exit_bb;
6035 tree scalar_dest;
6036 tree scalar_type;
6037 gimple *new_phi = NULL, *phi = NULL;
6038 gimple_stmt_iterator exit_gsi;
6039 tree new_temp = NULL_TREE, new_name, new_scalar_dest;
6040 gimple *epilog_stmt = NULL;
6041 gimple *exit_phi;
6042 tree bitsize;
6043 tree def;
6044 tree orig_name, scalar_result;
6045 imm_use_iterator imm_iter, phi_imm_iter;
6046 use_operand_p use_p, phi_use_p;
6047 gimple *use_stmt;
6048 auto_vec<tree> reduc_inputs;
6049 int j, i;
6050 vec<tree> &scalar_results = reduc_info->reduc_scalar_results;
6051 unsigned int group_size = 1, k;
6052 /* SLP reduction without reduction chain, e.g.,
6053 # a1 = phi <a2, a0>
6054 # b1 = phi <b2, b0>
6055 a2 = operation (a1)
6056 b2 = operation (b1) */
6057 bool slp_reduc
6058 = (slp_node
6059 && !REDUC_GROUP_FIRST_ELEMENT (STMT_VINFO_REDUC_DEF (reduc_info)));
6060 bool direct_slp_reduc;
6061 tree induction_index = NULL_TREE;
6062
6063 if (slp_node)
6064 group_size = SLP_TREE_LANES (slp_node);
6065
6066 if (nested_in_vect_loop_p (loop, stmt_info))
6067 {
6068 outer_loop = loop;
6069 loop = loop->inner;
6070 gcc_assert (double_reduc);
6071 }
6072
6073 vectype = STMT_VINFO_REDUC_VECTYPE (reduc_info);
6074 gcc_assert (vectype);
6075 mode = TYPE_MODE (vectype);
6076
6077 tree induc_val = NULL_TREE;
6078 tree adjustment_def = NULL;
6079 /* Optimize: for induction condition reduction, if we can't use zero
6080 for induc_val, use initial_def. */
6081 if (STMT_VINFO_REDUC_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
6082 induc_val = STMT_VINFO_VEC_INDUC_COND_INITIAL_VAL (reduc_info);
6083 else if (double_reduc)
6084 ;
6085 else
6086 adjustment_def = STMT_VINFO_REDUC_EPILOGUE_ADJUSTMENT (reduc_info);
6087
6088 stmt_vec_info single_live_out_stmt[] = { stmt_info };
6089 array_slice<const stmt_vec_info> live_out_stmts = single_live_out_stmt;
6090 if (slp_reduc)
6091 /* All statements produce live-out values. */
6092 live_out_stmts = SLP_TREE_SCALAR_STMTS (slp_node);
6093
6094 unsigned vec_num;
6095 int ncopies;
6096 if (slp_node)
6097 {
6098 vec_num = SLP_TREE_VEC_DEFS (slp_node_instance->reduc_phis).length ();
6099 ncopies = 1;
6100 }
6101 else
6102 {
6103 vec_num = 1;
6104 ncopies = STMT_VINFO_VEC_STMTS (reduc_info).length ();
6105 }
6106
6107 /* For cond reductions we want to create a new vector (INDEX_COND_EXPR)
6108 which is updated with the current index of the loop for every match of
6109 the original loop's cond_expr (VEC_STMT). This results in a vector
6110 containing the last time the condition passed for that vector lane.
6111 The first match will be a 1 to allow 0 to be used for non-matching
6112 indexes. If there are no matches at all then the vector will be all
6113 zeroes.
6114
6115 PR92772: This algorithm is broken for architectures that support
6116 masked vectors, but do not provide fold_extract_last. */
6117 if (STMT_VINFO_REDUC_TYPE (reduc_info) == COND_REDUCTION)
6118 {
6119 auto_vec<std::pair<tree, bool>, 2> ccompares;
6120 if (slp_node)
6121 {
6122 slp_tree cond_node = slp_node_instance->root;
6123 while (cond_node != slp_node_instance->reduc_phis)
6124 {
6125 stmt_vec_info cond_info = SLP_TREE_REPRESENTATIVE (cond_node);
6126 int slp_reduc_idx;
6127 if (gimple_assign_rhs_code (cond_info->stmt) == COND_EXPR)
6128 {
6129 gimple *vec_stmt
6130 = SSA_NAME_DEF_STMT (SLP_TREE_VEC_DEFS (cond_node)[0]);
6131 gcc_assert (gimple_assign_rhs_code (vec_stmt) == VEC_COND_EXPR);
6132 ccompares.safe_push
6133 (std::make_pair (gimple_assign_rhs1 (vec_stmt),
6134 STMT_VINFO_REDUC_IDX (cond_info) == 2));
6135 /* ??? We probably want to have REDUC_IDX on the SLP node?
6136 We have both three and four children COND_EXPR nodes
6137 dependent on whether the comparison is still embedded
6138 as GENERIC. So work backwards. */
6139 slp_reduc_idx = (SLP_TREE_CHILDREN (cond_node).length () - 3
6140 + STMT_VINFO_REDUC_IDX (cond_info));
6141 }
6142 else
6143 slp_reduc_idx = STMT_VINFO_REDUC_IDX (cond_info);
6144 cond_node = SLP_TREE_CHILDREN (cond_node)[slp_reduc_idx];
6145 }
6146 }
6147 else
6148 {
6149 stmt_vec_info cond_info = STMT_VINFO_REDUC_DEF (reduc_info);
6150 cond_info = vect_stmt_to_vectorize (cond_info);
6151 while (cond_info != reduc_info)
6152 {
6153 if (gimple_assign_rhs_code (cond_info->stmt) == COND_EXPR)
6154 {
6155 gimple *vec_stmt = STMT_VINFO_VEC_STMTS (cond_info)[0];
6156 gcc_assert (gimple_assign_rhs_code (vec_stmt) == VEC_COND_EXPR);
6157 ccompares.safe_push
6158 (std::make_pair (gimple_assign_rhs1 (vec_stmt),
6159 STMT_VINFO_REDUC_IDX (cond_info) == 2));
6160 }
6161 cond_info
6162 = loop_vinfo->lookup_def (gimple_op (cond_info->stmt,
6163 1 + STMT_VINFO_REDUC_IDX
6164 (cond_info)));
6165 cond_info = vect_stmt_to_vectorize (cond_info);
6166 }
6167 }
6168 gcc_assert (ccompares.length () != 0);
6169
6170 tree indx_before_incr, indx_after_incr;
6171 poly_uint64 nunits_out = TYPE_VECTOR_SUBPARTS (vectype);
6172 int scalar_precision
6173 = GET_MODE_PRECISION (SCALAR_TYPE_MODE (TREE_TYPE (vectype)));
6174 tree cr_index_scalar_type = make_unsigned_type (scalar_precision);
6175 tree cr_index_vector_type = get_related_vectype_for_scalar_type
6176 (TYPE_MODE (vectype), cr_index_scalar_type,
6177 TYPE_VECTOR_SUBPARTS (vectype));
6178
6179 /* First we create a simple vector induction variable which starts
6180 with the values {1,2,3,...} (SERIES_VECT) and increments by the
6181 vector size (STEP). */
6182
6183 /* Create a {1,2,3,...} vector. */
6184 tree series_vect = build_index_vector (cr_index_vector_type, 1, 1);
6185
6186 /* Create a vector of the step value. */
6187 tree step = build_int_cst (cr_index_scalar_type, nunits_out);
6188 tree vec_step = build_vector_from_val (cr_index_vector_type, step);
6189
6190 /* Create an induction variable. */
6191 gimple_stmt_iterator incr_gsi;
6192 bool insert_after;
6193 vect_iv_increment_position (LOOP_VINFO_IV_EXIT (loop_vinfo),
6194 &incr_gsi, &insert_after);
6195 create_iv (series_vect, PLUS_EXPR, vec_step, NULL_TREE, loop, &incr_gsi,
6196 insert_after, &indx_before_incr, &indx_after_incr);
6197
6198 /* Next create a new phi node vector (NEW_PHI_TREE) which starts
6199 filled with zeros (VEC_ZERO). */
6200
6201 /* Create a vector of 0s. */
6202 tree zero = build_zero_cst (cr_index_scalar_type);
6203 tree vec_zero = build_vector_from_val (cr_index_vector_type, zero);
6204
6205 /* Create a vector phi node. */
6206 tree new_phi_tree = make_ssa_name (cr_index_vector_type);
6207 new_phi = create_phi_node (new_phi_tree, loop->header);
6208 add_phi_arg (as_a <gphi *> (new_phi), vec_zero,
6209 loop_preheader_edge (loop), UNKNOWN_LOCATION);
6210
6211 /* Now take the condition from the loops original cond_exprs
6212 and produce a new cond_exprs (INDEX_COND_EXPR) which for
6213 every match uses values from the induction variable
6214 (INDEX_BEFORE_INCR) otherwise uses values from the phi node
6215 (NEW_PHI_TREE).
6216 Finally, we update the phi (NEW_PHI_TREE) to take the value of
6217 the new cond_expr (INDEX_COND_EXPR). */
6218 gimple_seq stmts = NULL;
6219 for (int i = ccompares.length () - 1; i != -1; --i)
6220 {
6221 tree ccompare = ccompares[i].first;
6222 if (ccompares[i].second)
6223 new_phi_tree = gimple_build (&stmts, VEC_COND_EXPR,
6224 cr_index_vector_type,
6225 ccompare,
6226 indx_before_incr, new_phi_tree);
6227 else
6228 new_phi_tree = gimple_build (&stmts, VEC_COND_EXPR,
6229 cr_index_vector_type,
6230 ccompare,
6231 new_phi_tree, indx_before_incr);
6232 }
6233 gsi_insert_seq_before (&incr_gsi, stmts, GSI_SAME_STMT);
6234
6235 /* Update the phi with the vec cond. */
6236 induction_index = new_phi_tree;
6237 add_phi_arg (as_a <gphi *> (new_phi), induction_index,
6238 loop_latch_edge (loop), UNKNOWN_LOCATION);
6239 }
6240
6241 /* 2. Create epilog code.
6242 The reduction epilog code operates across the elements of the vector
6243 of partial results computed by the vectorized loop.
6244 The reduction epilog code consists of:
6245
6246 step 1: compute the scalar result in a vector (v_out2)
6247 step 2: extract the scalar result (s_out3) from the vector (v_out2)
6248 step 3: adjust the scalar result (s_out3) if needed.
6249
6250 Step 1 can be accomplished using one the following three schemes:
6251 (scheme 1) using reduc_fn, if available.
6252 (scheme 2) using whole-vector shifts, if available.
6253 (scheme 3) using a scalar loop. In this case steps 1+2 above are
6254 combined.
6255
6256 The overall epilog code looks like this:
6257
6258 s_out0 = phi <s_loop> # original EXIT_PHI
6259 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
6260 v_out2 = reduce <v_out1> # step 1
6261 s_out3 = extract_field <v_out2, 0> # step 2
6262 s_out4 = adjust_result <s_out3> # step 3
6263
6264 (step 3 is optional, and steps 1 and 2 may be combined).
6265 Lastly, the uses of s_out0 are replaced by s_out4. */
6266
6267
6268 /* 2.1 Create new loop-exit-phis to preserve loop-closed form:
6269 v_out1 = phi <VECT_DEF>
6270 Store them in NEW_PHIS. */
6271 if (double_reduc)
6272 loop = outer_loop;
6273 /* We need to reduce values in all exits. */
6274 exit_bb = loop_exit->dest;
6275 exit_gsi = gsi_after_labels (exit_bb);
6276 reduc_inputs.create (slp_node ? vec_num : ncopies);
6277 for (unsigned i = 0; i < vec_num; i++)
6278 {
6279 gimple_seq stmts = NULL;
6280 if (slp_node)
6281 def = vect_get_slp_vect_def (slp_node, i);
6282 else
6283 def = gimple_get_lhs (STMT_VINFO_VEC_STMTS (rdef_info)[0]);
6284 for (j = 0; j < ncopies; j++)
6285 {
6286 tree new_def = copy_ssa_name (def);
6287 phi = create_phi_node (new_def, exit_bb);
6288 if (j)
6289 def = gimple_get_lhs (STMT_VINFO_VEC_STMTS (rdef_info)[j]);
6290 if (LOOP_VINFO_IV_EXIT (loop_vinfo) == loop_exit)
6291 SET_PHI_ARG_DEF (phi, loop_exit->dest_idx, def);
6292 else
6293 {
6294 for (unsigned k = 0; k < gimple_phi_num_args (phi); k++)
6295 SET_PHI_ARG_DEF (phi, k, def);
6296 }
6297 new_def = gimple_convert (&stmts, vectype, new_def);
6298 reduc_inputs.quick_push (new_def);
6299 }
6300 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
6301 }
6302
6303 /* 2.2 Get the relevant tree-code to use in the epilog for schemes 2,3
6304 (i.e. when reduc_fn is not available) and in the final adjustment
6305 code (if needed). Also get the original scalar reduction variable as
6306 defined in the loop. In case STMT is a "pattern-stmt" (i.e. - it
6307 represents a reduction pattern), the tree-code and scalar-def are
6308 taken from the original stmt that the pattern-stmt (STMT) replaces.
6309 Otherwise (it is a regular reduction) - the tree-code and scalar-def
6310 are taken from STMT. */
6311
6312 stmt_vec_info orig_stmt_info = vect_orig_stmt (stmt_info);
6313 if (orig_stmt_info != stmt_info)
6314 {
6315 /* Reduction pattern */
6316 gcc_assert (STMT_VINFO_IN_PATTERN_P (orig_stmt_info));
6317 gcc_assert (STMT_VINFO_RELATED_STMT (orig_stmt_info) == stmt_info);
6318 }
6319
6320 scalar_dest = gimple_get_lhs (orig_stmt_info->stmt);
6321 scalar_type = TREE_TYPE (scalar_dest);
6322 scalar_results.truncate (0);
6323 scalar_results.reserve_exact (group_size);
6324 new_scalar_dest = vect_create_destination_var (scalar_dest, NULL);
6325 bitsize = TYPE_SIZE (scalar_type);
6326
6327 /* True if we should implement SLP_REDUC using native reduction operations
6328 instead of scalar operations. */
6329 direct_slp_reduc = (reduc_fn != IFN_LAST
6330 && slp_reduc
6331 && !TYPE_VECTOR_SUBPARTS (vectype).is_constant ());
6332
6333 /* In case of reduction chain, e.g.,
6334 # a1 = phi <a3, a0>
6335 a2 = operation (a1)
6336 a3 = operation (a2),
6337
6338 we may end up with more than one vector result. Here we reduce them
6339 to one vector.
6340
6341 The same is true for a SLP reduction, e.g.,
6342 # a1 = phi <a2, a0>
6343 # b1 = phi <b2, b0>
6344 a2 = operation (a1)
6345 b2 = operation (a2),
6346
6347 where we can end up with more than one vector as well. We can
6348 easily accumulate vectors when the number of vector elements is
6349 a multiple of the SLP group size.
6350
6351 The same is true if we couldn't use a single defuse cycle. */
6352 if (REDUC_GROUP_FIRST_ELEMENT (STMT_VINFO_REDUC_DEF (reduc_info))
6353 || direct_slp_reduc
6354 || (slp_reduc
6355 && constant_multiple_p (TYPE_VECTOR_SUBPARTS (vectype), group_size))
6356 || ncopies > 1)
6357 {
6358 gimple_seq stmts = NULL;
6359 tree single_input = reduc_inputs[0];
6360 for (k = 1; k < reduc_inputs.length (); k++)
6361 single_input = gimple_build (&stmts, code, vectype,
6362 single_input, reduc_inputs[k]);
6363 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
6364
6365 reduc_inputs.truncate (0);
6366 reduc_inputs.safe_push (single_input);
6367 }
6368
6369 tree orig_reduc_input = reduc_inputs[0];
6370
6371 /* If this loop is an epilogue loop that can be skipped after the
6372 main loop, we can only share a reduction operation between the
6373 main loop and the epilogue if we put it at the target of the
6374 skip edge.
6375
6376 We can still reuse accumulators if this check fails. Doing so has
6377 the minor(?) benefit of making the epilogue loop's scalar result
6378 independent of the main loop's scalar result. */
6379 bool unify_with_main_loop_p = false;
6380 if (reduc_info->reused_accumulator
6381 && loop_vinfo->skip_this_loop_edge
6382 && single_succ_p (exit_bb)
6383 && single_succ (exit_bb) == loop_vinfo->skip_this_loop_edge->dest)
6384 {
6385 unify_with_main_loop_p = true;
6386
6387 basic_block reduc_block = loop_vinfo->skip_this_loop_edge->dest;
6388 reduc_inputs[0] = make_ssa_name (vectype);
6389 gphi *new_phi = create_phi_node (reduc_inputs[0], reduc_block);
6390 add_phi_arg (new_phi, orig_reduc_input, single_succ_edge (exit_bb),
6391 UNKNOWN_LOCATION);
6392 add_phi_arg (new_phi, reduc_info->reused_accumulator->reduc_input,
6393 loop_vinfo->skip_this_loop_edge, UNKNOWN_LOCATION);
6394 exit_gsi = gsi_after_labels (reduc_block);
6395 }
6396
6397 /* Shouldn't be used beyond this point. */
6398 exit_bb = nullptr;
6399
6400 if (STMT_VINFO_REDUC_TYPE (reduc_info) == COND_REDUCTION
6401 && reduc_fn != IFN_LAST)
6402 {
6403 /* For condition reductions, we have a vector (REDUC_INPUTS 0) containing
6404 various data values where the condition matched and another vector
6405 (INDUCTION_INDEX) containing all the indexes of those matches. We
6406 need to extract the last matching index (which will be the index with
6407 highest value) and use this to index into the data vector.
6408 For the case where there were no matches, the data vector will contain
6409 all default values and the index vector will be all zeros. */
6410
6411 /* Get various versions of the type of the vector of indexes. */
6412 tree index_vec_type = TREE_TYPE (induction_index);
6413 gcc_checking_assert (TYPE_UNSIGNED (index_vec_type));
6414 tree index_scalar_type = TREE_TYPE (index_vec_type);
6415 tree index_vec_cmp_type = truth_type_for (index_vec_type);
6416
6417 /* Get an unsigned integer version of the type of the data vector. */
6418 int scalar_precision
6419 = GET_MODE_PRECISION (SCALAR_TYPE_MODE (scalar_type));
6420 tree scalar_type_unsigned = make_unsigned_type (scalar_precision);
6421 tree vectype_unsigned = get_same_sized_vectype (scalar_type_unsigned,
6422 vectype);
6423
6424 /* First we need to create a vector (ZERO_VEC) of zeros and another
6425 vector (MAX_INDEX_VEC) filled with the last matching index, which we
6426 can create using a MAX reduction and then expanding.
6427 In the case where the loop never made any matches, the max index will
6428 be zero. */
6429
6430 /* Vector of {0, 0, 0,...}. */
6431 tree zero_vec = build_zero_cst (vectype);
6432
6433 /* Find maximum value from the vector of found indexes. */
6434 tree max_index = make_ssa_name (index_scalar_type);
6435 gcall *max_index_stmt = gimple_build_call_internal (IFN_REDUC_MAX,
6436 1, induction_index);
6437 gimple_call_set_lhs (max_index_stmt, max_index);
6438 gsi_insert_before (&exit_gsi, max_index_stmt, GSI_SAME_STMT);
6439
6440 /* Vector of {max_index, max_index, max_index,...}. */
6441 tree max_index_vec = make_ssa_name (index_vec_type);
6442 tree max_index_vec_rhs = build_vector_from_val (index_vec_type,
6443 max_index);
6444 gimple *max_index_vec_stmt = gimple_build_assign (max_index_vec,
6445 max_index_vec_rhs);
6446 gsi_insert_before (&exit_gsi, max_index_vec_stmt, GSI_SAME_STMT);
6447
6448 /* Next we compare the new vector (MAX_INDEX_VEC) full of max indexes
6449 with the vector (INDUCTION_INDEX) of found indexes, choosing values
6450 from the data vector (REDUC_INPUTS 0) for matches, 0 (ZERO_VEC)
6451 otherwise. Only one value should match, resulting in a vector
6452 (VEC_COND) with one data value and the rest zeros.
6453 In the case where the loop never made any matches, every index will
6454 match, resulting in a vector with all data values (which will all be
6455 the default value). */
6456
6457 /* Compare the max index vector to the vector of found indexes to find
6458 the position of the max value. */
6459 tree vec_compare = make_ssa_name (index_vec_cmp_type);
6460 gimple *vec_compare_stmt = gimple_build_assign (vec_compare, EQ_EXPR,
6461 induction_index,
6462 max_index_vec);
6463 gsi_insert_before (&exit_gsi, vec_compare_stmt, GSI_SAME_STMT);
6464
6465 /* Use the compare to choose either values from the data vector or
6466 zero. */
6467 tree vec_cond = make_ssa_name (vectype);
6468 gimple *vec_cond_stmt = gimple_build_assign (vec_cond, VEC_COND_EXPR,
6469 vec_compare,
6470 reduc_inputs[0],
6471 zero_vec);
6472 gsi_insert_before (&exit_gsi, vec_cond_stmt, GSI_SAME_STMT);
6473
6474 /* Finally we need to extract the data value from the vector (VEC_COND)
6475 into a scalar (MATCHED_DATA_REDUC). Logically we want to do a OR
6476 reduction, but because this doesn't exist, we can use a MAX reduction
6477 instead. The data value might be signed or a float so we need to cast
6478 it first.
6479 In the case where the loop never made any matches, the data values are
6480 all identical, and so will reduce down correctly. */
6481
6482 /* Make the matched data values unsigned. */
6483 tree vec_cond_cast = make_ssa_name (vectype_unsigned);
6484 tree vec_cond_cast_rhs = build1 (VIEW_CONVERT_EXPR, vectype_unsigned,
6485 vec_cond);
6486 gimple *vec_cond_cast_stmt = gimple_build_assign (vec_cond_cast,
6487 VIEW_CONVERT_EXPR,
6488 vec_cond_cast_rhs);
6489 gsi_insert_before (&exit_gsi, vec_cond_cast_stmt, GSI_SAME_STMT);
6490
6491 /* Reduce down to a scalar value. */
6492 tree data_reduc = make_ssa_name (scalar_type_unsigned);
6493 gcall *data_reduc_stmt = gimple_build_call_internal (IFN_REDUC_MAX,
6494 1, vec_cond_cast);
6495 gimple_call_set_lhs (data_reduc_stmt, data_reduc);
6496 gsi_insert_before (&exit_gsi, data_reduc_stmt, GSI_SAME_STMT);
6497
6498 /* Convert the reduced value back to the result type and set as the
6499 result. */
6500 gimple_seq stmts = NULL;
6501 new_temp = gimple_build (&stmts, VIEW_CONVERT_EXPR, scalar_type,
6502 data_reduc);
6503 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
6504 scalar_results.safe_push (new_temp);
6505 }
6506 else if (STMT_VINFO_REDUC_TYPE (reduc_info) == COND_REDUCTION
6507 && reduc_fn == IFN_LAST)
6508 {
6509 /* Condition reduction without supported IFN_REDUC_MAX. Generate
6510 idx = 0;
6511 idx_val = induction_index[0];
6512 val = data_reduc[0];
6513 for (idx = 0, val = init, i = 0; i < nelts; ++i)
6514 if (induction_index[i] > idx_val)
6515 val = data_reduc[i], idx_val = induction_index[i];
6516 return val; */
6517
6518 tree data_eltype = TREE_TYPE (vectype);
6519 tree idx_eltype = TREE_TYPE (TREE_TYPE (induction_index));
6520 unsigned HOST_WIDE_INT el_size = tree_to_uhwi (TYPE_SIZE (idx_eltype));
6521 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (TREE_TYPE (induction_index));
6522 /* Enforced by vectorizable_reduction, which ensures we have target
6523 support before allowing a conditional reduction on variable-length
6524 vectors. */
6525 unsigned HOST_WIDE_INT v_size = el_size * nunits.to_constant ();
6526 tree idx_val = NULL_TREE, val = NULL_TREE;
6527 for (unsigned HOST_WIDE_INT off = 0; off < v_size; off += el_size)
6528 {
6529 tree old_idx_val = idx_val;
6530 tree old_val = val;
6531 idx_val = make_ssa_name (idx_eltype);
6532 epilog_stmt = gimple_build_assign (idx_val, BIT_FIELD_REF,
6533 build3 (BIT_FIELD_REF, idx_eltype,
6534 induction_index,
6535 bitsize_int (el_size),
6536 bitsize_int (off)));
6537 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
6538 val = make_ssa_name (data_eltype);
6539 epilog_stmt = gimple_build_assign (val, BIT_FIELD_REF,
6540 build3 (BIT_FIELD_REF,
6541 data_eltype,
6542 reduc_inputs[0],
6543 bitsize_int (el_size),
6544 bitsize_int (off)));
6545 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
6546 if (off != 0)
6547 {
6548 tree new_idx_val = idx_val;
6549 if (off != v_size - el_size)
6550 {
6551 new_idx_val = make_ssa_name (idx_eltype);
6552 epilog_stmt = gimple_build_assign (new_idx_val,
6553 MAX_EXPR, idx_val,
6554 old_idx_val);
6555 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
6556 }
6557 tree cond = make_ssa_name (boolean_type_node);
6558 epilog_stmt = gimple_build_assign (cond, GT_EXPR,
6559 idx_val, old_idx_val);
6560 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
6561 tree new_val = make_ssa_name (data_eltype);
6562 epilog_stmt = gimple_build_assign (new_val, COND_EXPR,
6563 cond, val, old_val);
6564 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
6565 idx_val = new_idx_val;
6566 val = new_val;
6567 }
6568 }
6569 /* Convert the reduced value back to the result type and set as the
6570 result. */
6571 gimple_seq stmts = NULL;
6572 val = gimple_convert (&stmts, scalar_type, val);
6573 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
6574 scalar_results.safe_push (val);
6575 }
6576
6577 /* 2.3 Create the reduction code, using one of the three schemes described
6578 above. In SLP we simply need to extract all the elements from the
6579 vector (without reducing them), so we use scalar shifts. */
6580 else if (reduc_fn != IFN_LAST && (!slp_reduc || group_size == 1))
6581 {
6582 tree tmp;
6583 tree vec_elem_type;
6584
6585 /* Case 1: Create:
6586 v_out2 = reduc_expr <v_out1> */
6587
6588 if (dump_enabled_p ())
6589 dump_printf_loc (MSG_NOTE, vect_location,
6590 "Reduce using direct vector reduction.\n");
6591
6592 gimple_seq stmts = NULL;
6593 vec_elem_type = TREE_TYPE (vectype);
6594 new_temp = gimple_build (&stmts, as_combined_fn (reduc_fn),
6595 vec_elem_type, reduc_inputs[0]);
6596 new_temp = gimple_convert (&stmts, scalar_type, new_temp);
6597 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
6598
6599 if ((STMT_VINFO_REDUC_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
6600 && induc_val)
6601 {
6602 /* Earlier we set the initial value to be a vector if induc_val
6603 values. Check the result and if it is induc_val then replace
6604 with the original initial value, unless induc_val is
6605 the same as initial_def already. */
6606 tree zcompare = make_ssa_name (boolean_type_node);
6607 epilog_stmt = gimple_build_assign (zcompare, EQ_EXPR,
6608 new_temp, induc_val);
6609 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
6610 tree initial_def = reduc_info->reduc_initial_values[0];
6611 tmp = make_ssa_name (new_scalar_dest);
6612 epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
6613 initial_def, new_temp);
6614 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
6615 new_temp = tmp;
6616 }
6617
6618 scalar_results.safe_push (new_temp);
6619 }
6620 else if (direct_slp_reduc)
6621 {
6622 /* Here we create one vector for each of the REDUC_GROUP_SIZE results,
6623 with the elements for other SLP statements replaced with the
6624 neutral value. We can then do a normal reduction on each vector. */
6625
6626 /* Enforced by vectorizable_reduction. */
6627 gcc_assert (reduc_inputs.length () == 1);
6628 gcc_assert (pow2p_hwi (group_size));
6629
6630 gimple_seq seq = NULL;
6631
6632 /* Build a vector {0, 1, 2, ...}, with the same number of elements
6633 and the same element size as VECTYPE. */
6634 tree index = build_index_vector (vectype, 0, 1);
6635 tree index_type = TREE_TYPE (index);
6636 tree index_elt_type = TREE_TYPE (index_type);
6637 tree mask_type = truth_type_for (index_type);
6638
6639 /* Create a vector that, for each element, identifies which of
6640 the REDUC_GROUP_SIZE results should use it. */
6641 tree index_mask = build_int_cst (index_elt_type, group_size - 1);
6642 index = gimple_build (&seq, BIT_AND_EXPR, index_type, index,
6643 build_vector_from_val (index_type, index_mask));
6644
6645 /* Get a neutral vector value. This is simply a splat of the neutral
6646 scalar value if we have one, otherwise the initial scalar value
6647 is itself a neutral value. */
6648 tree vector_identity = NULL_TREE;
6649 tree neutral_op = NULL_TREE;
6650 if (slp_node)
6651 {
6652 tree initial_value = NULL_TREE;
6653 if (REDUC_GROUP_FIRST_ELEMENT (STMT_VINFO_REDUC_DEF (reduc_info)))
6654 initial_value = reduc_info->reduc_initial_values[0];
6655 neutral_op = neutral_op_for_reduction (TREE_TYPE (vectype), code,
6656 initial_value, false);
6657 }
6658 if (neutral_op)
6659 vector_identity = gimple_build_vector_from_val (&seq, vectype,
6660 neutral_op);
6661 for (unsigned int i = 0; i < group_size; ++i)
6662 {
6663 /* If there's no univeral neutral value, we can use the
6664 initial scalar value from the original PHI. This is used
6665 for MIN and MAX reduction, for example. */
6666 if (!neutral_op)
6667 {
6668 tree scalar_value = reduc_info->reduc_initial_values[i];
6669 scalar_value = gimple_convert (&seq, TREE_TYPE (vectype),
6670 scalar_value);
6671 vector_identity = gimple_build_vector_from_val (&seq, vectype,
6672 scalar_value);
6673 }
6674
6675 /* Calculate the equivalent of:
6676
6677 sel[j] = (index[j] == i);
6678
6679 which selects the elements of REDUC_INPUTS[0] that should
6680 be included in the result. */
6681 tree compare_val = build_int_cst (index_elt_type, i);
6682 compare_val = build_vector_from_val (index_type, compare_val);
6683 tree sel = gimple_build (&seq, EQ_EXPR, mask_type,
6684 index, compare_val);
6685
6686 /* Calculate the equivalent of:
6687
6688 vec = seq ? reduc_inputs[0] : vector_identity;
6689
6690 VEC is now suitable for a full vector reduction. */
6691 tree vec = gimple_build (&seq, VEC_COND_EXPR, vectype,
6692 sel, reduc_inputs[0], vector_identity);
6693
6694 /* Do the reduction and convert it to the appropriate type. */
6695 tree scalar = gimple_build (&seq, as_combined_fn (reduc_fn),
6696 TREE_TYPE (vectype), vec);
6697 scalar = gimple_convert (&seq, scalar_type, scalar);
6698 scalar_results.safe_push (scalar);
6699 }
6700 gsi_insert_seq_before (&exit_gsi, seq, GSI_SAME_STMT);
6701 }
6702 else
6703 {
6704 bool reduce_with_shift;
6705 tree vec_temp;
6706
6707 gcc_assert (slp_reduc || reduc_inputs.length () == 1);
6708
6709 /* See if the target wants to do the final (shift) reduction
6710 in a vector mode of smaller size and first reduce upper/lower
6711 halves against each other. */
6712 enum machine_mode mode1 = mode;
6713 tree stype = TREE_TYPE (vectype);
6714 unsigned nunits = TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
6715 unsigned nunits1 = nunits;
6716 if ((mode1 = targetm.vectorize.split_reduction (mode)) != mode
6717 && reduc_inputs.length () == 1)
6718 {
6719 nunits1 = GET_MODE_NUNITS (mode1).to_constant ();
6720 /* For SLP reductions we have to make sure lanes match up, but
6721 since we're doing individual element final reduction reducing
6722 vector width here is even more important.
6723 ??? We can also separate lanes with permutes, for the common
6724 case of power-of-two group-size odd/even extracts would work. */
6725 if (slp_reduc && nunits != nunits1)
6726 {
6727 nunits1 = least_common_multiple (nunits1, group_size);
6728 gcc_assert (exact_log2 (nunits1) != -1 && nunits1 <= nunits);
6729 }
6730 }
6731 if (!slp_reduc
6732 && (mode1 = targetm.vectorize.split_reduction (mode)) != mode)
6733 nunits1 = GET_MODE_NUNITS (mode1).to_constant ();
6734
6735 tree vectype1 = get_related_vectype_for_scalar_type (TYPE_MODE (vectype),
6736 stype, nunits1);
6737 reduce_with_shift = have_whole_vector_shift (mode1);
6738 if (!VECTOR_MODE_P (mode1)
6739 || !directly_supported_p (code, vectype1))
6740 reduce_with_shift = false;
6741
6742 /* First reduce the vector to the desired vector size we should
6743 do shift reduction on by combining upper and lower halves. */
6744 gimple_seq stmts = NULL;
6745 new_temp = vect_create_partial_epilog (reduc_inputs[0], vectype1,
6746 code, &stmts);
6747 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
6748 reduc_inputs[0] = new_temp;
6749
6750 if (reduce_with_shift && (!slp_reduc || group_size == 1))
6751 {
6752 int element_bitsize = tree_to_uhwi (bitsize);
6753 /* Enforced by vectorizable_reduction, which disallows SLP reductions
6754 for variable-length vectors and also requires direct target support
6755 for loop reductions. */
6756 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype1));
6757 int nelements = vec_size_in_bits / element_bitsize;
6758 vec_perm_builder sel;
6759 vec_perm_indices indices;
6760
6761 int elt_offset;
6762
6763 tree zero_vec = build_zero_cst (vectype1);
6764 /* Case 2: Create:
6765 for (offset = nelements/2; offset >= 1; offset/=2)
6766 {
6767 Create: va' = vec_shift <va, offset>
6768 Create: va = vop <va, va'>
6769 } */
6770
6771 tree rhs;
6772
6773 if (dump_enabled_p ())
6774 dump_printf_loc (MSG_NOTE, vect_location,
6775 "Reduce using vector shifts\n");
6776
6777 gimple_seq stmts = NULL;
6778 new_temp = gimple_convert (&stmts, vectype1, new_temp);
6779 for (elt_offset = nelements / 2;
6780 elt_offset >= 1;
6781 elt_offset /= 2)
6782 {
6783 calc_vec_perm_mask_for_shift (elt_offset, nelements, &sel);
6784 indices.new_vector (sel, 2, nelements);
6785 tree mask = vect_gen_perm_mask_any (vectype1, indices);
6786 new_name = gimple_build (&stmts, VEC_PERM_EXPR, vectype1,
6787 new_temp, zero_vec, mask);
6788 new_temp = gimple_build (&stmts, code,
6789 vectype1, new_name, new_temp);
6790 }
6791 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
6792
6793 /* 2.4 Extract the final scalar result. Create:
6794 s_out3 = extract_field <v_out2, bitpos> */
6795
6796 if (dump_enabled_p ())
6797 dump_printf_loc (MSG_NOTE, vect_location,
6798 "extract scalar result\n");
6799
6800 rhs = build3 (BIT_FIELD_REF, scalar_type, new_temp,
6801 bitsize, bitsize_zero_node);
6802 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
6803 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
6804 gimple_assign_set_lhs (epilog_stmt, new_temp);
6805 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
6806 scalar_results.safe_push (new_temp);
6807 }
6808 else
6809 {
6810 /* Case 3: Create:
6811 s = extract_field <v_out2, 0>
6812 for (offset = element_size;
6813 offset < vector_size;
6814 offset += element_size;)
6815 {
6816 Create: s' = extract_field <v_out2, offset>
6817 Create: s = op <s, s'> // For non SLP cases
6818 } */
6819
6820 if (dump_enabled_p ())
6821 dump_printf_loc (MSG_NOTE, vect_location,
6822 "Reduce using scalar code.\n");
6823
6824 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype1));
6825 int element_bitsize = tree_to_uhwi (bitsize);
6826 tree compute_type = TREE_TYPE (vectype);
6827 gimple_seq stmts = NULL;
6828 FOR_EACH_VEC_ELT (reduc_inputs, i, vec_temp)
6829 {
6830 int bit_offset;
6831 new_temp = gimple_build (&stmts, BIT_FIELD_REF, compute_type,
6832 vec_temp, bitsize, bitsize_zero_node);
6833
6834 /* In SLP we don't need to apply reduction operation, so we just
6835 collect s' values in SCALAR_RESULTS. */
6836 if (slp_reduc)
6837 scalar_results.safe_push (new_temp);
6838
6839 for (bit_offset = element_bitsize;
6840 bit_offset < vec_size_in_bits;
6841 bit_offset += element_bitsize)
6842 {
6843 tree bitpos = bitsize_int (bit_offset);
6844 new_name = gimple_build (&stmts, BIT_FIELD_REF,
6845 compute_type, vec_temp,
6846 bitsize, bitpos);
6847 if (slp_reduc)
6848 {
6849 /* In SLP we don't need to apply reduction operation, so
6850 we just collect s' values in SCALAR_RESULTS. */
6851 new_temp = new_name;
6852 scalar_results.safe_push (new_name);
6853 }
6854 else
6855 new_temp = gimple_build (&stmts, code, compute_type,
6856 new_name, new_temp);
6857 }
6858 }
6859
6860 /* The only case where we need to reduce scalar results in SLP, is
6861 unrolling. If the size of SCALAR_RESULTS is greater than
6862 REDUC_GROUP_SIZE, we reduce them combining elements modulo
6863 REDUC_GROUP_SIZE. */
6864 if (slp_reduc)
6865 {
6866 tree res, first_res, new_res;
6867
6868 /* Reduce multiple scalar results in case of SLP unrolling. */
6869 for (j = group_size; scalar_results.iterate (j, &res);
6870 j++)
6871 {
6872 first_res = scalar_results[j % group_size];
6873 new_res = gimple_build (&stmts, code, compute_type,
6874 first_res, res);
6875 scalar_results[j % group_size] = new_res;
6876 }
6877 scalar_results.truncate (group_size);
6878 for (k = 0; k < group_size; k++)
6879 scalar_results[k] = gimple_convert (&stmts, scalar_type,
6880 scalar_results[k]);
6881 }
6882 else
6883 {
6884 /* Not SLP - we have one scalar to keep in SCALAR_RESULTS. */
6885 new_temp = gimple_convert (&stmts, scalar_type, new_temp);
6886 scalar_results.safe_push (new_temp);
6887 }
6888
6889 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
6890 }
6891
6892 if ((STMT_VINFO_REDUC_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
6893 && induc_val)
6894 {
6895 /* Earlier we set the initial value to be a vector if induc_val
6896 values. Check the result and if it is induc_val then replace
6897 with the original initial value, unless induc_val is
6898 the same as initial_def already. */
6899 tree zcompare = make_ssa_name (boolean_type_node);
6900 epilog_stmt = gimple_build_assign (zcompare, EQ_EXPR,
6901 scalar_results[0], induc_val);
6902 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
6903 tree initial_def = reduc_info->reduc_initial_values[0];
6904 tree tmp = make_ssa_name (new_scalar_dest);
6905 epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
6906 initial_def, scalar_results[0]);
6907 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
6908 scalar_results[0] = tmp;
6909 }
6910 }
6911
6912 /* 2.5 Adjust the final result by the initial value of the reduction
6913 variable. (When such adjustment is not needed, then
6914 'adjustment_def' is zero). For example, if code is PLUS we create:
6915 new_temp = loop_exit_def + adjustment_def */
6916
6917 if (adjustment_def)
6918 {
6919 gcc_assert (!slp_reduc || group_size == 1);
6920 gimple_seq stmts = NULL;
6921 if (double_reduc)
6922 {
6923 gcc_assert (VECTOR_TYPE_P (TREE_TYPE (adjustment_def)));
6924 adjustment_def = gimple_convert (&stmts, vectype, adjustment_def);
6925 new_temp = gimple_build (&stmts, code, vectype,
6926 reduc_inputs[0], adjustment_def);
6927 }
6928 else
6929 {
6930 new_temp = scalar_results[0];
6931 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) != VECTOR_TYPE);
6932 adjustment_def = gimple_convert (&stmts, TREE_TYPE (vectype),
6933 adjustment_def);
6934 new_temp = gimple_convert (&stmts, TREE_TYPE (vectype), new_temp);
6935 new_temp = gimple_build (&stmts, code, TREE_TYPE (vectype),
6936 new_temp, adjustment_def);
6937 new_temp = gimple_convert (&stmts, scalar_type, new_temp);
6938 }
6939
6940 epilog_stmt = gimple_seq_last_stmt (stmts);
6941 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
6942 scalar_results[0] = new_temp;
6943 }
6944
6945 /* Record this operation if it could be reused by the epilogue loop. */
6946 if (STMT_VINFO_REDUC_TYPE (reduc_info) == TREE_CODE_REDUCTION
6947 && reduc_inputs.length () == 1)
6948 loop_vinfo->reusable_accumulators.put (scalar_results[0],
6949 { orig_reduc_input, reduc_info });
6950
6951 if (double_reduc)
6952 loop = outer_loop;
6953
6954 /* 2.6 Handle the loop-exit phis. Replace the uses of scalar loop-exit
6955 phis with new adjusted scalar results, i.e., replace use <s_out0>
6956 with use <s_out4>.
6957
6958 Transform:
6959 loop_exit:
6960 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
6961 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
6962 v_out2 = reduce <v_out1>
6963 s_out3 = extract_field <v_out2, 0>
6964 s_out4 = adjust_result <s_out3>
6965 use <s_out0>
6966 use <s_out0>
6967
6968 into:
6969
6970 loop_exit:
6971 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
6972 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
6973 v_out2 = reduce <v_out1>
6974 s_out3 = extract_field <v_out2, 0>
6975 s_out4 = adjust_result <s_out3>
6976 use <s_out4>
6977 use <s_out4> */
6978
6979 gcc_assert (live_out_stmts.size () == scalar_results.length ());
6980 auto_vec<gimple *> phis;
6981 for (k = 0; k < live_out_stmts.size (); k++)
6982 {
6983 stmt_vec_info scalar_stmt_info = vect_orig_stmt (live_out_stmts[k]);
6984 scalar_dest = gimple_get_lhs (scalar_stmt_info->stmt);
6985
6986 /* Find the loop-closed-use at the loop exit of the original scalar
6987 result. (The reduction result is expected to have two immediate uses,
6988 one at the latch block, and one at the loop exit). For double
6989 reductions we are looking for exit phis of the outer loop. */
6990 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
6991 {
6992 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
6993 {
6994 if (!is_gimple_debug (USE_STMT (use_p))
6995 && gimple_bb (USE_STMT (use_p)) == loop_exit->dest)
6996 phis.safe_push (USE_STMT (use_p));
6997 }
6998 else
6999 {
7000 if (double_reduc && gimple_code (USE_STMT (use_p)) == GIMPLE_PHI)
7001 {
7002 tree phi_res = PHI_RESULT (USE_STMT (use_p));
7003
7004 FOR_EACH_IMM_USE_FAST (phi_use_p, phi_imm_iter, phi_res)
7005 {
7006 if (!flow_bb_inside_loop_p (loop,
7007 gimple_bb (USE_STMT (phi_use_p)))
7008 && !is_gimple_debug (USE_STMT (phi_use_p)))
7009 phis.safe_push (USE_STMT (phi_use_p));
7010 }
7011 }
7012 }
7013 }
7014
7015 FOR_EACH_VEC_ELT (phis, i, exit_phi)
7016 {
7017 /* Replace the uses: */
7018 orig_name = PHI_RESULT (exit_phi);
7019
7020 /* Look for a single use at the target of the skip edge. */
7021 if (unify_with_main_loop_p)
7022 {
7023 use_operand_p use_p;
7024 gimple *user;
7025 if (!single_imm_use (orig_name, &use_p, &user))
7026 gcc_unreachable ();
7027 orig_name = gimple_get_lhs (user);
7028 }
7029
7030 scalar_result = scalar_results[k];
7031 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
7032 {
7033 gphi *use_phi = dyn_cast <gphi *> (use_stmt);
7034 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
7035 {
7036 if (use_phi
7037 && (phi_arg_edge_from_use (use_p)->flags & EDGE_ABNORMAL))
7038 {
7039 gcc_assert (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig_name));
7040 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (scalar_result) = 1;
7041 }
7042 SET_USE (use_p, scalar_result);
7043 }
7044 update_stmt (use_stmt);
7045 }
7046 }
7047
7048 phis.truncate (0);
7049 }
7050 }
7051
7052 /* Return a vector of type VECTYPE that is equal to the vector select
7053 operation "MASK ? VEC : IDENTITY". Insert the select statements
7054 before GSI. */
7055
7056 static tree
7057 merge_with_identity (gimple_stmt_iterator *gsi, tree mask, tree vectype,
7058 tree vec, tree identity)
7059 {
7060 tree cond = make_temp_ssa_name (vectype, NULL, "cond");
7061 gimple *new_stmt = gimple_build_assign (cond, VEC_COND_EXPR,
7062 mask, vec, identity);
7063 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
7064 return cond;
7065 }
7066
7067 /* Successively apply CODE to each element of VECTOR_RHS, in left-to-right
7068 order, starting with LHS. Insert the extraction statements before GSI and
7069 associate the new scalar SSA names with variable SCALAR_DEST.
7070 If MASK is nonzero mask the input and then operate on it unconditionally.
7071 Return the SSA name for the result. */
7072
7073 static tree
7074 vect_expand_fold_left (gimple_stmt_iterator *gsi, tree scalar_dest,
7075 tree_code code, tree lhs, tree vector_rhs,
7076 tree mask)
7077 {
7078 tree vectype = TREE_TYPE (vector_rhs);
7079 tree scalar_type = TREE_TYPE (vectype);
7080 tree bitsize = TYPE_SIZE (scalar_type);
7081 unsigned HOST_WIDE_INT vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
7082 unsigned HOST_WIDE_INT element_bitsize = tree_to_uhwi (bitsize);
7083
7084 /* Re-create a VEC_COND_EXPR to mask the input here in order to be able
7085 to perform an unconditional element-wise reduction of it. */
7086 if (mask)
7087 {
7088 tree masked_vector_rhs = make_temp_ssa_name (vectype, NULL,
7089 "masked_vector_rhs");
7090 tree neutral_op = neutral_op_for_reduction (scalar_type, code, NULL_TREE,
7091 false);
7092 tree vector_identity = build_vector_from_val (vectype, neutral_op);
7093 gassign *select = gimple_build_assign (masked_vector_rhs, VEC_COND_EXPR,
7094 mask, vector_rhs, vector_identity);
7095 gsi_insert_before (gsi, select, GSI_SAME_STMT);
7096 vector_rhs = masked_vector_rhs;
7097 }
7098
7099 for (unsigned HOST_WIDE_INT bit_offset = 0;
7100 bit_offset < vec_size_in_bits;
7101 bit_offset += element_bitsize)
7102 {
7103 tree bitpos = bitsize_int (bit_offset);
7104 tree rhs = build3 (BIT_FIELD_REF, scalar_type, vector_rhs,
7105 bitsize, bitpos);
7106
7107 gassign *stmt = gimple_build_assign (scalar_dest, rhs);
7108 rhs = make_ssa_name (scalar_dest, stmt);
7109 gimple_assign_set_lhs (stmt, rhs);
7110 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
7111 /* Fold the vector extract, combining it with a previous reversal
7112 like seen in PR90579. */
7113 auto gsi2 = gsi_for_stmt (stmt);
7114 if (fold_stmt (&gsi2, follow_all_ssa_edges))
7115 update_stmt (gsi_stmt (gsi2));
7116
7117 stmt = gimple_build_assign (scalar_dest, code, lhs, rhs);
7118 tree new_name = make_ssa_name (scalar_dest, stmt);
7119 gimple_assign_set_lhs (stmt, new_name);
7120 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
7121 lhs = new_name;
7122 }
7123 return lhs;
7124 }
7125
7126 /* Get a masked internal function equivalent to REDUC_FN. VECTYPE_IN is the
7127 type of the vector input. */
7128
7129 static internal_fn
7130 get_masked_reduction_fn (internal_fn reduc_fn, tree vectype_in)
7131 {
7132 internal_fn mask_reduc_fn;
7133 internal_fn mask_len_reduc_fn;
7134
7135 switch (reduc_fn)
7136 {
7137 case IFN_FOLD_LEFT_PLUS:
7138 mask_reduc_fn = IFN_MASK_FOLD_LEFT_PLUS;
7139 mask_len_reduc_fn = IFN_MASK_LEN_FOLD_LEFT_PLUS;
7140 break;
7141
7142 default:
7143 return IFN_LAST;
7144 }
7145
7146 if (direct_internal_fn_supported_p (mask_reduc_fn, vectype_in,
7147 OPTIMIZE_FOR_SPEED))
7148 return mask_reduc_fn;
7149 if (direct_internal_fn_supported_p (mask_len_reduc_fn, vectype_in,
7150 OPTIMIZE_FOR_SPEED))
7151 return mask_len_reduc_fn;
7152 return IFN_LAST;
7153 }
7154
7155 /* Perform an in-order reduction (FOLD_LEFT_REDUCTION). STMT_INFO is the
7156 statement that sets the live-out value. REDUC_DEF_STMT is the phi
7157 statement. CODE is the operation performed by STMT_INFO and OPS are
7158 its scalar operands. REDUC_INDEX is the index of the operand in
7159 OPS that is set by REDUC_DEF_STMT. REDUC_FN is the function that
7160 implements in-order reduction, or IFN_LAST if we should open-code it.
7161 VECTYPE_IN is the type of the vector input. MASKS specifies the masks
7162 that should be used to control the operation in a fully-masked loop. */
7163
7164 static bool
7165 vectorize_fold_left_reduction (loop_vec_info loop_vinfo,
7166 stmt_vec_info stmt_info,
7167 gimple_stmt_iterator *gsi,
7168 gimple **vec_stmt, slp_tree slp_node,
7169 gimple *reduc_def_stmt,
7170 code_helper code, internal_fn reduc_fn,
7171 tree *ops, int num_ops, tree vectype_in,
7172 int reduc_index, vec_loop_masks *masks,
7173 vec_loop_lens *lens)
7174 {
7175 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
7176 tree vectype_out = STMT_VINFO_VECTYPE (stmt_info);
7177 internal_fn mask_reduc_fn = get_masked_reduction_fn (reduc_fn, vectype_in);
7178
7179 int ncopies;
7180 if (slp_node)
7181 ncopies = 1;
7182 else
7183 ncopies = vect_get_num_copies (loop_vinfo, vectype_in);
7184
7185 gcc_assert (!nested_in_vect_loop_p (loop, stmt_info));
7186 gcc_assert (ncopies == 1);
7187
7188 bool is_cond_op = false;
7189 if (!code.is_tree_code ())
7190 {
7191 code = conditional_internal_fn_code (internal_fn (code));
7192 gcc_assert (code != ERROR_MARK);
7193 is_cond_op = true;
7194 }
7195
7196 gcc_assert (TREE_CODE_LENGTH (tree_code (code)) == binary_op);
7197
7198 if (slp_node)
7199 gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (vectype_out),
7200 TYPE_VECTOR_SUBPARTS (vectype_in)));
7201
7202 /* The operands either come from a binary operation or an IFN_COND operation.
7203 The former is a gimple assign with binary rhs and the latter is a
7204 gimple call with four arguments. */
7205 gcc_assert (num_ops == 2 || num_ops == 4);
7206
7207 int group_size = 1;
7208 stmt_vec_info scalar_dest_def_info;
7209 auto_vec<tree> vec_oprnds0, vec_opmask;
7210 if (slp_node)
7211 {
7212 vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[(is_cond_op ? 2 : 0)
7213 + (1 - reduc_index)],
7214 &vec_oprnds0);
7215 group_size = SLP_TREE_SCALAR_STMTS (slp_node).length ();
7216 scalar_dest_def_info = SLP_TREE_SCALAR_STMTS (slp_node)[group_size - 1];
7217 /* For an IFN_COND_OP we also need the vector mask operand. */
7218 if (is_cond_op)
7219 vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[0], &vec_opmask);
7220 }
7221 else
7222 {
7223 tree op0, opmask;
7224 if (!is_cond_op)
7225 op0 = ops[1 - reduc_index];
7226 else
7227 {
7228 op0 = ops[2 + (1 - reduc_index)];
7229 opmask = ops[0];
7230 }
7231 vect_get_vec_defs_for_operand (loop_vinfo, stmt_info, 1,
7232 op0, &vec_oprnds0);
7233 scalar_dest_def_info = stmt_info;
7234
7235 /* For an IFN_COND_OP we also need the vector mask operand. */
7236 if (is_cond_op)
7237 vect_get_vec_defs_for_operand (loop_vinfo, stmt_info, 1,
7238 opmask, &vec_opmask);
7239 }
7240
7241 gimple *sdef = vect_orig_stmt (scalar_dest_def_info)->stmt;
7242 tree scalar_dest = gimple_get_lhs (sdef);
7243 tree scalar_type = TREE_TYPE (scalar_dest);
7244 tree reduc_var = gimple_phi_result (reduc_def_stmt);
7245
7246 int vec_num = vec_oprnds0.length ();
7247 gcc_assert (vec_num == 1 || slp_node);
7248 tree vec_elem_type = TREE_TYPE (vectype_out);
7249 gcc_checking_assert (useless_type_conversion_p (scalar_type, vec_elem_type));
7250
7251 tree vector_identity = NULL_TREE;
7252 if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
7253 {
7254 vector_identity = build_zero_cst (vectype_out);
7255 if (!HONOR_SIGNED_ZEROS (vectype_out))
7256 ;
7257 else
7258 {
7259 gcc_assert (!HONOR_SIGN_DEPENDENT_ROUNDING (vectype_out));
7260 vector_identity = const_unop (NEGATE_EXPR, vectype_out,
7261 vector_identity);
7262 }
7263 }
7264
7265 tree scalar_dest_var = vect_create_destination_var (scalar_dest, NULL);
7266 int i;
7267 tree def0;
7268 FOR_EACH_VEC_ELT (vec_oprnds0, i, def0)
7269 {
7270 gimple *new_stmt;
7271 tree mask = NULL_TREE;
7272 tree len = NULL_TREE;
7273 tree bias = NULL_TREE;
7274 if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
7275 {
7276 tree loop_mask = vect_get_loop_mask (loop_vinfo, gsi, masks,
7277 vec_num, vectype_in, i);
7278 if (is_cond_op)
7279 mask = prepare_vec_mask (loop_vinfo, TREE_TYPE (loop_mask),
7280 loop_mask, vec_opmask[i], gsi);
7281 else
7282 mask = loop_mask;
7283 }
7284 else if (is_cond_op)
7285 mask = vec_opmask[i];
7286 if (LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
7287 {
7288 len = vect_get_loop_len (loop_vinfo, gsi, lens, vec_num, vectype_in,
7289 i, 1);
7290 signed char biasval = LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo);
7291 bias = build_int_cst (intQI_type_node, biasval);
7292 if (!is_cond_op)
7293 mask = build_minus_one_cst (truth_type_for (vectype_in));
7294 }
7295
7296 /* Handle MINUS by adding the negative. */
7297 if (reduc_fn != IFN_LAST && code == MINUS_EXPR)
7298 {
7299 tree negated = make_ssa_name (vectype_out);
7300 new_stmt = gimple_build_assign (negated, NEGATE_EXPR, def0);
7301 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
7302 def0 = negated;
7303 }
7304
7305 if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
7306 && mask && mask_reduc_fn == IFN_LAST)
7307 def0 = merge_with_identity (gsi, mask, vectype_out, def0,
7308 vector_identity);
7309
7310 /* On the first iteration the input is simply the scalar phi
7311 result, and for subsequent iterations it is the output of
7312 the preceding operation. */
7313 if (reduc_fn != IFN_LAST || (mask && mask_reduc_fn != IFN_LAST))
7314 {
7315 if (mask && len && mask_reduc_fn == IFN_MASK_LEN_FOLD_LEFT_PLUS)
7316 new_stmt = gimple_build_call_internal (mask_reduc_fn, 5, reduc_var,
7317 def0, mask, len, bias);
7318 else if (mask && mask_reduc_fn == IFN_MASK_FOLD_LEFT_PLUS)
7319 new_stmt = gimple_build_call_internal (mask_reduc_fn, 3, reduc_var,
7320 def0, mask);
7321 else
7322 new_stmt = gimple_build_call_internal (reduc_fn, 2, reduc_var,
7323 def0);
7324 /* For chained SLP reductions the output of the previous reduction
7325 operation serves as the input of the next. For the final statement
7326 the output cannot be a temporary - we reuse the original
7327 scalar destination of the last statement. */
7328 if (i != vec_num - 1)
7329 {
7330 gimple_set_lhs (new_stmt, scalar_dest_var);
7331 reduc_var = make_ssa_name (scalar_dest_var, new_stmt);
7332 gimple_set_lhs (new_stmt, reduc_var);
7333 }
7334 }
7335 else
7336 {
7337 reduc_var = vect_expand_fold_left (gsi, scalar_dest_var,
7338 tree_code (code), reduc_var, def0,
7339 mask);
7340 new_stmt = SSA_NAME_DEF_STMT (reduc_var);
7341 /* Remove the statement, so that we can use the same code paths
7342 as for statements that we've just created. */
7343 gimple_stmt_iterator tmp_gsi = gsi_for_stmt (new_stmt);
7344 gsi_remove (&tmp_gsi, true);
7345 }
7346
7347 if (i == vec_num - 1)
7348 {
7349 gimple_set_lhs (new_stmt, scalar_dest);
7350 vect_finish_replace_stmt (loop_vinfo,
7351 scalar_dest_def_info,
7352 new_stmt);
7353 }
7354 else
7355 vect_finish_stmt_generation (loop_vinfo,
7356 scalar_dest_def_info,
7357 new_stmt, gsi);
7358
7359 if (slp_node)
7360 slp_node->push_vec_def (new_stmt);
7361 else
7362 {
7363 STMT_VINFO_VEC_STMTS (stmt_info).safe_push (new_stmt);
7364 *vec_stmt = new_stmt;
7365 }
7366 }
7367
7368 return true;
7369 }
7370
7371 /* Function is_nonwrapping_integer_induction.
7372
7373 Check if STMT_VINO (which is part of loop LOOP) both increments and
7374 does not cause overflow. */
7375
7376 static bool
7377 is_nonwrapping_integer_induction (stmt_vec_info stmt_vinfo, class loop *loop)
7378 {
7379 gphi *phi = as_a <gphi *> (stmt_vinfo->stmt);
7380 tree base = STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo);
7381 tree step = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo);
7382 tree lhs_type = TREE_TYPE (gimple_phi_result (phi));
7383 widest_int ni, max_loop_value, lhs_max;
7384 wi::overflow_type overflow = wi::OVF_NONE;
7385
7386 /* Make sure the loop is integer based. */
7387 if (TREE_CODE (base) != INTEGER_CST
7388 || TREE_CODE (step) != INTEGER_CST)
7389 return false;
7390
7391 /* Check that the max size of the loop will not wrap. */
7392
7393 if (TYPE_OVERFLOW_UNDEFINED (lhs_type))
7394 return true;
7395
7396 if (! max_stmt_executions (loop, &ni))
7397 return false;
7398
7399 max_loop_value = wi::mul (wi::to_widest (step), ni, TYPE_SIGN (lhs_type),
7400 &overflow);
7401 if (overflow)
7402 return false;
7403
7404 max_loop_value = wi::add (wi::to_widest (base), max_loop_value,
7405 TYPE_SIGN (lhs_type), &overflow);
7406 if (overflow)
7407 return false;
7408
7409 return (wi::min_precision (max_loop_value, TYPE_SIGN (lhs_type))
7410 <= TYPE_PRECISION (lhs_type));
7411 }
7412
7413 /* Check if masking can be supported by inserting a conditional expression.
7414 CODE is the code for the operation. COND_FN is the conditional internal
7415 function, if it exists. VECTYPE_IN is the type of the vector input. */
7416 static bool
7417 use_mask_by_cond_expr_p (code_helper code, internal_fn cond_fn,
7418 tree vectype_in)
7419 {
7420 if (cond_fn != IFN_LAST
7421 && direct_internal_fn_supported_p (cond_fn, vectype_in,
7422 OPTIMIZE_FOR_SPEED))
7423 return false;
7424
7425 if (code.is_tree_code ())
7426 switch (tree_code (code))
7427 {
7428 case DOT_PROD_EXPR:
7429 case SAD_EXPR:
7430 return true;
7431
7432 default:
7433 break;
7434 }
7435 return false;
7436 }
7437
7438 /* Insert a conditional expression to enable masked vectorization. CODE is the
7439 code for the operation. VOP is the array of operands. MASK is the loop
7440 mask. GSI is a statement iterator used to place the new conditional
7441 expression. */
7442 static void
7443 build_vect_cond_expr (code_helper code, tree vop[3], tree mask,
7444 gimple_stmt_iterator *gsi)
7445 {
7446 switch (tree_code (code))
7447 {
7448 case DOT_PROD_EXPR:
7449 {
7450 tree vectype = TREE_TYPE (vop[1]);
7451 tree zero = build_zero_cst (vectype);
7452 tree masked_op1 = make_temp_ssa_name (vectype, NULL, "masked_op1");
7453 gassign *select = gimple_build_assign (masked_op1, VEC_COND_EXPR,
7454 mask, vop[1], zero);
7455 gsi_insert_before (gsi, select, GSI_SAME_STMT);
7456 vop[1] = masked_op1;
7457 break;
7458 }
7459
7460 case SAD_EXPR:
7461 {
7462 tree vectype = TREE_TYPE (vop[1]);
7463 tree masked_op1 = make_temp_ssa_name (vectype, NULL, "masked_op1");
7464 gassign *select = gimple_build_assign (masked_op1, VEC_COND_EXPR,
7465 mask, vop[1], vop[0]);
7466 gsi_insert_before (gsi, select, GSI_SAME_STMT);
7467 vop[1] = masked_op1;
7468 break;
7469 }
7470
7471 default:
7472 gcc_unreachable ();
7473 }
7474 }
7475
7476 /* Given an operation with CODE in loop reduction path whose reduction PHI is
7477 specified by REDUC_INFO, the operation has TYPE of scalar result, and its
7478 input vectype is represented by VECTYPE_IN. The vectype of vectorized result
7479 may be different from VECTYPE_IN, either in base type or vectype lanes,
7480 lane-reducing operation is the case. This function check if it is possible,
7481 and how to perform partial vectorization on the operation in the context
7482 of LOOP_VINFO. */
7483
7484 static void
7485 vect_reduction_update_partial_vector_usage (loop_vec_info loop_vinfo,
7486 stmt_vec_info reduc_info,
7487 slp_tree slp_node,
7488 code_helper code, tree type,
7489 tree vectype_in)
7490 {
7491 enum vect_reduction_type reduc_type = STMT_VINFO_REDUC_TYPE (reduc_info);
7492 internal_fn reduc_fn = STMT_VINFO_REDUC_FN (reduc_info);
7493 internal_fn cond_fn = get_conditional_internal_fn (code, type);
7494
7495 if (reduc_type != FOLD_LEFT_REDUCTION
7496 && !use_mask_by_cond_expr_p (code, cond_fn, vectype_in)
7497 && (cond_fn == IFN_LAST
7498 || !direct_internal_fn_supported_p (cond_fn, vectype_in,
7499 OPTIMIZE_FOR_SPEED)))
7500 {
7501 if (dump_enabled_p ())
7502 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
7503 "can't operate on partial vectors because"
7504 " no conditional operation is available.\n");
7505 LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
7506 }
7507 else if (reduc_type == FOLD_LEFT_REDUCTION
7508 && reduc_fn == IFN_LAST
7509 && !expand_vec_cond_expr_p (vectype_in, truth_type_for (vectype_in)))
7510 {
7511 if (dump_enabled_p ())
7512 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
7513 "can't operate on partial vectors because"
7514 " no conditional operation is available.\n");
7515 LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
7516 }
7517 else if (reduc_type == FOLD_LEFT_REDUCTION
7518 && internal_fn_mask_index (reduc_fn) == -1
7519 && FLOAT_TYPE_P (vectype_in)
7520 && HONOR_SIGN_DEPENDENT_ROUNDING (vectype_in))
7521 {
7522 if (dump_enabled_p ())
7523 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
7524 "can't operate on partial vectors because"
7525 " signed zeros cannot be preserved.\n");
7526 LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
7527 }
7528 else
7529 {
7530 internal_fn mask_reduc_fn
7531 = get_masked_reduction_fn (reduc_fn, vectype_in);
7532 vec_loop_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
7533 vec_loop_lens *lens = &LOOP_VINFO_LENS (loop_vinfo);
7534 unsigned nvectors = vect_get_num_copies (loop_vinfo, slp_node,
7535 vectype_in);
7536
7537 if (mask_reduc_fn == IFN_MASK_LEN_FOLD_LEFT_PLUS)
7538 vect_record_loop_len (loop_vinfo, lens, nvectors, vectype_in, 1);
7539 else
7540 vect_record_loop_mask (loop_vinfo, masks, nvectors, vectype_in, NULL);
7541 }
7542 }
7543
7544 /* Check if STMT_INFO is a lane-reducing operation that can be vectorized in
7545 the context of LOOP_VINFO, and vector cost will be recorded in COST_VEC,
7546 and the analysis is for slp if SLP_NODE is not NULL.
7547
7548 For a lane-reducing operation, the loop reduction path that it lies in,
7549 may contain normal operation, or other lane-reducing operation of different
7550 input type size, an example as:
7551
7552 int sum = 0;
7553 for (i)
7554 {
7555 ...
7556 sum += d0[i] * d1[i]; // dot-prod <vector(16) char>
7557 sum += w[i]; // widen-sum <vector(16) char>
7558 sum += abs(s0[i] - s1[i]); // sad <vector(8) short>
7559 sum += n[i]; // normal <vector(4) int>
7560 ...
7561 }
7562
7563 Vectorization factor is essentially determined by operation whose input
7564 vectype has the most lanes ("vector(16) char" in the example), while we
7565 need to choose input vectype with the least lanes ("vector(4) int" in the
7566 example) to determine effective number of vector reduction PHIs. */
7567
7568 bool
7569 vectorizable_lane_reducing (loop_vec_info loop_vinfo, stmt_vec_info stmt_info,
7570 slp_tree slp_node, stmt_vector_for_cost *cost_vec)
7571 {
7572 gimple *stmt = stmt_info->stmt;
7573
7574 if (!lane_reducing_stmt_p (stmt))
7575 return false;
7576
7577 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
7578
7579 if (!INTEGRAL_TYPE_P (type))
7580 return false;
7581
7582 /* Do not try to vectorize bit-precision reductions. */
7583 if (!type_has_mode_precision_p (type))
7584 return false;
7585
7586 stmt_vec_info reduc_info = STMT_VINFO_REDUC_DEF (vect_orig_stmt (stmt_info));
7587
7588 /* TODO: Support lane-reducing operation that does not directly participate
7589 in loop reduction. */
7590 if (!reduc_info || STMT_VINFO_REDUC_IDX (stmt_info) < 0)
7591 return false;
7592
7593 /* Lane-reducing pattern inside any inner loop of LOOP_VINFO is not
7594 recoginized. */
7595 gcc_assert (STMT_VINFO_DEF_TYPE (reduc_info) == vect_reduction_def);
7596 gcc_assert (STMT_VINFO_REDUC_TYPE (reduc_info) == TREE_CODE_REDUCTION);
7597
7598 for (int i = 0; i < (int) gimple_num_ops (stmt) - 1; i++)
7599 {
7600 stmt_vec_info def_stmt_info;
7601 slp_tree slp_op;
7602 tree op;
7603 tree vectype;
7604 enum vect_def_type dt;
7605
7606 if (!vect_is_simple_use (loop_vinfo, stmt_info, slp_node, i, &op,
7607 &slp_op, &dt, &vectype, &def_stmt_info))
7608 {
7609 if (dump_enabled_p ())
7610 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
7611 "use not simple.\n");
7612 return false;
7613 }
7614
7615 if (!vectype)
7616 {
7617 vectype = get_vectype_for_scalar_type (loop_vinfo, TREE_TYPE (op),
7618 slp_op);
7619 if (!vectype)
7620 return false;
7621 }
7622
7623 if (slp_node && !vect_maybe_update_slp_op_vectype (slp_op, vectype))
7624 {
7625 if (dump_enabled_p ())
7626 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
7627 "incompatible vector types for invariants\n");
7628 return false;
7629 }
7630
7631 if (i == STMT_VINFO_REDUC_IDX (stmt_info))
7632 continue;
7633
7634 /* There should be at most one cycle def in the stmt. */
7635 if (VECTORIZABLE_CYCLE_DEF (dt))
7636 return false;
7637 }
7638
7639 tree vectype_in = STMT_VINFO_REDUC_VECTYPE_IN (stmt_info);
7640
7641 gcc_assert (vectype_in);
7642
7643 /* Compute number of effective vector statements for costing. */
7644 unsigned int ncopies_for_cost = vect_get_num_copies (loop_vinfo, slp_node,
7645 vectype_in);
7646 gcc_assert (ncopies_for_cost >= 1);
7647
7648 if (vect_is_emulated_mixed_dot_prod (stmt_info))
7649 {
7650 /* We need extra two invariants: one that contains the minimum signed
7651 value and one that contains half of its negative. */
7652 int prologue_stmts = 2;
7653 unsigned cost = record_stmt_cost (cost_vec, prologue_stmts,
7654 scalar_to_vec, stmt_info, 0,
7655 vect_prologue);
7656 if (dump_enabled_p ())
7657 dump_printf (MSG_NOTE, "vectorizable_lane_reducing: "
7658 "extra prologue_cost = %d .\n", cost);
7659
7660 /* Three dot-products and a subtraction. */
7661 ncopies_for_cost *= 4;
7662 }
7663
7664 record_stmt_cost (cost_vec, (int) ncopies_for_cost, vector_stmt, stmt_info,
7665 0, vect_body);
7666
7667 if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
7668 {
7669 enum tree_code code = gimple_assign_rhs_code (stmt);
7670 vect_reduction_update_partial_vector_usage (loop_vinfo, reduc_info,
7671 slp_node, code, type,
7672 vectype_in);
7673 }
7674
7675 /* Transform via vect_transform_reduction. */
7676 STMT_VINFO_TYPE (stmt_info) = reduc_vec_info_type;
7677 return true;
7678 }
7679
7680 /* Function vectorizable_reduction.
7681
7682 Check if STMT_INFO performs a reduction operation that can be vectorized.
7683 If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
7684 stmt to replace it, put it in VEC_STMT, and insert it at GSI.
7685 Return true if STMT_INFO is vectorizable in this way.
7686
7687 This function also handles reduction idioms (patterns) that have been
7688 recognized in advance during vect_pattern_recog. In this case, STMT_INFO
7689 may be of this form:
7690 X = pattern_expr (arg0, arg1, ..., X)
7691 and its STMT_VINFO_RELATED_STMT points to the last stmt in the original
7692 sequence that had been detected and replaced by the pattern-stmt
7693 (STMT_INFO).
7694
7695 This function also handles reduction of condition expressions, for example:
7696 for (int i = 0; i < N; i++)
7697 if (a[i] < value)
7698 last = a[i];
7699 This is handled by vectorising the loop and creating an additional vector
7700 containing the loop indexes for which "a[i] < value" was true. In the
7701 function epilogue this is reduced to a single max value and then used to
7702 index into the vector of results.
7703
7704 In some cases of reduction patterns, the type of the reduction variable X is
7705 different than the type of the other arguments of STMT_INFO.
7706 In such cases, the vectype that is used when transforming STMT_INFO into
7707 a vector stmt is different than the vectype that is used to determine the
7708 vectorization factor, because it consists of a different number of elements
7709 than the actual number of elements that are being operated upon in parallel.
7710
7711 For example, consider an accumulation of shorts into an int accumulator.
7712 On some targets it's possible to vectorize this pattern operating on 8
7713 shorts at a time (hence, the vectype for purposes of determining the
7714 vectorization factor should be V8HI); on the other hand, the vectype that
7715 is used to create the vector form is actually V4SI (the type of the result).
7716
7717 Upon entry to this function, STMT_VINFO_VECTYPE records the vectype that
7718 indicates what is the actual level of parallelism (V8HI in the example), so
7719 that the right vectorization factor would be derived. This vectype
7720 corresponds to the type of arguments to the reduction stmt, and should *NOT*
7721 be used to create the vectorized stmt. The right vectype for the vectorized
7722 stmt is obtained from the type of the result X:
7723 get_vectype_for_scalar_type (vinfo, TREE_TYPE (X))
7724
7725 This means that, contrary to "regular" reductions (or "regular" stmts in
7726 general), the following equation:
7727 STMT_VINFO_VECTYPE == get_vectype_for_scalar_type (vinfo, TREE_TYPE (X))
7728 does *NOT* necessarily hold for reduction patterns. */
7729
7730 bool
7731 vectorizable_reduction (loop_vec_info loop_vinfo,
7732 stmt_vec_info stmt_info, slp_tree slp_node,
7733 slp_instance slp_node_instance,
7734 stmt_vector_for_cost *cost_vec)
7735 {
7736 tree vectype_in = NULL_TREE;
7737 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
7738 enum vect_def_type cond_reduc_dt = vect_unknown_def_type;
7739 stmt_vec_info cond_stmt_vinfo = NULL;
7740 int i;
7741 int ncopies;
7742 bool single_defuse_cycle = false;
7743 bool nested_cycle = false;
7744 bool double_reduc = false;
7745 tree cr_index_scalar_type = NULL_TREE, cr_index_vector_type = NULL_TREE;
7746 tree cond_reduc_val = NULL_TREE;
7747
7748 /* Make sure it was already recognized as a reduction computation. */
7749 if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_reduction_def
7750 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_double_reduction_def
7751 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_nested_cycle)
7752 return false;
7753
7754 /* The stmt we store reduction analysis meta on. */
7755 stmt_vec_info reduc_info = info_for_reduction (loop_vinfo, stmt_info);
7756 reduc_info->is_reduc_info = true;
7757
7758 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle)
7759 {
7760 if (is_a <gphi *> (stmt_info->stmt))
7761 {
7762 if (slp_node)
7763 {
7764 /* We eventually need to set a vector type on invariant
7765 arguments. */
7766 unsigned j;
7767 slp_tree child;
7768 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), j, child)
7769 if (!vect_maybe_update_slp_op_vectype
7770 (child, SLP_TREE_VECTYPE (slp_node)))
7771 {
7772 if (dump_enabled_p ())
7773 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
7774 "incompatible vector types for "
7775 "invariants\n");
7776 return false;
7777 }
7778 }
7779 /* Analysis for double-reduction is done on the outer
7780 loop PHI, nested cycles have no further restrictions. */
7781 STMT_VINFO_TYPE (stmt_info) = cycle_phi_info_type;
7782 }
7783 else
7784 STMT_VINFO_TYPE (stmt_info) = reduc_vec_info_type;
7785 return true;
7786 }
7787
7788 stmt_vec_info orig_stmt_of_analysis = stmt_info;
7789 stmt_vec_info phi_info = stmt_info;
7790 if (!is_a <gphi *> (stmt_info->stmt))
7791 {
7792 STMT_VINFO_TYPE (stmt_info) = reduc_vec_info_type;
7793 return true;
7794 }
7795 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
7796 {
7797 if (gimple_bb (stmt_info->stmt) != loop->header)
7798 {
7799 /* For SLP we arrive here for both the inner loop LC PHI and
7800 the outer loop PHI. The latter is what we want to analyze
7801 the reduction with. The LC PHI is handled by
7802 vectorizable_lc_phi. */
7803 gcc_assert (slp_node);
7804 return gimple_phi_num_args (as_a <gphi *> (stmt_info->stmt)) == 2;
7805 }
7806 use_operand_p use_p;
7807 gimple *use_stmt;
7808 bool res = single_imm_use (gimple_phi_result (stmt_info->stmt),
7809 &use_p, &use_stmt);
7810 gcc_assert (res);
7811 phi_info = loop_vinfo->lookup_stmt (use_stmt);
7812 }
7813
7814 if (slp_node)
7815 {
7816 slp_node_instance->reduc_phis = slp_node;
7817 /* ??? We're leaving slp_node to point to the PHIs, we only
7818 need it to get at the number of vector stmts which wasn't
7819 yet initialized for the instance root. */
7820 }
7821
7822 /* PHIs should not participate in patterns. */
7823 gcc_assert (!STMT_VINFO_RELATED_STMT (phi_info));
7824 gphi *reduc_def_phi = as_a <gphi *> (phi_info->stmt);
7825
7826 /* Verify following REDUC_IDX from the latch def leads us back to the PHI
7827 and compute the reduction chain length. Discover the real
7828 reduction operation stmt on the way (stmt_info and slp_for_stmt_info). */
7829 tree reduc_def
7830 = PHI_ARG_DEF_FROM_EDGE (reduc_def_phi,
7831 loop_latch_edge
7832 (gimple_bb (reduc_def_phi)->loop_father));
7833 unsigned reduc_chain_length = 0;
7834 bool only_slp_reduc_chain = true;
7835 stmt_info = NULL;
7836 slp_tree slp_for_stmt_info = slp_node ? slp_node_instance->root : NULL;
7837 /* For double-reductions we start SLP analysis at the inner loop LC PHI
7838 which is the def of the outer loop live stmt. */
7839 if (STMT_VINFO_DEF_TYPE (reduc_info) == vect_double_reduction_def
7840 && slp_node)
7841 slp_for_stmt_info = SLP_TREE_CHILDREN (slp_for_stmt_info)[0];
7842 while (reduc_def != PHI_RESULT (reduc_def_phi))
7843 {
7844 stmt_vec_info def = loop_vinfo->lookup_def (reduc_def);
7845 stmt_vec_info vdef = vect_stmt_to_vectorize (def);
7846 int reduc_idx = STMT_VINFO_REDUC_IDX (vdef);
7847
7848 if (reduc_idx == -1)
7849 {
7850 if (dump_enabled_p ())
7851 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
7852 "reduction chain broken by patterns.\n");
7853 return false;
7854 }
7855 if (!REDUC_GROUP_FIRST_ELEMENT (vdef))
7856 only_slp_reduc_chain = false;
7857 /* For epilogue generation live members of the chain need
7858 to point back to the PHI via their original stmt for
7859 info_for_reduction to work. For SLP we need to look at
7860 all lanes here - even though we only will vectorize from
7861 the SLP node with live lane zero the other live lanes also
7862 need to be identified as part of a reduction to be able
7863 to skip code generation for them. */
7864 if (slp_for_stmt_info)
7865 {
7866 for (auto s : SLP_TREE_SCALAR_STMTS (slp_for_stmt_info))
7867 if (STMT_VINFO_LIVE_P (s))
7868 STMT_VINFO_REDUC_DEF (vect_orig_stmt (s)) = phi_info;
7869 }
7870 else if (STMT_VINFO_LIVE_P (vdef))
7871 STMT_VINFO_REDUC_DEF (def) = phi_info;
7872 gimple_match_op op;
7873 if (!gimple_extract_op (vdef->stmt, &op))
7874 {
7875 if (dump_enabled_p ())
7876 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
7877 "reduction chain includes unsupported"
7878 " statement type.\n");
7879 return false;
7880 }
7881 if (CONVERT_EXPR_CODE_P (op.code))
7882 {
7883 if (!tree_nop_conversion_p (op.type, TREE_TYPE (op.ops[0])))
7884 {
7885 if (dump_enabled_p ())
7886 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
7887 "conversion in the reduction chain.\n");
7888 return false;
7889 }
7890 }
7891 else
7892 {
7893 /* First non-conversion stmt. */
7894 if (!stmt_info)
7895 stmt_info = vdef;
7896
7897 if (lane_reducing_op_p (op.code))
7898 {
7899 enum vect_def_type dt;
7900 tree vectype_op;
7901
7902 /* The last operand of lane-reducing operation is for
7903 reduction. */
7904 gcc_assert (reduc_idx > 0 && reduc_idx == (int) op.num_ops - 1);
7905
7906 if (!vect_is_simple_use (op.ops[0], loop_vinfo, &dt, &vectype_op))
7907 return false;
7908
7909 tree type_op = TREE_TYPE (op.ops[0]);
7910
7911 if (!vectype_op)
7912 {
7913 vectype_op = get_vectype_for_scalar_type (loop_vinfo,
7914 type_op);
7915 if (!vectype_op)
7916 return false;
7917 }
7918
7919 /* For lane-reducing operation vectorizable analysis needs the
7920 reduction PHI information. */
7921 STMT_VINFO_REDUC_DEF (def) = phi_info;
7922
7923 /* Each lane-reducing operation has its own input vectype, while
7924 reduction PHI will record the input vectype with the least
7925 lanes. */
7926 STMT_VINFO_REDUC_VECTYPE_IN (vdef) = vectype_op;
7927
7928 /* To accommodate lane-reducing operations of mixed input
7929 vectypes, choose input vectype with the least lanes for the
7930 reduction PHI statement, which would result in the most
7931 ncopies for vectorized reduction results. */
7932 if (!vectype_in
7933 || (GET_MODE_SIZE (SCALAR_TYPE_MODE (TREE_TYPE (vectype_in)))
7934 < GET_MODE_SIZE (SCALAR_TYPE_MODE (type_op))))
7935 vectype_in = vectype_op;
7936 }
7937 else
7938 vectype_in = STMT_VINFO_VECTYPE (phi_info);
7939 }
7940
7941 reduc_def = op.ops[reduc_idx];
7942 reduc_chain_length++;
7943 if (!stmt_info && slp_node)
7944 slp_for_stmt_info = SLP_TREE_CHILDREN (slp_for_stmt_info)[0];
7945 }
7946 /* PHIs should not participate in patterns. */
7947 gcc_assert (!STMT_VINFO_RELATED_STMT (phi_info));
7948
7949 if (nested_in_vect_loop_p (loop, stmt_info))
7950 {
7951 loop = loop->inner;
7952 nested_cycle = true;
7953 }
7954
7955 /* STMT_VINFO_REDUC_DEF doesn't point to the first but the last
7956 element. */
7957 if (slp_node && REDUC_GROUP_FIRST_ELEMENT (stmt_info))
7958 {
7959 gcc_assert (!REDUC_GROUP_NEXT_ELEMENT (stmt_info));
7960 stmt_info = REDUC_GROUP_FIRST_ELEMENT (stmt_info);
7961 }
7962 if (REDUC_GROUP_FIRST_ELEMENT (stmt_info))
7963 gcc_assert (slp_node
7964 && REDUC_GROUP_FIRST_ELEMENT (stmt_info) == stmt_info);
7965
7966 /* 1. Is vectorizable reduction? */
7967 /* Not supportable if the reduction variable is used in the loop, unless
7968 it's a reduction chain. */
7969 if (STMT_VINFO_RELEVANT (stmt_info) > vect_used_in_outer
7970 && !REDUC_GROUP_FIRST_ELEMENT (stmt_info))
7971 return false;
7972
7973 /* Reductions that are not used even in an enclosing outer-loop,
7974 are expected to be "live" (used out of the loop). */
7975 if (STMT_VINFO_RELEVANT (stmt_info) == vect_unused_in_scope
7976 && !STMT_VINFO_LIVE_P (stmt_info))
7977 return false;
7978
7979 /* 2. Has this been recognized as a reduction pattern?
7980
7981 Check if STMT represents a pattern that has been recognized
7982 in earlier analysis stages. For stmts that represent a pattern,
7983 the STMT_VINFO_RELATED_STMT field records the last stmt in
7984 the original sequence that constitutes the pattern. */
7985
7986 stmt_vec_info orig_stmt_info = STMT_VINFO_RELATED_STMT (stmt_info);
7987 if (orig_stmt_info)
7988 {
7989 gcc_assert (STMT_VINFO_IN_PATTERN_P (orig_stmt_info));
7990 gcc_assert (!STMT_VINFO_IN_PATTERN_P (stmt_info));
7991 }
7992
7993 /* 3. Check the operands of the operation. The first operands are defined
7994 inside the loop body. The last operand is the reduction variable,
7995 which is defined by the loop-header-phi. */
7996
7997 tree vectype_out = STMT_VINFO_VECTYPE (stmt_info);
7998 STMT_VINFO_REDUC_VECTYPE (reduc_info) = vectype_out;
7999 STMT_VINFO_REDUC_VECTYPE_IN (reduc_info) = vectype_in;
8000
8001 gimple_match_op op;
8002 if (!gimple_extract_op (stmt_info->stmt, &op))
8003 gcc_unreachable ();
8004 bool lane_reducing = lane_reducing_op_p (op.code);
8005
8006 if (!POINTER_TYPE_P (op.type) && !INTEGRAL_TYPE_P (op.type)
8007 && !SCALAR_FLOAT_TYPE_P (op.type))
8008 return false;
8009
8010 /* Do not try to vectorize bit-precision reductions. */
8011 if (!type_has_mode_precision_p (op.type))
8012 return false;
8013
8014 /* Lane-reducing ops also never can be used in a SLP reduction group
8015 since we'll mix lanes belonging to different reductions. But it's
8016 OK to use them in a reduction chain or when the reduction group
8017 has just one element. */
8018 if (lane_reducing
8019 && slp_node
8020 && !REDUC_GROUP_FIRST_ELEMENT (stmt_info)
8021 && SLP_TREE_LANES (slp_node) > 1)
8022 {
8023 if (dump_enabled_p ())
8024 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8025 "lane-reducing reduction in reduction group.\n");
8026 return false;
8027 }
8028
8029 /* All uses but the last are expected to be defined in the loop.
8030 The last use is the reduction variable. In case of nested cycle this
8031 assumption is not true: we use reduc_index to record the index of the
8032 reduction variable. */
8033 slp_tree *slp_op = XALLOCAVEC (slp_tree, op.num_ops);
8034 tree *vectype_op = XALLOCAVEC (tree, op.num_ops);
8035 /* We need to skip an extra operand for COND_EXPRs with embedded
8036 comparison. */
8037 unsigned opno_adjust = 0;
8038 if (op.code == COND_EXPR && COMPARISON_CLASS_P (op.ops[0]))
8039 opno_adjust = 1;
8040 for (i = 0; i < (int) op.num_ops; i++)
8041 {
8042 /* The condition of COND_EXPR is checked in vectorizable_condition(). */
8043 if (i == 0 && op.code == COND_EXPR)
8044 continue;
8045
8046 stmt_vec_info def_stmt_info;
8047 enum vect_def_type dt;
8048 if (!vect_is_simple_use (loop_vinfo, stmt_info, slp_for_stmt_info,
8049 i + opno_adjust, &op.ops[i], &slp_op[i], &dt,
8050 &vectype_op[i], &def_stmt_info))
8051 {
8052 if (dump_enabled_p ())
8053 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8054 "use not simple.\n");
8055 return false;
8056 }
8057
8058 /* Skip reduction operands, and for an IFN_COND_OP we might hit the
8059 reduction operand twice (once as definition, once as else). */
8060 if (op.ops[i] == op.ops[STMT_VINFO_REDUC_IDX (stmt_info)])
8061 continue;
8062
8063 /* There should be only one cycle def in the stmt, the one
8064 leading to reduc_def. */
8065 if (VECTORIZABLE_CYCLE_DEF (dt))
8066 return false;
8067
8068 if (!vectype_op[i])
8069 vectype_op[i]
8070 = get_vectype_for_scalar_type (loop_vinfo,
8071 TREE_TYPE (op.ops[i]), slp_op[i]);
8072
8073 /* Record how the non-reduction-def value of COND_EXPR is defined.
8074 ??? For a chain of multiple CONDs we'd have to match them up all. */
8075 if (op.code == COND_EXPR && reduc_chain_length == 1)
8076 {
8077 if (dt == vect_constant_def)
8078 {
8079 cond_reduc_dt = dt;
8080 cond_reduc_val = op.ops[i];
8081 }
8082 else if (dt == vect_induction_def
8083 && def_stmt_info
8084 && is_nonwrapping_integer_induction (def_stmt_info, loop))
8085 {
8086 cond_reduc_dt = dt;
8087 cond_stmt_vinfo = def_stmt_info;
8088 }
8089 }
8090 }
8091
8092 enum vect_reduction_type reduction_type = STMT_VINFO_REDUC_TYPE (phi_info);
8093 STMT_VINFO_REDUC_TYPE (reduc_info) = reduction_type;
8094 /* If we have a condition reduction, see if we can simplify it further. */
8095 if (reduction_type == COND_REDUCTION)
8096 {
8097 if (slp_node && SLP_TREE_LANES (slp_node) != 1)
8098 return false;
8099
8100 /* When the condition uses the reduction value in the condition, fail. */
8101 if (STMT_VINFO_REDUC_IDX (stmt_info) == 0)
8102 {
8103 if (dump_enabled_p ())
8104 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8105 "condition depends on previous iteration\n");
8106 return false;
8107 }
8108
8109 if (reduc_chain_length == 1
8110 && (direct_internal_fn_supported_p (IFN_FOLD_EXTRACT_LAST, vectype_in,
8111 OPTIMIZE_FOR_SPEED)
8112 || direct_internal_fn_supported_p (IFN_LEN_FOLD_EXTRACT_LAST,
8113 vectype_in,
8114 OPTIMIZE_FOR_SPEED)))
8115 {
8116 if (dump_enabled_p ())
8117 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8118 "optimizing condition reduction with"
8119 " FOLD_EXTRACT_LAST.\n");
8120 STMT_VINFO_REDUC_TYPE (reduc_info) = EXTRACT_LAST_REDUCTION;
8121 }
8122 else if (cond_reduc_dt == vect_induction_def)
8123 {
8124 tree base
8125 = STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (cond_stmt_vinfo);
8126 tree step = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (cond_stmt_vinfo);
8127
8128 gcc_assert (TREE_CODE (base) == INTEGER_CST
8129 && TREE_CODE (step) == INTEGER_CST);
8130 cond_reduc_val = NULL_TREE;
8131 enum tree_code cond_reduc_op_code = ERROR_MARK;
8132 tree res = PHI_RESULT (STMT_VINFO_STMT (cond_stmt_vinfo));
8133 if (!types_compatible_p (TREE_TYPE (res), TREE_TYPE (base)))
8134 ;
8135 /* Find a suitable value, for MAX_EXPR below base, for MIN_EXPR
8136 above base; punt if base is the minimum value of the type for
8137 MAX_EXPR or maximum value of the type for MIN_EXPR for now. */
8138 else if (tree_int_cst_sgn (step) == -1)
8139 {
8140 cond_reduc_op_code = MIN_EXPR;
8141 if (tree_int_cst_sgn (base) == -1)
8142 cond_reduc_val = build_int_cst (TREE_TYPE (base), 0);
8143 else if (tree_int_cst_lt (base,
8144 TYPE_MAX_VALUE (TREE_TYPE (base))))
8145 cond_reduc_val
8146 = int_const_binop (PLUS_EXPR, base, integer_one_node);
8147 }
8148 else
8149 {
8150 cond_reduc_op_code = MAX_EXPR;
8151 if (tree_int_cst_sgn (base) == 1)
8152 cond_reduc_val = build_int_cst (TREE_TYPE (base), 0);
8153 else if (tree_int_cst_lt (TYPE_MIN_VALUE (TREE_TYPE (base)),
8154 base))
8155 cond_reduc_val
8156 = int_const_binop (MINUS_EXPR, base, integer_one_node);
8157 }
8158 if (cond_reduc_val)
8159 {
8160 if (dump_enabled_p ())
8161 dump_printf_loc (MSG_NOTE, vect_location,
8162 "condition expression based on "
8163 "integer induction.\n");
8164 STMT_VINFO_REDUC_CODE (reduc_info) = cond_reduc_op_code;
8165 STMT_VINFO_VEC_INDUC_COND_INITIAL_VAL (reduc_info)
8166 = cond_reduc_val;
8167 STMT_VINFO_REDUC_TYPE (reduc_info) = INTEGER_INDUC_COND_REDUCTION;
8168 }
8169 }
8170 else if (cond_reduc_dt == vect_constant_def)
8171 {
8172 enum vect_def_type cond_initial_dt;
8173 tree cond_initial_val = vect_phi_initial_value (reduc_def_phi);
8174 vect_is_simple_use (cond_initial_val, loop_vinfo, &cond_initial_dt);
8175 if (cond_initial_dt == vect_constant_def
8176 && types_compatible_p (TREE_TYPE (cond_initial_val),
8177 TREE_TYPE (cond_reduc_val)))
8178 {
8179 tree e = fold_binary (LE_EXPR, boolean_type_node,
8180 cond_initial_val, cond_reduc_val);
8181 if (e && (integer_onep (e) || integer_zerop (e)))
8182 {
8183 if (dump_enabled_p ())
8184 dump_printf_loc (MSG_NOTE, vect_location,
8185 "condition expression based on "
8186 "compile time constant.\n");
8187 /* Record reduction code at analysis stage. */
8188 STMT_VINFO_REDUC_CODE (reduc_info)
8189 = integer_onep (e) ? MAX_EXPR : MIN_EXPR;
8190 STMT_VINFO_REDUC_TYPE (reduc_info) = CONST_COND_REDUCTION;
8191 }
8192 }
8193 }
8194 }
8195
8196 if (STMT_VINFO_LIVE_P (phi_info))
8197 return false;
8198
8199 if (slp_node)
8200 ncopies = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
8201 else
8202 ncopies = vect_get_num_copies (loop_vinfo, vectype_in);
8203
8204 gcc_assert (ncopies >= 1);
8205
8206 poly_uint64 nunits_out = TYPE_VECTOR_SUBPARTS (vectype_out);
8207
8208 if (nested_cycle)
8209 {
8210 gcc_assert (STMT_VINFO_DEF_TYPE (reduc_info)
8211 == vect_double_reduction_def);
8212 double_reduc = true;
8213 }
8214
8215 /* 4.2. Check support for the epilog operation.
8216
8217 If STMT represents a reduction pattern, then the type of the
8218 reduction variable may be different than the type of the rest
8219 of the arguments. For example, consider the case of accumulation
8220 of shorts into an int accumulator; The original code:
8221 S1: int_a = (int) short_a;
8222 orig_stmt-> S2: int_acc = plus <int_a ,int_acc>;
8223
8224 was replaced with:
8225 STMT: int_acc = widen_sum <short_a, int_acc>
8226
8227 This means that:
8228 1. The tree-code that is used to create the vector operation in the
8229 epilog code (that reduces the partial results) is not the
8230 tree-code of STMT, but is rather the tree-code of the original
8231 stmt from the pattern that STMT is replacing. I.e, in the example
8232 above we want to use 'widen_sum' in the loop, but 'plus' in the
8233 epilog.
8234 2. The type (mode) we use to check available target support
8235 for the vector operation to be created in the *epilog*, is
8236 determined by the type of the reduction variable (in the example
8237 above we'd check this: optab_handler (plus_optab, vect_int_mode])).
8238 However the type (mode) we use to check available target support
8239 for the vector operation to be created *inside the loop*, is
8240 determined by the type of the other arguments to STMT (in the
8241 example we'd check this: optab_handler (widen_sum_optab,
8242 vect_short_mode)).
8243
8244 This is contrary to "regular" reductions, in which the types of all
8245 the arguments are the same as the type of the reduction variable.
8246 For "regular" reductions we can therefore use the same vector type
8247 (and also the same tree-code) when generating the epilog code and
8248 when generating the code inside the loop. */
8249
8250 code_helper orig_code = STMT_VINFO_REDUC_CODE (phi_info);
8251
8252 /* If conversion might have created a conditional operation like
8253 IFN_COND_ADD already. Use the internal code for the following checks. */
8254 if (orig_code.is_internal_fn ())
8255 {
8256 tree_code new_code = conditional_internal_fn_code (internal_fn (orig_code));
8257 orig_code = new_code != ERROR_MARK ? new_code : orig_code;
8258 }
8259
8260 STMT_VINFO_REDUC_CODE (reduc_info) = orig_code;
8261
8262 reduction_type = STMT_VINFO_REDUC_TYPE (reduc_info);
8263 if (reduction_type == TREE_CODE_REDUCTION)
8264 {
8265 /* Check whether it's ok to change the order of the computation.
8266 Generally, when vectorizing a reduction we change the order of the
8267 computation. This may change the behavior of the program in some
8268 cases, so we need to check that this is ok. One exception is when
8269 vectorizing an outer-loop: the inner-loop is executed sequentially,
8270 and therefore vectorizing reductions in the inner-loop during
8271 outer-loop vectorization is safe. Likewise when we are vectorizing
8272 a series of reductions using SLP and the VF is one the reductions
8273 are performed in scalar order. */
8274 if (slp_node
8275 && !REDUC_GROUP_FIRST_ELEMENT (stmt_info)
8276 && known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), 1u))
8277 ;
8278 else if (needs_fold_left_reduction_p (op.type, orig_code))
8279 {
8280 /* When vectorizing a reduction chain w/o SLP the reduction PHI
8281 is not directy used in stmt. */
8282 if (!only_slp_reduc_chain
8283 && reduc_chain_length != 1)
8284 {
8285 if (dump_enabled_p ())
8286 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8287 "in-order reduction chain without SLP.\n");
8288 return false;
8289 }
8290 STMT_VINFO_REDUC_TYPE (reduc_info)
8291 = reduction_type = FOLD_LEFT_REDUCTION;
8292 }
8293 else if (!commutative_binary_op_p (orig_code, op.type)
8294 || !associative_binary_op_p (orig_code, op.type))
8295 {
8296 if (dump_enabled_p ())
8297 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8298 "reduction: not commutative/associative\n");
8299 return false;
8300 }
8301 }
8302
8303 if ((reduction_type == COND_REDUCTION
8304 || reduction_type == INTEGER_INDUC_COND_REDUCTION
8305 || reduction_type == CONST_COND_REDUCTION
8306 || reduction_type == EXTRACT_LAST_REDUCTION)
8307 && slp_node
8308 && ncopies > 1)
8309 {
8310 if (dump_enabled_p ())
8311 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8312 "multiple types in condition reduction.\n");
8313 return false;
8314 }
8315
8316 if ((double_reduc || reduction_type != TREE_CODE_REDUCTION)
8317 && !slp_node
8318 && ncopies > 1)
8319 {
8320 if (dump_enabled_p ())
8321 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8322 "multiple types in double reduction or condition "
8323 "reduction or fold-left reduction.\n");
8324 return false;
8325 }
8326
8327 internal_fn reduc_fn = IFN_LAST;
8328 if (reduction_type == TREE_CODE_REDUCTION
8329 || reduction_type == FOLD_LEFT_REDUCTION
8330 || reduction_type == INTEGER_INDUC_COND_REDUCTION
8331 || reduction_type == CONST_COND_REDUCTION)
8332 {
8333 if (reduction_type == FOLD_LEFT_REDUCTION
8334 ? fold_left_reduction_fn (orig_code, &reduc_fn)
8335 : reduction_fn_for_scalar_code (orig_code, &reduc_fn))
8336 {
8337 if (reduc_fn != IFN_LAST
8338 && !direct_internal_fn_supported_p (reduc_fn, vectype_out,
8339 OPTIMIZE_FOR_SPEED))
8340 {
8341 if (dump_enabled_p ())
8342 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8343 "reduc op not supported by target.\n");
8344
8345 reduc_fn = IFN_LAST;
8346 }
8347 }
8348 else
8349 {
8350 if (!nested_cycle || double_reduc)
8351 {
8352 if (dump_enabled_p ())
8353 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8354 "no reduc code for scalar code.\n");
8355
8356 return false;
8357 }
8358 }
8359 }
8360 else if (reduction_type == COND_REDUCTION)
8361 {
8362 int scalar_precision
8363 = GET_MODE_PRECISION (SCALAR_TYPE_MODE (op.type));
8364 cr_index_scalar_type = make_unsigned_type (scalar_precision);
8365 cr_index_vector_type = get_same_sized_vectype (cr_index_scalar_type,
8366 vectype_out);
8367
8368 if (direct_internal_fn_supported_p (IFN_REDUC_MAX, cr_index_vector_type,
8369 OPTIMIZE_FOR_SPEED))
8370 reduc_fn = IFN_REDUC_MAX;
8371 }
8372 STMT_VINFO_REDUC_FN (reduc_info) = reduc_fn;
8373
8374 if (reduction_type != EXTRACT_LAST_REDUCTION
8375 && (!nested_cycle || double_reduc)
8376 && reduc_fn == IFN_LAST
8377 && !nunits_out.is_constant ())
8378 {
8379 if (dump_enabled_p ())
8380 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8381 "missing target support for reduction on"
8382 " variable-length vectors.\n");
8383 return false;
8384 }
8385
8386 /* For SLP reductions, see if there is a neutral value we can use. */
8387 tree neutral_op = NULL_TREE;
8388 if (slp_node)
8389 {
8390 tree initial_value = NULL_TREE;
8391 if (REDUC_GROUP_FIRST_ELEMENT (stmt_info) != NULL)
8392 initial_value = vect_phi_initial_value (reduc_def_phi);
8393 neutral_op = neutral_op_for_reduction (TREE_TYPE (vectype_out),
8394 orig_code, initial_value);
8395 }
8396
8397 if (double_reduc && reduction_type == FOLD_LEFT_REDUCTION)
8398 {
8399 /* We can't support in-order reductions of code such as this:
8400
8401 for (int i = 0; i < n1; ++i)
8402 for (int j = 0; j < n2; ++j)
8403 l += a[j];
8404
8405 since GCC effectively transforms the loop when vectorizing:
8406
8407 for (int i = 0; i < n1 / VF; ++i)
8408 for (int j = 0; j < n2; ++j)
8409 for (int k = 0; k < VF; ++k)
8410 l += a[j];
8411
8412 which is a reassociation of the original operation. */
8413 if (dump_enabled_p ())
8414 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8415 "in-order double reduction not supported.\n");
8416
8417 return false;
8418 }
8419
8420 if (reduction_type == FOLD_LEFT_REDUCTION
8421 && (slp_node && SLP_TREE_LANES (slp_node) > 1)
8422 && !REDUC_GROUP_FIRST_ELEMENT (stmt_info))
8423 {
8424 /* We cannot use in-order reductions in this case because there is
8425 an implicit reassociation of the operations involved. */
8426 if (dump_enabled_p ())
8427 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8428 "in-order unchained SLP reductions not supported.\n");
8429 return false;
8430 }
8431
8432 /* For double reductions, and for SLP reductions with a neutral value,
8433 we construct a variable-length initial vector by loading a vector
8434 full of the neutral value and then shift-and-inserting the start
8435 values into the low-numbered elements. */
8436 if ((double_reduc || neutral_op)
8437 && !nunits_out.is_constant ()
8438 && !direct_internal_fn_supported_p (IFN_VEC_SHL_INSERT,
8439 vectype_out, OPTIMIZE_FOR_SPEED))
8440 {
8441 if (dump_enabled_p ())
8442 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8443 "reduction on variable-length vectors requires"
8444 " target support for a vector-shift-and-insert"
8445 " operation.\n");
8446 return false;
8447 }
8448
8449 /* Check extra constraints for variable-length unchained SLP reductions. */
8450 if (slp_node
8451 && !REDUC_GROUP_FIRST_ELEMENT (stmt_info)
8452 && !nunits_out.is_constant ())
8453 {
8454 /* We checked above that we could build the initial vector when
8455 there's a neutral element value. Check here for the case in
8456 which each SLP statement has its own initial value and in which
8457 that value needs to be repeated for every instance of the
8458 statement within the initial vector. */
8459 unsigned int group_size = SLP_TREE_LANES (slp_node);
8460 if (!neutral_op
8461 && !can_duplicate_and_interleave_p (loop_vinfo, group_size,
8462 TREE_TYPE (vectype_out)))
8463 {
8464 if (dump_enabled_p ())
8465 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8466 "unsupported form of SLP reduction for"
8467 " variable-length vectors: cannot build"
8468 " initial vector.\n");
8469 return false;
8470 }
8471 /* The epilogue code relies on the number of elements being a multiple
8472 of the group size. The duplicate-and-interleave approach to setting
8473 up the initial vector does too. */
8474 if (!multiple_p (nunits_out, group_size))
8475 {
8476 if (dump_enabled_p ())
8477 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8478 "unsupported form of SLP reduction for"
8479 " variable-length vectors: the vector size"
8480 " is not a multiple of the number of results.\n");
8481 return false;
8482 }
8483 }
8484
8485 if (reduction_type == COND_REDUCTION)
8486 {
8487 widest_int ni;
8488
8489 if (! max_loop_iterations (loop, &ni))
8490 {
8491 if (dump_enabled_p ())
8492 dump_printf_loc (MSG_NOTE, vect_location,
8493 "loop count not known, cannot create cond "
8494 "reduction.\n");
8495 return false;
8496 }
8497 /* Convert backedges to iterations. */
8498 ni += 1;
8499
8500 /* The additional index will be the same type as the condition. Check
8501 that the loop can fit into this less one (because we'll use up the
8502 zero slot for when there are no matches). */
8503 tree max_index = TYPE_MAX_VALUE (cr_index_scalar_type);
8504 if (wi::geu_p (ni, wi::to_widest (max_index)))
8505 {
8506 if (dump_enabled_p ())
8507 dump_printf_loc (MSG_NOTE, vect_location,
8508 "loop size is greater than data size.\n");
8509 return false;
8510 }
8511 }
8512
8513 /* In case the vectorization factor (VF) is bigger than the number
8514 of elements that we can fit in a vectype (nunits), we have to generate
8515 more than one vector stmt - i.e - we need to "unroll" the
8516 vector stmt by a factor VF/nunits. For more details see documentation
8517 in vectorizable_operation. */
8518
8519 /* If the reduction is used in an outer loop we need to generate
8520 VF intermediate results, like so (e.g. for ncopies=2):
8521 r0 = phi (init, r0)
8522 r1 = phi (init, r1)
8523 r0 = x0 + r0;
8524 r1 = x1 + r1;
8525 (i.e. we generate VF results in 2 registers).
8526 In this case we have a separate def-use cycle for each copy, and therefore
8527 for each copy we get the vector def for the reduction variable from the
8528 respective phi node created for this copy.
8529
8530 Otherwise (the reduction is unused in the loop nest), we can combine
8531 together intermediate results, like so (e.g. for ncopies=2):
8532 r = phi (init, r)
8533 r = x0 + r;
8534 r = x1 + r;
8535 (i.e. we generate VF/2 results in a single register).
8536 In this case for each copy we get the vector def for the reduction variable
8537 from the vectorized reduction operation generated in the previous iteration.
8538
8539 This only works when we see both the reduction PHI and its only consumer
8540 in vectorizable_reduction and there are no intermediate stmts
8541 participating. When unrolling we want each unrolled iteration to have its
8542 own reduction accumulator since one of the main goals of unrolling a
8543 reduction is to reduce the aggregate loop-carried latency. */
8544 if (ncopies > 1
8545 && (!slp_node
8546 || (!REDUC_GROUP_FIRST_ELEMENT (stmt_info)
8547 && SLP_TREE_LANES (slp_node) == 1))
8548 && (STMT_VINFO_RELEVANT (stmt_info) <= vect_used_only_live)
8549 && reduc_chain_length == 1
8550 && loop_vinfo->suggested_unroll_factor == 1)
8551 single_defuse_cycle = true;
8552
8553 if (single_defuse_cycle && !lane_reducing)
8554 {
8555 gcc_assert (op.code != COND_EXPR);
8556
8557 /* 4. check support for the operation in the loop
8558
8559 This isn't necessary for the lane reduction codes, since they
8560 can only be produced by pattern matching, and it's up to the
8561 pattern matcher to test for support. The main reason for
8562 specifically skipping this step is to avoid rechecking whether
8563 mixed-sign dot-products can be implemented using signed
8564 dot-products. */
8565 machine_mode vec_mode = TYPE_MODE (vectype_in);
8566 if (!directly_supported_p (op.code, vectype_in, optab_vector))
8567 {
8568 if (dump_enabled_p ())
8569 dump_printf (MSG_NOTE, "op not supported by target.\n");
8570 if (maybe_ne (GET_MODE_SIZE (vec_mode), UNITS_PER_WORD)
8571 || !vect_can_vectorize_without_simd_p (op.code))
8572 single_defuse_cycle = false;
8573 else
8574 if (dump_enabled_p ())
8575 dump_printf (MSG_NOTE, "proceeding using word mode.\n");
8576 }
8577
8578 if (vect_emulated_vector_p (vectype_in)
8579 && !vect_can_vectorize_without_simd_p (op.code))
8580 {
8581 if (dump_enabled_p ())
8582 dump_printf (MSG_NOTE, "using word mode not possible.\n");
8583 return false;
8584 }
8585 }
8586 if (dump_enabled_p () && single_defuse_cycle)
8587 dump_printf_loc (MSG_NOTE, vect_location,
8588 "using single def-use cycle for reduction by reducing "
8589 "multiple vectors to one in the loop body\n");
8590 STMT_VINFO_FORCE_SINGLE_CYCLE (reduc_info) = single_defuse_cycle;
8591
8592 /* For lane-reducing operation, the below processing related to single
8593 defuse-cycle will be done in its own vectorizable function. One more
8594 thing to note is that the operation must not be involved in fold-left
8595 reduction. */
8596 single_defuse_cycle &= !lane_reducing;
8597
8598 if (slp_node
8599 && (single_defuse_cycle || reduction_type == FOLD_LEFT_REDUCTION))
8600 for (i = 0; i < (int) op.num_ops; i++)
8601 if (!vect_maybe_update_slp_op_vectype (slp_op[i], vectype_op[i]))
8602 {
8603 if (dump_enabled_p ())
8604 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8605 "incompatible vector types for invariants\n");
8606 return false;
8607 }
8608
8609 vect_model_reduction_cost (loop_vinfo, stmt_info, reduc_fn,
8610 reduction_type, ncopies, cost_vec);
8611 /* Cost the reduction op inside the loop if transformed via
8612 vect_transform_reduction for non-lane-reducing operation. Otherwise
8613 this is costed by the separate vectorizable_* routines. */
8614 if (single_defuse_cycle)
8615 record_stmt_cost (cost_vec, ncopies, vector_stmt, stmt_info, 0, vect_body);
8616
8617 if (dump_enabled_p ()
8618 && reduction_type == FOLD_LEFT_REDUCTION)
8619 dump_printf_loc (MSG_NOTE, vect_location,
8620 "using an in-order (fold-left) reduction.\n");
8621 STMT_VINFO_TYPE (orig_stmt_of_analysis) = cycle_phi_info_type;
8622
8623 /* All but single defuse-cycle optimized and fold-left reductions go
8624 through their own vectorizable_* routines. */
8625 if (!single_defuse_cycle && reduction_type != FOLD_LEFT_REDUCTION)
8626 {
8627 stmt_vec_info tem
8628 = vect_stmt_to_vectorize (STMT_VINFO_REDUC_DEF (phi_info));
8629 if (slp_node && REDUC_GROUP_FIRST_ELEMENT (tem))
8630 {
8631 gcc_assert (!REDUC_GROUP_NEXT_ELEMENT (tem));
8632 tem = REDUC_GROUP_FIRST_ELEMENT (tem);
8633 }
8634 STMT_VINFO_DEF_TYPE (vect_orig_stmt (tem)) = vect_internal_def;
8635 STMT_VINFO_DEF_TYPE (tem) = vect_internal_def;
8636 }
8637 else if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
8638 vect_reduction_update_partial_vector_usage (loop_vinfo, reduc_info,
8639 slp_node, op.code, op.type,
8640 vectype_in);
8641 return true;
8642 }
8643
8644 /* STMT_INFO is a dot-product reduction whose multiplication operands
8645 have different signs. Emit a sequence to emulate the operation
8646 using a series of signed DOT_PROD_EXPRs and return the last
8647 statement generated. VEC_DEST is the result of the vector operation
8648 and VOP lists its inputs. */
8649
8650 static gassign *
8651 vect_emulate_mixed_dot_prod (loop_vec_info loop_vinfo, stmt_vec_info stmt_info,
8652 gimple_stmt_iterator *gsi, tree vec_dest,
8653 tree vop[3])
8654 {
8655 tree wide_vectype = signed_type_for (TREE_TYPE (vec_dest));
8656 tree narrow_vectype = signed_type_for (TREE_TYPE (vop[0]));
8657 tree narrow_elttype = TREE_TYPE (narrow_vectype);
8658 gimple *new_stmt;
8659
8660 /* Make VOP[0] the unsigned operand VOP[1] the signed operand. */
8661 if (!TYPE_UNSIGNED (TREE_TYPE (vop[0])))
8662 std::swap (vop[0], vop[1]);
8663
8664 /* Convert all inputs to signed types. */
8665 for (int i = 0; i < 3; ++i)
8666 if (TYPE_UNSIGNED (TREE_TYPE (vop[i])))
8667 {
8668 tree tmp = make_ssa_name (signed_type_for (TREE_TYPE (vop[i])));
8669 new_stmt = gimple_build_assign (tmp, NOP_EXPR, vop[i]);
8670 vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
8671 vop[i] = tmp;
8672 }
8673
8674 /* In the comments below we assume 8-bit inputs for simplicity,
8675 but the approach works for any full integer type. */
8676
8677 /* Create a vector of -128. */
8678 tree min_narrow_elttype = TYPE_MIN_VALUE (narrow_elttype);
8679 tree min_narrow = build_vector_from_val (narrow_vectype,
8680 min_narrow_elttype);
8681
8682 /* Create a vector of 64. */
8683 auto half_wi = wi::lrshift (wi::to_wide (min_narrow_elttype), 1);
8684 tree half_narrow = wide_int_to_tree (narrow_elttype, half_wi);
8685 half_narrow = build_vector_from_val (narrow_vectype, half_narrow);
8686
8687 /* Emit: SUB_RES = VOP[0] - 128. */
8688 tree sub_res = make_ssa_name (narrow_vectype);
8689 new_stmt = gimple_build_assign (sub_res, PLUS_EXPR, vop[0], min_narrow);
8690 vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
8691
8692 /* Emit:
8693
8694 STAGE1 = DOT_PROD_EXPR <VOP[1], 64, VOP[2]>;
8695 STAGE2 = DOT_PROD_EXPR <VOP[1], 64, STAGE1>;
8696 STAGE3 = DOT_PROD_EXPR <SUB_RES, -128, STAGE2>;
8697
8698 on the basis that x * y == (x - 128) * y + 64 * y + 64 * y
8699 Doing the two 64 * y steps first allows more time to compute x. */
8700 tree stage1 = make_ssa_name (wide_vectype);
8701 new_stmt = gimple_build_assign (stage1, DOT_PROD_EXPR,
8702 vop[1], half_narrow, vop[2]);
8703 vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
8704
8705 tree stage2 = make_ssa_name (wide_vectype);
8706 new_stmt = gimple_build_assign (stage2, DOT_PROD_EXPR,
8707 vop[1], half_narrow, stage1);
8708 vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
8709
8710 tree stage3 = make_ssa_name (wide_vectype);
8711 new_stmt = gimple_build_assign (stage3, DOT_PROD_EXPR,
8712 sub_res, vop[1], stage2);
8713 vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
8714
8715 /* Convert STAGE3 to the reduction type. */
8716 return gimple_build_assign (vec_dest, CONVERT_EXPR, stage3);
8717 }
8718
8719 /* Transform the definition stmt STMT_INFO of a reduction PHI backedge
8720 value. */
8721
8722 bool
8723 vect_transform_reduction (loop_vec_info loop_vinfo,
8724 stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
8725 gimple **vec_stmt, slp_tree slp_node)
8726 {
8727 tree vectype_out = STMT_VINFO_VECTYPE (stmt_info);
8728 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
8729 unsigned ncopies;
8730 unsigned vec_num;
8731
8732 stmt_vec_info reduc_info = info_for_reduction (loop_vinfo, stmt_info);
8733 gcc_assert (reduc_info->is_reduc_info);
8734
8735 if (nested_in_vect_loop_p (loop, stmt_info))
8736 {
8737 loop = loop->inner;
8738 gcc_assert (STMT_VINFO_DEF_TYPE (reduc_info) == vect_double_reduction_def);
8739 }
8740
8741 gimple_match_op op;
8742 if (!gimple_extract_op (stmt_info->stmt, &op))
8743 gcc_unreachable ();
8744
8745 /* All uses but the last are expected to be defined in the loop.
8746 The last use is the reduction variable. In case of nested cycle this
8747 assumption is not true: we use reduc_index to record the index of the
8748 reduction variable. */
8749 stmt_vec_info phi_info = STMT_VINFO_REDUC_DEF (vect_orig_stmt (stmt_info));
8750 gphi *reduc_def_phi = as_a <gphi *> (phi_info->stmt);
8751 int reduc_index = STMT_VINFO_REDUC_IDX (stmt_info);
8752 tree vectype_in = STMT_VINFO_REDUC_VECTYPE_IN (stmt_info);
8753
8754 if (!vectype_in)
8755 vectype_in = STMT_VINFO_VECTYPE (stmt_info);
8756
8757 if (slp_node)
8758 {
8759 ncopies = 1;
8760 vec_num = vect_get_num_copies (loop_vinfo, slp_node, vectype_in);
8761 }
8762 else
8763 {
8764 ncopies = vect_get_num_copies (loop_vinfo, vectype_in);
8765 vec_num = 1;
8766 }
8767
8768 code_helper code = canonicalize_code (op.code, op.type);
8769 internal_fn cond_fn = get_conditional_internal_fn (code, op.type);
8770
8771 vec_loop_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
8772 vec_loop_lens *lens = &LOOP_VINFO_LENS (loop_vinfo);
8773 bool mask_by_cond_expr = use_mask_by_cond_expr_p (code, cond_fn, vectype_in);
8774
8775 /* Transform. */
8776 tree new_temp = NULL_TREE;
8777 auto_vec<tree> vec_oprnds[3];
8778
8779 if (dump_enabled_p ())
8780 dump_printf_loc (MSG_NOTE, vect_location, "transform reduction.\n");
8781
8782 /* FORNOW: Multiple types are not supported for condition. */
8783 if (code == COND_EXPR)
8784 gcc_assert (ncopies == 1);
8785
8786 /* A binary COND_OP reduction must have the same definition and else
8787 value. */
8788 bool cond_fn_p = code.is_internal_fn ()
8789 && conditional_internal_fn_code (internal_fn (code)) != ERROR_MARK;
8790 if (cond_fn_p)
8791 {
8792 gcc_assert (code == IFN_COND_ADD || code == IFN_COND_SUB
8793 || code == IFN_COND_MUL || code == IFN_COND_AND
8794 || code == IFN_COND_IOR || code == IFN_COND_XOR
8795 || code == IFN_COND_MIN || code == IFN_COND_MAX);
8796 gcc_assert (op.num_ops == 4
8797 && (op.ops[reduc_index]
8798 == op.ops[internal_fn_else_index ((internal_fn) code)]));
8799 }
8800
8801 bool masked_loop_p = LOOP_VINFO_FULLY_MASKED_P (loop_vinfo);
8802
8803 vect_reduction_type reduction_type = STMT_VINFO_REDUC_TYPE (reduc_info);
8804 if (reduction_type == FOLD_LEFT_REDUCTION)
8805 {
8806 internal_fn reduc_fn = STMT_VINFO_REDUC_FN (reduc_info);
8807 gcc_assert (code.is_tree_code () || cond_fn_p);
8808 return vectorize_fold_left_reduction
8809 (loop_vinfo, stmt_info, gsi, vec_stmt, slp_node, reduc_def_phi,
8810 code, reduc_fn, op.ops, op.num_ops, vectype_in,
8811 reduc_index, masks, lens);
8812 }
8813
8814 bool single_defuse_cycle = STMT_VINFO_FORCE_SINGLE_CYCLE (reduc_info);
8815 bool lane_reducing = lane_reducing_op_p (code);
8816 gcc_assert (single_defuse_cycle || lane_reducing);
8817
8818 if (lane_reducing)
8819 {
8820 /* The last operand of lane-reducing op is for reduction. */
8821 gcc_assert (reduc_index == (int) op.num_ops - 1);
8822 }
8823
8824 /* Create the destination vector */
8825 tree scalar_dest = gimple_get_lhs (stmt_info->stmt);
8826 tree vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
8827
8828 if (lane_reducing && !slp_node && !single_defuse_cycle)
8829 {
8830 /* Note: there are still vectorizable cases that can not be handled by
8831 single-lane slp. Probably it would take some time to evolve the
8832 feature to a mature state. So we have to keep the below non-slp code
8833 path as failsafe for lane-reducing support. */
8834 gcc_assert (op.num_ops <= 3);
8835 for (unsigned i = 0; i < op.num_ops; i++)
8836 {
8837 unsigned oprnd_ncopies = ncopies;
8838
8839 if ((int) i == reduc_index)
8840 {
8841 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
8842 oprnd_ncopies = vect_get_num_copies (loop_vinfo, vectype);
8843 }
8844
8845 vect_get_vec_defs_for_operand (loop_vinfo, stmt_info, oprnd_ncopies,
8846 op.ops[i], &vec_oprnds[i]);
8847 }
8848 }
8849 /* Get NCOPIES vector definitions for all operands except the reduction
8850 definition. */
8851 else if (!cond_fn_p)
8852 {
8853 gcc_assert (reduc_index >= 0 && reduc_index <= 2);
8854 vect_get_vec_defs (loop_vinfo, stmt_info, slp_node, ncopies,
8855 single_defuse_cycle && reduc_index == 0
8856 ? NULL_TREE : op.ops[0], &vec_oprnds[0],
8857 single_defuse_cycle && reduc_index == 1
8858 ? NULL_TREE : op.ops[1], &vec_oprnds[1],
8859 op.num_ops == 3
8860 && !(single_defuse_cycle && reduc_index == 2)
8861 ? op.ops[2] : NULL_TREE, &vec_oprnds[2]);
8862 }
8863 else
8864 {
8865 /* For a conditional operation pass the truth type as mask
8866 vectype. */
8867 gcc_assert (single_defuse_cycle
8868 && (reduc_index == 1 || reduc_index == 2));
8869 vect_get_vec_defs (loop_vinfo, stmt_info, slp_node, ncopies, op.ops[0],
8870 truth_type_for (vectype_in), &vec_oprnds[0],
8871 reduc_index == 1 ? NULL_TREE : op.ops[1],
8872 NULL_TREE, &vec_oprnds[1],
8873 reduc_index == 2 ? NULL_TREE : op.ops[2],
8874 NULL_TREE, &vec_oprnds[2]);
8875 }
8876
8877 /* For single def-use cycles get one copy of the vectorized reduction
8878 definition. */
8879 if (single_defuse_cycle)
8880 {
8881 vect_get_vec_defs (loop_vinfo, stmt_info, slp_node, 1,
8882 reduc_index == 0 ? op.ops[0] : NULL_TREE,
8883 &vec_oprnds[0],
8884 reduc_index == 1 ? op.ops[1] : NULL_TREE,
8885 &vec_oprnds[1],
8886 reduc_index == 2 ? op.ops[2] : NULL_TREE,
8887 &vec_oprnds[2]);
8888 }
8889 else if (lane_reducing)
8890 {
8891 /* For normal reduction, consistency between vectorized def/use is
8892 naturally ensured when mapping from scalar statement. But if lane-
8893 reducing op is involved in reduction, thing would become somewhat
8894 complicated in that the op's result and operand for accumulation are
8895 limited to less lanes than other operands, which certainly causes
8896 def/use mismatch on adjacent statements around the op if do not have
8897 any kind of specific adjustment. One approach is to refit lane-
8898 reducing op in the way of introducing new trivial pass-through copies
8899 to fix possible def/use gap, so as to make it behave like a normal op.
8900 And vector reduction PHIs are always generated to the full extent, no
8901 matter lane-reducing op exists or not. If some copies or PHIs are
8902 actually superfluous, they would be cleaned up by passes after
8903 vectorization. An example for single-lane slp, lane-reducing ops
8904 with mixed input vectypes in a reduction chain, is given as below.
8905 Similarly, this handling is applicable for multiple-lane slp as well.
8906
8907 int sum = 1;
8908 for (i)
8909 {
8910 sum += d0[i] * d1[i]; // dot-prod <vector(16) char>
8911 sum += w[i]; // widen-sum <vector(16) char>
8912 sum += abs(s0[i] - s1[i]); // sad <vector(8) short>
8913 sum += n[i]; // normal <vector(4) int>
8914 }
8915
8916 The vector size is 128-bit,vectorization factor is 16. Reduction
8917 statements would be transformed as:
8918
8919 vector<4> int sum_v0 = { 0, 0, 0, 1 };
8920 vector<4> int sum_v1 = { 0, 0, 0, 0 };
8921 vector<4> int sum_v2 = { 0, 0, 0, 0 };
8922 vector<4> int sum_v3 = { 0, 0, 0, 0 };
8923
8924 for (i / 16)
8925 {
8926 sum_v0 = DOT_PROD (d0_v0[i: 0 ~ 15], d1_v0[i: 0 ~ 15], sum_v0);
8927 sum_v1 = sum_v1; // copy
8928 sum_v2 = sum_v2; // copy
8929 sum_v3 = sum_v3; // copy
8930
8931 sum_v0 = sum_v0; // copy
8932 sum_v1 = WIDEN_SUM (w_v1[i: 0 ~ 15], sum_v1);
8933 sum_v2 = sum_v2; // copy
8934 sum_v3 = sum_v3; // copy
8935
8936 sum_v0 = sum_v0; // copy
8937 sum_v1 = SAD (s0_v1[i: 0 ~ 7 ], s1_v1[i: 0 ~ 7 ], sum_v1);
8938 sum_v2 = SAD (s0_v2[i: 8 ~ 15], s1_v2[i: 8 ~ 15], sum_v2);
8939 sum_v3 = sum_v3; // copy
8940
8941 sum_v0 += n_v0[i: 0 ~ 3 ];
8942 sum_v1 += n_v1[i: 4 ~ 7 ];
8943 sum_v2 += n_v2[i: 8 ~ 11];
8944 sum_v3 += n_v3[i: 12 ~ 15];
8945 }
8946
8947 Moreover, for a higher instruction parallelism in final vectorized
8948 loop, it is considered to make those effective vector lane-reducing
8949 ops be distributed evenly among all def-use cycles. In the above
8950 example, DOT_PROD, WIDEN_SUM and SADs are generated into disparate
8951 cycles, instruction dependency among them could be eliminated. */
8952 unsigned effec_ncopies = vec_oprnds[0].length ();
8953 unsigned total_ncopies = vec_oprnds[reduc_index].length ();
8954
8955 gcc_assert (effec_ncopies <= total_ncopies);
8956
8957 if (effec_ncopies < total_ncopies)
8958 {
8959 for (unsigned i = 0; i < op.num_ops - 1; i++)
8960 {
8961 gcc_assert (vec_oprnds[i].length () == effec_ncopies);
8962 vec_oprnds[i].safe_grow_cleared (total_ncopies);
8963 }
8964 }
8965
8966 tree reduc_vectype_in = STMT_VINFO_REDUC_VECTYPE_IN (reduc_info);
8967 gcc_assert (reduc_vectype_in);
8968
8969 unsigned effec_reduc_ncopies
8970 = vect_get_num_copies (loop_vinfo, slp_node, reduc_vectype_in);
8971
8972 gcc_assert (effec_ncopies <= effec_reduc_ncopies);
8973
8974 if (effec_ncopies < effec_reduc_ncopies)
8975 {
8976 /* Find suitable def-use cycles to generate vectorized statements
8977 into, and reorder operands based on the selection. */
8978 unsigned curr_pos = reduc_info->reduc_result_pos;
8979 unsigned next_pos = (curr_pos + effec_ncopies) % effec_reduc_ncopies;
8980
8981 gcc_assert (curr_pos < effec_reduc_ncopies);
8982 reduc_info->reduc_result_pos = next_pos;
8983
8984 if (curr_pos)
8985 {
8986 unsigned count = effec_reduc_ncopies - effec_ncopies;
8987 unsigned start = curr_pos - count;
8988
8989 if ((int) start < 0)
8990 {
8991 count = curr_pos;
8992 start = 0;
8993 }
8994
8995 for (unsigned i = 0; i < op.num_ops - 1; i++)
8996 {
8997 for (unsigned j = effec_ncopies; j > start; j--)
8998 {
8999 unsigned k = j - 1;
9000 std::swap (vec_oprnds[i][k], vec_oprnds[i][k + count]);
9001 gcc_assert (!vec_oprnds[i][k]);
9002 }
9003 }
9004 }
9005 }
9006 }
9007
9008 bool emulated_mixed_dot_prod = vect_is_emulated_mixed_dot_prod (stmt_info);
9009 unsigned num = vec_oprnds[reduc_index == 0 ? 1 : 0].length ();
9010 unsigned mask_index = 0;
9011
9012 for (unsigned i = 0; i < num; ++i)
9013 {
9014 gimple *new_stmt;
9015 tree vop[3] = { vec_oprnds[0][i], vec_oprnds[1][i], NULL_TREE };
9016 if (!vop[0] || !vop[1])
9017 {
9018 tree reduc_vop = vec_oprnds[reduc_index][i];
9019
9020 /* If could not generate an effective vector statement for current
9021 portion of reduction operand, insert a trivial copy to simply
9022 handle over the operand to other dependent statements. */
9023 gcc_assert (reduc_vop);
9024
9025 if (slp_node && TREE_CODE (reduc_vop) == SSA_NAME
9026 && !SSA_NAME_IS_DEFAULT_DEF (reduc_vop))
9027 new_stmt = SSA_NAME_DEF_STMT (reduc_vop);
9028 else
9029 {
9030 new_temp = make_ssa_name (vec_dest);
9031 new_stmt = gimple_build_assign (new_temp, reduc_vop);
9032 vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt,
9033 gsi);
9034 }
9035 }
9036 else if (masked_loop_p && !mask_by_cond_expr)
9037 {
9038 /* No conditional ifns have been defined for lane-reducing op
9039 yet. */
9040 gcc_assert (!lane_reducing);
9041
9042 /* Make sure that the reduction accumulator is vop[0]. */
9043 if (reduc_index == 1)
9044 {
9045 gcc_assert (commutative_binary_op_p (code, op.type));
9046 std::swap (vop[0], vop[1]);
9047 }
9048 tree mask = vect_get_loop_mask (loop_vinfo, gsi, masks,
9049 vec_num * ncopies, vectype_in,
9050 mask_index++);
9051 gcall *call = gimple_build_call_internal (cond_fn, 4, mask,
9052 vop[0], vop[1], vop[0]);
9053 new_temp = make_ssa_name (vec_dest, call);
9054 gimple_call_set_lhs (call, new_temp);
9055 gimple_call_set_nothrow (call, true);
9056 vect_finish_stmt_generation (loop_vinfo, stmt_info, call, gsi);
9057 new_stmt = call;
9058 }
9059 else
9060 {
9061 if (op.num_ops >= 3)
9062 vop[2] = vec_oprnds[2][i];
9063
9064 if (masked_loop_p && mask_by_cond_expr)
9065 {
9066 tree mask = vect_get_loop_mask (loop_vinfo, gsi, masks,
9067 vec_num * ncopies, vectype_in,
9068 mask_index++);
9069 build_vect_cond_expr (code, vop, mask, gsi);
9070 }
9071
9072 if (emulated_mixed_dot_prod)
9073 new_stmt = vect_emulate_mixed_dot_prod (loop_vinfo, stmt_info, gsi,
9074 vec_dest, vop);
9075
9076 else if (code.is_internal_fn () && !cond_fn_p)
9077 new_stmt = gimple_build_call_internal (internal_fn (code),
9078 op.num_ops,
9079 vop[0], vop[1], vop[2]);
9080 else if (code.is_internal_fn () && cond_fn_p)
9081 new_stmt = gimple_build_call_internal (internal_fn (code),
9082 op.num_ops,
9083 vop[0], vop[1], vop[2],
9084 vop[reduc_index]);
9085 else
9086 new_stmt = gimple_build_assign (vec_dest, tree_code (op.code),
9087 vop[0], vop[1], vop[2]);
9088 new_temp = make_ssa_name (vec_dest, new_stmt);
9089 gimple_set_lhs (new_stmt, new_temp);
9090 vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
9091 }
9092
9093 if (single_defuse_cycle && i < num - 1)
9094 vec_oprnds[reduc_index].safe_push (gimple_get_lhs (new_stmt));
9095 else if (slp_node)
9096 slp_node->push_vec_def (new_stmt);
9097 else
9098 STMT_VINFO_VEC_STMTS (stmt_info).safe_push (new_stmt);
9099 }
9100
9101 if (!slp_node)
9102 *vec_stmt = STMT_VINFO_VEC_STMTS (stmt_info)[0];
9103
9104 return true;
9105 }
9106
9107 /* Transform phase of a cycle PHI. */
9108
9109 bool
9110 vect_transform_cycle_phi (loop_vec_info loop_vinfo,
9111 stmt_vec_info stmt_info, gimple **vec_stmt,
9112 slp_tree slp_node, slp_instance slp_node_instance)
9113 {
9114 tree vectype_out = STMT_VINFO_VECTYPE (stmt_info);
9115 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
9116 int i;
9117 int ncopies;
9118 int j;
9119 bool nested_cycle = false;
9120 int vec_num;
9121
9122 if (nested_in_vect_loop_p (loop, stmt_info))
9123 {
9124 loop = loop->inner;
9125 nested_cycle = true;
9126 }
9127
9128 stmt_vec_info reduc_stmt_info = STMT_VINFO_REDUC_DEF (stmt_info);
9129 reduc_stmt_info = vect_stmt_to_vectorize (reduc_stmt_info);
9130 stmt_vec_info reduc_info = info_for_reduction (loop_vinfo, stmt_info);
9131 gcc_assert (reduc_info->is_reduc_info);
9132
9133 if (STMT_VINFO_REDUC_TYPE (reduc_info) == EXTRACT_LAST_REDUCTION
9134 || STMT_VINFO_REDUC_TYPE (reduc_info) == FOLD_LEFT_REDUCTION)
9135 /* Leave the scalar phi in place. */
9136 return true;
9137
9138 if (slp_node)
9139 {
9140 vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
9141 ncopies = 1;
9142 }
9143 else
9144 {
9145 vec_num = 1;
9146 ncopies = vect_get_num_copies (loop_vinfo,
9147 STMT_VINFO_VECTYPE (stmt_info));
9148 }
9149
9150 /* Check whether we should use a single PHI node and accumulate
9151 vectors to one before the backedge. */
9152 if (STMT_VINFO_FORCE_SINGLE_CYCLE (reduc_info))
9153 {
9154 ncopies = 1;
9155 vec_num = 1;
9156 }
9157
9158 /* Create the destination vector */
9159 gphi *phi = as_a <gphi *> (stmt_info->stmt);
9160 tree vec_dest = vect_create_destination_var (gimple_phi_result (phi),
9161 vectype_out);
9162
9163 /* Get the loop-entry arguments. */
9164 tree vec_initial_def = NULL_TREE;
9165 auto_vec<tree> vec_initial_defs;
9166 if (slp_node)
9167 {
9168 vec_initial_defs.reserve (vec_num);
9169 /* Optimize: if initial_def is for REDUC_MAX smaller than the base
9170 and we can't use zero for induc_val, use initial_def. Similarly
9171 for REDUC_MIN and initial_def larger than the base. */
9172 if (STMT_VINFO_REDUC_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
9173 {
9174 gcc_assert (SLP_TREE_LANES (slp_node) == 1);
9175 tree initial_def = vect_phi_initial_value (phi);
9176 reduc_info->reduc_initial_values.safe_push (initial_def);
9177 tree induc_val = STMT_VINFO_VEC_INDUC_COND_INITIAL_VAL (reduc_info);
9178 if (TREE_CODE (initial_def) == INTEGER_CST
9179 && !integer_zerop (induc_val)
9180 && ((STMT_VINFO_REDUC_CODE (reduc_info) == MAX_EXPR
9181 && tree_int_cst_lt (initial_def, induc_val))
9182 || (STMT_VINFO_REDUC_CODE (reduc_info) == MIN_EXPR
9183 && tree_int_cst_lt (induc_val, initial_def))))
9184 {
9185 induc_val = initial_def;
9186 /* Communicate we used the initial_def to epilouge
9187 generation. */
9188 STMT_VINFO_VEC_INDUC_COND_INITIAL_VAL (reduc_info) = NULL_TREE;
9189 }
9190 vec_initial_defs.quick_push
9191 (build_vector_from_val (vectype_out, induc_val));
9192 }
9193 else if (nested_cycle)
9194 {
9195 unsigned phi_idx = loop_preheader_edge (loop)->dest_idx;
9196 vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[phi_idx],
9197 &vec_initial_defs);
9198 }
9199 else
9200 {
9201 gcc_assert (slp_node == slp_node_instance->reduc_phis);
9202 vec<tree> &initial_values = reduc_info->reduc_initial_values;
9203 vec<stmt_vec_info> &stmts = SLP_TREE_SCALAR_STMTS (slp_node);
9204
9205 unsigned int num_phis = stmts.length ();
9206 if (REDUC_GROUP_FIRST_ELEMENT (reduc_stmt_info))
9207 num_phis = 1;
9208 initial_values.reserve (num_phis);
9209 for (unsigned int i = 0; i < num_phis; ++i)
9210 {
9211 gphi *this_phi = as_a<gphi *> (stmts[i]->stmt);
9212 initial_values.quick_push (vect_phi_initial_value (this_phi));
9213 }
9214 if (vec_num == 1)
9215 vect_find_reusable_accumulator (loop_vinfo, reduc_info);
9216 if (!initial_values.is_empty ())
9217 {
9218 tree initial_value
9219 = (num_phis == 1 ? initial_values[0] : NULL_TREE);
9220 code_helper code = STMT_VINFO_REDUC_CODE (reduc_info);
9221 tree neutral_op
9222 = neutral_op_for_reduction (TREE_TYPE (vectype_out),
9223 code, initial_value);
9224 /* Try to simplify the vector initialization by applying an
9225 adjustment after the reduction has been performed. This
9226 can also break a critical path but on the other hand
9227 requires to keep the initial value live across the loop. */
9228 if (neutral_op
9229 && initial_values.length () == 1
9230 && !reduc_info->reused_accumulator
9231 && STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
9232 && !operand_equal_p (neutral_op, initial_values[0]))
9233 {
9234 STMT_VINFO_REDUC_EPILOGUE_ADJUSTMENT (reduc_info)
9235 = initial_values[0];
9236 initial_values[0] = neutral_op;
9237 }
9238 get_initial_defs_for_reduction (loop_vinfo, reduc_info,
9239 &vec_initial_defs, vec_num,
9240 stmts.length (), neutral_op);
9241 }
9242 }
9243 }
9244 else
9245 {
9246 /* Get at the scalar def before the loop, that defines the initial
9247 value of the reduction variable. */
9248 tree initial_def = vect_phi_initial_value (phi);
9249 reduc_info->reduc_initial_values.safe_push (initial_def);
9250 /* Optimize: if initial_def is for REDUC_MAX smaller than the base
9251 and we can't use zero for induc_val, use initial_def. Similarly
9252 for REDUC_MIN and initial_def larger than the base. */
9253 if (STMT_VINFO_REDUC_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
9254 {
9255 tree induc_val = STMT_VINFO_VEC_INDUC_COND_INITIAL_VAL (reduc_info);
9256 if (TREE_CODE (initial_def) == INTEGER_CST
9257 && !integer_zerop (induc_val)
9258 && ((STMT_VINFO_REDUC_CODE (reduc_info) == MAX_EXPR
9259 && tree_int_cst_lt (initial_def, induc_val))
9260 || (STMT_VINFO_REDUC_CODE (reduc_info) == MIN_EXPR
9261 && tree_int_cst_lt (induc_val, initial_def))))
9262 {
9263 induc_val = initial_def;
9264 /* Communicate we used the initial_def to epilouge
9265 generation. */
9266 STMT_VINFO_VEC_INDUC_COND_INITIAL_VAL (reduc_info) = NULL_TREE;
9267 }
9268 vec_initial_def = build_vector_from_val (vectype_out, induc_val);
9269 }
9270 else if (nested_cycle)
9271 {
9272 /* Do not use an adjustment def as that case is not supported
9273 correctly if ncopies is not one. */
9274 vect_get_vec_defs_for_operand (loop_vinfo, reduc_stmt_info,
9275 ncopies, initial_def,
9276 &vec_initial_defs);
9277 }
9278 else if (STMT_VINFO_REDUC_TYPE (reduc_info) == CONST_COND_REDUCTION
9279 || STMT_VINFO_REDUC_TYPE (reduc_info) == COND_REDUCTION)
9280 /* Fill the initial vector with the initial scalar value. */
9281 vec_initial_def
9282 = get_initial_def_for_reduction (loop_vinfo, reduc_stmt_info,
9283 initial_def, initial_def);
9284 else
9285 {
9286 if (ncopies == 1)
9287 vect_find_reusable_accumulator (loop_vinfo, reduc_info);
9288 if (!reduc_info->reduc_initial_values.is_empty ())
9289 {
9290 initial_def = reduc_info->reduc_initial_values[0];
9291 code_helper code = STMT_VINFO_REDUC_CODE (reduc_info);
9292 tree neutral_op
9293 = neutral_op_for_reduction (TREE_TYPE (initial_def),
9294 code, initial_def);
9295 gcc_assert (neutral_op);
9296 /* Try to simplify the vector initialization by applying an
9297 adjustment after the reduction has been performed. */
9298 if (!reduc_info->reused_accumulator
9299 && STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
9300 && !operand_equal_p (neutral_op, initial_def))
9301 {
9302 STMT_VINFO_REDUC_EPILOGUE_ADJUSTMENT (reduc_info)
9303 = initial_def;
9304 initial_def = neutral_op;
9305 }
9306 vec_initial_def
9307 = get_initial_def_for_reduction (loop_vinfo, reduc_info,
9308 initial_def, neutral_op);
9309 }
9310 }
9311 }
9312
9313 if (vec_initial_def)
9314 {
9315 vec_initial_defs.create (ncopies);
9316 for (i = 0; i < ncopies; ++i)
9317 vec_initial_defs.quick_push (vec_initial_def);
9318 }
9319
9320 if (auto *accumulator = reduc_info->reused_accumulator)
9321 {
9322 tree def = accumulator->reduc_input;
9323 if (!useless_type_conversion_p (vectype_out, TREE_TYPE (def)))
9324 {
9325 unsigned int nreduc;
9326 bool res = constant_multiple_p (TYPE_VECTOR_SUBPARTS
9327 (TREE_TYPE (def)),
9328 TYPE_VECTOR_SUBPARTS (vectype_out),
9329 &nreduc);
9330 gcc_assert (res);
9331 gimple_seq stmts = NULL;
9332 /* Reduce the single vector to a smaller one. */
9333 if (nreduc != 1)
9334 {
9335 /* Perform the reduction in the appropriate type. */
9336 tree rvectype = vectype_out;
9337 if (!useless_type_conversion_p (TREE_TYPE (vectype_out),
9338 TREE_TYPE (TREE_TYPE (def))))
9339 rvectype = build_vector_type (TREE_TYPE (TREE_TYPE (def)),
9340 TYPE_VECTOR_SUBPARTS
9341 (vectype_out));
9342 def = vect_create_partial_epilog (def, rvectype,
9343 STMT_VINFO_REDUC_CODE
9344 (reduc_info),
9345 &stmts);
9346 }
9347 /* The epilogue loop might use a different vector mode, like
9348 VNx2DI vs. V2DI. */
9349 if (TYPE_MODE (vectype_out) != TYPE_MODE (TREE_TYPE (def)))
9350 {
9351 tree reduc_type = build_vector_type_for_mode
9352 (TREE_TYPE (TREE_TYPE (def)), TYPE_MODE (vectype_out));
9353 def = gimple_convert (&stmts, reduc_type, def);
9354 }
9355 /* Adjust the input so we pick up the partially reduced value
9356 for the skip edge in vect_create_epilog_for_reduction. */
9357 accumulator->reduc_input = def;
9358 /* And the reduction could be carried out using a different sign. */
9359 if (!useless_type_conversion_p (vectype_out, TREE_TYPE (def)))
9360 def = gimple_convert (&stmts, vectype_out, def);
9361 edge e;
9362 if ((e = loop_vinfo->main_loop_edge)
9363 || (e = loop_vinfo->skip_this_loop_edge))
9364 {
9365 /* While we'd like to insert on the edge this will split
9366 blocks and disturb bookkeeping, we also will eventually
9367 need this on the skip edge. Rely on sinking to
9368 fixup optimal placement and insert in the pred. */
9369 gimple_stmt_iterator gsi = gsi_last_bb (e->src);
9370 /* Insert before a cond that eventually skips the
9371 epilogue. */
9372 if (!gsi_end_p (gsi) && stmt_ends_bb_p (gsi_stmt (gsi)))
9373 gsi_prev (&gsi);
9374 gsi_insert_seq_after (&gsi, stmts, GSI_CONTINUE_LINKING);
9375 }
9376 else
9377 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop),
9378 stmts);
9379 }
9380 if (loop_vinfo->main_loop_edge)
9381 vec_initial_defs[0]
9382 = vect_get_main_loop_result (loop_vinfo, def,
9383 vec_initial_defs[0]);
9384 else
9385 vec_initial_defs.safe_push (def);
9386 }
9387
9388 /* Generate the reduction PHIs upfront. */
9389 for (i = 0; i < vec_num; i++)
9390 {
9391 tree vec_init_def = vec_initial_defs[i];
9392 for (j = 0; j < ncopies; j++)
9393 {
9394 /* Create the reduction-phi that defines the reduction
9395 operand. */
9396 gphi *new_phi = create_phi_node (vec_dest, loop->header);
9397
9398 /* Set the loop-entry arg of the reduction-phi. */
9399 if (j != 0 && nested_cycle)
9400 vec_init_def = vec_initial_defs[j];
9401 add_phi_arg (new_phi, vec_init_def, loop_preheader_edge (loop),
9402 UNKNOWN_LOCATION);
9403
9404 /* The loop-latch arg is set in epilogue processing. */
9405
9406 if (slp_node)
9407 slp_node->push_vec_def (new_phi);
9408 else
9409 {
9410 if (j == 0)
9411 *vec_stmt = new_phi;
9412 STMT_VINFO_VEC_STMTS (stmt_info).safe_push (new_phi);
9413 }
9414 }
9415 }
9416
9417 return true;
9418 }
9419
9420 /* Vectorizes LC PHIs. */
9421
9422 bool
9423 vectorizable_lc_phi (loop_vec_info loop_vinfo,
9424 stmt_vec_info stmt_info, gimple **vec_stmt,
9425 slp_tree slp_node)
9426 {
9427 if (!loop_vinfo
9428 || !is_a <gphi *> (stmt_info->stmt)
9429 || gimple_phi_num_args (stmt_info->stmt) != 1)
9430 return false;
9431
9432 if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
9433 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_double_reduction_def)
9434 return false;
9435
9436 if (!vec_stmt) /* transformation not required. */
9437 {
9438 /* Deal with copies from externs or constants that disguise as
9439 loop-closed PHI nodes (PR97886). */
9440 if (slp_node
9441 && !vect_maybe_update_slp_op_vectype (SLP_TREE_CHILDREN (slp_node)[0],
9442 SLP_TREE_VECTYPE (slp_node)))
9443 {
9444 if (dump_enabled_p ())
9445 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9446 "incompatible vector types for invariants\n");
9447 return false;
9448 }
9449 STMT_VINFO_TYPE (stmt_info) = lc_phi_info_type;
9450 return true;
9451 }
9452
9453 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
9454 tree scalar_dest = gimple_phi_result (stmt_info->stmt);
9455 basic_block bb = gimple_bb (stmt_info->stmt);
9456 edge e = single_pred_edge (bb);
9457 tree vec_dest = vect_create_destination_var (scalar_dest, vectype);
9458 auto_vec<tree> vec_oprnds;
9459 vect_get_vec_defs (loop_vinfo, stmt_info, slp_node,
9460 !slp_node ? vect_get_num_copies (loop_vinfo, vectype) : 1,
9461 gimple_phi_arg_def (stmt_info->stmt, 0), &vec_oprnds);
9462 for (unsigned i = 0; i < vec_oprnds.length (); i++)
9463 {
9464 /* Create the vectorized LC PHI node. */
9465 gphi *new_phi = create_phi_node (vec_dest, bb);
9466 add_phi_arg (new_phi, vec_oprnds[i], e, UNKNOWN_LOCATION);
9467 if (slp_node)
9468 slp_node->push_vec_def (new_phi);
9469 else
9470 STMT_VINFO_VEC_STMTS (stmt_info).safe_push (new_phi);
9471 }
9472 if (!slp_node)
9473 *vec_stmt = STMT_VINFO_VEC_STMTS (stmt_info)[0];
9474
9475 return true;
9476 }
9477
9478 /* Vectorizes PHIs. */
9479
9480 bool
9481 vectorizable_phi (vec_info *,
9482 stmt_vec_info stmt_info, gimple **vec_stmt,
9483 slp_tree slp_node, stmt_vector_for_cost *cost_vec)
9484 {
9485 if (!is_a <gphi *> (stmt_info->stmt) || !slp_node)
9486 return false;
9487
9488 if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def)
9489 return false;
9490
9491 tree vectype = SLP_TREE_VECTYPE (slp_node);
9492
9493 if (!vec_stmt) /* transformation not required. */
9494 {
9495 slp_tree child;
9496 unsigned i;
9497 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), i, child)
9498 if (!child)
9499 {
9500 if (dump_enabled_p ())
9501 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9502 "PHI node with unvectorized backedge def\n");
9503 return false;
9504 }
9505 else if (!vect_maybe_update_slp_op_vectype (child, vectype))
9506 {
9507 if (dump_enabled_p ())
9508 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9509 "incompatible vector types for invariants\n");
9510 return false;
9511 }
9512 else if (SLP_TREE_DEF_TYPE (child) == vect_internal_def
9513 && !useless_type_conversion_p (vectype,
9514 SLP_TREE_VECTYPE (child)))
9515 {
9516 /* With bools we can have mask and non-mask precision vectors
9517 or different non-mask precisions. while pattern recog is
9518 supposed to guarantee consistency here bugs in it can cause
9519 mismatches (PR103489 and PR103800 for example).
9520 Deal with them here instead of ICEing later. */
9521 if (dump_enabled_p ())
9522 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9523 "incompatible vector type setup from "
9524 "bool pattern detection\n");
9525 return false;
9526 }
9527
9528 /* For single-argument PHIs assume coalescing which means zero cost
9529 for the scalar and the vector PHIs. This avoids artificially
9530 favoring the vector path (but may pessimize it in some cases). */
9531 if (gimple_phi_num_args (as_a <gphi *> (stmt_info->stmt)) > 1)
9532 record_stmt_cost (cost_vec, SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node),
9533 vector_stmt, stmt_info, vectype, 0, vect_body);
9534 STMT_VINFO_TYPE (stmt_info) = phi_info_type;
9535 return true;
9536 }
9537
9538 tree scalar_dest = gimple_phi_result (stmt_info->stmt);
9539 basic_block bb = gimple_bb (stmt_info->stmt);
9540 tree vec_dest = vect_create_destination_var (scalar_dest, vectype);
9541 auto_vec<gphi *> new_phis;
9542 for (unsigned i = 0; i < gimple_phi_num_args (stmt_info->stmt); ++i)
9543 {
9544 slp_tree child = SLP_TREE_CHILDREN (slp_node)[i];
9545
9546 /* Skip not yet vectorized defs. */
9547 if (SLP_TREE_DEF_TYPE (child) == vect_internal_def
9548 && SLP_TREE_VEC_DEFS (child).is_empty ())
9549 continue;
9550
9551 auto_vec<tree> vec_oprnds;
9552 vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[i], &vec_oprnds);
9553 if (!new_phis.exists ())
9554 {
9555 new_phis.create (vec_oprnds.length ());
9556 for (unsigned j = 0; j < vec_oprnds.length (); j++)
9557 {
9558 /* Create the vectorized LC PHI node. */
9559 new_phis.quick_push (create_phi_node (vec_dest, bb));
9560 slp_node->push_vec_def (new_phis[j]);
9561 }
9562 }
9563 edge e = gimple_phi_arg_edge (as_a <gphi *> (stmt_info->stmt), i);
9564 for (unsigned j = 0; j < vec_oprnds.length (); j++)
9565 add_phi_arg (new_phis[j], vec_oprnds[j], e, UNKNOWN_LOCATION);
9566 }
9567 /* We should have at least one already vectorized child. */
9568 gcc_assert (new_phis.exists ());
9569
9570 return true;
9571 }
9572
9573 /* Vectorizes first order recurrences. An overview of the transformation
9574 is described below. Suppose we have the following loop.
9575
9576 int t = 0;
9577 for (int i = 0; i < n; ++i)
9578 {
9579 b[i] = a[i] - t;
9580 t = a[i];
9581 }
9582
9583 There is a first-order recurrence on 'a'. For this loop, the scalar IR
9584 looks (simplified) like:
9585
9586 scalar.preheader:
9587 init = 0;
9588
9589 scalar.body:
9590 i = PHI <0(scalar.preheader), i+1(scalar.body)>
9591 _2 = PHI <(init(scalar.preheader), <_1(scalar.body)>
9592 _1 = a[i]
9593 b[i] = _1 - _2
9594 if (i < n) goto scalar.body
9595
9596 In this example, _2 is a recurrence because it's value depends on the
9597 previous iteration. We vectorize this as (VF = 4)
9598
9599 vector.preheader:
9600 vect_init = vect_cst(..., ..., ..., 0)
9601
9602 vector.body
9603 i = PHI <0(vector.preheader), i+4(vector.body)>
9604 vect_1 = PHI <vect_init(vector.preheader), v2(vector.body)>
9605 vect_2 = a[i, i+1, i+2, i+3];
9606 vect_3 = vec_perm (vect_1, vect_2, { 3, 4, 5, 6 })
9607 b[i, i+1, i+2, i+3] = vect_2 - vect_3
9608 if (..) goto vector.body
9609
9610 In this function, vectorizable_recurr, we code generate both the
9611 vector PHI node and the permute since those together compute the
9612 vectorized value of the scalar PHI. We do not yet have the
9613 backedge value to fill in there nor into the vec_perm. Those
9614 are filled in maybe_set_vectorized_backedge_value and
9615 vect_schedule_scc.
9616
9617 TODO: Since the scalar loop does not have a use of the recurrence
9618 outside of the loop the natural way to implement peeling via
9619 vectorizing the live value doesn't work. For now peeling of loops
9620 with a recurrence is not implemented. For SLP the supported cases
9621 are restricted to those requiring a single vector recurrence PHI. */
9622
9623 bool
9624 vectorizable_recurr (loop_vec_info loop_vinfo, stmt_vec_info stmt_info,
9625 gimple **vec_stmt, slp_tree slp_node,
9626 stmt_vector_for_cost *cost_vec)
9627 {
9628 if (!loop_vinfo || !is_a<gphi *> (stmt_info->stmt))
9629 return false;
9630
9631 gphi *phi = as_a<gphi *> (stmt_info->stmt);
9632
9633 /* So far we only support first-order recurrence auto-vectorization. */
9634 if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_first_order_recurrence)
9635 return false;
9636
9637 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
9638 unsigned ncopies;
9639 if (slp_node)
9640 ncopies = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
9641 else
9642 ncopies = vect_get_num_copies (loop_vinfo, vectype);
9643 poly_int64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
9644 unsigned dist = slp_node ? SLP_TREE_LANES (slp_node) : 1;
9645 /* We need to be able to make progress with a single vector. */
9646 if (maybe_gt (dist * 2, nunits))
9647 {
9648 if (dump_enabled_p ())
9649 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9650 "first order recurrence exceeds half of "
9651 "a vector\n");
9652 return false;
9653 }
9654
9655 /* We need to be able to build a { ..., a, b } init vector with
9656 dist number of distinct trailing values. Always possible
9657 when dist == 1 or when nunits is constant or when the initializations
9658 are uniform. */
9659 tree uniform_initval = NULL_TREE;
9660 edge pe = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
9661 if (slp_node)
9662 for (stmt_vec_info s : SLP_TREE_SCALAR_STMTS (slp_node))
9663 {
9664 gphi *phi = as_a <gphi *> (s->stmt);
9665 if (! uniform_initval)
9666 uniform_initval = PHI_ARG_DEF_FROM_EDGE (phi, pe);
9667 else if (! operand_equal_p (uniform_initval,
9668 PHI_ARG_DEF_FROM_EDGE (phi, pe)))
9669 {
9670 uniform_initval = NULL_TREE;
9671 break;
9672 }
9673 }
9674 else
9675 uniform_initval = PHI_ARG_DEF_FROM_EDGE (phi, pe);
9676 if (!uniform_initval && !nunits.is_constant ())
9677 {
9678 if (dump_enabled_p ())
9679 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9680 "cannot build initialization vector for "
9681 "first order recurrence\n");
9682 return false;
9683 }
9684
9685 /* First-order recurrence autovectorization needs to handle permutation
9686 with indices = [nunits-1, nunits, nunits+1, ...]. */
9687 vec_perm_builder sel (nunits, 1, 3);
9688 for (int i = 0; i < 3; ++i)
9689 sel.quick_push (nunits - dist + i);
9690 vec_perm_indices indices (sel, 2, nunits);
9691
9692 if (!vec_stmt) /* transformation not required. */
9693 {
9694 if (!can_vec_perm_const_p (TYPE_MODE (vectype), TYPE_MODE (vectype),
9695 indices))
9696 return false;
9697
9698 if (slp_node)
9699 {
9700 /* We eventually need to set a vector type on invariant
9701 arguments. */
9702 unsigned j;
9703 slp_tree child;
9704 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), j, child)
9705 if (!vect_maybe_update_slp_op_vectype
9706 (child, SLP_TREE_VECTYPE (slp_node)))
9707 {
9708 if (dump_enabled_p ())
9709 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9710 "incompatible vector types for "
9711 "invariants\n");
9712 return false;
9713 }
9714 }
9715
9716 /* Verify we have set up compatible types. */
9717 edge le = loop_latch_edge (LOOP_VINFO_LOOP (loop_vinfo));
9718 tree latch_vectype = NULL_TREE;
9719 if (slp_node)
9720 {
9721 slp_tree latch_def = SLP_TREE_CHILDREN (slp_node)[le->dest_idx];
9722 latch_vectype = SLP_TREE_VECTYPE (latch_def);
9723 }
9724 else
9725 {
9726 tree latch_def = PHI_ARG_DEF_FROM_EDGE (phi, le);
9727 if (TREE_CODE (latch_def) == SSA_NAME)
9728 {
9729 stmt_vec_info latch_def_info = loop_vinfo->lookup_def (latch_def);
9730 latch_def_info = vect_stmt_to_vectorize (latch_def_info);
9731 latch_vectype = STMT_VINFO_VECTYPE (latch_def_info);
9732 }
9733 }
9734 if (!types_compatible_p (latch_vectype, vectype))
9735 return false;
9736
9737 /* The recurrence costs the initialization vector and one permute
9738 for each copy. With SLP the prologue value is explicitly
9739 represented and costed separately. */
9740 unsigned prologue_cost = 0;
9741 if (!slp_node)
9742 prologue_cost = record_stmt_cost (cost_vec, 1, scalar_to_vec,
9743 stmt_info, 0, vect_prologue);
9744 unsigned inside_cost = record_stmt_cost (cost_vec, ncopies, vector_stmt,
9745 stmt_info, 0, vect_body);
9746 if (dump_enabled_p ())
9747 dump_printf_loc (MSG_NOTE, vect_location,
9748 "vectorizable_recurr: inside_cost = %d, "
9749 "prologue_cost = %d .\n", inside_cost,
9750 prologue_cost);
9751
9752 STMT_VINFO_TYPE (stmt_info) = recurr_info_type;
9753 return true;
9754 }
9755
9756 tree vec_init;
9757 if (! uniform_initval)
9758 {
9759 vec<constructor_elt, va_gc> *v = NULL;
9760 vec_alloc (v, nunits.to_constant ());
9761 for (unsigned i = 0; i < nunits.to_constant () - dist; ++i)
9762 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
9763 build_zero_cst (TREE_TYPE (vectype)));
9764 for (stmt_vec_info s : SLP_TREE_SCALAR_STMTS (slp_node))
9765 {
9766 gphi *phi = as_a <gphi *> (s->stmt);
9767 tree preheader = PHI_ARG_DEF_FROM_EDGE (phi, pe);
9768 if (!useless_type_conversion_p (TREE_TYPE (vectype),
9769 TREE_TYPE (preheader)))
9770 {
9771 gimple_seq stmts = NULL;
9772 preheader = gimple_convert (&stmts,
9773 TREE_TYPE (vectype), preheader);
9774 gsi_insert_seq_on_edge_immediate (pe, stmts);
9775 }
9776 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, preheader);
9777 }
9778 vec_init = build_constructor (vectype, v);
9779 }
9780 else
9781 vec_init = uniform_initval;
9782 vec_init = vect_init_vector (loop_vinfo, stmt_info, vec_init, vectype, NULL);
9783
9784 /* Create the vectorized first-order PHI node. */
9785 tree vec_dest = vect_get_new_vect_var (vectype,
9786 vect_simple_var, "vec_recur_");
9787 basic_block bb = gimple_bb (phi);
9788 gphi *new_phi = create_phi_node (vec_dest, bb);
9789 add_phi_arg (new_phi, vec_init, pe, UNKNOWN_LOCATION);
9790
9791 /* Insert shuffles the first-order recurrence autovectorization.
9792 result = VEC_PERM <vec_recur, vect_1, index[nunits-1, nunits, ...]>. */
9793 tree perm = vect_gen_perm_mask_checked (vectype, indices);
9794
9795 /* Insert the required permute after the latch definition. The
9796 second and later operands are tentative and will be updated when we have
9797 vectorized the latch definition. */
9798 edge le = loop_latch_edge (LOOP_VINFO_LOOP (loop_vinfo));
9799 gimple *latch_def = SSA_NAME_DEF_STMT (PHI_ARG_DEF_FROM_EDGE (phi, le));
9800 gimple_stmt_iterator gsi2 = gsi_for_stmt (latch_def);
9801 do
9802 {
9803 gsi_next (&gsi2);
9804 }
9805 /* Skip inserted vectorized stmts for the latch definition. We have to
9806 insert after those. */
9807 while (gsi_stmt (gsi2) && gimple_uid (gsi_stmt (gsi2)) == 0);
9808
9809 for (unsigned i = 0; i < ncopies; ++i)
9810 {
9811 vec_dest = make_ssa_name (vectype);
9812 gassign *vperm
9813 = gimple_build_assign (vec_dest, VEC_PERM_EXPR,
9814 i == 0 ? gimple_phi_result (new_phi) : NULL,
9815 NULL, perm);
9816 vect_finish_stmt_generation (loop_vinfo, stmt_info, vperm, &gsi2);
9817
9818 if (slp_node)
9819 slp_node->push_vec_def (vperm);
9820 else
9821 STMT_VINFO_VEC_STMTS (stmt_info).safe_push (vperm);
9822 }
9823
9824 if (!slp_node)
9825 *vec_stmt = STMT_VINFO_VEC_STMTS (stmt_info)[0];
9826 return true;
9827 }
9828
9829 /* Return true if VECTYPE represents a vector that requires lowering
9830 by the vector lowering pass. */
9831
9832 bool
9833 vect_emulated_vector_p (tree vectype)
9834 {
9835 return (!VECTOR_MODE_P (TYPE_MODE (vectype))
9836 && (!VECTOR_BOOLEAN_TYPE_P (vectype)
9837 || TYPE_PRECISION (TREE_TYPE (vectype)) != 1));
9838 }
9839
9840 /* Return true if we can emulate CODE on an integer mode representation
9841 of a vector. */
9842
9843 bool
9844 vect_can_vectorize_without_simd_p (tree_code code)
9845 {
9846 switch (code)
9847 {
9848 case PLUS_EXPR:
9849 case MINUS_EXPR:
9850 case NEGATE_EXPR:
9851 case BIT_AND_EXPR:
9852 case BIT_IOR_EXPR:
9853 case BIT_XOR_EXPR:
9854 case BIT_NOT_EXPR:
9855 return true;
9856
9857 default:
9858 return false;
9859 }
9860 }
9861
9862 /* Likewise, but taking a code_helper. */
9863
9864 bool
9865 vect_can_vectorize_without_simd_p (code_helper code)
9866 {
9867 return (code.is_tree_code ()
9868 && vect_can_vectorize_without_simd_p (tree_code (code)));
9869 }
9870
9871 /* Create vector init for vectorized iv. */
9872 static tree
9873 vect_create_nonlinear_iv_init (gimple_seq* stmts, tree init_expr,
9874 tree step_expr, poly_uint64 nunits,
9875 tree vectype,
9876 enum vect_induction_op_type induction_type)
9877 {
9878 unsigned HOST_WIDE_INT const_nunits;
9879 tree vec_shift, vec_init, new_name;
9880 unsigned i;
9881 tree itype = TREE_TYPE (vectype);
9882
9883 /* iv_loop is the loop to be vectorized. Create:
9884 vec_init = [X, X+S, X+2*S, X+3*S] (S = step_expr, X = init_expr). */
9885 new_name = gimple_convert (stmts, itype, init_expr);
9886 switch (induction_type)
9887 {
9888 case vect_step_op_shr:
9889 case vect_step_op_shl:
9890 /* Build the Initial value from shift_expr. */
9891 vec_init = gimple_build_vector_from_val (stmts,
9892 vectype,
9893 new_name);
9894 vec_shift = gimple_build (stmts, VEC_SERIES_EXPR, vectype,
9895 build_zero_cst (itype), step_expr);
9896 vec_init = gimple_build (stmts,
9897 (induction_type == vect_step_op_shr
9898 ? RSHIFT_EXPR : LSHIFT_EXPR),
9899 vectype, vec_init, vec_shift);
9900 break;
9901
9902 case vect_step_op_neg:
9903 {
9904 vec_init = gimple_build_vector_from_val (stmts,
9905 vectype,
9906 new_name);
9907 tree vec_neg = gimple_build (stmts, NEGATE_EXPR,
9908 vectype, vec_init);
9909 /* The encoding has 2 interleaved stepped patterns. */
9910 vec_perm_builder sel (nunits, 2, 3);
9911 sel.quick_grow (6);
9912 for (i = 0; i < 3; i++)
9913 {
9914 sel[2 * i] = i;
9915 sel[2 * i + 1] = i + nunits;
9916 }
9917 vec_perm_indices indices (sel, 2, nunits);
9918 /* Don't use vect_gen_perm_mask_checked since can_vec_perm_const_p may
9919 fail when vec_init is const vector. In that situation vec_perm is not
9920 really needed. */
9921 tree perm_mask_even
9922 = vect_gen_perm_mask_any (vectype, indices);
9923 vec_init = gimple_build (stmts, VEC_PERM_EXPR,
9924 vectype,
9925 vec_init, vec_neg,
9926 perm_mask_even);
9927 }
9928 break;
9929
9930 case vect_step_op_mul:
9931 {
9932 /* Use unsigned mult to avoid UD integer overflow. */
9933 gcc_assert (nunits.is_constant (&const_nunits));
9934 tree utype = unsigned_type_for (itype);
9935 tree uvectype = build_vector_type (utype,
9936 TYPE_VECTOR_SUBPARTS (vectype));
9937 new_name = gimple_convert (stmts, utype, new_name);
9938 vec_init = gimple_build_vector_from_val (stmts,
9939 uvectype,
9940 new_name);
9941 tree_vector_builder elts (uvectype, const_nunits, 1);
9942 tree elt_step = build_one_cst (utype);
9943
9944 elts.quick_push (elt_step);
9945 for (i = 1; i < const_nunits; i++)
9946 {
9947 /* Create: new_name_i = new_name + step_expr. */
9948 elt_step = gimple_build (stmts, MULT_EXPR,
9949 utype, elt_step, step_expr);
9950 elts.quick_push (elt_step);
9951 }
9952 /* Create a vector from [new_name_0, new_name_1, ...,
9953 new_name_nunits-1]. */
9954 tree vec_mul = gimple_build_vector (stmts, &elts);
9955 vec_init = gimple_build (stmts, MULT_EXPR, uvectype,
9956 vec_init, vec_mul);
9957 vec_init = gimple_convert (stmts, vectype, vec_init);
9958 }
9959 break;
9960
9961 default:
9962 gcc_unreachable ();
9963 }
9964
9965 return vec_init;
9966 }
9967
9968 /* Peel init_expr by skip_niter for induction_type. */
9969 tree
9970 vect_peel_nonlinear_iv_init (gimple_seq* stmts, tree init_expr,
9971 tree skip_niters, tree step_expr,
9972 enum vect_induction_op_type induction_type)
9973 {
9974 gcc_assert (TREE_CODE (skip_niters) == INTEGER_CST);
9975 tree type = TREE_TYPE (init_expr);
9976 unsigned prec = TYPE_PRECISION (type);
9977 switch (induction_type)
9978 {
9979 case vect_step_op_neg:
9980 if (TREE_INT_CST_LOW (skip_niters) % 2)
9981 init_expr = gimple_build (stmts, NEGATE_EXPR, type, init_expr);
9982 /* else no change. */
9983 break;
9984
9985 case vect_step_op_shr:
9986 case vect_step_op_shl:
9987 skip_niters = gimple_convert (stmts, type, skip_niters);
9988 step_expr = gimple_build (stmts, MULT_EXPR, type, step_expr, skip_niters);
9989 /* When shift mount >= precision, need to avoid UD.
9990 In the original loop, there's no UD, and according to semantic,
9991 init_expr should be 0 for lshr, ashl, and >>= (prec - 1) for ashr. */
9992 if (!tree_fits_uhwi_p (step_expr)
9993 || tree_to_uhwi (step_expr) >= prec)
9994 {
9995 if (induction_type == vect_step_op_shl
9996 || TYPE_UNSIGNED (type))
9997 init_expr = build_zero_cst (type);
9998 else
9999 init_expr = gimple_build (stmts, RSHIFT_EXPR, type,
10000 init_expr,
10001 wide_int_to_tree (type, prec - 1));
10002 }
10003 else
10004 init_expr = gimple_build (stmts, (induction_type == vect_step_op_shr
10005 ? RSHIFT_EXPR : LSHIFT_EXPR),
10006 type, init_expr, step_expr);
10007 break;
10008
10009 case vect_step_op_mul:
10010 {
10011 tree utype = unsigned_type_for (type);
10012 init_expr = gimple_convert (stmts, utype, init_expr);
10013 wide_int skipn = wi::to_wide (skip_niters);
10014 wide_int begin = wi::to_wide (step_expr);
10015 auto_mpz base, exp, mod, res;
10016 wi::to_mpz (begin, base, TYPE_SIGN (type));
10017 wi::to_mpz (skipn, exp, UNSIGNED);
10018 mpz_ui_pow_ui (mod, 2, TYPE_PRECISION (type));
10019 mpz_powm (res, base, exp, mod);
10020 begin = wi::from_mpz (utype, res, true);
10021 tree mult_expr = wide_int_to_tree (utype, begin);
10022 init_expr = gimple_build (stmts, MULT_EXPR, utype,
10023 init_expr, mult_expr);
10024 init_expr = gimple_convert (stmts, type, init_expr);
10025 }
10026 break;
10027
10028 default:
10029 gcc_unreachable ();
10030 }
10031
10032 return init_expr;
10033 }
10034
10035 /* Create vector step for vectorized iv. */
10036 static tree
10037 vect_create_nonlinear_iv_step (gimple_seq* stmts, tree step_expr,
10038 poly_uint64 vf,
10039 enum vect_induction_op_type induction_type)
10040 {
10041 tree expr = build_int_cst (TREE_TYPE (step_expr), vf);
10042 tree new_name = NULL;
10043 /* Step should be pow (step, vf) for mult induction. */
10044 if (induction_type == vect_step_op_mul)
10045 {
10046 gcc_assert (vf.is_constant ());
10047 wide_int begin = wi::to_wide (step_expr);
10048
10049 for (unsigned i = 0; i != vf.to_constant () - 1; i++)
10050 begin = wi::mul (begin, wi::to_wide (step_expr));
10051
10052 new_name = wide_int_to_tree (TREE_TYPE (step_expr), begin);
10053 }
10054 else if (induction_type == vect_step_op_neg)
10055 /* Do nothing. */
10056 ;
10057 else
10058 new_name = gimple_build (stmts, MULT_EXPR, TREE_TYPE (step_expr),
10059 expr, step_expr);
10060 return new_name;
10061 }
10062
10063 static tree
10064 vect_create_nonlinear_iv_vec_step (loop_vec_info loop_vinfo,
10065 stmt_vec_info stmt_info,
10066 tree new_name, tree vectype,
10067 enum vect_induction_op_type induction_type)
10068 {
10069 /* No step is needed for neg induction. */
10070 if (induction_type == vect_step_op_neg)
10071 return NULL;
10072
10073 tree t = unshare_expr (new_name);
10074 gcc_assert (CONSTANT_CLASS_P (new_name)
10075 || TREE_CODE (new_name) == SSA_NAME);
10076 tree new_vec = build_vector_from_val (vectype, t);
10077 tree vec_step = vect_init_vector (loop_vinfo, stmt_info,
10078 new_vec, vectype, NULL);
10079 return vec_step;
10080 }
10081
10082 /* Update vectorized iv with vect_step, induc_def is init. */
10083 static tree
10084 vect_update_nonlinear_iv (gimple_seq* stmts, tree vectype,
10085 tree induc_def, tree vec_step,
10086 enum vect_induction_op_type induction_type)
10087 {
10088 tree vec_def = induc_def;
10089 switch (induction_type)
10090 {
10091 case vect_step_op_mul:
10092 {
10093 /* Use unsigned mult to avoid UD integer overflow. */
10094 tree uvectype
10095 = build_vector_type (unsigned_type_for (TREE_TYPE (vectype)),
10096 TYPE_VECTOR_SUBPARTS (vectype));
10097 vec_def = gimple_convert (stmts, uvectype, vec_def);
10098 vec_step = gimple_convert (stmts, uvectype, vec_step);
10099 vec_def = gimple_build (stmts, MULT_EXPR, uvectype,
10100 vec_def, vec_step);
10101 vec_def = gimple_convert (stmts, vectype, vec_def);
10102 }
10103 break;
10104
10105 case vect_step_op_shr:
10106 vec_def = gimple_build (stmts, RSHIFT_EXPR, vectype,
10107 vec_def, vec_step);
10108 break;
10109
10110 case vect_step_op_shl:
10111 vec_def = gimple_build (stmts, LSHIFT_EXPR, vectype,
10112 vec_def, vec_step);
10113 break;
10114 case vect_step_op_neg:
10115 vec_def = induc_def;
10116 /* Do nothing. */
10117 break;
10118 default:
10119 gcc_unreachable ();
10120 }
10121
10122 return vec_def;
10123
10124 }
10125
10126 /* Function vectorizable_induction
10127
10128 Check if STMT_INFO performs an nonlinear induction computation that can be
10129 vectorized. If VEC_STMT is also passed, vectorize the induction PHI: create
10130 a vectorized phi to replace it, put it in VEC_STMT, and add it to the same
10131 basic block.
10132 Return true if STMT_INFO is vectorizable in this way. */
10133
10134 static bool
10135 vectorizable_nonlinear_induction (loop_vec_info loop_vinfo,
10136 stmt_vec_info stmt_info,
10137 gimple **vec_stmt, slp_tree slp_node,
10138 stmt_vector_for_cost *cost_vec)
10139 {
10140 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
10141 unsigned ncopies;
10142 bool nested_in_vect_loop = false;
10143 class loop *iv_loop;
10144 tree vec_def;
10145 edge pe = loop_preheader_edge (loop);
10146 basic_block new_bb;
10147 tree vec_init, vec_step;
10148 tree new_name;
10149 gimple *new_stmt;
10150 gphi *induction_phi;
10151 tree induc_def, vec_dest;
10152 tree init_expr, step_expr;
10153 tree niters_skip;
10154 poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
10155 unsigned i;
10156 gimple_stmt_iterator si;
10157
10158 gphi *phi = dyn_cast <gphi *> (stmt_info->stmt);
10159
10160 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
10161 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
10162 enum vect_induction_op_type induction_type
10163 = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info);
10164
10165 gcc_assert (induction_type > vect_step_op_add);
10166
10167 ncopies = vect_get_num_copies (loop_vinfo, slp_node, vectype);
10168 gcc_assert (ncopies >= 1);
10169
10170 /* FORNOW. Only handle nonlinear induction in the same loop. */
10171 if (nested_in_vect_loop_p (loop, stmt_info))
10172 {
10173 if (dump_enabled_p ())
10174 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10175 "nonlinear induction in nested loop.\n");
10176 return false;
10177 }
10178
10179 iv_loop = loop;
10180 gcc_assert (iv_loop == (gimple_bb (phi))->loop_father);
10181
10182 /* TODO: Support multi-lane SLP for nonlinear iv. There should be separate
10183 vector iv update for each iv and a permutation to generate wanted
10184 vector iv. */
10185 if (slp_node && SLP_TREE_LANES (slp_node) > 1)
10186 {
10187 if (dump_enabled_p ())
10188 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10189 "SLP induction not supported for nonlinear"
10190 " induction.\n");
10191 return false;
10192 }
10193
10194 if (!INTEGRAL_TYPE_P (TREE_TYPE (vectype)))
10195 {
10196 if (dump_enabled_p ())
10197 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10198 "floating point nonlinear induction vectorization"
10199 " not supported.\n");
10200 return false;
10201 }
10202
10203 step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info);
10204 init_expr = vect_phi_initial_value (phi);
10205 gcc_assert (step_expr != NULL_TREE && init_expr != NULL
10206 && TREE_CODE (step_expr) == INTEGER_CST);
10207 /* step_expr should be aligned with init_expr,
10208 .i.e. uint64 a >> 1, step is int, but vector<uint64> shift is used. */
10209 step_expr = fold_convert (TREE_TYPE (vectype), step_expr);
10210
10211 if (TREE_CODE (init_expr) == INTEGER_CST)
10212 init_expr = fold_convert (TREE_TYPE (vectype), init_expr);
10213 else if (!tree_nop_conversion_p (TREE_TYPE (vectype), TREE_TYPE (init_expr)))
10214 {
10215 /* INIT_EXPR could be a bit_field, bail out for such case. */
10216 if (dump_enabled_p ())
10217 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10218 "nonlinear induction vectorization failed:"
10219 " component type of vectype is not a nop conversion"
10220 " from type of init_expr.\n");
10221 return false;
10222 }
10223
10224 switch (induction_type)
10225 {
10226 case vect_step_op_neg:
10227 if (maybe_eq (TYPE_VECTOR_SUBPARTS (vectype), 1u))
10228 return false;
10229 if (TREE_CODE (init_expr) != INTEGER_CST
10230 && TREE_CODE (init_expr) != REAL_CST)
10231 {
10232 /* Check for backend support of NEGATE_EXPR and vec_perm. */
10233 if (!directly_supported_p (NEGATE_EXPR, vectype))
10234 return false;
10235
10236 /* The encoding has 2 interleaved stepped patterns. */
10237 vec_perm_builder sel (nunits, 2, 3);
10238 machine_mode mode = TYPE_MODE (vectype);
10239 sel.quick_grow (6);
10240 for (i = 0; i < 3; i++)
10241 {
10242 sel[i * 2] = i;
10243 sel[i * 2 + 1] = i + nunits;
10244 }
10245 vec_perm_indices indices (sel, 2, nunits);
10246 if (!can_vec_perm_const_p (mode, mode, indices))
10247 return false;
10248 }
10249 break;
10250
10251 case vect_step_op_mul:
10252 {
10253 /* Check for backend support of MULT_EXPR. */
10254 if (!directly_supported_p (MULT_EXPR, vectype))
10255 return false;
10256
10257 /* ?? How to construct vector step for variable number vector.
10258 [ 1, step, pow (step, 2), pow (step, 4), .. ]. */
10259 if (!vf.is_constant ())
10260 return false;
10261 }
10262 break;
10263
10264 case vect_step_op_shr:
10265 /* Check for backend support of RSHIFT_EXPR. */
10266 if (!directly_supported_p (RSHIFT_EXPR, vectype, optab_vector))
10267 return false;
10268
10269 /* Don't shift more than type precision to avoid UD. */
10270 if (!tree_fits_uhwi_p (step_expr)
10271 || maybe_ge (nunits * tree_to_uhwi (step_expr),
10272 TYPE_PRECISION (TREE_TYPE (init_expr))))
10273 return false;
10274 break;
10275
10276 case vect_step_op_shl:
10277 /* Check for backend support of RSHIFT_EXPR. */
10278 if (!directly_supported_p (LSHIFT_EXPR, vectype, optab_vector))
10279 return false;
10280
10281 /* Don't shift more than type precision to avoid UD. */
10282 if (!tree_fits_uhwi_p (step_expr)
10283 || maybe_ge (nunits * tree_to_uhwi (step_expr),
10284 TYPE_PRECISION (TREE_TYPE (init_expr))))
10285 return false;
10286
10287 break;
10288
10289 default:
10290 gcc_unreachable ();
10291 }
10292
10293 if (!vec_stmt) /* transformation not required. */
10294 {
10295 unsigned inside_cost = 0, prologue_cost = 0;
10296 /* loop cost for vec_loop. Neg induction doesn't have any
10297 inside_cost. */
10298 inside_cost = record_stmt_cost (cost_vec, ncopies, vector_stmt,
10299 stmt_info, 0, vect_body);
10300
10301 /* loop cost for vec_loop. Neg induction doesn't have any
10302 inside_cost. */
10303 if (induction_type == vect_step_op_neg)
10304 inside_cost = 0;
10305
10306 /* prologue cost for vec_init and vec_step. */
10307 prologue_cost = record_stmt_cost (cost_vec, 2, scalar_to_vec,
10308 stmt_info, 0, vect_prologue);
10309
10310 if (dump_enabled_p ())
10311 dump_printf_loc (MSG_NOTE, vect_location,
10312 "vect_model_induction_cost: inside_cost = %d, "
10313 "prologue_cost = %d. \n", inside_cost,
10314 prologue_cost);
10315
10316 STMT_VINFO_TYPE (stmt_info) = induc_vec_info_type;
10317 DUMP_VECT_SCOPE ("vectorizable_nonlinear_induction");
10318 return true;
10319 }
10320
10321 /* Transform. */
10322
10323 /* Compute a vector variable, initialized with the first VF values of
10324 the induction variable. E.g., for an iv with IV_PHI='X' and
10325 evolution S, for a vector of 4 units, we want to compute:
10326 [X, X + S, X + 2*S, X + 3*S]. */
10327
10328 if (dump_enabled_p ())
10329 dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
10330
10331 pe = loop_preheader_edge (iv_loop);
10332 /* Find the first insertion point in the BB. */
10333 basic_block bb = gimple_bb (phi);
10334 si = gsi_after_labels (bb);
10335
10336 gimple_seq stmts = NULL;
10337
10338 niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
10339 /* If we are using the loop mask to "peel" for alignment then we need
10340 to adjust the start value here. */
10341 if (niters_skip != NULL_TREE)
10342 init_expr = vect_peel_nonlinear_iv_init (&stmts, init_expr, niters_skip,
10343 step_expr, induction_type);
10344
10345 vec_init = vect_create_nonlinear_iv_init (&stmts, init_expr,
10346 step_expr, nunits, vectype,
10347 induction_type);
10348 if (stmts)
10349 {
10350 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
10351 gcc_assert (!new_bb);
10352 }
10353
10354 stmts = NULL;
10355 new_name = vect_create_nonlinear_iv_step (&stmts, step_expr,
10356 vf, induction_type);
10357 if (stmts)
10358 {
10359 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
10360 gcc_assert (!new_bb);
10361 }
10362
10363 vec_step = vect_create_nonlinear_iv_vec_step (loop_vinfo, stmt_info,
10364 new_name, vectype,
10365 induction_type);
10366 /* Create the following def-use cycle:
10367 loop prolog:
10368 vec_init = ...
10369 vec_step = ...
10370 loop:
10371 vec_iv = PHI <vec_init, vec_loop>
10372 ...
10373 STMT
10374 ...
10375 vec_loop = vec_iv + vec_step; */
10376
10377 /* Create the induction-phi that defines the induction-operand. */
10378 vec_dest = vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_");
10379 induction_phi = create_phi_node (vec_dest, iv_loop->header);
10380 induc_def = PHI_RESULT (induction_phi);
10381
10382 /* Create the iv update inside the loop. */
10383 stmts = NULL;
10384 vec_def = vect_update_nonlinear_iv (&stmts, vectype,
10385 induc_def, vec_step,
10386 induction_type);
10387
10388 gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
10389 new_stmt = SSA_NAME_DEF_STMT (vec_def);
10390
10391 /* Set the arguments of the phi node: */
10392 add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
10393 add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
10394 UNKNOWN_LOCATION);
10395
10396 if (slp_node)
10397 slp_node->push_vec_def (induction_phi);
10398 else
10399 {
10400 STMT_VINFO_VEC_STMTS (stmt_info).safe_push (induction_phi);
10401 *vec_stmt = induction_phi;
10402 }
10403
10404 /* In case that vectorization factor (VF) is bigger than the number
10405 of elements that we can fit in a vectype (nunits), we have to generate
10406 more than one vector stmt - i.e - we need to "unroll" the
10407 vector stmt by a factor VF/nunits. For more details see documentation
10408 in vectorizable_operation. */
10409
10410 if (ncopies > 1)
10411 {
10412 stmts = NULL;
10413 /* FORNOW. This restriction should be relaxed. */
10414 gcc_assert (!nested_in_vect_loop);
10415
10416 new_name = vect_create_nonlinear_iv_step (&stmts, step_expr,
10417 nunits, induction_type);
10418
10419 vec_step = vect_create_nonlinear_iv_vec_step (loop_vinfo, stmt_info,
10420 new_name, vectype,
10421 induction_type);
10422 vec_def = induc_def;
10423 for (i = 1; i < ncopies; i++)
10424 {
10425 /* vec_i = vec_prev + vec_step. */
10426 stmts = NULL;
10427 vec_def = vect_update_nonlinear_iv (&stmts, vectype,
10428 vec_def, vec_step,
10429 induction_type);
10430 gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
10431 new_stmt = SSA_NAME_DEF_STMT (vec_def);
10432 if (slp_node)
10433 slp_node->push_vec_def (new_stmt);
10434 else
10435 STMT_VINFO_VEC_STMTS (stmt_info).safe_push (new_stmt);
10436 }
10437 }
10438
10439 if (dump_enabled_p ())
10440 dump_printf_loc (MSG_NOTE, vect_location,
10441 "transform induction: created def-use cycle: %G%G",
10442 (gimple *) induction_phi, SSA_NAME_DEF_STMT (vec_def));
10443
10444 return true;
10445 }
10446
10447 /* Function vectorizable_induction
10448
10449 Check if STMT_INFO performs an induction computation that can be vectorized.
10450 If VEC_STMT is also passed, vectorize the induction PHI: create a vectorized
10451 phi to replace it, put it in VEC_STMT, and add it to the same basic block.
10452 Return true if STMT_INFO is vectorizable in this way. */
10453
10454 bool
10455 vectorizable_induction (loop_vec_info loop_vinfo,
10456 stmt_vec_info stmt_info,
10457 gimple **vec_stmt, slp_tree slp_node,
10458 stmt_vector_for_cost *cost_vec)
10459 {
10460 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
10461 unsigned ncopies;
10462 bool nested_in_vect_loop = false;
10463 class loop *iv_loop;
10464 tree vec_def;
10465 edge pe = loop_preheader_edge (loop);
10466 basic_block new_bb;
10467 tree new_vec, vec_init = NULL_TREE, vec_step, t;
10468 tree new_name;
10469 gimple *new_stmt;
10470 gphi *induction_phi;
10471 tree induc_def, vec_dest;
10472 poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
10473 unsigned i;
10474 tree expr;
10475 gimple_stmt_iterator si;
10476 enum vect_induction_op_type induction_type
10477 = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info);
10478
10479 gphi *phi = dyn_cast <gphi *> (stmt_info->stmt);
10480 if (!phi)
10481 return false;
10482
10483 if (!STMT_VINFO_RELEVANT_P (stmt_info))
10484 return false;
10485
10486 /* Make sure it was recognized as induction computation. */
10487 if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_induction_def)
10488 return false;
10489
10490 /* Handle nonlinear induction in a separate place. */
10491 if (induction_type != vect_step_op_add)
10492 return vectorizable_nonlinear_induction (loop_vinfo, stmt_info,
10493 vec_stmt, slp_node, cost_vec);
10494
10495 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
10496 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
10497
10498 if (slp_node)
10499 ncopies = 1;
10500 else
10501 ncopies = vect_get_num_copies (loop_vinfo, vectype);
10502 gcc_assert (ncopies >= 1);
10503
10504 /* FORNOW. These restrictions should be relaxed. */
10505 if (nested_in_vect_loop_p (loop, stmt_info))
10506 {
10507 imm_use_iterator imm_iter;
10508 use_operand_p use_p;
10509 gimple *exit_phi;
10510 edge latch_e;
10511 tree loop_arg;
10512
10513 if (ncopies > 1)
10514 {
10515 if (dump_enabled_p ())
10516 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10517 "multiple types in nested loop.\n");
10518 return false;
10519 }
10520
10521 exit_phi = NULL;
10522 latch_e = loop_latch_edge (loop->inner);
10523 loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
10524 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
10525 {
10526 gimple *use_stmt = USE_STMT (use_p);
10527 if (is_gimple_debug (use_stmt))
10528 continue;
10529
10530 if (!flow_bb_inside_loop_p (loop->inner, gimple_bb (use_stmt)))
10531 {
10532 exit_phi = use_stmt;
10533 break;
10534 }
10535 }
10536 if (exit_phi)
10537 {
10538 stmt_vec_info exit_phi_vinfo = loop_vinfo->lookup_stmt (exit_phi);
10539 if (!(STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
10540 && !STMT_VINFO_LIVE_P (exit_phi_vinfo)))
10541 {
10542 if (dump_enabled_p ())
10543 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10544 "inner-loop induction only used outside "
10545 "of the outer vectorized loop.\n");
10546 return false;
10547 }
10548 }
10549
10550 nested_in_vect_loop = true;
10551 iv_loop = loop->inner;
10552 }
10553 else
10554 iv_loop = loop;
10555 gcc_assert (iv_loop == (gimple_bb (phi))->loop_father);
10556
10557 if (slp_node && (!nunits.is_constant () && SLP_TREE_LANES (slp_node) != 1))
10558 {
10559 /* The current SLP code creates the step value element-by-element. */
10560 if (dump_enabled_p ())
10561 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10562 "SLP induction not supported for variable-length"
10563 " vectors.\n");
10564 return false;
10565 }
10566
10567 if (FLOAT_TYPE_P (vectype) && !param_vect_induction_float)
10568 {
10569 if (dump_enabled_p ())
10570 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10571 "floating point induction vectorization disabled\n");
10572 return false;
10573 }
10574
10575 tree step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info);
10576 gcc_assert (step_expr != NULL_TREE);
10577 if (INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
10578 && !type_has_mode_precision_p (TREE_TYPE (step_expr)))
10579 {
10580 if (dump_enabled_p ())
10581 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10582 "bit-precision induction vectorization not "
10583 "supported.\n");
10584 return false;
10585 }
10586 tree step_vectype = get_same_sized_vectype (TREE_TYPE (step_expr), vectype);
10587
10588 /* Check for backend support of PLUS/MINUS_EXPR. */
10589 if (!directly_supported_p (PLUS_EXPR, step_vectype)
10590 || !directly_supported_p (MINUS_EXPR, step_vectype))
10591 return false;
10592
10593 if (!vec_stmt) /* transformation not required. */
10594 {
10595 unsigned inside_cost = 0, prologue_cost = 0;
10596 if (slp_node)
10597 {
10598 /* We eventually need to set a vector type on invariant
10599 arguments. */
10600 unsigned j;
10601 slp_tree child;
10602 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), j, child)
10603 if (!vect_maybe_update_slp_op_vectype
10604 (child, SLP_TREE_VECTYPE (slp_node)))
10605 {
10606 if (dump_enabled_p ())
10607 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10608 "incompatible vector types for "
10609 "invariants\n");
10610 return false;
10611 }
10612 /* loop cost for vec_loop. */
10613 inside_cost
10614 = record_stmt_cost (cost_vec,
10615 SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node),
10616 vector_stmt, stmt_info, 0, vect_body);
10617 /* prologue cost for vec_init (if not nested) and step. */
10618 prologue_cost = record_stmt_cost (cost_vec, 1 + !nested_in_vect_loop,
10619 scalar_to_vec,
10620 stmt_info, 0, vect_prologue);
10621 }
10622 else /* if (!slp_node) */
10623 {
10624 /* loop cost for vec_loop. */
10625 inside_cost = record_stmt_cost (cost_vec, ncopies, vector_stmt,
10626 stmt_info, 0, vect_body);
10627 /* prologue cost for vec_init and vec_step. */
10628 prologue_cost = record_stmt_cost (cost_vec, 2, scalar_to_vec,
10629 stmt_info, 0, vect_prologue);
10630 }
10631 if (dump_enabled_p ())
10632 dump_printf_loc (MSG_NOTE, vect_location,
10633 "vect_model_induction_cost: inside_cost = %d, "
10634 "prologue_cost = %d .\n", inside_cost,
10635 prologue_cost);
10636
10637 STMT_VINFO_TYPE (stmt_info) = induc_vec_info_type;
10638 DUMP_VECT_SCOPE ("vectorizable_induction");
10639 return true;
10640 }
10641
10642 /* Transform. */
10643
10644 /* Compute a vector variable, initialized with the first VF values of
10645 the induction variable. E.g., for an iv with IV_PHI='X' and
10646 evolution S, for a vector of 4 units, we want to compute:
10647 [X, X + S, X + 2*S, X + 3*S]. */
10648
10649 if (dump_enabled_p ())
10650 dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
10651
10652 pe = loop_preheader_edge (iv_loop);
10653 /* Find the first insertion point in the BB. */
10654 basic_block bb = gimple_bb (phi);
10655 si = gsi_after_labels (bb);
10656
10657 /* For SLP induction we have to generate several IVs as for example
10658 with group size 3 we need
10659 [i0, i1, i2, i0 + S0] [i1 + S1, i2 + S2, i0 + 2*S0, i1 + 2*S1]
10660 [i2 + 2*S2, i0 + 3*S0, i1 + 3*S1, i2 + 3*S2]. */
10661 if (slp_node)
10662 {
10663 gimple_stmt_iterator incr_si;
10664 bool insert_after;
10665 standard_iv_increment_position (iv_loop, &incr_si, &insert_after);
10666
10667 /* The initial values are vectorized, but any lanes > group_size
10668 need adjustment. */
10669 slp_tree init_node
10670 = SLP_TREE_CHILDREN (slp_node)[pe->dest_idx];
10671
10672 /* Gather steps. Since we do not vectorize inductions as
10673 cycles we have to reconstruct the step from SCEV data. */
10674 unsigned group_size = SLP_TREE_LANES (slp_node);
10675 tree *steps = XALLOCAVEC (tree, group_size);
10676 tree *inits = XALLOCAVEC (tree, group_size);
10677 stmt_vec_info phi_info;
10678 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (slp_node), i, phi_info)
10679 {
10680 steps[i] = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (phi_info);
10681 if (!init_node)
10682 inits[i] = gimple_phi_arg_def (as_a<gphi *> (phi_info->stmt),
10683 pe->dest_idx);
10684 }
10685
10686 /* Now generate the IVs. */
10687 unsigned nvects = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
10688 gcc_assert (multiple_p (nunits * nvects, group_size));
10689 unsigned nivs;
10690 unsigned HOST_WIDE_INT const_nunits;
10691 if (nested_in_vect_loop)
10692 nivs = nvects;
10693 else if (nunits.is_constant (&const_nunits))
10694 {
10695 /* Compute the number of distinct IVs we need. First reduce
10696 group_size if it is a multiple of const_nunits so we get
10697 one IV for a group_size of 4 but const_nunits 2. */
10698 unsigned group_sizep = group_size;
10699 if (group_sizep % const_nunits == 0)
10700 group_sizep = group_sizep / const_nunits;
10701 nivs = least_common_multiple (group_sizep,
10702 const_nunits) / const_nunits;
10703 }
10704 else
10705 {
10706 gcc_assert (SLP_TREE_LANES (slp_node) == 1);
10707 nivs = 1;
10708 }
10709 gimple_seq init_stmts = NULL;
10710 tree stept = TREE_TYPE (step_vectype);
10711 tree lupdate_mul = NULL_TREE;
10712 if (!nested_in_vect_loop)
10713 {
10714 if (nunits.is_constant (&const_nunits))
10715 {
10716 /* The number of iterations covered in one vector iteration. */
10717 unsigned lup_mul = (nvects * const_nunits) / group_size;
10718 lupdate_mul
10719 = build_vector_from_val (step_vectype,
10720 SCALAR_FLOAT_TYPE_P (stept)
10721 ? build_real_from_wide (stept, lup_mul,
10722 UNSIGNED)
10723 : build_int_cstu (stept, lup_mul));
10724 }
10725 else
10726 {
10727 if (SCALAR_FLOAT_TYPE_P (stept))
10728 {
10729 tree tem = build_int_cst (integer_type_node, vf);
10730 lupdate_mul = gimple_build (&init_stmts, FLOAT_EXPR,
10731 stept, tem);
10732 }
10733 else
10734 lupdate_mul = build_int_cst (stept, vf);
10735 lupdate_mul = gimple_build_vector_from_val (&init_stmts,
10736 step_vectype,
10737 lupdate_mul);
10738 }
10739 }
10740 tree peel_mul = NULL_TREE;
10741 if (LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo))
10742 {
10743 if (SCALAR_FLOAT_TYPE_P (stept))
10744 peel_mul = gimple_build (&init_stmts, FLOAT_EXPR, stept,
10745 LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo));
10746 else
10747 peel_mul = gimple_convert (&init_stmts, stept,
10748 LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo));
10749 peel_mul = gimple_build_vector_from_val (&init_stmts,
10750 step_vectype, peel_mul);
10751
10752 /* If early break then we have to create a new PHI which we can use as
10753 an offset to adjust the induction reduction in early exits.
10754
10755 This is because when peeling for alignment using masking, the first
10756 few elements of the vector can be inactive. As such if we find the
10757 entry in the first iteration we have adjust the starting point of
10758 the scalar code.
10759
10760 We do this by creating a new scalar PHI that keeps track of whether
10761 we are the first iteration of the loop (with the additional masking)
10762 or whether we have taken a loop iteration already.
10763
10764 The generated sequence:
10765
10766 pre-header:
10767 bb1:
10768 i_1 = <number of leading inactive elements>
10769
10770 header:
10771 bb2:
10772 i_2 = PHI <i_1(bb1), 0(latch)>
10773 …
10774
10775 early-exit:
10776 bb3:
10777 i_3 = iv_step * i_2 + PHI<vector-iv>
10778
10779 The first part of the adjustment to create i_1 and i_2 are done here
10780 and the last part creating i_3 is done in
10781 vectorizable_live_operations when the induction extraction is
10782 materialized. */
10783 if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
10784 && !LOOP_VINFO_MASK_NITERS_PFA_OFFSET (loop_vinfo))
10785 {
10786 auto skip_niters = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
10787 tree ty_skip_niters = TREE_TYPE (skip_niters);
10788 tree break_lhs_phi = vect_get_new_vect_var (ty_skip_niters,
10789 vect_scalar_var,
10790 "pfa_iv_offset");
10791 gphi *nphi = create_phi_node (break_lhs_phi, bb);
10792 add_phi_arg (nphi, skip_niters, pe, UNKNOWN_LOCATION);
10793 add_phi_arg (nphi, build_zero_cst (ty_skip_niters),
10794 loop_latch_edge (iv_loop), UNKNOWN_LOCATION);
10795
10796 LOOP_VINFO_MASK_NITERS_PFA_OFFSET (loop_vinfo)
10797 = PHI_RESULT (nphi);
10798 }
10799 }
10800 tree step_mul = NULL_TREE;
10801 unsigned ivn;
10802 auto_vec<tree> vec_steps;
10803 for (ivn = 0; ivn < nivs; ++ivn)
10804 {
10805 gimple_seq stmts = NULL;
10806 bool invariant = true;
10807 if (nunits.is_constant (&const_nunits))
10808 {
10809 tree_vector_builder step_elts (step_vectype, const_nunits, 1);
10810 tree_vector_builder init_elts (vectype, const_nunits, 1);
10811 tree_vector_builder mul_elts (step_vectype, const_nunits, 1);
10812 for (unsigned eltn = 0; eltn < const_nunits; ++eltn)
10813 {
10814 /* The scalar steps of the IVs. */
10815 tree elt = steps[(ivn*const_nunits + eltn) % group_size];
10816 elt = gimple_convert (&init_stmts,
10817 TREE_TYPE (step_vectype), elt);
10818 step_elts.quick_push (elt);
10819 if (!init_node)
10820 {
10821 /* The scalar inits of the IVs if not vectorized. */
10822 elt = inits[(ivn*const_nunits + eltn) % group_size];
10823 if (!useless_type_conversion_p (TREE_TYPE (vectype),
10824 TREE_TYPE (elt)))
10825 elt = gimple_build (&init_stmts, VIEW_CONVERT_EXPR,
10826 TREE_TYPE (vectype), elt);
10827 init_elts.quick_push (elt);
10828 }
10829 /* The number of steps to add to the initial values. */
10830 unsigned mul_elt = (ivn*const_nunits + eltn) / group_size;
10831 mul_elts.quick_push (SCALAR_FLOAT_TYPE_P (stept)
10832 ? build_real_from_wide (stept, mul_elt,
10833 UNSIGNED)
10834 : build_int_cstu (stept, mul_elt));
10835 }
10836 vec_step = gimple_build_vector (&init_stmts, &step_elts);
10837 step_mul = gimple_build_vector (&init_stmts, &mul_elts);
10838 if (!init_node)
10839 vec_init = gimple_build_vector (&init_stmts, &init_elts);
10840 }
10841 else
10842 {
10843 if (init_node)
10844 ;
10845 else if (INTEGRAL_TYPE_P (TREE_TYPE (steps[0])))
10846 {
10847 new_name = gimple_convert (&init_stmts, stept, inits[0]);
10848 /* Build the initial value directly as a VEC_SERIES_EXPR. */
10849 vec_init = gimple_build (&init_stmts, VEC_SERIES_EXPR,
10850 step_vectype, new_name, steps[0]);
10851 if (!useless_type_conversion_p (vectype, step_vectype))
10852 vec_init = gimple_build (&init_stmts, VIEW_CONVERT_EXPR,
10853 vectype, vec_init);
10854 }
10855 else
10856 {
10857 /* Build:
10858 [base, base, base, ...]
10859 + (vectype) [0, 1, 2, ...] * [step, step, step, ...]. */
10860 gcc_assert (SCALAR_FLOAT_TYPE_P (TREE_TYPE (steps[0])));
10861 gcc_assert (flag_associative_math);
10862 tree index = build_index_vector (step_vectype, 0, 1);
10863 new_name = gimple_convert (&init_stmts, TREE_TYPE (steps[0]),
10864 inits[0]);
10865 tree base_vec = gimple_build_vector_from_val (&init_stmts,
10866 step_vectype,
10867 new_name);
10868 tree step_vec = gimple_build_vector_from_val (&init_stmts,
10869 step_vectype,
10870 steps[0]);
10871 vec_init = gimple_build (&init_stmts, FLOAT_EXPR,
10872 step_vectype, index);
10873 vec_init = gimple_build (&init_stmts, MULT_EXPR,
10874 step_vectype, vec_init, step_vec);
10875 vec_init = gimple_build (&init_stmts, PLUS_EXPR,
10876 step_vectype, vec_init, base_vec);
10877 if (!useless_type_conversion_p (vectype, step_vectype))
10878 vec_init = gimple_build (&init_stmts, VIEW_CONVERT_EXPR,
10879 vectype, vec_init);
10880 }
10881 /* iv_loop is nested in the loop to be vectorized. Generate:
10882 vec_step = [S, S, S, S] */
10883 t = unshare_expr (steps[0]);
10884 gcc_assert (CONSTANT_CLASS_P (t)
10885 || TREE_CODE (t) == SSA_NAME);
10886 vec_step = gimple_build_vector_from_val (&init_stmts,
10887 step_vectype, t);
10888 }
10889 vec_steps.safe_push (vec_step);
10890 if (peel_mul)
10891 {
10892 if (!step_mul)
10893 step_mul = peel_mul;
10894 else
10895 step_mul = gimple_build (&init_stmts,
10896 MINUS_EXPR, step_vectype,
10897 step_mul, peel_mul);
10898 }
10899
10900 /* Create the induction-phi that defines the induction-operand. */
10901 vec_dest = vect_get_new_vect_var (vectype, vect_simple_var,
10902 "vec_iv_");
10903 induction_phi = create_phi_node (vec_dest, iv_loop->header);
10904 induc_def = PHI_RESULT (induction_phi);
10905
10906 /* Create the iv update inside the loop */
10907 tree up = vec_step;
10908 if (lupdate_mul)
10909 {
10910 if (LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo))
10911 {
10912 /* When we're using loop_len produced by SELEC_VL, the
10913 non-final iterations are not always processing VF
10914 elements. So vectorize induction variable instead of
10915
10916 _21 = vect_vec_iv_.6_22 + { VF, ... };
10917
10918 We should generate:
10919
10920 _35 = .SELECT_VL (ivtmp_33, VF);
10921 vect_cst__22 = [vec_duplicate_expr] _35;
10922 _21 = vect_vec_iv_.6_22 + vect_cst__22; */
10923 vec_loop_lens *lens = &LOOP_VINFO_LENS (loop_vinfo);
10924 tree len = vect_get_loop_len (loop_vinfo, NULL, lens, 1,
10925 vectype, 0, 0);
10926 if (SCALAR_FLOAT_TYPE_P (stept))
10927 expr = gimple_build (&stmts, FLOAT_EXPR, stept, len);
10928 else
10929 expr = gimple_convert (&stmts, stept, len);
10930 lupdate_mul = gimple_build_vector_from_val (&stmts,
10931 step_vectype,
10932 expr);
10933 up = gimple_build (&stmts, MULT_EXPR,
10934 step_vectype, vec_step, lupdate_mul);
10935 }
10936 else
10937 up = gimple_build (&init_stmts,
10938 MULT_EXPR, step_vectype,
10939 vec_step, lupdate_mul);
10940 }
10941 vec_def = gimple_convert (&stmts, step_vectype, induc_def);
10942 vec_def = gimple_build (&stmts,
10943 PLUS_EXPR, step_vectype, vec_def, up);
10944 vec_def = gimple_convert (&stmts, vectype, vec_def);
10945 insert_iv_increment (&incr_si, insert_after, stmts);
10946 add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
10947 UNKNOWN_LOCATION);
10948
10949 if (init_node)
10950 vec_init = vect_get_slp_vect_def (init_node, ivn);
10951 if (!nested_in_vect_loop
10952 && step_mul
10953 && !integer_zerop (step_mul))
10954 {
10955 gcc_assert (invariant);
10956 vec_def = gimple_convert (&init_stmts, step_vectype, vec_init);
10957 up = gimple_build (&init_stmts, MULT_EXPR, step_vectype,
10958 vec_step, step_mul);
10959 vec_def = gimple_build (&init_stmts, PLUS_EXPR, step_vectype,
10960 vec_def, up);
10961 vec_init = gimple_convert (&init_stmts, vectype, vec_def);
10962 }
10963
10964 /* Set the arguments of the phi node: */
10965 add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
10966
10967 slp_node->push_vec_def (induction_phi);
10968 }
10969 if (!nested_in_vect_loop)
10970 {
10971 /* Fill up to the number of vectors we need for the whole group. */
10972 if (nunits.is_constant (&const_nunits))
10973 nivs = least_common_multiple (group_size,
10974 const_nunits) / const_nunits;
10975 else
10976 nivs = 1;
10977 vec_steps.reserve (nivs-ivn);
10978 for (; ivn < nivs; ++ivn)
10979 {
10980 slp_node->push_vec_def (SLP_TREE_VEC_DEFS (slp_node)[0]);
10981 vec_steps.quick_push (vec_steps[0]);
10982 }
10983 }
10984
10985 /* Re-use IVs when we can. We are generating further vector
10986 stmts by adding VF' * stride to the IVs generated above. */
10987 if (ivn < nvects)
10988 {
10989 if (nunits.is_constant (&const_nunits))
10990 {
10991 unsigned vfp = (least_common_multiple (group_size, const_nunits)
10992 / group_size);
10993 lupdate_mul
10994 = build_vector_from_val (step_vectype,
10995 SCALAR_FLOAT_TYPE_P (stept)
10996 ? build_real_from_wide (stept,
10997 vfp, UNSIGNED)
10998 : build_int_cstu (stept, vfp));
10999 }
11000 else
11001 {
11002 if (SCALAR_FLOAT_TYPE_P (stept))
11003 {
11004 tree tem = build_int_cst (integer_type_node, nunits);
11005 lupdate_mul = gimple_build (&init_stmts, FLOAT_EXPR,
11006 stept, tem);
11007 }
11008 else
11009 lupdate_mul = build_int_cst (stept, nunits);
11010 lupdate_mul = gimple_build_vector_from_val (&init_stmts,
11011 step_vectype,
11012 lupdate_mul);
11013 }
11014 for (; ivn < nvects; ++ivn)
11015 {
11016 gimple *iv
11017 = SSA_NAME_DEF_STMT (SLP_TREE_VEC_DEFS (slp_node)[ivn - nivs]);
11018 tree def = gimple_get_lhs (iv);
11019 if (ivn < 2*nivs)
11020 vec_steps[ivn - nivs]
11021 = gimple_build (&init_stmts, MULT_EXPR, step_vectype,
11022 vec_steps[ivn - nivs], lupdate_mul);
11023 gimple_seq stmts = NULL;
11024 def = gimple_convert (&stmts, step_vectype, def);
11025 def = gimple_build (&stmts, PLUS_EXPR, step_vectype,
11026 def, vec_steps[ivn % nivs]);
11027 def = gimple_convert (&stmts, vectype, def);
11028 if (gimple_code (iv) == GIMPLE_PHI)
11029 gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
11030 else
11031 {
11032 gimple_stmt_iterator tgsi = gsi_for_stmt (iv);
11033 gsi_insert_seq_after (&tgsi, stmts, GSI_CONTINUE_LINKING);
11034 }
11035 slp_node->push_vec_def (def);
11036 }
11037 }
11038
11039 new_bb = gsi_insert_seq_on_edge_immediate (pe, init_stmts);
11040 gcc_assert (!new_bb);
11041
11042 return true;
11043 }
11044
11045 tree init_expr = vect_phi_initial_value (phi);
11046
11047 gimple_seq stmts = NULL;
11048 if (!nested_in_vect_loop)
11049 {
11050 /* Convert the initial value to the IV update type. */
11051 tree new_type = TREE_TYPE (step_expr);
11052 init_expr = gimple_convert (&stmts, new_type, init_expr);
11053
11054 /* If we are using the loop mask to "peel" for alignment then we need
11055 to adjust the start value here. */
11056 tree skip_niters = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
11057 if (skip_niters != NULL_TREE)
11058 {
11059 if (FLOAT_TYPE_P (vectype))
11060 skip_niters = gimple_build (&stmts, FLOAT_EXPR, new_type,
11061 skip_niters);
11062 else
11063 skip_niters = gimple_convert (&stmts, new_type, skip_niters);
11064 tree skip_step = gimple_build (&stmts, MULT_EXPR, new_type,
11065 skip_niters, step_expr);
11066 init_expr = gimple_build (&stmts, MINUS_EXPR, new_type,
11067 init_expr, skip_step);
11068 }
11069 }
11070
11071 if (stmts)
11072 {
11073 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
11074 gcc_assert (!new_bb);
11075 }
11076
11077 /* Create the vector that holds the initial_value of the induction. */
11078 if (nested_in_vect_loop)
11079 {
11080 /* iv_loop is nested in the loop to be vectorized. init_expr had already
11081 been created during vectorization of previous stmts. We obtain it
11082 from the STMT_VINFO_VEC_STMT of the defining stmt. */
11083 auto_vec<tree> vec_inits;
11084 vect_get_vec_defs_for_operand (loop_vinfo, stmt_info, 1,
11085 init_expr, &vec_inits);
11086 vec_init = vec_inits[0];
11087 /* If the initial value is not of proper type, convert it. */
11088 if (!useless_type_conversion_p (vectype, TREE_TYPE (vec_init)))
11089 {
11090 new_stmt
11091 = gimple_build_assign (vect_get_new_ssa_name (vectype,
11092 vect_simple_var,
11093 "vec_iv_"),
11094 VIEW_CONVERT_EXPR,
11095 build1 (VIEW_CONVERT_EXPR, vectype,
11096 vec_init));
11097 vec_init = gimple_assign_lhs (new_stmt);
11098 new_bb = gsi_insert_on_edge_immediate (loop_preheader_edge (iv_loop),
11099 new_stmt);
11100 gcc_assert (!new_bb);
11101 }
11102 }
11103 else
11104 {
11105 /* iv_loop is the loop to be vectorized. Create:
11106 vec_init = [X, X+S, X+2*S, X+3*S] (S = step_expr, X = init_expr) */
11107 stmts = NULL;
11108 new_name = gimple_convert (&stmts, TREE_TYPE (step_expr), init_expr);
11109
11110 unsigned HOST_WIDE_INT const_nunits;
11111 if (nunits.is_constant (&const_nunits))
11112 {
11113 tree_vector_builder elts (step_vectype, const_nunits, 1);
11114 elts.quick_push (new_name);
11115 for (i = 1; i < const_nunits; i++)
11116 {
11117 /* Create: new_name_i = new_name + step_expr */
11118 new_name = gimple_build (&stmts, PLUS_EXPR, TREE_TYPE (new_name),
11119 new_name, step_expr);
11120 elts.quick_push (new_name);
11121 }
11122 /* Create a vector from [new_name_0, new_name_1, ...,
11123 new_name_nunits-1] */
11124 vec_init = gimple_build_vector (&stmts, &elts);
11125 }
11126 else if (INTEGRAL_TYPE_P (TREE_TYPE (step_expr)))
11127 /* Build the initial value directly from a VEC_SERIES_EXPR. */
11128 vec_init = gimple_build (&stmts, VEC_SERIES_EXPR, step_vectype,
11129 new_name, step_expr);
11130 else
11131 {
11132 /* Build:
11133 [base, base, base, ...]
11134 + (vectype) [0, 1, 2, ...] * [step, step, step, ...]. */
11135 gcc_assert (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)));
11136 gcc_assert (flag_associative_math);
11137 tree index = build_index_vector (step_vectype, 0, 1);
11138 tree base_vec = gimple_build_vector_from_val (&stmts, step_vectype,
11139 new_name);
11140 tree step_vec = gimple_build_vector_from_val (&stmts, step_vectype,
11141 step_expr);
11142 vec_init = gimple_build (&stmts, FLOAT_EXPR, step_vectype, index);
11143 vec_init = gimple_build (&stmts, MULT_EXPR, step_vectype,
11144 vec_init, step_vec);
11145 vec_init = gimple_build (&stmts, PLUS_EXPR, step_vectype,
11146 vec_init, base_vec);
11147 }
11148 vec_init = gimple_convert (&stmts, vectype, vec_init);
11149
11150 if (stmts)
11151 {
11152 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
11153 gcc_assert (!new_bb);
11154 }
11155 }
11156
11157
11158 /* Create the vector that holds the step of the induction. */
11159 gimple_stmt_iterator *step_iv_si = NULL;
11160 if (nested_in_vect_loop)
11161 /* iv_loop is nested in the loop to be vectorized. Generate:
11162 vec_step = [S, S, S, S] */
11163 new_name = step_expr;
11164 else if (LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo))
11165 {
11166 /* When we're using loop_len produced by SELEC_VL, the non-final
11167 iterations are not always processing VF elements. So vectorize
11168 induction variable instead of
11169
11170 _21 = vect_vec_iv_.6_22 + { VF, ... };
11171
11172 We should generate:
11173
11174 _35 = .SELECT_VL (ivtmp_33, VF);
11175 vect_cst__22 = [vec_duplicate_expr] _35;
11176 _21 = vect_vec_iv_.6_22 + vect_cst__22; */
11177 gcc_assert (!slp_node);
11178 gimple_seq seq = NULL;
11179 vec_loop_lens *lens = &LOOP_VINFO_LENS (loop_vinfo);
11180 tree len = vect_get_loop_len (loop_vinfo, NULL, lens, 1, vectype, 0, 0);
11181 expr = force_gimple_operand (fold_convert (TREE_TYPE (step_expr),
11182 unshare_expr (len)),
11183 &seq, true, NULL_TREE);
11184 new_name = gimple_build (&seq, MULT_EXPR, TREE_TYPE (step_expr), expr,
11185 step_expr);
11186 gsi_insert_seq_before (&si, seq, GSI_SAME_STMT);
11187 step_iv_si = &si;
11188 }
11189 else
11190 {
11191 /* iv_loop is the loop to be vectorized. Generate:
11192 vec_step = [VF*S, VF*S, VF*S, VF*S] */
11193 gimple_seq seq = NULL;
11194 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
11195 {
11196 expr = build_int_cst (integer_type_node, vf);
11197 expr = gimple_build (&seq, FLOAT_EXPR, TREE_TYPE (step_expr), expr);
11198 }
11199 else
11200 expr = build_int_cst (TREE_TYPE (step_expr), vf);
11201 new_name = gimple_build (&seq, MULT_EXPR, TREE_TYPE (step_expr),
11202 expr, step_expr);
11203 if (seq)
11204 {
11205 new_bb = gsi_insert_seq_on_edge_immediate (pe, seq);
11206 gcc_assert (!new_bb);
11207 }
11208 }
11209
11210 t = unshare_expr (new_name);
11211 gcc_assert (CONSTANT_CLASS_P (new_name)
11212 || TREE_CODE (new_name) == SSA_NAME);
11213 new_vec = build_vector_from_val (step_vectype, t);
11214 vec_step = vect_init_vector (loop_vinfo, stmt_info,
11215 new_vec, step_vectype, step_iv_si);
11216
11217
11218 /* Create the following def-use cycle:
11219 loop prolog:
11220 vec_init = ...
11221 vec_step = ...
11222 loop:
11223 vec_iv = PHI <vec_init, vec_loop>
11224 ...
11225 STMT
11226 ...
11227 vec_loop = vec_iv + vec_step; */
11228
11229 /* Create the induction-phi that defines the induction-operand. */
11230 vec_dest = vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_");
11231 induction_phi = create_phi_node (vec_dest, iv_loop->header);
11232 induc_def = PHI_RESULT (induction_phi);
11233
11234 /* Create the iv update inside the loop */
11235 stmts = NULL;
11236 vec_def = gimple_convert (&stmts, step_vectype, induc_def);
11237 vec_def = gimple_build (&stmts, PLUS_EXPR, step_vectype, vec_def, vec_step);
11238 vec_def = gimple_convert (&stmts, vectype, vec_def);
11239 gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
11240 new_stmt = SSA_NAME_DEF_STMT (vec_def);
11241
11242 /* Set the arguments of the phi node: */
11243 add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
11244 add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
11245 UNKNOWN_LOCATION);
11246
11247 STMT_VINFO_VEC_STMTS (stmt_info).safe_push (induction_phi);
11248 *vec_stmt = induction_phi;
11249
11250 /* In case that vectorization factor (VF) is bigger than the number
11251 of elements that we can fit in a vectype (nunits), we have to generate
11252 more than one vector stmt - i.e - we need to "unroll" the
11253 vector stmt by a factor VF/nunits. For more details see documentation
11254 in vectorizable_operation. */
11255
11256 if (ncopies > 1)
11257 {
11258 gimple_seq seq = NULL;
11259 /* FORNOW. This restriction should be relaxed. */
11260 gcc_assert (!nested_in_vect_loop);
11261 /* We expect LOOP_VINFO_USING_SELECT_VL_P to be false if ncopies > 1. */
11262 gcc_assert (!LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo));
11263
11264 /* Create the vector that holds the step of the induction. */
11265 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
11266 {
11267 expr = build_int_cst (integer_type_node, nunits);
11268 expr = gimple_build (&seq, FLOAT_EXPR, TREE_TYPE (step_expr), expr);
11269 }
11270 else
11271 expr = build_int_cst (TREE_TYPE (step_expr), nunits);
11272 new_name = gimple_build (&seq, MULT_EXPR, TREE_TYPE (step_expr),
11273 expr, step_expr);
11274 if (seq)
11275 {
11276 new_bb = gsi_insert_seq_on_edge_immediate (pe, seq);
11277 gcc_assert (!new_bb);
11278 }
11279
11280 t = unshare_expr (new_name);
11281 gcc_assert (CONSTANT_CLASS_P (new_name)
11282 || TREE_CODE (new_name) == SSA_NAME);
11283 new_vec = build_vector_from_val (step_vectype, t);
11284 vec_step = vect_init_vector (loop_vinfo, stmt_info,
11285 new_vec, step_vectype, NULL);
11286
11287 vec_def = induc_def;
11288 for (i = 1; i < ncopies + 1; i++)
11289 {
11290 /* vec_i = vec_prev + vec_step */
11291 gimple_seq stmts = NULL;
11292 vec_def = gimple_convert (&stmts, step_vectype, vec_def);
11293 vec_def = gimple_build (&stmts,
11294 PLUS_EXPR, step_vectype, vec_def, vec_step);
11295 vec_def = gimple_convert (&stmts, vectype, vec_def);
11296
11297 gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
11298 if (i < ncopies)
11299 {
11300 new_stmt = SSA_NAME_DEF_STMT (vec_def);
11301 STMT_VINFO_VEC_STMTS (stmt_info).safe_push (new_stmt);
11302 }
11303 else
11304 {
11305 /* vec_1 = vec_iv + (VF/n * S)
11306 vec_2 = vec_1 + (VF/n * S)
11307 ...
11308 vec_n = vec_prev + (VF/n * S) = vec_iv + VF * S = vec_loop
11309
11310 vec_n is used as vec_loop to save the large step register and
11311 related operations. */
11312 add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
11313 UNKNOWN_LOCATION);
11314 }
11315 }
11316 }
11317
11318 if (dump_enabled_p ())
11319 dump_printf_loc (MSG_NOTE, vect_location,
11320 "transform induction: created def-use cycle: %G%G",
11321 (gimple *) induction_phi, SSA_NAME_DEF_STMT (vec_def));
11322
11323 return true;
11324 }
11325
11326 /* Function vectorizable_live_operation_1.
11327
11328 helper function for vectorizable_live_operation. */
11329
11330 static tree
11331 vectorizable_live_operation_1 (loop_vec_info loop_vinfo,
11332 stmt_vec_info stmt_info, basic_block exit_bb,
11333 tree vectype, int ncopies, slp_tree slp_node,
11334 tree bitsize, tree bitstart, tree vec_lhs,
11335 tree lhs_type, gimple_stmt_iterator *exit_gsi)
11336 {
11337 gcc_assert (single_pred_p (exit_bb) || LOOP_VINFO_EARLY_BREAKS (loop_vinfo));
11338
11339 tree vec_lhs_phi = copy_ssa_name (vec_lhs);
11340 gimple *phi = create_phi_node (vec_lhs_phi, exit_bb);
11341 for (unsigned i = 0; i < gimple_phi_num_args (phi); i++)
11342 SET_PHI_ARG_DEF (phi, i, vec_lhs);
11343
11344 gimple_seq stmts = NULL;
11345 tree new_tree;
11346
11347 /* If bitstart is 0 then we can use a BIT_FIELD_REF */
11348 if (integer_zerop (bitstart))
11349 {
11350 tree scalar_res = gimple_build (&stmts, BIT_FIELD_REF, TREE_TYPE (vectype),
11351 vec_lhs_phi, bitsize, bitstart);
11352
11353 /* Convert the extracted vector element to the scalar type. */
11354 new_tree = gimple_convert (&stmts, lhs_type, scalar_res);
11355 }
11356 else if (LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
11357 {
11358 /* Emit:
11359
11360 SCALAR_RES = VEC_EXTRACT <VEC_LHS, LEN + BIAS - 1>
11361
11362 where VEC_LHS is the vectorized live-out result and MASK is
11363 the loop mask for the final iteration. */
11364 gcc_assert (ncopies == 1
11365 && (!slp_node || SLP_TREE_LANES (slp_node) == 1));
11366 gimple_seq tem = NULL;
11367 gimple_stmt_iterator gsi = gsi_last (tem);
11368 tree len = vect_get_loop_len (loop_vinfo, &gsi,
11369 &LOOP_VINFO_LENS (loop_vinfo),
11370 1, vectype, 0, 1);
11371 gimple_seq_add_seq (&stmts, tem);
11372
11373 /* BIAS - 1. */
11374 signed char biasval = LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo);
11375 tree bias_minus_one
11376 = int_const_binop (MINUS_EXPR,
11377 build_int_cst (TREE_TYPE (len), biasval),
11378 build_one_cst (TREE_TYPE (len)));
11379
11380 /* LAST_INDEX = LEN + (BIAS - 1). */
11381 tree last_index = gimple_build (&stmts, PLUS_EXPR, TREE_TYPE (len),
11382 len, bias_minus_one);
11383
11384 /* SCALAR_RES = VEC_EXTRACT <VEC_LHS, LEN + BIAS - 1>. */
11385 tree scalar_res
11386 = gimple_build (&stmts, CFN_VEC_EXTRACT, TREE_TYPE (vectype),
11387 vec_lhs_phi, last_index);
11388
11389 /* Convert the extracted vector element to the scalar type. */
11390 new_tree = gimple_convert (&stmts, lhs_type, scalar_res);
11391 }
11392 else if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
11393 {
11394 /* Emit:
11395
11396 SCALAR_RES = EXTRACT_LAST <VEC_LHS, MASK>
11397
11398 where VEC_LHS is the vectorized live-out result and MASK is
11399 the loop mask for the final iteration. */
11400 gcc_assert (!slp_node || SLP_TREE_LANES (slp_node) == 1);
11401 tree scalar_type = TREE_TYPE (STMT_VINFO_VECTYPE (stmt_info));
11402 gimple_seq tem = NULL;
11403 gimple_stmt_iterator gsi = gsi_last (tem);
11404 tree mask = vect_get_loop_mask (loop_vinfo, &gsi,
11405 &LOOP_VINFO_MASKS (loop_vinfo),
11406 1, vectype, 0);
11407 tree scalar_res;
11408 gimple_seq_add_seq (&stmts, tem);
11409
11410 scalar_res = gimple_build (&stmts, CFN_EXTRACT_LAST, scalar_type,
11411 mask, vec_lhs_phi);
11412
11413 /* Convert the extracted vector element to the scalar type. */
11414 new_tree = gimple_convert (&stmts, lhs_type, scalar_res);
11415 }
11416 else
11417 {
11418 tree bftype = TREE_TYPE (vectype);
11419 if (VECTOR_BOOLEAN_TYPE_P (vectype))
11420 bftype = build_nonstandard_integer_type (tree_to_uhwi (bitsize), 1);
11421 new_tree = build3 (BIT_FIELD_REF, bftype, vec_lhs_phi, bitsize, bitstart);
11422 new_tree = force_gimple_operand (fold_convert (lhs_type, new_tree),
11423 &stmts, true, NULL_TREE);
11424 }
11425
11426 *exit_gsi = gsi_after_labels (exit_bb);
11427 if (stmts)
11428 gsi_insert_seq_before (exit_gsi, stmts, GSI_SAME_STMT);
11429
11430 return new_tree;
11431 }
11432
11433 /* Function vectorizable_live_operation.
11434
11435 STMT_INFO computes a value that is used outside the loop. Check if
11436 it can be supported. */
11437
11438 bool
11439 vectorizable_live_operation (vec_info *vinfo, stmt_vec_info stmt_info,
11440 slp_tree slp_node, slp_instance slp_node_instance,
11441 int slp_index, bool vec_stmt_p,
11442 stmt_vector_for_cost *cost_vec)
11443 {
11444 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
11445 imm_use_iterator imm_iter;
11446 tree lhs, lhs_type, bitsize;
11447 tree vectype = (slp_node
11448 ? SLP_TREE_VECTYPE (slp_node)
11449 : STMT_VINFO_VECTYPE (stmt_info));
11450 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
11451 int ncopies;
11452 gimple *use_stmt;
11453 use_operand_p use_p;
11454 auto_vec<tree> vec_oprnds;
11455 int vec_entry = 0;
11456 poly_uint64 vec_index = 0;
11457
11458 gcc_assert (STMT_VINFO_LIVE_P (stmt_info)
11459 || LOOP_VINFO_EARLY_BREAKS (loop_vinfo));
11460
11461 /* If a stmt of a reduction is live, vectorize it via
11462 vect_create_epilog_for_reduction. vectorizable_reduction assessed
11463 validity so just trigger the transform here. */
11464 if (STMT_VINFO_REDUC_DEF (vect_orig_stmt (stmt_info)))
11465 {
11466 if (!vec_stmt_p)
11467 return true;
11468 /* For SLP reductions we vectorize the epilogue for all involved stmts
11469 together. */
11470 if (slp_node && !REDUC_GROUP_FIRST_ELEMENT (stmt_info) && slp_index != 0)
11471 return true;
11472 stmt_vec_info reduc_info = info_for_reduction (loop_vinfo, stmt_info);
11473 gcc_assert (reduc_info->is_reduc_info);
11474 if (STMT_VINFO_REDUC_TYPE (reduc_info) == FOLD_LEFT_REDUCTION
11475 || STMT_VINFO_REDUC_TYPE (reduc_info) == EXTRACT_LAST_REDUCTION)
11476 return true;
11477
11478 if (!LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
11479 || !LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
11480 vect_create_epilog_for_reduction (loop_vinfo, stmt_info, slp_node,
11481 slp_node_instance,
11482 LOOP_VINFO_IV_EXIT (loop_vinfo));
11483
11484 /* If early break we only have to materialize the reduction on the merge
11485 block, but we have to find an alternate exit first. */
11486 if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
11487 {
11488 slp_tree phis_node = slp_node ? slp_node_instance->reduc_phis : NULL;
11489 for (auto exit : get_loop_exit_edges (LOOP_VINFO_LOOP (loop_vinfo)))
11490 if (exit != LOOP_VINFO_IV_EXIT (loop_vinfo))
11491 {
11492 vect_create_epilog_for_reduction (loop_vinfo, reduc_info,
11493 phis_node, slp_node_instance,
11494 exit);
11495 break;
11496 }
11497 if (LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
11498 vect_create_epilog_for_reduction (loop_vinfo, reduc_info,
11499 phis_node, slp_node_instance,
11500 LOOP_VINFO_IV_EXIT (loop_vinfo));
11501 }
11502
11503 return true;
11504 }
11505
11506 /* If STMT is not relevant and it is a simple assignment and its inputs are
11507 invariant then it can remain in place, unvectorized. The original last
11508 scalar value that it computes will be used. */
11509 if (!STMT_VINFO_RELEVANT_P (stmt_info))
11510 {
11511 gcc_assert (is_simple_and_all_uses_invariant (stmt_info, loop_vinfo));
11512 if (dump_enabled_p ())
11513 dump_printf_loc (MSG_NOTE, vect_location,
11514 "statement is simple and uses invariant. Leaving in "
11515 "place.\n");
11516 return true;
11517 }
11518
11519 if (slp_node)
11520 ncopies = 1;
11521 else
11522 ncopies = vect_get_num_copies (loop_vinfo, vectype);
11523
11524 if (slp_node)
11525 {
11526 gcc_assert (slp_index >= 0);
11527
11528 /* Get the last occurrence of the scalar index from the concatenation of
11529 all the slp vectors. Calculate which slp vector it is and the index
11530 within. */
11531 int num_scalar = SLP_TREE_LANES (slp_node);
11532 int num_vec = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
11533 poly_uint64 pos = (num_vec * nunits) - num_scalar + slp_index;
11534
11535 /* Calculate which vector contains the result, and which lane of
11536 that vector we need. */
11537 if (!can_div_trunc_p (pos, nunits, &vec_entry, &vec_index))
11538 {
11539 if (dump_enabled_p ())
11540 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
11541 "Cannot determine which vector holds the"
11542 " final result.\n");
11543 return false;
11544 }
11545 }
11546
11547 if (!vec_stmt_p)
11548 {
11549 /* No transformation required. */
11550 if (loop_vinfo && LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
11551 {
11552 if (slp_node && SLP_TREE_LANES (slp_node) != 1)
11553 {
11554 if (dump_enabled_p ())
11555 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
11556 "can't operate on partial vectors "
11557 "because an SLP statement is live after "
11558 "the loop.\n");
11559 LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
11560 }
11561 else if (ncopies > 1
11562 || (slp_node && SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node) > 1))
11563 {
11564 if (dump_enabled_p ())
11565 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
11566 "can't operate on partial vectors "
11567 "because ncopies is greater than 1.\n");
11568 LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
11569 }
11570 else
11571 {
11572 gcc_assert (ncopies == 1
11573 && (!slp_node || SLP_TREE_LANES (slp_node) == 1));
11574 if (direct_internal_fn_supported_p (IFN_EXTRACT_LAST, vectype,
11575 OPTIMIZE_FOR_SPEED))
11576 vect_record_loop_mask (loop_vinfo,
11577 &LOOP_VINFO_MASKS (loop_vinfo),
11578 1, vectype, NULL);
11579 else if (can_vec_extract_var_idx_p (
11580 TYPE_MODE (vectype), TYPE_MODE (TREE_TYPE (vectype))))
11581 vect_record_loop_len (loop_vinfo,
11582 &LOOP_VINFO_LENS (loop_vinfo),
11583 1, vectype, 1);
11584 else
11585 {
11586 if (dump_enabled_p ())
11587 dump_printf_loc (
11588 MSG_MISSED_OPTIMIZATION, vect_location,
11589 "can't operate on partial vectors "
11590 "because the target doesn't support extract "
11591 "last reduction.\n");
11592 LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
11593 }
11594 }
11595 }
11596 /* ??? Enable for loop costing as well. */
11597 if (!loop_vinfo)
11598 record_stmt_cost (cost_vec, 1, vec_to_scalar, stmt_info, NULL_TREE,
11599 0, vect_epilogue);
11600 return true;
11601 }
11602
11603 /* Use the lhs of the original scalar statement. */
11604 gimple *stmt = vect_orig_stmt (stmt_info)->stmt;
11605 if (dump_enabled_p ())
11606 dump_printf_loc (MSG_NOTE, vect_location, "extracting lane for live "
11607 "stmt %G", stmt);
11608
11609 lhs = gimple_get_lhs (stmt);
11610 lhs_type = TREE_TYPE (lhs);
11611
11612 bitsize = vector_element_bits_tree (vectype);
11613
11614 /* Get the vectorized lhs of STMT and the lane to use (counted in bits). */
11615 tree vec_lhs, vec_lhs0, bitstart;
11616 gimple *vec_stmt, *vec_stmt0;
11617 if (slp_node)
11618 {
11619 gcc_assert (!loop_vinfo
11620 || ((!LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
11621 && !LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
11622 || SLP_TREE_LANES (slp_node) == 1));
11623
11624 /* Get the correct slp vectorized stmt. */
11625 vec_lhs = SLP_TREE_VEC_DEFS (slp_node)[vec_entry];
11626 vec_stmt = SSA_NAME_DEF_STMT (vec_lhs);
11627
11628 /* In case we need to early break vectorize also get the first stmt. */
11629 vec_lhs0 = SLP_TREE_VEC_DEFS (slp_node)[0];
11630 vec_stmt0 = SSA_NAME_DEF_STMT (vec_lhs0);
11631
11632 /* Get entry to use. */
11633 bitstart = bitsize_int (vec_index);
11634 bitstart = int_const_binop (MULT_EXPR, bitsize, bitstart);
11635 }
11636 else
11637 {
11638 /* For multiple copies, get the last copy. */
11639 vec_stmt = STMT_VINFO_VEC_STMTS (stmt_info).last ();
11640 vec_lhs = gimple_get_lhs (vec_stmt);
11641
11642 /* In case we need to early break vectorize also get the first stmt. */
11643 vec_stmt0 = STMT_VINFO_VEC_STMTS (stmt_info)[0];
11644 vec_lhs0 = gimple_get_lhs (vec_stmt0);
11645
11646 /* Get the last lane in the vector. */
11647 bitstart = int_const_binop (MULT_EXPR, bitsize, bitsize_int (nunits - 1));
11648 }
11649
11650 if (loop_vinfo)
11651 {
11652 /* Ensure the VEC_LHS for lane extraction stmts satisfy loop-closed PHI
11653 requirement, insert one phi node for it. It looks like:
11654 loop;
11655 BB:
11656 # lhs' = PHI <lhs>
11657 ==>
11658 loop;
11659 BB:
11660 # vec_lhs' = PHI <vec_lhs>
11661 new_tree = lane_extract <vec_lhs', ...>;
11662 lhs' = new_tree; */
11663
11664 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
11665 /* Check if we have a loop where the chosen exit is not the main exit,
11666 in these cases for an early break we restart the iteration the vector code
11667 did. For the live values we want the value at the start of the iteration
11668 rather than at the end. */
11669 edge main_e = LOOP_VINFO_IV_EXIT (loop_vinfo);
11670 bool all_exits_as_early_p = LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo);
11671 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
11672 if (!is_gimple_debug (use_stmt)
11673 && !flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
11674 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
11675 {
11676 edge e = gimple_phi_arg_edge (as_a <gphi *> (use_stmt),
11677 phi_arg_index_from_use (use_p));
11678 gcc_assert (loop_exit_edge_p (loop, e));
11679 bool main_exit_edge = e == main_e;
11680 tree tmp_vec_lhs = vec_lhs;
11681 tree tmp_bitstart = bitstart;
11682
11683 /* For early exit where the exit is not in the BB that leads
11684 to the latch then we're restarting the iteration in the
11685 scalar loop. So get the first live value. */
11686 bool early_break_first_element_p
11687 = (all_exits_as_early_p || !main_exit_edge)
11688 && STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def;
11689 if (early_break_first_element_p)
11690 {
11691 tmp_vec_lhs = vec_lhs0;
11692 tmp_bitstart = build_zero_cst (TREE_TYPE (bitstart));
11693 }
11694
11695 gimple_stmt_iterator exit_gsi;
11696 tree new_tree
11697 = vectorizable_live_operation_1 (loop_vinfo, stmt_info,
11698 e->dest, vectype, ncopies,
11699 slp_node, bitsize,
11700 tmp_bitstart, tmp_vec_lhs,
11701 lhs_type, &exit_gsi);
11702
11703 auto gsi = gsi_for_stmt (use_stmt);
11704 if (early_break_first_element_p
11705 && LOOP_VINFO_MASK_NITERS_PFA_OFFSET (loop_vinfo))
11706 {
11707 tree step_expr
11708 = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info);
11709 tree break_lhs_phi
11710 = LOOP_VINFO_MASK_NITERS_PFA_OFFSET (loop_vinfo);
11711 tree ty_skip_niters = TREE_TYPE (break_lhs_phi);
11712 gimple_seq iv_stmts = NULL;
11713
11714 /* Now create the PHI for the outside loop usage to
11715 retrieve the value for the offset counter. */
11716 tree rphi_step
11717 = gimple_convert (&iv_stmts, ty_skip_niters, step_expr);
11718 tree tmp2
11719 = gimple_build (&iv_stmts, MULT_EXPR,
11720 ty_skip_niters, rphi_step,
11721 break_lhs_phi);
11722
11723 if (POINTER_TYPE_P (TREE_TYPE (new_tree)))
11724 {
11725 tmp2 = gimple_convert (&iv_stmts, sizetype, tmp2);
11726 tmp2 = gimple_build (&iv_stmts, POINTER_PLUS_EXPR,
11727 TREE_TYPE (new_tree), new_tree,
11728 tmp2);
11729 }
11730 else
11731 {
11732 tmp2 = gimple_convert (&iv_stmts, TREE_TYPE (new_tree),
11733 tmp2);
11734 tmp2 = gimple_build (&iv_stmts, PLUS_EXPR,
11735 TREE_TYPE (new_tree), new_tree,
11736 tmp2);
11737 }
11738
11739 new_tree = tmp2;
11740 gsi_insert_seq_before (&exit_gsi, iv_stmts, GSI_SAME_STMT);
11741 }
11742
11743 tree lhs_phi = gimple_phi_result (use_stmt);
11744 remove_phi_node (&gsi, false);
11745 gimple *copy = gimple_build_assign (lhs_phi, new_tree);
11746 gsi_insert_before (&exit_gsi, copy, GSI_SAME_STMT);
11747 break;
11748 }
11749
11750 /* There a no further out-of-loop uses of lhs by LC-SSA construction. */
11751 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
11752 gcc_assert (is_gimple_debug (use_stmt)
11753 || flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)));
11754 }
11755 else
11756 {
11757 /* For basic-block vectorization simply insert the lane-extraction. */
11758 tree bftype = TREE_TYPE (vectype);
11759 if (VECTOR_BOOLEAN_TYPE_P (vectype))
11760 bftype = build_nonstandard_integer_type (tree_to_uhwi (bitsize), 1);
11761 tree new_tree = build3 (BIT_FIELD_REF, bftype,
11762 vec_lhs, bitsize, bitstart);
11763 gimple_seq stmts = NULL;
11764 new_tree = force_gimple_operand (fold_convert (lhs_type, new_tree),
11765 &stmts, true, NULL_TREE);
11766 if (TREE_CODE (new_tree) == SSA_NAME
11767 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
11768 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_tree) = 1;
11769 if (is_a <gphi *> (vec_stmt))
11770 {
11771 gimple_stmt_iterator si = gsi_after_labels (gimple_bb (vec_stmt));
11772 gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
11773 }
11774 else
11775 {
11776 gimple_stmt_iterator si = gsi_for_stmt (vec_stmt);
11777 gsi_insert_seq_after (&si, stmts, GSI_SAME_STMT);
11778 }
11779
11780 /* Replace use of lhs with newly computed result. If the use stmt is a
11781 single arg PHI, just replace all uses of PHI result. It's necessary
11782 because lcssa PHI defining lhs may be before newly inserted stmt. */
11783 use_operand_p use_p;
11784 stmt_vec_info use_stmt_info;
11785 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
11786 if (!is_gimple_debug (use_stmt)
11787 && (!(use_stmt_info = vinfo->lookup_stmt (use_stmt))
11788 || !PURE_SLP_STMT (vect_stmt_to_vectorize (use_stmt_info))))
11789 {
11790 /* ??? This can happen when the live lane ends up being
11791 rooted in a vector construction code-generated by an
11792 external SLP node (and code-generation for that already
11793 happened). See gcc.dg/vect/bb-slp-47.c.
11794 Doing this is what would happen if that vector CTOR
11795 were not code-generated yet so it is not too bad.
11796 ??? In fact we'd likely want to avoid this situation
11797 in the first place. */
11798 if (TREE_CODE (new_tree) == SSA_NAME
11799 && !SSA_NAME_IS_DEFAULT_DEF (new_tree)
11800 && gimple_code (use_stmt) != GIMPLE_PHI
11801 && !vect_stmt_dominates_stmt_p (SSA_NAME_DEF_STMT (new_tree),
11802 use_stmt))
11803 {
11804 if (dump_enabled_p ())
11805 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
11806 "Using original scalar computation for "
11807 "live lane because use preceeds vector "
11808 "def\n");
11809 continue;
11810 }
11811 /* ??? It can also happen that we end up pulling a def into
11812 a loop where replacing out-of-loop uses would require
11813 a new LC SSA PHI node. Retain the original scalar in
11814 those cases as well. PR98064. */
11815 if (TREE_CODE (new_tree) == SSA_NAME
11816 && !SSA_NAME_IS_DEFAULT_DEF (new_tree)
11817 && (gimple_bb (use_stmt)->loop_father
11818 != gimple_bb (vec_stmt)->loop_father)
11819 && !flow_loop_nested_p (gimple_bb (vec_stmt)->loop_father,
11820 gimple_bb (use_stmt)->loop_father))
11821 {
11822 if (dump_enabled_p ())
11823 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
11824 "Using original scalar computation for "
11825 "live lane because there is an out-of-loop "
11826 "definition for it\n");
11827 continue;
11828 }
11829 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
11830 SET_USE (use_p, new_tree);
11831 update_stmt (use_stmt);
11832 }
11833 }
11834
11835 return true;
11836 }
11837
11838 /* Kill any debug uses outside LOOP of SSA names defined in STMT_INFO. */
11839
11840 static void
11841 vect_loop_kill_debug_uses (class loop *loop, stmt_vec_info stmt_info)
11842 {
11843 ssa_op_iter op_iter;
11844 imm_use_iterator imm_iter;
11845 def_operand_p def_p;
11846 gimple *ustmt;
11847
11848 FOR_EACH_PHI_OR_STMT_DEF (def_p, stmt_info->stmt, op_iter, SSA_OP_DEF)
11849 {
11850 FOR_EACH_IMM_USE_STMT (ustmt, imm_iter, DEF_FROM_PTR (def_p))
11851 {
11852 basic_block bb;
11853
11854 if (!is_gimple_debug (ustmt))
11855 continue;
11856
11857 bb = gimple_bb (ustmt);
11858
11859 if (!flow_bb_inside_loop_p (loop, bb))
11860 {
11861 if (gimple_debug_bind_p (ustmt))
11862 {
11863 if (dump_enabled_p ())
11864 dump_printf_loc (MSG_NOTE, vect_location,
11865 "killing debug use\n");
11866
11867 gimple_debug_bind_reset_value (ustmt);
11868 update_stmt (ustmt);
11869 }
11870 else
11871 gcc_unreachable ();
11872 }
11873 }
11874 }
11875 }
11876
11877 /* Given loop represented by LOOP_VINFO, return true if computation of
11878 LOOP_VINFO_NITERS (= LOOP_VINFO_NITERSM1 + 1) doesn't overflow, false
11879 otherwise. */
11880
11881 static bool
11882 loop_niters_no_overflow (loop_vec_info loop_vinfo)
11883 {
11884 /* Constant case. */
11885 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
11886 {
11887 tree cst_niters = LOOP_VINFO_NITERS (loop_vinfo);
11888 tree cst_nitersm1 = LOOP_VINFO_NITERSM1 (loop_vinfo);
11889
11890 gcc_assert (TREE_CODE (cst_niters) == INTEGER_CST);
11891 gcc_assert (TREE_CODE (cst_nitersm1) == INTEGER_CST);
11892 if (wi::to_widest (cst_nitersm1) < wi::to_widest (cst_niters))
11893 return true;
11894 }
11895
11896 widest_int max;
11897 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
11898 /* Check the upper bound of loop niters. */
11899 if (get_max_loop_iterations (loop, &max))
11900 {
11901 tree type = TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo));
11902 signop sgn = TYPE_SIGN (type);
11903 widest_int type_max = widest_int::from (wi::max_value (type), sgn);
11904 if (max < type_max)
11905 return true;
11906 }
11907 return false;
11908 }
11909
11910 /* Return a mask type with half the number of elements as OLD_TYPE,
11911 given that it should have mode NEW_MODE. */
11912
11913 tree
11914 vect_halve_mask_nunits (tree old_type, machine_mode new_mode)
11915 {
11916 poly_uint64 nunits = exact_div (TYPE_VECTOR_SUBPARTS (old_type), 2);
11917 return build_truth_vector_type_for_mode (nunits, new_mode);
11918 }
11919
11920 /* Return a mask type with twice as many elements as OLD_TYPE,
11921 given that it should have mode NEW_MODE. */
11922
11923 tree
11924 vect_double_mask_nunits (tree old_type, machine_mode new_mode)
11925 {
11926 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (old_type) * 2;
11927 return build_truth_vector_type_for_mode (nunits, new_mode);
11928 }
11929
11930 /* Record that a fully-masked version of LOOP_VINFO would need MASKS to
11931 contain a sequence of NVECTORS masks that each control a vector of type
11932 VECTYPE. If SCALAR_MASK is nonnull, the fully-masked loop would AND
11933 these vector masks with the vector version of SCALAR_MASK. */
11934
11935 void
11936 vect_record_loop_mask (loop_vec_info loop_vinfo, vec_loop_masks *masks,
11937 unsigned int nvectors, tree vectype, tree scalar_mask)
11938 {
11939 gcc_assert (nvectors != 0);
11940
11941 if (scalar_mask)
11942 {
11943 scalar_cond_masked_key cond (scalar_mask, nvectors);
11944 loop_vinfo->scalar_cond_masked_set.add (cond);
11945 }
11946
11947 masks->mask_set.add (std::make_pair (vectype, nvectors));
11948 }
11949
11950 /* Given a complete set of masks MASKS, extract mask number INDEX
11951 for an rgroup that operates on NVECTORS vectors of type VECTYPE,
11952 where 0 <= INDEX < NVECTORS. Insert any set-up statements before GSI.
11953
11954 See the comment above vec_loop_masks for more details about the mask
11955 arrangement. */
11956
11957 tree
11958 vect_get_loop_mask (loop_vec_info loop_vinfo,
11959 gimple_stmt_iterator *gsi, vec_loop_masks *masks,
11960 unsigned int nvectors, tree vectype, unsigned int index)
11961 {
11962 if (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo)
11963 == vect_partial_vectors_while_ult)
11964 {
11965 rgroup_controls *rgm = &(masks->rgc_vec)[nvectors - 1];
11966 tree mask_type = rgm->type;
11967
11968 /* Populate the rgroup's mask array, if this is the first time we've
11969 used it. */
11970 if (rgm->controls.is_empty ())
11971 {
11972 rgm->controls.safe_grow_cleared (nvectors, true);
11973 for (unsigned int i = 0; i < nvectors; ++i)
11974 {
11975 tree mask = make_temp_ssa_name (mask_type, NULL, "loop_mask");
11976 /* Provide a dummy definition until the real one is available. */
11977 SSA_NAME_DEF_STMT (mask) = gimple_build_nop ();
11978 rgm->controls[i] = mask;
11979 }
11980 }
11981
11982 tree mask = rgm->controls[index];
11983 if (maybe_ne (TYPE_VECTOR_SUBPARTS (mask_type),
11984 TYPE_VECTOR_SUBPARTS (vectype)))
11985 {
11986 /* A loop mask for data type X can be reused for data type Y
11987 if X has N times more elements than Y and if Y's elements
11988 are N times bigger than X's. In this case each sequence
11989 of N elements in the loop mask will be all-zero or all-one.
11990 We can then view-convert the mask so that each sequence of
11991 N elements is replaced by a single element. */
11992 gcc_assert (multiple_p (TYPE_VECTOR_SUBPARTS (mask_type),
11993 TYPE_VECTOR_SUBPARTS (vectype)));
11994 gimple_seq seq = NULL;
11995 mask_type = truth_type_for (vectype);
11996 mask = gimple_build (&seq, VIEW_CONVERT_EXPR, mask_type, mask);
11997 if (seq)
11998 gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
11999 }
12000 return mask;
12001 }
12002 else if (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo)
12003 == vect_partial_vectors_avx512)
12004 {
12005 /* The number of scalars per iteration and the number of vectors are
12006 both compile-time constants. */
12007 unsigned int nscalars_per_iter
12008 = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
12009 LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
12010
12011 rgroup_controls *rgm = &masks->rgc_vec[nscalars_per_iter - 1];
12012
12013 /* The stored nV is dependent on the mask type produced. */
12014 gcc_assert (exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
12015 TYPE_VECTOR_SUBPARTS (rgm->type)).to_constant ()
12016 == rgm->factor);
12017 nvectors = rgm->factor;
12018
12019 /* Populate the rgroup's mask array, if this is the first time we've
12020 used it. */
12021 if (rgm->controls.is_empty ())
12022 {
12023 rgm->controls.safe_grow_cleared (nvectors, true);
12024 for (unsigned int i = 0; i < nvectors; ++i)
12025 {
12026 tree mask = make_temp_ssa_name (rgm->type, NULL, "loop_mask");
12027 /* Provide a dummy definition until the real one is available. */
12028 SSA_NAME_DEF_STMT (mask) = gimple_build_nop ();
12029 rgm->controls[i] = mask;
12030 }
12031 }
12032 if (known_eq (TYPE_VECTOR_SUBPARTS (rgm->type),
12033 TYPE_VECTOR_SUBPARTS (vectype)))
12034 return rgm->controls[index];
12035
12036 /* Split the vector if needed. Since we are dealing with integer mode
12037 masks with AVX512 we can operate on the integer representation
12038 performing the whole vector shifting. */
12039 unsigned HOST_WIDE_INT factor;
12040 bool ok = constant_multiple_p (TYPE_VECTOR_SUBPARTS (rgm->type),
12041 TYPE_VECTOR_SUBPARTS (vectype), &factor);
12042 gcc_assert (ok);
12043 gcc_assert (GET_MODE_CLASS (TYPE_MODE (rgm->type)) == MODE_INT);
12044 tree mask_type = truth_type_for (vectype);
12045 gcc_assert (GET_MODE_CLASS (TYPE_MODE (mask_type)) == MODE_INT);
12046 unsigned vi = index / factor;
12047 unsigned vpart = index % factor;
12048 tree vec = rgm->controls[vi];
12049 gimple_seq seq = NULL;
12050 vec = gimple_build (&seq, VIEW_CONVERT_EXPR,
12051 lang_hooks.types.type_for_mode
12052 (TYPE_MODE (rgm->type), 1), vec);
12053 /* For integer mode masks simply shift the right bits into position. */
12054 if (vpart != 0)
12055 vec = gimple_build (&seq, RSHIFT_EXPR, TREE_TYPE (vec), vec,
12056 build_int_cst (integer_type_node,
12057 (TYPE_VECTOR_SUBPARTS (vectype)
12058 * vpart)));
12059 vec = gimple_convert (&seq, lang_hooks.types.type_for_mode
12060 (TYPE_MODE (mask_type), 1), vec);
12061 vec = gimple_build (&seq, VIEW_CONVERT_EXPR, mask_type, vec);
12062 if (seq)
12063 gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
12064 return vec;
12065 }
12066 else
12067 gcc_unreachable ();
12068 }
12069
12070 /* Record that LOOP_VINFO would need LENS to contain a sequence of NVECTORS
12071 lengths for controlling an operation on VECTYPE. The operation splits
12072 each element of VECTYPE into FACTOR separate subelements, measuring the
12073 length as a number of these subelements. */
12074
12075 void
12076 vect_record_loop_len (loop_vec_info loop_vinfo, vec_loop_lens *lens,
12077 unsigned int nvectors, tree vectype, unsigned int factor)
12078 {
12079 gcc_assert (nvectors != 0);
12080 if (lens->length () < nvectors)
12081 lens->safe_grow_cleared (nvectors, true);
12082 rgroup_controls *rgl = &(*lens)[nvectors - 1];
12083
12084 /* The number of scalars per iteration, scalar occupied bytes and
12085 the number of vectors are both compile-time constants. */
12086 unsigned int nscalars_per_iter
12087 = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
12088 LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
12089
12090 if (rgl->max_nscalars_per_iter < nscalars_per_iter)
12091 {
12092 /* For now, we only support cases in which all loads and stores fall back
12093 to VnQI or none do. */
12094 gcc_assert (!rgl->max_nscalars_per_iter
12095 || (rgl->factor == 1 && factor == 1)
12096 || (rgl->max_nscalars_per_iter * rgl->factor
12097 == nscalars_per_iter * factor));
12098 rgl->max_nscalars_per_iter = nscalars_per_iter;
12099 rgl->type = vectype;
12100 rgl->factor = factor;
12101 }
12102 }
12103
12104 /* Given a complete set of lengths LENS, extract length number INDEX
12105 for an rgroup that operates on NVECTORS vectors of type VECTYPE,
12106 where 0 <= INDEX < NVECTORS. Return a value that contains FACTOR
12107 multipled by the number of elements that should be processed.
12108 Insert any set-up statements before GSI. */
12109
12110 tree
12111 vect_get_loop_len (loop_vec_info loop_vinfo, gimple_stmt_iterator *gsi,
12112 vec_loop_lens *lens, unsigned int nvectors, tree vectype,
12113 unsigned int index, unsigned int factor)
12114 {
12115 rgroup_controls *rgl = &(*lens)[nvectors - 1];
12116 bool use_bias_adjusted_len =
12117 LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo) != 0;
12118
12119 /* Populate the rgroup's len array, if this is the first time we've
12120 used it. */
12121 if (rgl->controls.is_empty ())
12122 {
12123 rgl->controls.safe_grow_cleared (nvectors, true);
12124 for (unsigned int i = 0; i < nvectors; ++i)
12125 {
12126 tree len_type = LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo);
12127 gcc_assert (len_type != NULL_TREE);
12128
12129 tree len = make_temp_ssa_name (len_type, NULL, "loop_len");
12130
12131 /* Provide a dummy definition until the real one is available. */
12132 SSA_NAME_DEF_STMT (len) = gimple_build_nop ();
12133 rgl->controls[i] = len;
12134
12135 if (use_bias_adjusted_len)
12136 {
12137 gcc_assert (i == 0);
12138 tree adjusted_len =
12139 make_temp_ssa_name (len_type, NULL, "adjusted_loop_len");
12140 SSA_NAME_DEF_STMT (adjusted_len) = gimple_build_nop ();
12141 rgl->bias_adjusted_ctrl = adjusted_len;
12142 }
12143 }
12144 }
12145
12146 if (use_bias_adjusted_len)
12147 return rgl->bias_adjusted_ctrl;
12148
12149 tree loop_len = rgl->controls[index];
12150 if (rgl->factor == 1 && factor == 1)
12151 {
12152 poly_int64 nunits1 = TYPE_VECTOR_SUBPARTS (rgl->type);
12153 poly_int64 nunits2 = TYPE_VECTOR_SUBPARTS (vectype);
12154 if (maybe_ne (nunits1, nunits2))
12155 {
12156 /* A loop len for data type X can be reused for data type Y
12157 if X has N times more elements than Y and if Y's elements
12158 are N times bigger than X's. */
12159 gcc_assert (multiple_p (nunits1, nunits2));
12160 factor = exact_div (nunits1, nunits2).to_constant ();
12161 tree iv_type = LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo);
12162 gimple_seq seq = NULL;
12163 loop_len = gimple_build (&seq, RDIV_EXPR, iv_type, loop_len,
12164 build_int_cst (iv_type, factor));
12165 if (seq)
12166 gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
12167 }
12168 }
12169 return loop_len;
12170 }
12171
12172 /* Generate the tree for the loop len mask and return it. Given the lens,
12173 nvectors, vectype, index and factor to gen the len mask as below.
12174
12175 tree len_mask = VCOND_MASK_LEN (compare_mask, ones, zero, len, bias)
12176 */
12177 tree
12178 vect_gen_loop_len_mask (loop_vec_info loop_vinfo, gimple_stmt_iterator *gsi,
12179 gimple_stmt_iterator *cond_gsi, vec_loop_lens *lens,
12180 unsigned int nvectors, tree vectype, tree stmt,
12181 unsigned int index, unsigned int factor)
12182 {
12183 tree all_one_mask = build_all_ones_cst (vectype);
12184 tree all_zero_mask = build_zero_cst (vectype);
12185 tree len = vect_get_loop_len (loop_vinfo, gsi, lens, nvectors, vectype, index,
12186 factor);
12187 tree bias = build_int_cst (intQI_type_node,
12188 LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo));
12189 tree len_mask = make_temp_ssa_name (TREE_TYPE (stmt), NULL, "vec_len_mask");
12190 gcall *call = gimple_build_call_internal (IFN_VCOND_MASK_LEN, 5, stmt,
12191 all_one_mask, all_zero_mask, len,
12192 bias);
12193 gimple_call_set_lhs (call, len_mask);
12194 gsi_insert_before (cond_gsi, call, GSI_SAME_STMT);
12195
12196 return len_mask;
12197 }
12198
12199 /* Scale profiling counters by estimation for LOOP which is vectorized
12200 by factor VF.
12201 If FLAT is true, the loop we started with had unrealistically flat
12202 profile. */
12203
12204 static void
12205 scale_profile_for_vect_loop (class loop *loop, edge exit_e, unsigned vf, bool flat)
12206 {
12207 /* For flat profiles do not scale down proportionally by VF and only
12208 cap by known iteration count bounds. */
12209 if (flat)
12210 {
12211 if (dump_file && (dump_flags & TDF_DETAILS))
12212 fprintf (dump_file,
12213 "Vectorized loop profile seems flat; not scaling iteration "
12214 "count down by the vectorization factor %i\n", vf);
12215 scale_loop_profile (loop, profile_probability::always (),
12216 get_likely_max_loop_iterations_int (loop));
12217 return;
12218 }
12219 /* Loop body executes VF fewer times and exit increases VF times. */
12220 profile_count entry_count = loop_preheader_edge (loop)->count ();
12221
12222 /* If we have unreliable loop profile avoid dropping entry
12223 count bellow header count. This can happen since loops
12224 has unrealistically low trip counts. */
12225 while (vf > 1
12226 && loop->header->count > entry_count
12227 && loop->header->count < entry_count * vf)
12228 {
12229 if (dump_file && (dump_flags & TDF_DETAILS))
12230 fprintf (dump_file,
12231 "Vectorization factor %i seems too large for profile "
12232 "prevoiusly believed to be consistent; reducing.\n", vf);
12233 vf /= 2;
12234 }
12235
12236 if (entry_count.nonzero_p ())
12237 set_edge_probability_and_rescale_others
12238 (exit_e,
12239 entry_count.probability_in (loop->header->count / vf));
12240 /* Avoid producing very large exit probability when we do not have
12241 sensible profile. */
12242 else if (exit_e->probability < profile_probability::always () / (vf * 2))
12243 set_edge_probability_and_rescale_others (exit_e, exit_e->probability * vf);
12244 loop->latch->count = single_pred_edge (loop->latch)->count ();
12245
12246 scale_loop_profile (loop, profile_probability::always () / vf,
12247 get_likely_max_loop_iterations_int (loop));
12248 }
12249
12250 /* For a vectorized stmt DEF_STMT_INFO adjust all vectorized PHI
12251 latch edge values originally defined by it. */
12252
12253 static void
12254 maybe_set_vectorized_backedge_value (loop_vec_info loop_vinfo,
12255 stmt_vec_info def_stmt_info)
12256 {
12257 tree def = gimple_get_lhs (vect_orig_stmt (def_stmt_info)->stmt);
12258 if (!def || TREE_CODE (def) != SSA_NAME)
12259 return;
12260 stmt_vec_info phi_info;
12261 imm_use_iterator iter;
12262 use_operand_p use_p;
12263 FOR_EACH_IMM_USE_FAST (use_p, iter, def)
12264 {
12265 gphi *phi = dyn_cast <gphi *> (USE_STMT (use_p));
12266 if (!phi)
12267 continue;
12268 if (!(gimple_bb (phi)->loop_father->header == gimple_bb (phi)
12269 && (phi_info = loop_vinfo->lookup_stmt (phi))
12270 && STMT_VINFO_RELEVANT_P (phi_info)))
12271 continue;
12272 loop_p loop = gimple_bb (phi)->loop_father;
12273 edge e = loop_latch_edge (loop);
12274 if (PHI_ARG_DEF_FROM_EDGE (phi, e) != def)
12275 continue;
12276
12277 if (VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (phi_info))
12278 && STMT_VINFO_REDUC_TYPE (phi_info) != FOLD_LEFT_REDUCTION
12279 && STMT_VINFO_REDUC_TYPE (phi_info) != EXTRACT_LAST_REDUCTION)
12280 {
12281 vec<gimple *> &phi_defs = STMT_VINFO_VEC_STMTS (phi_info);
12282 vec<gimple *> &latch_defs = STMT_VINFO_VEC_STMTS (def_stmt_info);
12283 gcc_assert (phi_defs.length () == latch_defs.length ());
12284 for (unsigned i = 0; i < phi_defs.length (); ++i)
12285 add_phi_arg (as_a <gphi *> (phi_defs[i]),
12286 gimple_get_lhs (latch_defs[i]), e,
12287 gimple_phi_arg_location (phi, e->dest_idx));
12288 }
12289 else if (STMT_VINFO_DEF_TYPE (phi_info) == vect_first_order_recurrence)
12290 {
12291 /* For first order recurrences we have to update both uses of
12292 the latch definition, the one in the PHI node and the one
12293 in the generated VEC_PERM_EXPR. */
12294 vec<gimple *> &phi_defs = STMT_VINFO_VEC_STMTS (phi_info);
12295 vec<gimple *> &latch_defs = STMT_VINFO_VEC_STMTS (def_stmt_info);
12296 gcc_assert (phi_defs.length () == latch_defs.length ());
12297 tree phidef = gimple_assign_rhs1 (phi_defs[0]);
12298 gphi *vphi = as_a <gphi *> (SSA_NAME_DEF_STMT (phidef));
12299 for (unsigned i = 0; i < phi_defs.length (); ++i)
12300 {
12301 gassign *perm = as_a <gassign *> (phi_defs[i]);
12302 if (i > 0)
12303 gimple_assign_set_rhs1 (perm, gimple_get_lhs (latch_defs[i-1]));
12304 gimple_assign_set_rhs2 (perm, gimple_get_lhs (latch_defs[i]));
12305 update_stmt (perm);
12306 }
12307 add_phi_arg (vphi, gimple_get_lhs (latch_defs.last ()), e,
12308 gimple_phi_arg_location (phi, e->dest_idx));
12309 }
12310 }
12311 }
12312
12313 /* Vectorize STMT_INFO if relevant, inserting any new instructions before GSI.
12314 When vectorizing STMT_INFO as a store, set *SEEN_STORE to its
12315 stmt_vec_info. */
12316
12317 static bool
12318 vect_transform_loop_stmt (loop_vec_info loop_vinfo, stmt_vec_info stmt_info,
12319 gimple_stmt_iterator *gsi, stmt_vec_info *seen_store)
12320 {
12321 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
12322 poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
12323
12324 if (dump_enabled_p ())
12325 dump_printf_loc (MSG_NOTE, vect_location,
12326 "------>vectorizing statement: %G", stmt_info->stmt);
12327
12328 if (MAY_HAVE_DEBUG_BIND_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
12329 vect_loop_kill_debug_uses (loop, stmt_info);
12330
12331 if (!STMT_VINFO_RELEVANT_P (stmt_info)
12332 && !STMT_VINFO_LIVE_P (stmt_info))
12333 {
12334 if (is_gimple_call (stmt_info->stmt)
12335 && gimple_call_internal_p (stmt_info->stmt, IFN_MASK_CALL))
12336 {
12337 gcc_assert (!gimple_call_lhs (stmt_info->stmt));
12338 *seen_store = stmt_info;
12339 return false;
12340 }
12341 return false;
12342 }
12343
12344 if (STMT_VINFO_VECTYPE (stmt_info))
12345 {
12346 poly_uint64 nunits
12347 = TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info));
12348 if (!STMT_SLP_TYPE (stmt_info)
12349 && maybe_ne (nunits, vf)
12350 && dump_enabled_p ())
12351 /* For SLP VF is set according to unrolling factor, and not
12352 to vector size, hence for SLP this print is not valid. */
12353 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
12354 }
12355
12356 /* Pure SLP statements have already been vectorized. We still need
12357 to apply loop vectorization to hybrid SLP statements. */
12358 if (PURE_SLP_STMT (stmt_info))
12359 return false;
12360
12361 if (dump_enabled_p ())
12362 dump_printf_loc (MSG_NOTE, vect_location, "transform statement.\n");
12363
12364 if (vect_transform_stmt (loop_vinfo, stmt_info, gsi, NULL, NULL))
12365 *seen_store = stmt_info;
12366
12367 return true;
12368 }
12369
12370 /* Helper function to pass to simplify_replace_tree to enable replacing tree's
12371 in the hash_map with its corresponding values. */
12372
12373 static tree
12374 find_in_mapping (tree t, void *context)
12375 {
12376 hash_map<tree,tree>* mapping = (hash_map<tree, tree>*) context;
12377
12378 tree *value = mapping->get (t);
12379 return value ? *value : t;
12380 }
12381
12382 /* Update EPILOGUE's loop_vec_info. EPILOGUE was constructed as a copy of the
12383 original loop that has now been vectorized.
12384
12385 The inits of the data_references need to be advanced with the number of
12386 iterations of the main loop. This has been computed in vect_do_peeling and
12387 is stored in parameter ADVANCE. We first restore the data_references
12388 initial offset with the values recored in ORIG_DRS_INIT.
12389
12390 Since the loop_vec_info of this EPILOGUE was constructed for the original
12391 loop, its stmt_vec_infos all point to the original statements. These need
12392 to be updated to point to their corresponding copies as well as the SSA_NAMES
12393 in their PATTERN_DEF_SEQs and RELATED_STMTs.
12394
12395 The data_reference's connections also need to be updated. Their
12396 corresponding dr_vec_info need to be reconnected to the EPILOGUE's
12397 stmt_vec_infos, their statements need to point to their corresponding copy,
12398 if they are gather loads or scatter stores then their reference needs to be
12399 updated to point to its corresponding copy. */
12400
12401 static void
12402 update_epilogue_loop_vinfo (class loop *epilogue, tree advance)
12403 {
12404 loop_vec_info epilogue_vinfo = loop_vec_info_for_loop (epilogue);
12405 auto_vec<gimple *> stmt_worklist;
12406 hash_map<tree,tree> mapping;
12407 gimple *orig_stmt, *new_stmt;
12408 gimple_stmt_iterator epilogue_gsi;
12409 gphi_iterator epilogue_phi_gsi;
12410 stmt_vec_info stmt_vinfo = NULL, related_vinfo;
12411 basic_block *epilogue_bbs = get_loop_body (epilogue);
12412 unsigned i;
12413
12414 free (LOOP_VINFO_BBS (epilogue_vinfo));
12415 LOOP_VINFO_BBS (epilogue_vinfo) = epilogue_bbs;
12416 LOOP_VINFO_NBBS (epilogue_vinfo) = epilogue->num_nodes;
12417
12418 /* The EPILOGUE loop is a copy of the original loop so they share the same
12419 gimple UIDs. In this loop we update the loop_vec_info of the EPILOGUE to
12420 point to the copied statements. We also create a mapping of all LHS' in
12421 the original loop and all the LHS' in the EPILOGUE and create worklists to
12422 update teh STMT_VINFO_PATTERN_DEF_SEQs and STMT_VINFO_RELATED_STMTs. */
12423 for (unsigned i = 0; i < epilogue->num_nodes; ++i)
12424 {
12425 for (epilogue_phi_gsi = gsi_start_phis (epilogue_bbs[i]);
12426 !gsi_end_p (epilogue_phi_gsi); gsi_next (&epilogue_phi_gsi))
12427 {
12428 new_stmt = epilogue_phi_gsi.phi ();
12429
12430 gcc_assert (gimple_uid (new_stmt) > 0);
12431 stmt_vinfo
12432 = epilogue_vinfo->stmt_vec_infos[gimple_uid (new_stmt) - 1];
12433
12434 orig_stmt = STMT_VINFO_STMT (stmt_vinfo);
12435 STMT_VINFO_STMT (stmt_vinfo) = new_stmt;
12436
12437 mapping.put (gimple_phi_result (orig_stmt),
12438 gimple_phi_result (new_stmt));
12439 /* PHI nodes can not have patterns or related statements. */
12440 gcc_assert (STMT_VINFO_PATTERN_DEF_SEQ (stmt_vinfo) == NULL
12441 && STMT_VINFO_RELATED_STMT (stmt_vinfo) == NULL);
12442 }
12443
12444 for (epilogue_gsi = gsi_start_bb (epilogue_bbs[i]);
12445 !gsi_end_p (epilogue_gsi); gsi_next (&epilogue_gsi))
12446 {
12447 new_stmt = gsi_stmt (epilogue_gsi);
12448 if (is_gimple_debug (new_stmt))
12449 continue;
12450
12451 gcc_assert (gimple_uid (new_stmt) > 0);
12452 stmt_vinfo
12453 = epilogue_vinfo->stmt_vec_infos[gimple_uid (new_stmt) - 1];
12454
12455 orig_stmt = STMT_VINFO_STMT (stmt_vinfo);
12456 STMT_VINFO_STMT (stmt_vinfo) = new_stmt;
12457
12458 if (tree old_lhs = gimple_get_lhs (orig_stmt))
12459 mapping.put (old_lhs, gimple_get_lhs (new_stmt));
12460
12461 if (STMT_VINFO_PATTERN_DEF_SEQ (stmt_vinfo))
12462 {
12463 gimple_seq seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_vinfo);
12464 for (gimple_stmt_iterator gsi = gsi_start (seq);
12465 !gsi_end_p (gsi); gsi_next (&gsi))
12466 stmt_worklist.safe_push (gsi_stmt (gsi));
12467 }
12468
12469 related_vinfo = STMT_VINFO_RELATED_STMT (stmt_vinfo);
12470 if (related_vinfo != NULL && related_vinfo != stmt_vinfo)
12471 {
12472 gimple *stmt = STMT_VINFO_STMT (related_vinfo);
12473 stmt_worklist.safe_push (stmt);
12474 /* Set BB such that the assert in
12475 'get_initial_def_for_reduction' is able to determine that
12476 the BB of the related stmt is inside this loop. */
12477 gimple_set_bb (stmt,
12478 gimple_bb (new_stmt));
12479 related_vinfo = STMT_VINFO_RELATED_STMT (related_vinfo);
12480 gcc_assert (related_vinfo == NULL
12481 || related_vinfo == stmt_vinfo);
12482 }
12483 }
12484 }
12485
12486 /* The PATTERN_DEF_SEQs and RELATED_STMTs in the epilogue were constructed
12487 using the original main loop and thus need to be updated to refer to the
12488 cloned variables used in the epilogue. */
12489 for (unsigned i = 0; i < stmt_worklist.length (); ++i)
12490 {
12491 gimple *stmt = stmt_worklist[i];
12492 tree *new_op;
12493
12494 for (unsigned j = 1; j < gimple_num_ops (stmt); ++j)
12495 {
12496 tree op = gimple_op (stmt, j);
12497 if ((new_op = mapping.get(op)))
12498 gimple_set_op (stmt, j, *new_op);
12499 else
12500 {
12501 /* PR92429: The last argument of simplify_replace_tree disables
12502 folding when replacing arguments. This is required as
12503 otherwise you might end up with different statements than the
12504 ones analyzed in vect_loop_analyze, leading to different
12505 vectorization. */
12506 op = simplify_replace_tree (op, NULL_TREE, NULL_TREE,
12507 &find_in_mapping, &mapping, false);
12508 gimple_set_op (stmt, j, op);
12509 }
12510 }
12511 }
12512
12513 struct data_reference *dr;
12514 vec<data_reference_p> datarefs = LOOP_VINFO_DATAREFS (epilogue_vinfo);
12515 FOR_EACH_VEC_ELT (datarefs, i, dr)
12516 {
12517 orig_stmt = DR_STMT (dr);
12518 gcc_assert (gimple_uid (orig_stmt) > 0);
12519 stmt_vinfo = epilogue_vinfo->stmt_vec_infos[gimple_uid (orig_stmt) - 1];
12520 /* Data references for gather loads and scatter stores do not use the
12521 updated offset we set using ADVANCE. Instead we have to make sure the
12522 reference in the data references point to the corresponding copy of
12523 the original in the epilogue. Make sure to update both
12524 gather/scatters recognized by dataref analysis and also other
12525 refs that get_load_store_type classified as VMAT_GATHER_SCATTER. */
12526 auto vstmt_vinfo = vect_stmt_to_vectorize (stmt_vinfo);
12527 if (STMT_VINFO_MEMORY_ACCESS_TYPE (vstmt_vinfo) == VMAT_GATHER_SCATTER
12528 || STMT_VINFO_STRIDED_P (vstmt_vinfo)
12529 || STMT_VINFO_GATHER_SCATTER_P (vstmt_vinfo))
12530 {
12531 /* ??? As we copy epilogues from the main loop incremental
12532 replacement from an already replaced DR_REF from vectorizing
12533 the first epilogue will fail. */
12534 DR_REF (dr)
12535 = simplify_replace_tree (DR_REF (dr), NULL_TREE, NULL_TREE,
12536 &find_in_mapping, &mapping);
12537 DR_BASE_ADDRESS (dr)
12538 = simplify_replace_tree (DR_BASE_ADDRESS (dr), NULL_TREE, NULL_TREE,
12539 &find_in_mapping, &mapping);
12540 }
12541 DR_STMT (dr) = STMT_VINFO_STMT (stmt_vinfo);
12542 }
12543
12544 /* Advance data_reference's with the number of iterations of the previous
12545 loop and its prologue. */
12546 vect_update_inits_of_drs (epilogue_vinfo, advance, PLUS_EXPR);
12547
12548 /* Remember the advancement made. */
12549 LOOP_VINFO_DRS_ADVANCED_BY (epilogue_vinfo) = advance;
12550
12551 epilogue_vinfo->shared->datarefs_copy.release ();
12552 epilogue_vinfo->shared->save_datarefs ();
12553 }
12554
12555 /* When vectorizing early break statements instructions that happen before
12556 the early break in the current BB need to be moved to after the early
12557 break. This function deals with that and assumes that any validity
12558 checks has already been performed.
12559
12560 While moving the instructions if it encounters a VUSE or VDEF it then
12561 corrects the VUSES as it moves the statements along. GDEST is the location
12562 in which to insert the new statements. */
12563
12564 static void
12565 move_early_exit_stmts (loop_vec_info loop_vinfo)
12566 {
12567 DUMP_VECT_SCOPE ("move_early_exit_stmts");
12568
12569 if (LOOP_VINFO_EARLY_BRK_STORES (loop_vinfo).is_empty ())
12570 return;
12571
12572 /* Move all stmts that need moving. */
12573 basic_block dest_bb = LOOP_VINFO_EARLY_BRK_DEST_BB (loop_vinfo);
12574 gimple_stmt_iterator dest_gsi = gsi_after_labels (dest_bb);
12575
12576 tree last_seen_vuse = NULL_TREE;
12577 for (gimple *stmt : LOOP_VINFO_EARLY_BRK_STORES (loop_vinfo))
12578 {
12579 /* We have to update crossed degenerate virtual PHIs. Simply
12580 elide them. */
12581 if (gphi *vphi = dyn_cast <gphi *> (stmt))
12582 {
12583 tree vdef = gimple_phi_result (vphi);
12584 tree vuse = gimple_phi_arg_def (vphi, 0);
12585 imm_use_iterator iter;
12586 use_operand_p use_p;
12587 gimple *use_stmt;
12588 FOR_EACH_IMM_USE_STMT (use_stmt, iter, vdef)
12589 {
12590 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
12591 SET_USE (use_p, vuse);
12592 }
12593 auto gsi = gsi_for_stmt (stmt);
12594 remove_phi_node (&gsi, true);
12595 last_seen_vuse = vuse;
12596 continue;
12597 }
12598
12599 /* Check to see if statement is still required for vect or has been
12600 elided. */
12601 auto stmt_info = loop_vinfo->lookup_stmt (stmt);
12602 if (!stmt_info)
12603 continue;
12604
12605 if (dump_enabled_p ())
12606 dump_printf_loc (MSG_NOTE, vect_location, "moving stmt %G", stmt);
12607
12608 gimple_stmt_iterator stmt_gsi = gsi_for_stmt (stmt);
12609 gsi_move_before (&stmt_gsi, &dest_gsi, GSI_NEW_STMT);
12610 last_seen_vuse = gimple_vuse (stmt);
12611 }
12612
12613 /* Update all the stmts with their new reaching VUSES. */
12614 for (auto p : LOOP_VINFO_EARLY_BRK_VUSES (loop_vinfo))
12615 {
12616 if (dump_enabled_p ())
12617 dump_printf_loc (MSG_NOTE, vect_location,
12618 "updating vuse to %T for load %G",
12619 last_seen_vuse, p);
12620 gimple_set_vuse (p, last_seen_vuse);
12621 update_stmt (p);
12622 }
12623
12624 /* And update the LC PHIs on exits. */
12625 for (edge e : get_loop_exit_edges (LOOP_VINFO_LOOP (loop_vinfo)))
12626 if (!dominated_by_p (CDI_DOMINATORS, e->src, dest_bb))
12627 if (gphi *phi = get_virtual_phi (e->dest))
12628 SET_PHI_ARG_DEF_ON_EDGE (phi, e, last_seen_vuse);
12629 }
12630
12631 /* Function vect_transform_loop.
12632
12633 The analysis phase has determined that the loop is vectorizable.
12634 Vectorize the loop - created vectorized stmts to replace the scalar
12635 stmts in the loop, and update the loop exit condition.
12636 Returns scalar epilogue loop if any. */
12637
12638 class loop *
12639 vect_transform_loop (loop_vec_info loop_vinfo, gimple *loop_vectorized_call)
12640 {
12641 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
12642 class loop *epilogue = NULL;
12643 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
12644 int nbbs = loop->num_nodes;
12645 int i;
12646 tree niters_vector = NULL_TREE;
12647 tree step_vector = NULL_TREE;
12648 tree niters_vector_mult_vf = NULL_TREE;
12649 poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
12650 unsigned int lowest_vf = constant_lower_bound (vf);
12651 gimple *stmt;
12652 bool check_profitability = false;
12653 unsigned int th;
12654 bool flat = maybe_flat_loop_profile (loop);
12655
12656 DUMP_VECT_SCOPE ("vec_transform_loop");
12657
12658 loop_vinfo->shared->check_datarefs ();
12659
12660 /* Use the more conservative vectorization threshold. If the number
12661 of iterations is constant assume the cost check has been performed
12662 by our caller. If the threshold makes all loops profitable that
12663 run at least the (estimated) vectorization factor number of times
12664 checking is pointless, too. */
12665 th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
12666 if (vect_apply_runtime_profitability_check_p (loop_vinfo))
12667 {
12668 if (dump_enabled_p ())
12669 dump_printf_loc (MSG_NOTE, vect_location,
12670 "Profitability threshold is %d loop iterations.\n",
12671 th);
12672 check_profitability = true;
12673 }
12674
12675 /* Make sure there exists a single-predecessor exit bb. Do this before
12676 versioning. */
12677 edge e = LOOP_VINFO_IV_EXIT (loop_vinfo);
12678 if (! single_pred_p (e->dest) && !LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
12679 {
12680 split_loop_exit_edge (e, true);
12681 if (dump_enabled_p ())
12682 dump_printf (MSG_NOTE, "split exit edge\n");
12683 }
12684
12685 /* Version the loop first, if required, so the profitability check
12686 comes first. */
12687
12688 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
12689 {
12690 class loop *sloop
12691 = vect_loop_versioning (loop_vinfo, loop_vectorized_call);
12692 sloop->force_vectorize = false;
12693 check_profitability = false;
12694 }
12695
12696 /* Make sure there exists a single-predecessor exit bb also on the
12697 scalar loop copy. Do this after versioning but before peeling
12698 so CFG structure is fine for both scalar and if-converted loop
12699 to make slpeel_duplicate_current_defs_from_edges face matched
12700 loop closed PHI nodes on the exit. */
12701 if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))
12702 {
12703 e = LOOP_VINFO_SCALAR_IV_EXIT (loop_vinfo);
12704 if (! single_pred_p (e->dest))
12705 {
12706 split_loop_exit_edge (e, true);
12707 if (dump_enabled_p ())
12708 dump_printf (MSG_NOTE, "split exit edge of scalar loop\n");
12709 }
12710 }
12711
12712 tree niters = vect_build_loop_niters (loop_vinfo);
12713 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = niters;
12714 tree nitersm1 = unshare_expr (LOOP_VINFO_NITERSM1 (loop_vinfo));
12715 bool niters_no_overflow = loop_niters_no_overflow (loop_vinfo);
12716 tree advance;
12717 drs_init_vec orig_drs_init;
12718
12719 epilogue = vect_do_peeling (loop_vinfo, niters, nitersm1, &niters_vector,
12720 &step_vector, &niters_vector_mult_vf, th,
12721 check_profitability, niters_no_overflow,
12722 &advance);
12723 if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo)
12724 && LOOP_VINFO_SCALAR_LOOP_SCALING (loop_vinfo).initialized_p ())
12725 {
12726 /* Ifcvt duplicates loop preheader, loop body and produces an basic
12727 block after loop exit. We need to scale all that. */
12728 basic_block preheader
12729 = loop_preheader_edge (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))->src;
12730 preheader->count
12731 = preheader->count.apply_probability
12732 (LOOP_VINFO_SCALAR_LOOP_SCALING (loop_vinfo));
12733 scale_loop_frequencies (LOOP_VINFO_SCALAR_LOOP (loop_vinfo),
12734 LOOP_VINFO_SCALAR_LOOP_SCALING (loop_vinfo));
12735 LOOP_VINFO_SCALAR_IV_EXIT (loop_vinfo)->dest->count = preheader->count;
12736 }
12737
12738 if (niters_vector == NULL_TREE)
12739 {
12740 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
12741 && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
12742 && known_eq (lowest_vf, vf))
12743 {
12744 niters_vector
12745 = build_int_cst (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)),
12746 LOOP_VINFO_INT_NITERS (loop_vinfo) / lowest_vf);
12747 step_vector = build_one_cst (TREE_TYPE (niters));
12748 }
12749 else if (vect_use_loop_mask_for_alignment_p (loop_vinfo))
12750 vect_gen_vector_loop_niters (loop_vinfo, niters, &niters_vector,
12751 &step_vector, niters_no_overflow);
12752 else
12753 /* vect_do_peeling subtracted the number of peeled prologue
12754 iterations from LOOP_VINFO_NITERS. */
12755 vect_gen_vector_loop_niters (loop_vinfo, LOOP_VINFO_NITERS (loop_vinfo),
12756 &niters_vector, &step_vector,
12757 niters_no_overflow);
12758 }
12759
12760 /* 1) Make sure the loop header has exactly two entries
12761 2) Make sure we have a preheader basic block. */
12762
12763 gcc_assert (EDGE_COUNT (loop->header->preds) == 2);
12764
12765 split_edge (loop_preheader_edge (loop));
12766
12767 if (vect_use_loop_mask_for_alignment_p (loop_vinfo))
12768 /* This will deal with any possible peeling. */
12769 vect_prepare_for_masked_peels (loop_vinfo);
12770
12771 /* Handle any code motion that we need to for early-break vectorization after
12772 we've done peeling but just before we start vectorizing. */
12773 if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
12774 move_early_exit_stmts (loop_vinfo);
12775
12776 /* Remove existing clobber stmts and prefetches. */
12777 for (i = 0; i < nbbs; i++)
12778 {
12779 basic_block bb = bbs[i];
12780 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);)
12781 {
12782 stmt = gsi_stmt (si);
12783 if (gimple_clobber_p (stmt)
12784 || gimple_call_builtin_p (stmt, BUILT_IN_PREFETCH))
12785 {
12786 unlink_stmt_vdef (stmt);
12787 gsi_remove (&si, true);
12788 release_defs (stmt);
12789 }
12790 else
12791 gsi_next (&si);
12792 }
12793 }
12794
12795 /* Schedule the SLP instances first, then handle loop vectorization
12796 below. */
12797 if (!loop_vinfo->slp_instances.is_empty ())
12798 {
12799 DUMP_VECT_SCOPE ("scheduling SLP instances");
12800 vect_schedule_slp (loop_vinfo, LOOP_VINFO_SLP_INSTANCES (loop_vinfo));
12801 }
12802
12803 /* Generate the loop invariant statements. */
12804 if (!gimple_seq_empty_p (LOOP_VINFO_INV_PATTERN_DEF_SEQ (loop_vinfo)))
12805 {
12806 if (dump_enabled_p ())
12807 dump_printf_loc (MSG_NOTE, vect_location,
12808 "------>generating loop invariant statements\n");
12809 gimple_stmt_iterator gsi;
12810 gsi = gsi_after_labels (loop_preheader_edge (loop)->src);
12811 gsi_insert_seq_before (&gsi, LOOP_VINFO_INV_PATTERN_DEF_SEQ (loop_vinfo),
12812 GSI_CONTINUE_LINKING);
12813 }
12814
12815 /* FORNOW: the vectorizer supports only loops which body consist
12816 of one basic block (header + empty latch). When the vectorizer will
12817 support more involved loop forms, the order by which the BBs are
12818 traversed need to be reconsidered. */
12819
12820 for (i = 0; i < nbbs; i++)
12821 {
12822 basic_block bb = bbs[i];
12823 stmt_vec_info stmt_info;
12824
12825 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
12826 gsi_next (&si))
12827 {
12828 gphi *phi = si.phi ();
12829 if (dump_enabled_p ())
12830 dump_printf_loc (MSG_NOTE, vect_location,
12831 "------>vectorizing phi: %G", (gimple *) phi);
12832 stmt_info = loop_vinfo->lookup_stmt (phi);
12833 if (!stmt_info)
12834 continue;
12835
12836 if (MAY_HAVE_DEBUG_BIND_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
12837 vect_loop_kill_debug_uses (loop, stmt_info);
12838
12839 if (!STMT_VINFO_RELEVANT_P (stmt_info)
12840 && !STMT_VINFO_LIVE_P (stmt_info))
12841 continue;
12842
12843 if (STMT_VINFO_VECTYPE (stmt_info)
12844 && (maybe_ne
12845 (TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info)), vf))
12846 && dump_enabled_p ())
12847 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
12848
12849 if ((STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def
12850 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
12851 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def
12852 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle
12853 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_first_order_recurrence
12854 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_internal_def)
12855 && ! PURE_SLP_STMT (stmt_info))
12856 {
12857 if (dump_enabled_p ())
12858 dump_printf_loc (MSG_NOTE, vect_location, "transform phi.\n");
12859 vect_transform_stmt (loop_vinfo, stmt_info, NULL, NULL, NULL);
12860 }
12861 }
12862
12863 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
12864 gsi_next (&si))
12865 {
12866 gphi *phi = si.phi ();
12867 stmt_info = loop_vinfo->lookup_stmt (phi);
12868 if (!stmt_info)
12869 continue;
12870
12871 if (!STMT_VINFO_RELEVANT_P (stmt_info)
12872 && !STMT_VINFO_LIVE_P (stmt_info))
12873 continue;
12874
12875 if ((STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def
12876 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
12877 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def
12878 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle
12879 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_internal_def
12880 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_first_order_recurrence)
12881 && ! PURE_SLP_STMT (stmt_info))
12882 maybe_set_vectorized_backedge_value (loop_vinfo, stmt_info);
12883 }
12884
12885 for (gimple_stmt_iterator si = gsi_start_bb (bb);
12886 !gsi_end_p (si);)
12887 {
12888 stmt = gsi_stmt (si);
12889
12890 /* Ignore vector stmts created in the outer loop. */
12891 stmt_info = loop_vinfo->lookup_stmt (stmt);
12892
12893 /* vector stmts created in the outer-loop during vectorization of
12894 stmts in an inner-loop may not have a stmt_info, and do not
12895 need to be vectorized. */
12896 stmt_vec_info seen_store = NULL;
12897 if (stmt_info)
12898 {
12899 if (STMT_VINFO_IN_PATTERN_P (stmt_info))
12900 {
12901 gimple *def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
12902 for (gimple_stmt_iterator subsi = gsi_start (def_seq);
12903 !gsi_end_p (subsi); gsi_next (&subsi))
12904 {
12905 stmt_vec_info pat_stmt_info
12906 = loop_vinfo->lookup_stmt (gsi_stmt (subsi));
12907 vect_transform_loop_stmt (loop_vinfo, pat_stmt_info,
12908 &si, &seen_store);
12909 }
12910 stmt_vec_info pat_stmt_info
12911 = STMT_VINFO_RELATED_STMT (stmt_info);
12912 if (vect_transform_loop_stmt (loop_vinfo, pat_stmt_info,
12913 &si, &seen_store))
12914 maybe_set_vectorized_backedge_value (loop_vinfo,
12915 pat_stmt_info);
12916 }
12917 else
12918 {
12919 if (vect_transform_loop_stmt (loop_vinfo, stmt_info, &si,
12920 &seen_store))
12921 maybe_set_vectorized_backedge_value (loop_vinfo,
12922 stmt_info);
12923 }
12924 }
12925 gsi_next (&si);
12926 if (seen_store)
12927 {
12928 if (STMT_VINFO_GROUPED_ACCESS (seen_store))
12929 /* Interleaving. If IS_STORE is TRUE, the
12930 vectorization of the interleaving chain was
12931 completed - free all the stores in the chain. */
12932 vect_remove_stores (loop_vinfo,
12933 DR_GROUP_FIRST_ELEMENT (seen_store));
12934 else
12935 /* Free the attached stmt_vec_info and remove the stmt. */
12936 loop_vinfo->remove_stmt (stmt_info);
12937 }
12938 }
12939
12940 /* Stub out scalar statements that must not survive vectorization.
12941 Doing this here helps with grouped statements, or statements that
12942 are involved in patterns. */
12943 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
12944 !gsi_end_p (gsi); gsi_next (&gsi))
12945 {
12946 gcall *call = dyn_cast <gcall *> (gsi_stmt (gsi));
12947 if (!call || !gimple_call_internal_p (call))
12948 continue;
12949 internal_fn ifn = gimple_call_internal_fn (call);
12950 if (ifn == IFN_MASK_LOAD)
12951 {
12952 tree lhs = gimple_get_lhs (call);
12953 if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
12954 {
12955 tree zero = build_zero_cst (TREE_TYPE (lhs));
12956 gimple *new_stmt = gimple_build_assign (lhs, zero);
12957 gsi_replace (&gsi, new_stmt, true);
12958 }
12959 }
12960 else if (conditional_internal_fn_code (ifn) != ERROR_MARK)
12961 {
12962 tree lhs = gimple_get_lhs (call);
12963 if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
12964 {
12965 tree else_arg
12966 = gimple_call_arg (call, gimple_call_num_args (call) - 1);
12967 gimple *new_stmt = gimple_build_assign (lhs, else_arg);
12968 gsi_replace (&gsi, new_stmt, true);
12969 }
12970 }
12971 }
12972 } /* BBs in loop */
12973
12974 /* The vectorization factor is always > 1, so if we use an IV increment of 1.
12975 a zero NITERS becomes a nonzero NITERS_VECTOR. */
12976 if (integer_onep (step_vector))
12977 niters_no_overflow = true;
12978 vect_set_loop_condition (loop, LOOP_VINFO_IV_EXIT (loop_vinfo), loop_vinfo,
12979 niters_vector, step_vector, niters_vector_mult_vf,
12980 !niters_no_overflow);
12981
12982 unsigned int assumed_vf = vect_vf_for_cost (loop_vinfo);
12983
12984 /* True if the final iteration might not handle a full vector's
12985 worth of scalar iterations. */
12986 bool final_iter_may_be_partial
12987 = LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
12988 || LOOP_VINFO_EARLY_BREAKS (loop_vinfo);
12989
12990 /* +1 to convert latch counts to loop iteration counts. */
12991 int bias_for_lowest = 1;
12992
12993 /* When we are peeling for gaps then we take away one scalar iteration
12994 from the vector loop. Thus we can adjust the upper bound by one
12995 scalar iteration. But only when we know the bound applies to the
12996 IV exit test which might not be true when we have multiple exits. */
12997 if (!LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
12998 bias_for_lowest -= LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) ? 1 : 0;
12999
13000 int bias_for_assumed = bias_for_lowest;
13001 int alignment_npeels = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
13002 if (alignment_npeels && LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
13003 {
13004 /* When the amount of peeling is known at compile time, the first
13005 iteration will have exactly alignment_npeels active elements.
13006 In the worst case it will have at least one. */
13007 int min_first_active = (alignment_npeels > 0 ? alignment_npeels : 1);
13008 bias_for_lowest += lowest_vf - min_first_active;
13009 bias_for_assumed += assumed_vf - min_first_active;
13010 }
13011 /* In these calculations the "- 1" converts loop iteration counts
13012 back to latch counts. */
13013 if (loop->any_upper_bound)
13014 {
13015 loop_vec_info main_vinfo = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
13016 loop->nb_iterations_upper_bound
13017 = (final_iter_may_be_partial
13018 ? wi::udiv_ceil (loop->nb_iterations_upper_bound + bias_for_lowest,
13019 lowest_vf) - 1
13020 : wi::udiv_floor (loop->nb_iterations_upper_bound + bias_for_lowest,
13021 lowest_vf) - 1);
13022 if (main_vinfo
13023 /* Both peeling for alignment and peeling for gaps can end up
13024 with the scalar epilogue running for more than VF-1 iterations. */
13025 && !main_vinfo->peeling_for_alignment
13026 && !main_vinfo->peeling_for_gaps)
13027 {
13028 unsigned int bound;
13029 poly_uint64 main_iters
13030 = upper_bound (LOOP_VINFO_VECT_FACTOR (main_vinfo),
13031 LOOP_VINFO_COST_MODEL_THRESHOLD (main_vinfo));
13032 main_iters
13033 = upper_bound (main_iters,
13034 LOOP_VINFO_VERSIONING_THRESHOLD (main_vinfo));
13035 if (can_div_away_from_zero_p (main_iters,
13036 LOOP_VINFO_VECT_FACTOR (loop_vinfo),
13037 &bound))
13038 loop->nb_iterations_upper_bound
13039 = wi::umin ((bound_wide_int) (bound - 1),
13040 loop->nb_iterations_upper_bound);
13041 }
13042 }
13043 if (loop->any_likely_upper_bound)
13044 loop->nb_iterations_likely_upper_bound
13045 = (final_iter_may_be_partial
13046 ? wi::udiv_ceil (loop->nb_iterations_likely_upper_bound
13047 + bias_for_lowest, lowest_vf) - 1
13048 : wi::udiv_floor (loop->nb_iterations_likely_upper_bound
13049 + bias_for_lowest, lowest_vf) - 1);
13050 if (loop->any_estimate)
13051 loop->nb_iterations_estimate
13052 = (final_iter_may_be_partial
13053 ? wi::udiv_ceil (loop->nb_iterations_estimate + bias_for_assumed,
13054 assumed_vf) - 1
13055 : wi::udiv_floor (loop->nb_iterations_estimate + bias_for_assumed,
13056 assumed_vf) - 1);
13057 scale_profile_for_vect_loop (loop, LOOP_VINFO_IV_EXIT (loop_vinfo),
13058 assumed_vf, flat);
13059
13060 if (dump_enabled_p ())
13061 {
13062 if (!LOOP_VINFO_EPILOGUE_P (loop_vinfo))
13063 {
13064 dump_printf_loc (MSG_NOTE, vect_location,
13065 "LOOP VECTORIZED\n");
13066 if (loop->inner)
13067 dump_printf_loc (MSG_NOTE, vect_location,
13068 "OUTER LOOP VECTORIZED\n");
13069 dump_printf (MSG_NOTE, "\n");
13070 }
13071 else
13072 dump_printf_loc (MSG_NOTE, vect_location,
13073 "LOOP EPILOGUE VECTORIZED (MODE=%s)\n",
13074 GET_MODE_NAME (loop_vinfo->vector_mode));
13075 }
13076
13077 /* Loops vectorized with a variable factor won't benefit from
13078 unrolling/peeling. */
13079 if (!vf.is_constant ())
13080 {
13081 loop->unroll = 1;
13082 if (dump_enabled_p ())
13083 dump_printf_loc (MSG_NOTE, vect_location, "Disabling unrolling due to"
13084 " variable-length vectorization factor\n");
13085 }
13086 /* Free SLP instances here because otherwise stmt reference counting
13087 won't work. */
13088 slp_instance instance;
13089 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
13090 vect_free_slp_instance (instance);
13091 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
13092 /* Clear-up safelen field since its value is invalid after vectorization
13093 since vectorized loop can have loop-carried dependencies. */
13094 loop->safelen = 0;
13095
13096 if (epilogue)
13097 {
13098 /* Accumulate past advancements made. */
13099 if (LOOP_VINFO_DRS_ADVANCED_BY (loop_vinfo))
13100 advance = fold_build2 (PLUS_EXPR, TREE_TYPE (advance),
13101 LOOP_VINFO_DRS_ADVANCED_BY (loop_vinfo),
13102 advance);
13103 update_epilogue_loop_vinfo (epilogue, advance);
13104
13105 epilogue->simduid = loop->simduid;
13106 epilogue->force_vectorize = loop->force_vectorize;
13107 epilogue->dont_vectorize = false;
13108 }
13109
13110 return epilogue;
13111 }
13112
13113 /* The code below is trying to perform simple optimization - revert
13114 if-conversion for masked stores, i.e. if the mask of a store is zero
13115 do not perform it and all stored value producers also if possible.
13116 For example,
13117 for (i=0; i<n; i++)
13118 if (c[i])
13119 {
13120 p1[i] += 1;
13121 p2[i] = p3[i] +2;
13122 }
13123 this transformation will produce the following semi-hammock:
13124
13125 if (!mask__ifc__42.18_165 == { 0, 0, 0, 0, 0, 0, 0, 0 })
13126 {
13127 vect__11.19_170 = MASK_LOAD (vectp_p1.20_168, 0B, mask__ifc__42.18_165);
13128 vect__12.22_172 = vect__11.19_170 + vect_cst__171;
13129 MASK_STORE (vectp_p1.23_175, 0B, mask__ifc__42.18_165, vect__12.22_172);
13130 vect__18.25_182 = MASK_LOAD (vectp_p3.26_180, 0B, mask__ifc__42.18_165);
13131 vect__19.28_184 = vect__18.25_182 + vect_cst__183;
13132 MASK_STORE (vectp_p2.29_187, 0B, mask__ifc__42.18_165, vect__19.28_184);
13133 }
13134 */
13135
13136 void
13137 optimize_mask_stores (class loop *loop)
13138 {
13139 basic_block *bbs = get_loop_body (loop);
13140 unsigned nbbs = loop->num_nodes;
13141 unsigned i;
13142 basic_block bb;
13143 class loop *bb_loop;
13144 gimple_stmt_iterator gsi;
13145 gimple *stmt;
13146 auto_vec<gimple *> worklist;
13147 auto_purge_vect_location sentinel;
13148
13149 vect_location = find_loop_location (loop);
13150 /* Pick up all masked stores in loop if any. */
13151 for (i = 0; i < nbbs; i++)
13152 {
13153 bb = bbs[i];
13154 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
13155 gsi_next (&gsi))
13156 {
13157 stmt = gsi_stmt (gsi);
13158 if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
13159 worklist.safe_push (stmt);
13160 }
13161 }
13162
13163 free (bbs);
13164 if (worklist.is_empty ())
13165 return;
13166
13167 /* Loop has masked stores. */
13168 while (!worklist.is_empty ())
13169 {
13170 gimple *last, *last_store;
13171 edge e, efalse;
13172 tree mask;
13173 basic_block store_bb, join_bb;
13174 gimple_stmt_iterator gsi_to;
13175 tree vdef, new_vdef;
13176 gphi *phi;
13177 tree vectype;
13178 tree zero;
13179
13180 last = worklist.pop ();
13181 mask = gimple_call_arg (last, 2);
13182 bb = gimple_bb (last);
13183 /* Create then_bb and if-then structure in CFG, then_bb belongs to
13184 the same loop as if_bb. It could be different to LOOP when two
13185 level loop-nest is vectorized and mask_store belongs to the inner
13186 one. */
13187 e = split_block (bb, last);
13188 bb_loop = bb->loop_father;
13189 gcc_assert (loop == bb_loop || flow_loop_nested_p (loop, bb_loop));
13190 join_bb = e->dest;
13191 store_bb = create_empty_bb (bb);
13192 add_bb_to_loop (store_bb, bb_loop);
13193 e->flags = EDGE_TRUE_VALUE;
13194 efalse = make_edge (bb, store_bb, EDGE_FALSE_VALUE);
13195 /* Put STORE_BB to likely part. */
13196 efalse->probability = profile_probability::likely ();
13197 e->probability = efalse->probability.invert ();
13198 store_bb->count = efalse->count ();
13199 make_single_succ_edge (store_bb, join_bb, EDGE_FALLTHRU);
13200 if (dom_info_available_p (CDI_DOMINATORS))
13201 set_immediate_dominator (CDI_DOMINATORS, store_bb, bb);
13202 if (dump_enabled_p ())
13203 dump_printf_loc (MSG_NOTE, vect_location,
13204 "Create new block %d to sink mask stores.",
13205 store_bb->index);
13206 /* Create vector comparison with boolean result. */
13207 vectype = TREE_TYPE (mask);
13208 zero = build_zero_cst (vectype);
13209 stmt = gimple_build_cond (EQ_EXPR, mask, zero, NULL_TREE, NULL_TREE);
13210 gsi = gsi_last_bb (bb);
13211 gsi_insert_after (&gsi, stmt, GSI_SAME_STMT);
13212 /* Create new PHI node for vdef of the last masked store:
13213 .MEM_2 = VDEF <.MEM_1>
13214 will be converted to
13215 .MEM.3 = VDEF <.MEM_1>
13216 and new PHI node will be created in join bb
13217 .MEM_2 = PHI <.MEM_1, .MEM_3>
13218 */
13219 vdef = gimple_vdef (last);
13220 new_vdef = make_ssa_name (gimple_vop (cfun), last);
13221 gimple_set_vdef (last, new_vdef);
13222 phi = create_phi_node (vdef, join_bb);
13223 add_phi_arg (phi, new_vdef, EDGE_SUCC (store_bb, 0), UNKNOWN_LOCATION);
13224
13225 /* Put all masked stores with the same mask to STORE_BB if possible. */
13226 while (true)
13227 {
13228 gimple_stmt_iterator gsi_from;
13229 gimple *stmt1 = NULL;
13230
13231 /* Move masked store to STORE_BB. */
13232 last_store = last;
13233 gsi = gsi_for_stmt (last);
13234 gsi_from = gsi;
13235 /* Shift GSI to the previous stmt for further traversal. */
13236 gsi_prev (&gsi);
13237 gsi_to = gsi_start_bb (store_bb);
13238 gsi_move_before (&gsi_from, &gsi_to);
13239 /* Setup GSI_TO to the non-empty block start. */
13240 gsi_to = gsi_start_bb (store_bb);
13241 if (dump_enabled_p ())
13242 dump_printf_loc (MSG_NOTE, vect_location,
13243 "Move stmt to created bb\n%G", last);
13244 /* Move all stored value producers if possible. */
13245 while (!gsi_end_p (gsi))
13246 {
13247 tree lhs;
13248 imm_use_iterator imm_iter;
13249 use_operand_p use_p;
13250 bool res;
13251
13252 /* Skip debug statements. */
13253 if (is_gimple_debug (gsi_stmt (gsi)))
13254 {
13255 gsi_prev (&gsi);
13256 continue;
13257 }
13258 stmt1 = gsi_stmt (gsi);
13259 /* Do not consider statements writing to memory or having
13260 volatile operand. */
13261 if (gimple_vdef (stmt1)
13262 || gimple_has_volatile_ops (stmt1))
13263 break;
13264 gsi_from = gsi;
13265 gsi_prev (&gsi);
13266 lhs = gimple_get_lhs (stmt1);
13267 if (!lhs)
13268 break;
13269
13270 /* LHS of vectorized stmt must be SSA_NAME. */
13271 if (TREE_CODE (lhs) != SSA_NAME)
13272 break;
13273
13274 if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
13275 {
13276 /* Remove dead scalar statement. */
13277 if (has_zero_uses (lhs))
13278 {
13279 gsi_remove (&gsi_from, true);
13280 release_defs (stmt1);
13281 continue;
13282 }
13283 }
13284
13285 /* Check that LHS does not have uses outside of STORE_BB. */
13286 res = true;
13287 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
13288 {
13289 gimple *use_stmt;
13290 use_stmt = USE_STMT (use_p);
13291 if (is_gimple_debug (use_stmt))
13292 continue;
13293 if (gimple_bb (use_stmt) != store_bb)
13294 {
13295 res = false;
13296 break;
13297 }
13298 }
13299 if (!res)
13300 break;
13301
13302 if (gimple_vuse (stmt1)
13303 && gimple_vuse (stmt1) != gimple_vuse (last_store))
13304 break;
13305
13306 /* Can move STMT1 to STORE_BB. */
13307 if (dump_enabled_p ())
13308 dump_printf_loc (MSG_NOTE, vect_location,
13309 "Move stmt to created bb\n%G", stmt1);
13310 gsi_move_before (&gsi_from, &gsi_to);
13311 /* Shift GSI_TO for further insertion. */
13312 gsi_prev (&gsi_to);
13313 }
13314 /* Put other masked stores with the same mask to STORE_BB. */
13315 if (worklist.is_empty ()
13316 || gimple_call_arg (worklist.last (), 2) != mask
13317 || worklist.last () != stmt1)
13318 break;
13319 last = worklist.pop ();
13320 }
13321 add_phi_arg (phi, gimple_vuse (last_store), e, UNKNOWN_LOCATION);
13322 }
13323 }
13324
13325 /* Decide whether it is possible to use a zero-based induction variable
13326 when vectorizing LOOP_VINFO with partial vectors. If it is, return
13327 the value that the induction variable must be able to hold in order
13328 to ensure that the rgroups eventually have no active vector elements.
13329 Return -1 otherwise. */
13330
13331 widest_int
13332 vect_iv_limit_for_partial_vectors (loop_vec_info loop_vinfo)
13333 {
13334 tree niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
13335 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
13336 unsigned HOST_WIDE_INT max_vf = vect_max_vf (loop_vinfo);
13337
13338 /* Calculate the value that the induction variable must be able
13339 to hit in order to ensure that we end the loop with an all-false mask.
13340 This involves adding the maximum number of inactive trailing scalar
13341 iterations. */
13342 widest_int iv_limit = -1;
13343 if (max_loop_iterations (loop, &iv_limit))
13344 {
13345 if (niters_skip)
13346 {
13347 /* Add the maximum number of skipped iterations to the
13348 maximum iteration count. */
13349 if (TREE_CODE (niters_skip) == INTEGER_CST)
13350 iv_limit += wi::to_widest (niters_skip);
13351 else
13352 iv_limit += max_vf - 1;
13353 }
13354 else if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo))
13355 /* Make a conservatively-correct assumption. */
13356 iv_limit += max_vf - 1;
13357
13358 /* IV_LIMIT is the maximum number of latch iterations, which is also
13359 the maximum in-range IV value. Round this value down to the previous
13360 vector alignment boundary and then add an extra full iteration. */
13361 poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
13362 iv_limit = (iv_limit & -(int) known_alignment (vf)) + max_vf;
13363 }
13364 return iv_limit;
13365 }
13366
13367 /* For the given rgroup_controls RGC, check whether an induction variable
13368 would ever hit a value that produces a set of all-false masks or zero
13369 lengths before wrapping around. Return true if it's possible to wrap
13370 around before hitting the desirable value, otherwise return false. */
13371
13372 bool
13373 vect_rgroup_iv_might_wrap_p (loop_vec_info loop_vinfo, rgroup_controls *rgc)
13374 {
13375 widest_int iv_limit = vect_iv_limit_for_partial_vectors (loop_vinfo);
13376
13377 if (iv_limit == -1)
13378 return true;
13379
13380 tree compare_type = LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo);
13381 unsigned int compare_precision = TYPE_PRECISION (compare_type);
13382 unsigned nitems = rgc->max_nscalars_per_iter * rgc->factor;
13383
13384 if (wi::min_precision (iv_limit * nitems, UNSIGNED) > compare_precision)
13385 return true;
13386
13387 return false;
13388 }