[ree] PR rtl-optimization/78038: Handle global register dataflow definitions in ree
[official-gcc.git] / gcc / tree-vect-loop.c
blob9cca9b717a6990042190f9a49e97cfa8cd94af44
1 /* Loop Vectorization
2 Copyright (C) 2003-2016 Free Software Foundation, Inc.
3 Contributed by Dorit Naishlos <dorit@il.ibm.com> and
4 Ira Rosen <irar@il.ibm.com>
6 This file is part of GCC.
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.
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.
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/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "backend.h"
26 #include "target.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "gimple.h"
30 #include "cfghooks.h"
31 #include "tree-pass.h"
32 #include "ssa.h"
33 #include "optabs-tree.h"
34 #include "diagnostic-core.h"
35 #include "fold-const.h"
36 #include "stor-layout.h"
37 #include "cfganal.h"
38 #include "gimplify.h"
39 #include "gimple-iterator.h"
40 #include "gimplify-me.h"
41 #include "tree-ssa-loop-ivopts.h"
42 #include "tree-ssa-loop-manip.h"
43 #include "tree-ssa-loop-niter.h"
44 #include "tree-ssa-loop.h"
45 #include "cfgloop.h"
46 #include "params.h"
47 #include "tree-scalar-evolution.h"
48 #include "tree-vectorizer.h"
49 #include "gimple-fold.h"
50 #include "cgraph.h"
51 #include "tree-cfg.h"
53 /* Loop Vectorization Pass.
55 This pass tries to vectorize loops.
57 For example, the vectorizer transforms the following simple loop:
59 short a[N]; short b[N]; short c[N]; int i;
61 for (i=0; i<N; i++){
62 a[i] = b[i] + c[i];
65 as if it was manually vectorized by rewriting the source code into:
67 typedef int __attribute__((mode(V8HI))) v8hi;
68 short a[N]; short b[N]; short c[N]; int i;
69 v8hi *pa = (v8hi*)a, *pb = (v8hi*)b, *pc = (v8hi*)c;
70 v8hi va, vb, vc;
72 for (i=0; i<N/8; i++){
73 vb = pb[i];
74 vc = pc[i];
75 va = vb + vc;
76 pa[i] = va;
79 The main entry to this pass is vectorize_loops(), in which
80 the vectorizer applies a set of analyses on a given set of loops,
81 followed by the actual vectorization transformation for the loops that
82 had successfully passed the analysis phase.
83 Throughout this pass we make a distinction between two types of
84 data: scalars (which are represented by SSA_NAMES), and memory references
85 ("data-refs"). These two types of data require different handling both
86 during analysis and transformation. The types of data-refs that the
87 vectorizer currently supports are ARRAY_REFS which base is an array DECL
88 (not a pointer), and INDIRECT_REFS through pointers; both array and pointer
89 accesses are required to have a simple (consecutive) access pattern.
91 Analysis phase:
92 ===============
93 The driver for the analysis phase is vect_analyze_loop().
94 It applies a set of analyses, some of which rely on the scalar evolution
95 analyzer (scev) developed by Sebastian Pop.
97 During the analysis phase the vectorizer records some information
98 per stmt in a "stmt_vec_info" struct which is attached to each stmt in the
99 loop, as well as general information about the loop as a whole, which is
100 recorded in a "loop_vec_info" struct attached to each loop.
102 Transformation phase:
103 =====================
104 The loop transformation phase scans all the stmts in the loop, and
105 creates a vector stmt (or a sequence of stmts) for each scalar stmt S in
106 the loop that needs to be vectorized. It inserts the vector code sequence
107 just before the scalar stmt S, and records a pointer to the vector code
108 in STMT_VINFO_VEC_STMT (stmt_info) (stmt_info is the stmt_vec_info struct
109 attached to S). This pointer will be used for the vectorization of following
110 stmts which use the def of stmt S. Stmt S is removed if it writes to memory;
111 otherwise, we rely on dead code elimination for removing it.
113 For example, say stmt S1 was vectorized into stmt VS1:
115 VS1: vb = px[i];
116 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
117 S2: a = b;
119 To vectorize stmt S2, the vectorizer first finds the stmt that defines
120 the operand 'b' (S1), and gets the relevant vector def 'vb' from the
121 vector stmt VS1 pointed to by STMT_VINFO_VEC_STMT (stmt_info (S1)). The
122 resulting sequence would be:
124 VS1: vb = px[i];
125 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
126 VS2: va = vb;
127 S2: a = b; STMT_VINFO_VEC_STMT (stmt_info (S2)) = VS2
129 Operands that are not SSA_NAMEs, are data-refs that appear in
130 load/store operations (like 'x[i]' in S1), and are handled differently.
132 Target modeling:
133 =================
134 Currently the only target specific information that is used is the
135 size of the vector (in bytes) - "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD".
136 Targets that can support different sizes of vectors, for now will need
137 to specify one value for "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD". More
138 flexibility will be added in the future.
140 Since we only vectorize operations which vector form can be
141 expressed using existing tree codes, to verify that an operation is
142 supported, the vectorizer checks the relevant optab at the relevant
143 machine_mode (e.g, optab_handler (add_optab, V8HImode)). If
144 the value found is CODE_FOR_nothing, then there's no target support, and
145 we can't vectorize the stmt.
147 For additional information on this project see:
148 http://gcc.gnu.org/projects/tree-ssa/vectorization.html
151 static void vect_estimate_min_profitable_iters (loop_vec_info, int *, int *);
153 /* Function vect_determine_vectorization_factor
155 Determine the vectorization factor (VF). VF is the number of data elements
156 that are operated upon in parallel in a single iteration of the vectorized
157 loop. For example, when vectorizing a loop that operates on 4byte elements,
158 on a target with vector size (VS) 16byte, the VF is set to 4, since 4
159 elements can fit in a single vector register.
161 We currently support vectorization of loops in which all types operated upon
162 are of the same size. Therefore this function currently sets VF according to
163 the size of the types operated upon, and fails if there are multiple sizes
164 in the loop.
166 VF is also the factor by which the loop iterations are strip-mined, e.g.:
167 original loop:
168 for (i=0; i<N; i++){
169 a[i] = b[i] + c[i];
172 vectorized loop:
173 for (i=0; i<N; i+=VF){
174 a[i:VF] = b[i:VF] + c[i:VF];
178 static bool
179 vect_determine_vectorization_factor (loop_vec_info loop_vinfo)
181 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
182 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
183 unsigned nbbs = loop->num_nodes;
184 unsigned int vectorization_factor = 0;
185 tree scalar_type;
186 gphi *phi;
187 tree vectype;
188 unsigned int nunits;
189 stmt_vec_info stmt_info;
190 unsigned i;
191 HOST_WIDE_INT dummy;
192 gimple *stmt, *pattern_stmt = NULL;
193 gimple_seq pattern_def_seq = NULL;
194 gimple_stmt_iterator pattern_def_si = gsi_none ();
195 bool analyze_pattern_stmt = false;
196 bool bool_result;
197 auto_vec<stmt_vec_info> mask_producers;
199 if (dump_enabled_p ())
200 dump_printf_loc (MSG_NOTE, vect_location,
201 "=== vect_determine_vectorization_factor ===\n");
203 for (i = 0; i < nbbs; i++)
205 basic_block bb = bbs[i];
207 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
208 gsi_next (&si))
210 phi = si.phi ();
211 stmt_info = vinfo_for_stmt (phi);
212 if (dump_enabled_p ())
214 dump_printf_loc (MSG_NOTE, vect_location, "==> examining phi: ");
215 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
218 gcc_assert (stmt_info);
220 if (STMT_VINFO_RELEVANT_P (stmt_info)
221 || STMT_VINFO_LIVE_P (stmt_info))
223 gcc_assert (!STMT_VINFO_VECTYPE (stmt_info));
224 scalar_type = TREE_TYPE (PHI_RESULT (phi));
226 if (dump_enabled_p ())
228 dump_printf_loc (MSG_NOTE, vect_location,
229 "get vectype for scalar type: ");
230 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
231 dump_printf (MSG_NOTE, "\n");
234 vectype = get_vectype_for_scalar_type (scalar_type);
235 if (!vectype)
237 if (dump_enabled_p ())
239 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
240 "not vectorized: unsupported "
241 "data-type ");
242 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
243 scalar_type);
244 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
246 return false;
248 STMT_VINFO_VECTYPE (stmt_info) = vectype;
250 if (dump_enabled_p ())
252 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
253 dump_generic_expr (MSG_NOTE, TDF_SLIM, vectype);
254 dump_printf (MSG_NOTE, "\n");
257 nunits = TYPE_VECTOR_SUBPARTS (vectype);
258 if (dump_enabled_p ())
259 dump_printf_loc (MSG_NOTE, vect_location, "nunits = %d\n",
260 nunits);
262 if (!vectorization_factor
263 || (nunits > vectorization_factor))
264 vectorization_factor = nunits;
268 for (gimple_stmt_iterator si = gsi_start_bb (bb);
269 !gsi_end_p (si) || analyze_pattern_stmt;)
271 tree vf_vectype;
273 if (analyze_pattern_stmt)
274 stmt = pattern_stmt;
275 else
276 stmt = gsi_stmt (si);
278 stmt_info = vinfo_for_stmt (stmt);
280 if (dump_enabled_p ())
282 dump_printf_loc (MSG_NOTE, vect_location,
283 "==> examining statement: ");
284 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
287 gcc_assert (stmt_info);
289 /* Skip stmts which do not need to be vectorized. */
290 if ((!STMT_VINFO_RELEVANT_P (stmt_info)
291 && !STMT_VINFO_LIVE_P (stmt_info))
292 || gimple_clobber_p (stmt))
294 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
295 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
296 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
297 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
299 stmt = pattern_stmt;
300 stmt_info = vinfo_for_stmt (pattern_stmt);
301 if (dump_enabled_p ())
303 dump_printf_loc (MSG_NOTE, vect_location,
304 "==> examining pattern statement: ");
305 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
308 else
310 if (dump_enabled_p ())
311 dump_printf_loc (MSG_NOTE, vect_location, "skip.\n");
312 gsi_next (&si);
313 continue;
316 else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
317 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
318 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
319 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
320 analyze_pattern_stmt = true;
322 /* If a pattern statement has def stmts, analyze them too. */
323 if (is_pattern_stmt_p (stmt_info))
325 if (pattern_def_seq == NULL)
327 pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
328 pattern_def_si = gsi_start (pattern_def_seq);
330 else if (!gsi_end_p (pattern_def_si))
331 gsi_next (&pattern_def_si);
332 if (pattern_def_seq != NULL)
334 gimple *pattern_def_stmt = NULL;
335 stmt_vec_info pattern_def_stmt_info = NULL;
337 while (!gsi_end_p (pattern_def_si))
339 pattern_def_stmt = gsi_stmt (pattern_def_si);
340 pattern_def_stmt_info
341 = vinfo_for_stmt (pattern_def_stmt);
342 if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
343 || STMT_VINFO_LIVE_P (pattern_def_stmt_info))
344 break;
345 gsi_next (&pattern_def_si);
348 if (!gsi_end_p (pattern_def_si))
350 if (dump_enabled_p ())
352 dump_printf_loc (MSG_NOTE, vect_location,
353 "==> examining pattern def stmt: ");
354 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
355 pattern_def_stmt, 0);
358 stmt = pattern_def_stmt;
359 stmt_info = pattern_def_stmt_info;
361 else
363 pattern_def_si = gsi_none ();
364 analyze_pattern_stmt = false;
367 else
368 analyze_pattern_stmt = false;
371 if (gimple_get_lhs (stmt) == NULL_TREE
372 /* MASK_STORE has no lhs, but is ok. */
373 && (!is_gimple_call (stmt)
374 || !gimple_call_internal_p (stmt)
375 || gimple_call_internal_fn (stmt) != IFN_MASK_STORE))
377 if (is_gimple_call (stmt))
379 /* Ignore calls with no lhs. These must be calls to
380 #pragma omp simd functions, and what vectorization factor
381 it really needs can't be determined until
382 vectorizable_simd_clone_call. */
383 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
385 pattern_def_seq = NULL;
386 gsi_next (&si);
388 continue;
390 if (dump_enabled_p ())
392 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
393 "not vectorized: irregular stmt.");
394 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
397 return false;
400 if (VECTOR_MODE_P (TYPE_MODE (gimple_expr_type (stmt))))
402 if (dump_enabled_p ())
404 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
405 "not vectorized: vector stmt in loop:");
406 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
408 return false;
411 bool_result = false;
413 if (STMT_VINFO_VECTYPE (stmt_info))
415 /* The only case when a vectype had been already set is for stmts
416 that contain a dataref, or for "pattern-stmts" (stmts
417 generated by the vectorizer to represent/replace a certain
418 idiom). */
419 gcc_assert (STMT_VINFO_DATA_REF (stmt_info)
420 || is_pattern_stmt_p (stmt_info)
421 || !gsi_end_p (pattern_def_si));
422 vectype = STMT_VINFO_VECTYPE (stmt_info);
424 else
426 gcc_assert (!STMT_VINFO_DATA_REF (stmt_info));
427 if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
428 scalar_type = TREE_TYPE (gimple_call_arg (stmt, 3));
429 else
430 scalar_type = TREE_TYPE (gimple_get_lhs (stmt));
432 /* Bool ops don't participate in vectorization factor
433 computation. For comparison use compared types to
434 compute a factor. */
435 if (TREE_CODE (scalar_type) == BOOLEAN_TYPE
436 && is_gimple_assign (stmt)
437 && gimple_assign_rhs_code (stmt) != COND_EXPR)
439 if (STMT_VINFO_RELEVANT_P (stmt_info)
440 || STMT_VINFO_LIVE_P (stmt_info))
441 mask_producers.safe_push (stmt_info);
442 bool_result = true;
444 if (gimple_code (stmt) == GIMPLE_ASSIGN
445 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt))
446 == tcc_comparison
447 && TREE_CODE (TREE_TYPE (gimple_assign_rhs1 (stmt)))
448 != BOOLEAN_TYPE)
449 scalar_type = TREE_TYPE (gimple_assign_rhs1 (stmt));
450 else
452 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
454 pattern_def_seq = NULL;
455 gsi_next (&si);
457 continue;
461 if (dump_enabled_p ())
463 dump_printf_loc (MSG_NOTE, vect_location,
464 "get vectype for scalar type: ");
465 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
466 dump_printf (MSG_NOTE, "\n");
468 vectype = get_vectype_for_scalar_type (scalar_type);
469 if (!vectype)
471 if (dump_enabled_p ())
473 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
474 "not vectorized: unsupported "
475 "data-type ");
476 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
477 scalar_type);
478 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
480 return false;
483 if (!bool_result)
484 STMT_VINFO_VECTYPE (stmt_info) = vectype;
486 if (dump_enabled_p ())
488 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
489 dump_generic_expr (MSG_NOTE, TDF_SLIM, vectype);
490 dump_printf (MSG_NOTE, "\n");
494 /* Don't try to compute VF out scalar types if we stmt
495 produces boolean vector. Use result vectype instead. */
496 if (VECTOR_BOOLEAN_TYPE_P (vectype))
497 vf_vectype = vectype;
498 else
500 /* The vectorization factor is according to the smallest
501 scalar type (or the largest vector size, but we only
502 support one vector size per loop). */
503 if (!bool_result)
504 scalar_type = vect_get_smallest_scalar_type (stmt, &dummy,
505 &dummy);
506 if (dump_enabled_p ())
508 dump_printf_loc (MSG_NOTE, vect_location,
509 "get vectype for scalar type: ");
510 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
511 dump_printf (MSG_NOTE, "\n");
513 vf_vectype = get_vectype_for_scalar_type (scalar_type);
515 if (!vf_vectype)
517 if (dump_enabled_p ())
519 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
520 "not vectorized: unsupported data-type ");
521 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
522 scalar_type);
523 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
525 return false;
528 if ((GET_MODE_SIZE (TYPE_MODE (vectype))
529 != GET_MODE_SIZE (TYPE_MODE (vf_vectype))))
531 if (dump_enabled_p ())
533 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
534 "not vectorized: different sized vector "
535 "types in statement, ");
536 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
537 vectype);
538 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
539 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
540 vf_vectype);
541 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
543 return false;
546 if (dump_enabled_p ())
548 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
549 dump_generic_expr (MSG_NOTE, TDF_SLIM, vf_vectype);
550 dump_printf (MSG_NOTE, "\n");
553 nunits = TYPE_VECTOR_SUBPARTS (vf_vectype);
554 if (dump_enabled_p ())
555 dump_printf_loc (MSG_NOTE, vect_location, "nunits = %d\n", nunits);
556 if (!vectorization_factor
557 || (nunits > vectorization_factor))
558 vectorization_factor = nunits;
560 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
562 pattern_def_seq = NULL;
563 gsi_next (&si);
568 /* TODO: Analyze cost. Decide if worth while to vectorize. */
569 if (dump_enabled_p ())
570 dump_printf_loc (MSG_NOTE, vect_location, "vectorization factor = %d\n",
571 vectorization_factor);
572 if (vectorization_factor <= 1)
574 if (dump_enabled_p ())
575 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
576 "not vectorized: unsupported data-type\n");
577 return false;
579 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
581 for (i = 0; i < mask_producers.length (); i++)
583 tree mask_type = NULL;
585 stmt = STMT_VINFO_STMT (mask_producers[i]);
587 if (gimple_code (stmt) == GIMPLE_ASSIGN
588 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison
589 && TREE_CODE (TREE_TYPE (gimple_assign_rhs1 (stmt))) != BOOLEAN_TYPE)
591 scalar_type = TREE_TYPE (gimple_assign_rhs1 (stmt));
592 mask_type = get_mask_type_for_scalar_type (scalar_type);
594 if (!mask_type)
596 if (dump_enabled_p ())
597 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
598 "not vectorized: unsupported mask\n");
599 return false;
602 else
604 tree rhs;
605 ssa_op_iter iter;
606 gimple *def_stmt;
607 enum vect_def_type dt;
609 FOR_EACH_SSA_TREE_OPERAND (rhs, stmt, iter, SSA_OP_USE)
611 if (!vect_is_simple_use (rhs, mask_producers[i]->vinfo,
612 &def_stmt, &dt, &vectype))
614 if (dump_enabled_p ())
616 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
617 "not vectorized: can't compute mask type "
618 "for statement, ");
619 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
622 return false;
625 /* No vectype probably means external definition.
626 Allow it in case there is another operand which
627 allows to determine mask type. */
628 if (!vectype)
629 continue;
631 if (!mask_type)
632 mask_type = vectype;
633 else if (TYPE_VECTOR_SUBPARTS (mask_type)
634 != TYPE_VECTOR_SUBPARTS (vectype))
636 if (dump_enabled_p ())
638 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
639 "not vectorized: different sized masks "
640 "types in statement, ");
641 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
642 mask_type);
643 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
644 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
645 vectype);
646 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
648 return false;
650 else if (VECTOR_BOOLEAN_TYPE_P (mask_type)
651 != VECTOR_BOOLEAN_TYPE_P (vectype))
653 if (dump_enabled_p ())
655 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
656 "not vectorized: mixed mask and "
657 "nonmask vector types in statement, ");
658 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
659 mask_type);
660 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
661 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
662 vectype);
663 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
665 return false;
669 /* We may compare boolean value loaded as vector of integers.
670 Fix mask_type in such case. */
671 if (mask_type
672 && !VECTOR_BOOLEAN_TYPE_P (mask_type)
673 && gimple_code (stmt) == GIMPLE_ASSIGN
674 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
675 mask_type = build_same_sized_truth_vector_type (mask_type);
678 /* No mask_type should mean loop invariant predicate.
679 This is probably a subject for optimization in
680 if-conversion. */
681 if (!mask_type)
683 if (dump_enabled_p ())
685 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
686 "not vectorized: can't compute mask type "
687 "for statement, ");
688 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
691 return false;
694 STMT_VINFO_VECTYPE (mask_producers[i]) = mask_type;
697 return true;
701 /* Function vect_is_simple_iv_evolution.
703 FORNOW: A simple evolution of an induction variables in the loop is
704 considered a polynomial evolution. */
706 static bool
707 vect_is_simple_iv_evolution (unsigned loop_nb, tree access_fn, tree * init,
708 tree * step)
710 tree init_expr;
711 tree step_expr;
712 tree evolution_part = evolution_part_in_loop_num (access_fn, loop_nb);
713 basic_block bb;
715 /* When there is no evolution in this loop, the evolution function
716 is not "simple". */
717 if (evolution_part == NULL_TREE)
718 return false;
720 /* When the evolution is a polynomial of degree >= 2
721 the evolution function is not "simple". */
722 if (tree_is_chrec (evolution_part))
723 return false;
725 step_expr = evolution_part;
726 init_expr = unshare_expr (initial_condition_in_loop_num (access_fn, loop_nb));
728 if (dump_enabled_p ())
730 dump_printf_loc (MSG_NOTE, vect_location, "step: ");
731 dump_generic_expr (MSG_NOTE, TDF_SLIM, step_expr);
732 dump_printf (MSG_NOTE, ", init: ");
733 dump_generic_expr (MSG_NOTE, TDF_SLIM, init_expr);
734 dump_printf (MSG_NOTE, "\n");
737 *init = init_expr;
738 *step = step_expr;
740 if (TREE_CODE (step_expr) != INTEGER_CST
741 && (TREE_CODE (step_expr) != SSA_NAME
742 || ((bb = gimple_bb (SSA_NAME_DEF_STMT (step_expr)))
743 && flow_bb_inside_loop_p (get_loop (cfun, loop_nb), bb))
744 || (!INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
745 && (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr))
746 || !flag_associative_math)))
747 && (TREE_CODE (step_expr) != REAL_CST
748 || !flag_associative_math))
750 if (dump_enabled_p ())
751 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
752 "step unknown.\n");
753 return false;
756 return true;
759 /* Function vect_analyze_scalar_cycles_1.
761 Examine the cross iteration def-use cycles of scalar variables
762 in LOOP. LOOP_VINFO represents the loop that is now being
763 considered for vectorization (can be LOOP, or an outer-loop
764 enclosing LOOP). */
766 static void
767 vect_analyze_scalar_cycles_1 (loop_vec_info loop_vinfo, struct loop *loop)
769 basic_block bb = loop->header;
770 tree init, step;
771 auto_vec<gimple *, 64> worklist;
772 gphi_iterator gsi;
773 bool double_reduc;
775 if (dump_enabled_p ())
776 dump_printf_loc (MSG_NOTE, vect_location,
777 "=== vect_analyze_scalar_cycles ===\n");
779 /* First - identify all inductions. Reduction detection assumes that all the
780 inductions have been identified, therefore, this order must not be
781 changed. */
782 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
784 gphi *phi = gsi.phi ();
785 tree access_fn = NULL;
786 tree def = PHI_RESULT (phi);
787 stmt_vec_info stmt_vinfo = vinfo_for_stmt (phi);
789 if (dump_enabled_p ())
791 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: ");
792 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
795 /* Skip virtual phi's. The data dependences that are associated with
796 virtual defs/uses (i.e., memory accesses) are analyzed elsewhere. */
797 if (virtual_operand_p (def))
798 continue;
800 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_unknown_def_type;
802 /* Analyze the evolution function. */
803 access_fn = analyze_scalar_evolution (loop, def);
804 if (access_fn)
806 STRIP_NOPS (access_fn);
807 if (dump_enabled_p ())
809 dump_printf_loc (MSG_NOTE, vect_location,
810 "Access function of PHI: ");
811 dump_generic_expr (MSG_NOTE, TDF_SLIM, access_fn);
812 dump_printf (MSG_NOTE, "\n");
814 STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
815 = initial_condition_in_loop_num (access_fn, loop->num);
816 STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo)
817 = evolution_part_in_loop_num (access_fn, loop->num);
820 if (!access_fn
821 || !vect_is_simple_iv_evolution (loop->num, access_fn, &init, &step)
822 || (LOOP_VINFO_LOOP (loop_vinfo) != loop
823 && TREE_CODE (step) != INTEGER_CST))
825 worklist.safe_push (phi);
826 continue;
829 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
830 != NULL_TREE);
831 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo) != NULL_TREE);
833 if (dump_enabled_p ())
834 dump_printf_loc (MSG_NOTE, vect_location, "Detected induction.\n");
835 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_induction_def;
839 /* Second - identify all reductions and nested cycles. */
840 while (worklist.length () > 0)
842 gimple *phi = worklist.pop ();
843 tree def = PHI_RESULT (phi);
844 stmt_vec_info stmt_vinfo = vinfo_for_stmt (phi);
845 gimple *reduc_stmt;
846 bool nested_cycle;
848 if (dump_enabled_p ())
850 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: ");
851 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
854 gcc_assert (!virtual_operand_p (def)
855 && STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_unknown_def_type);
857 nested_cycle = (loop != LOOP_VINFO_LOOP (loop_vinfo));
858 reduc_stmt = vect_force_simple_reduction (loop_vinfo, phi, !nested_cycle,
859 &double_reduc, false);
860 if (reduc_stmt)
862 if (double_reduc)
864 if (dump_enabled_p ())
865 dump_printf_loc (MSG_NOTE, vect_location,
866 "Detected double reduction.\n");
868 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_double_reduction_def;
869 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
870 vect_double_reduction_def;
872 else
874 if (nested_cycle)
876 if (dump_enabled_p ())
877 dump_printf_loc (MSG_NOTE, vect_location,
878 "Detected vectorizable nested cycle.\n");
880 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_nested_cycle;
881 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
882 vect_nested_cycle;
884 else
886 if (dump_enabled_p ())
887 dump_printf_loc (MSG_NOTE, vect_location,
888 "Detected reduction.\n");
890 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_reduction_def;
891 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
892 vect_reduction_def;
893 /* Store the reduction cycles for possible vectorization in
894 loop-aware SLP. */
895 LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push (reduc_stmt);
899 else
900 if (dump_enabled_p ())
901 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
902 "Unknown def-use cycle pattern.\n");
907 /* Function vect_analyze_scalar_cycles.
909 Examine the cross iteration def-use cycles of scalar variables, by
910 analyzing the loop-header PHIs of scalar variables. Classify each
911 cycle as one of the following: invariant, induction, reduction, unknown.
912 We do that for the loop represented by LOOP_VINFO, and also to its
913 inner-loop, if exists.
914 Examples for scalar cycles:
916 Example1: reduction:
918 loop1:
919 for (i=0; i<N; i++)
920 sum += a[i];
922 Example2: induction:
924 loop2:
925 for (i=0; i<N; i++)
926 a[i] = i; */
928 static void
929 vect_analyze_scalar_cycles (loop_vec_info loop_vinfo)
931 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
933 vect_analyze_scalar_cycles_1 (loop_vinfo, loop);
935 /* When vectorizing an outer-loop, the inner-loop is executed sequentially.
936 Reductions in such inner-loop therefore have different properties than
937 the reductions in the nest that gets vectorized:
938 1. When vectorized, they are executed in the same order as in the original
939 scalar loop, so we can't change the order of computation when
940 vectorizing them.
941 2. FIXME: Inner-loop reductions can be used in the inner-loop, so the
942 current checks are too strict. */
944 if (loop->inner)
945 vect_analyze_scalar_cycles_1 (loop_vinfo, loop->inner);
948 /* Transfer group and reduction information from STMT to its pattern stmt. */
950 static void
951 vect_fixup_reduc_chain (gimple *stmt)
953 gimple *firstp = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
954 gimple *stmtp;
955 gcc_assert (!GROUP_FIRST_ELEMENT (vinfo_for_stmt (firstp))
956 && GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)));
957 GROUP_SIZE (vinfo_for_stmt (firstp)) = GROUP_SIZE (vinfo_for_stmt (stmt));
960 stmtp = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
961 GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmtp)) = firstp;
962 stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (stmt));
963 if (stmt)
964 GROUP_NEXT_ELEMENT (vinfo_for_stmt (stmtp))
965 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
967 while (stmt);
968 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmtp)) = vect_reduction_def;
971 /* Fixup scalar cycles that now have their stmts detected as patterns. */
973 static void
974 vect_fixup_scalar_cycles_with_patterns (loop_vec_info loop_vinfo)
976 gimple *first;
977 unsigned i;
979 FOR_EACH_VEC_ELT (LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo), i, first)
980 if (STMT_VINFO_IN_PATTERN_P (vinfo_for_stmt (first)))
982 gimple *next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (first));
983 while (next)
985 if (! STMT_VINFO_IN_PATTERN_P (vinfo_for_stmt (next)))
986 break;
987 next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next));
989 /* If not all stmt in the chain are patterns try to handle
990 the chain without patterns. */
991 if (! next)
993 vect_fixup_reduc_chain (first);
994 LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo)[i]
995 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (first));
1000 /* Function vect_get_loop_niters.
1002 Determine how many iterations the loop is executed and place it
1003 in NUMBER_OF_ITERATIONS. Place the number of latch iterations
1004 in NUMBER_OF_ITERATIONSM1. Place the condition under which the
1005 niter information holds in ASSUMPTIONS.
1007 Return the loop exit condition. */
1010 static gcond *
1011 vect_get_loop_niters (struct loop *loop, tree *assumptions,
1012 tree *number_of_iterations, tree *number_of_iterationsm1)
1014 edge exit = single_exit (loop);
1015 struct tree_niter_desc niter_desc;
1016 tree niter_assumptions, niter, may_be_zero;
1017 gcond *cond = get_loop_exit_condition (loop);
1019 *assumptions = boolean_true_node;
1020 *number_of_iterationsm1 = chrec_dont_know;
1021 *number_of_iterations = chrec_dont_know;
1022 if (dump_enabled_p ())
1023 dump_printf_loc (MSG_NOTE, vect_location,
1024 "=== get_loop_niters ===\n");
1026 if (!exit)
1027 return cond;
1029 niter = chrec_dont_know;
1030 may_be_zero = NULL_TREE;
1031 niter_assumptions = boolean_true_node;
1032 if (!number_of_iterations_exit_assumptions (loop, exit, &niter_desc, NULL)
1033 || chrec_contains_undetermined (niter_desc.niter))
1034 return cond;
1036 niter_assumptions = niter_desc.assumptions;
1037 may_be_zero = niter_desc.may_be_zero;
1038 niter = niter_desc.niter;
1040 if (may_be_zero && integer_zerop (may_be_zero))
1041 may_be_zero = NULL_TREE;
1043 if (may_be_zero)
1045 if (COMPARISON_CLASS_P (may_be_zero))
1047 /* Try to combine may_be_zero with assumptions, this can simplify
1048 computation of niter expression. */
1049 if (niter_assumptions && !integer_nonzerop (niter_assumptions))
1050 niter_assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1051 niter_assumptions,
1052 fold_build1 (TRUTH_NOT_EXPR,
1053 boolean_type_node,
1054 may_be_zero));
1055 else
1056 niter = fold_build3 (COND_EXPR, TREE_TYPE (niter), may_be_zero,
1057 build_int_cst (TREE_TYPE (niter), 0), niter);
1059 may_be_zero = NULL_TREE;
1061 else if (integer_nonzerop (may_be_zero))
1063 *number_of_iterationsm1 = build_int_cst (TREE_TYPE (niter), 0);
1064 *number_of_iterations = build_int_cst (TREE_TYPE (niter), 1);
1065 return cond;
1067 else
1068 return cond;
1071 *assumptions = niter_assumptions;
1072 *number_of_iterationsm1 = niter;
1074 /* We want the number of loop header executions which is the number
1075 of latch executions plus one.
1076 ??? For UINT_MAX latch executions this number overflows to zero
1077 for loops like do { n++; } while (n != 0); */
1078 if (niter && !chrec_contains_undetermined (niter))
1079 niter = fold_build2 (PLUS_EXPR, TREE_TYPE (niter), unshare_expr (niter),
1080 build_int_cst (TREE_TYPE (niter), 1));
1081 *number_of_iterations = niter;
1083 return cond;
1086 /* Function bb_in_loop_p
1088 Used as predicate for dfs order traversal of the loop bbs. */
1090 static bool
1091 bb_in_loop_p (const_basic_block bb, const void *data)
1093 const struct loop *const loop = (const struct loop *)data;
1094 if (flow_bb_inside_loop_p (loop, bb))
1095 return true;
1096 return false;
1100 /* Function new_loop_vec_info.
1102 Create and initialize a new loop_vec_info struct for LOOP, as well as
1103 stmt_vec_info structs for all the stmts in LOOP. */
1105 static loop_vec_info
1106 new_loop_vec_info (struct loop *loop)
1108 loop_vec_info res;
1109 basic_block *bbs;
1110 gimple_stmt_iterator si;
1111 unsigned int i, nbbs;
1113 res = (loop_vec_info) xcalloc (1, sizeof (struct _loop_vec_info));
1114 res->kind = vec_info::loop;
1115 LOOP_VINFO_LOOP (res) = loop;
1117 bbs = get_loop_body (loop);
1119 /* Create/Update stmt_info for all stmts in the loop. */
1120 for (i = 0; i < loop->num_nodes; i++)
1122 basic_block bb = bbs[i];
1124 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
1126 gimple *phi = gsi_stmt (si);
1127 gimple_set_uid (phi, 0);
1128 set_vinfo_for_stmt (phi, new_stmt_vec_info (phi, res));
1131 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1133 gimple *stmt = gsi_stmt (si);
1134 gimple_set_uid (stmt, 0);
1135 set_vinfo_for_stmt (stmt, new_stmt_vec_info (stmt, res));
1139 /* CHECKME: We want to visit all BBs before their successors (except for
1140 latch blocks, for which this assertion wouldn't hold). In the simple
1141 case of the loop forms we allow, a dfs order of the BBs would the same
1142 as reversed postorder traversal, so we are safe. */
1144 free (bbs);
1145 bbs = XCNEWVEC (basic_block, loop->num_nodes);
1146 nbbs = dfs_enumerate_from (loop->header, 0, bb_in_loop_p,
1147 bbs, loop->num_nodes, loop);
1148 gcc_assert (nbbs == loop->num_nodes);
1150 LOOP_VINFO_BBS (res) = bbs;
1151 LOOP_VINFO_NITERSM1 (res) = NULL;
1152 LOOP_VINFO_NITERS (res) = NULL;
1153 LOOP_VINFO_NITERS_UNCHANGED (res) = NULL;
1154 LOOP_VINFO_NITERS_ASSUMPTIONS (res) = NULL;
1155 LOOP_VINFO_COST_MODEL_THRESHOLD (res) = 0;
1156 LOOP_VINFO_VECTORIZABLE_P (res) = 0;
1157 LOOP_VINFO_PEELING_FOR_ALIGNMENT (res) = 0;
1158 LOOP_VINFO_VECT_FACTOR (res) = 0;
1159 LOOP_VINFO_LOOP_NEST (res) = vNULL;
1160 LOOP_VINFO_DATAREFS (res) = vNULL;
1161 LOOP_VINFO_DDRS (res) = vNULL;
1162 LOOP_VINFO_UNALIGNED_DR (res) = NULL;
1163 LOOP_VINFO_MAY_MISALIGN_STMTS (res) = vNULL;
1164 LOOP_VINFO_MAY_ALIAS_DDRS (res) = vNULL;
1165 LOOP_VINFO_GROUPED_STORES (res) = vNULL;
1166 LOOP_VINFO_REDUCTIONS (res) = vNULL;
1167 LOOP_VINFO_REDUCTION_CHAINS (res) = vNULL;
1168 LOOP_VINFO_SLP_INSTANCES (res) = vNULL;
1169 LOOP_VINFO_SLP_UNROLLING_FACTOR (res) = 1;
1170 LOOP_VINFO_TARGET_COST_DATA (res) = init_cost (loop);
1171 LOOP_VINFO_PEELING_FOR_GAPS (res) = false;
1172 LOOP_VINFO_PEELING_FOR_NITER (res) = false;
1173 LOOP_VINFO_OPERANDS_SWAPPED (res) = false;
1175 return res;
1179 /* Function destroy_loop_vec_info.
1181 Free LOOP_VINFO struct, as well as all the stmt_vec_info structs of all the
1182 stmts in the loop. */
1184 void
1185 destroy_loop_vec_info (loop_vec_info loop_vinfo, bool clean_stmts)
1187 struct loop *loop;
1188 basic_block *bbs;
1189 int nbbs;
1190 gimple_stmt_iterator si;
1191 int j;
1192 vec<slp_instance> slp_instances;
1193 slp_instance instance;
1194 bool swapped;
1196 if (!loop_vinfo)
1197 return;
1199 loop = LOOP_VINFO_LOOP (loop_vinfo);
1201 bbs = LOOP_VINFO_BBS (loop_vinfo);
1202 nbbs = clean_stmts ? loop->num_nodes : 0;
1203 swapped = LOOP_VINFO_OPERANDS_SWAPPED (loop_vinfo);
1205 for (j = 0; j < nbbs; j++)
1207 basic_block bb = bbs[j];
1208 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
1209 free_stmt_vec_info (gsi_stmt (si));
1211 for (si = gsi_start_bb (bb); !gsi_end_p (si); )
1213 gimple *stmt = gsi_stmt (si);
1215 /* We may have broken canonical form by moving a constant
1216 into RHS1 of a commutative op. Fix such occurrences. */
1217 if (swapped && is_gimple_assign (stmt))
1219 enum tree_code code = gimple_assign_rhs_code (stmt);
1221 if ((code == PLUS_EXPR
1222 || code == POINTER_PLUS_EXPR
1223 || code == MULT_EXPR)
1224 && CONSTANT_CLASS_P (gimple_assign_rhs1 (stmt)))
1225 swap_ssa_operands (stmt,
1226 gimple_assign_rhs1_ptr (stmt),
1227 gimple_assign_rhs2_ptr (stmt));
1230 /* Free stmt_vec_info. */
1231 free_stmt_vec_info (stmt);
1232 gsi_next (&si);
1236 free (LOOP_VINFO_BBS (loop_vinfo));
1237 vect_destroy_datarefs (loop_vinfo);
1238 free_dependence_relations (LOOP_VINFO_DDRS (loop_vinfo));
1239 LOOP_VINFO_LOOP_NEST (loop_vinfo).release ();
1240 LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).release ();
1241 LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).release ();
1242 LOOP_VINFO_MAY_ALIAS_DDRS (loop_vinfo).release ();
1243 slp_instances = LOOP_VINFO_SLP_INSTANCES (loop_vinfo);
1244 FOR_EACH_VEC_ELT (slp_instances, j, instance)
1245 vect_free_slp_instance (instance);
1247 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
1248 LOOP_VINFO_GROUPED_STORES (loop_vinfo).release ();
1249 LOOP_VINFO_REDUCTIONS (loop_vinfo).release ();
1250 LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo).release ();
1252 destroy_cost_data (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
1253 loop_vinfo->scalar_cost_vec.release ();
1255 free (loop_vinfo);
1256 loop->aux = NULL;
1260 /* Calculate the cost of one scalar iteration of the loop. */
1261 static void
1262 vect_compute_single_scalar_iteration_cost (loop_vec_info loop_vinfo)
1264 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1265 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1266 int nbbs = loop->num_nodes, factor, scalar_single_iter_cost = 0;
1267 int innerloop_iters, i;
1269 /* Count statements in scalar loop. Using this as scalar cost for a single
1270 iteration for now.
1272 TODO: Add outer loop support.
1274 TODO: Consider assigning different costs to different scalar
1275 statements. */
1277 /* FORNOW. */
1278 innerloop_iters = 1;
1279 if (loop->inner)
1280 innerloop_iters = 50; /* FIXME */
1282 for (i = 0; i < nbbs; i++)
1284 gimple_stmt_iterator si;
1285 basic_block bb = bbs[i];
1287 if (bb->loop_father == loop->inner)
1288 factor = innerloop_iters;
1289 else
1290 factor = 1;
1292 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1294 gimple *stmt = gsi_stmt (si);
1295 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
1297 if (!is_gimple_assign (stmt) && !is_gimple_call (stmt))
1298 continue;
1300 /* Skip stmts that are not vectorized inside the loop. */
1301 if (stmt_info
1302 && !STMT_VINFO_RELEVANT_P (stmt_info)
1303 && (!STMT_VINFO_LIVE_P (stmt_info)
1304 || !VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
1305 && !STMT_VINFO_IN_PATTERN_P (stmt_info))
1306 continue;
1308 vect_cost_for_stmt kind;
1309 if (STMT_VINFO_DATA_REF (vinfo_for_stmt (stmt)))
1311 if (DR_IS_READ (STMT_VINFO_DATA_REF (vinfo_for_stmt (stmt))))
1312 kind = scalar_load;
1313 else
1314 kind = scalar_store;
1316 else
1317 kind = scalar_stmt;
1319 scalar_single_iter_cost
1320 += record_stmt_cost (&LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo),
1321 factor, kind, NULL, 0, vect_prologue);
1324 LOOP_VINFO_SINGLE_SCALAR_ITERATION_COST (loop_vinfo)
1325 = scalar_single_iter_cost;
1329 /* Function vect_analyze_loop_form_1.
1331 Verify that certain CFG restrictions hold, including:
1332 - the loop has a pre-header
1333 - the loop has a single entry and exit
1334 - the loop exit condition is simple enough
1335 - the number of iterations can be analyzed, i.e, a countable loop. The
1336 niter could be analyzed under some assumptions. */
1338 bool
1339 vect_analyze_loop_form_1 (struct loop *loop, gcond **loop_cond,
1340 tree *assumptions, tree *number_of_iterationsm1,
1341 tree *number_of_iterations, gcond **inner_loop_cond)
1343 if (dump_enabled_p ())
1344 dump_printf_loc (MSG_NOTE, vect_location,
1345 "=== vect_analyze_loop_form ===\n");
1347 /* Different restrictions apply when we are considering an inner-most loop,
1348 vs. an outer (nested) loop.
1349 (FORNOW. May want to relax some of these restrictions in the future). */
1351 if (!loop->inner)
1353 /* Inner-most loop. We currently require that the number of BBs is
1354 exactly 2 (the header and latch). Vectorizable inner-most loops
1355 look like this:
1357 (pre-header)
1359 header <--------+
1360 | | |
1361 | +--> latch --+
1363 (exit-bb) */
1365 if (loop->num_nodes != 2)
1367 if (dump_enabled_p ())
1368 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1369 "not vectorized: control flow in loop.\n");
1370 return false;
1373 if (empty_block_p (loop->header))
1375 if (dump_enabled_p ())
1376 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1377 "not vectorized: empty loop.\n");
1378 return false;
1381 else
1383 struct loop *innerloop = loop->inner;
1384 edge entryedge;
1386 /* Nested loop. We currently require that the loop is doubly-nested,
1387 contains a single inner loop, and the number of BBs is exactly 5.
1388 Vectorizable outer-loops look like this:
1390 (pre-header)
1392 header <---+
1394 inner-loop |
1396 tail ------+
1398 (exit-bb)
1400 The inner-loop has the properties expected of inner-most loops
1401 as described above. */
1403 if ((loop->inner)->inner || (loop->inner)->next)
1405 if (dump_enabled_p ())
1406 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1407 "not vectorized: multiple nested loops.\n");
1408 return false;
1411 if (loop->num_nodes != 5)
1413 if (dump_enabled_p ())
1414 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1415 "not vectorized: control flow in loop.\n");
1416 return false;
1419 entryedge = loop_preheader_edge (innerloop);
1420 if (entryedge->src != loop->header
1421 || !single_exit (innerloop)
1422 || single_exit (innerloop)->dest != EDGE_PRED (loop->latch, 0)->src)
1424 if (dump_enabled_p ())
1425 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1426 "not vectorized: unsupported outerloop form.\n");
1427 return false;
1430 /* Analyze the inner-loop. */
1431 tree inner_niterm1, inner_niter, inner_assumptions;
1432 if (! vect_analyze_loop_form_1 (loop->inner, inner_loop_cond,
1433 &inner_assumptions, &inner_niterm1,
1434 &inner_niter, NULL)
1435 /* Don't support analyzing niter under assumptions for inner
1436 loop. */
1437 || !integer_onep (inner_assumptions))
1439 if (dump_enabled_p ())
1440 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1441 "not vectorized: Bad inner loop.\n");
1442 return false;
1445 if (!expr_invariant_in_loop_p (loop, inner_niter))
1447 if (dump_enabled_p ())
1448 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1449 "not vectorized: inner-loop count not"
1450 " invariant.\n");
1451 return false;
1454 if (dump_enabled_p ())
1455 dump_printf_loc (MSG_NOTE, vect_location,
1456 "Considering outer-loop vectorization.\n");
1459 if (!single_exit (loop)
1460 || EDGE_COUNT (loop->header->preds) != 2)
1462 if (dump_enabled_p ())
1464 if (!single_exit (loop))
1465 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1466 "not vectorized: multiple exits.\n");
1467 else if (EDGE_COUNT (loop->header->preds) != 2)
1468 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1469 "not vectorized: too many incoming edges.\n");
1471 return false;
1474 /* We assume that the loop exit condition is at the end of the loop. i.e,
1475 that the loop is represented as a do-while (with a proper if-guard
1476 before the loop if needed), where the loop header contains all the
1477 executable statements, and the latch is empty. */
1478 if (!empty_block_p (loop->latch)
1479 || !gimple_seq_empty_p (phi_nodes (loop->latch)))
1481 if (dump_enabled_p ())
1482 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1483 "not vectorized: latch block not empty.\n");
1484 return false;
1487 /* Make sure the exit is not abnormal. */
1488 edge e = single_exit (loop);
1489 if (e->flags & EDGE_ABNORMAL)
1491 if (dump_enabled_p ())
1492 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1493 "not vectorized: abnormal loop exit edge.\n");
1494 return false;
1497 *loop_cond = vect_get_loop_niters (loop, assumptions, number_of_iterations,
1498 number_of_iterationsm1);
1499 if (!*loop_cond)
1501 if (dump_enabled_p ())
1502 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1503 "not vectorized: complicated exit condition.\n");
1504 return false;
1507 if (integer_zerop (*assumptions)
1508 || !*number_of_iterations
1509 || chrec_contains_undetermined (*number_of_iterations))
1511 if (dump_enabled_p ())
1512 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1513 "not vectorized: number of iterations cannot be "
1514 "computed.\n");
1515 return false;
1518 if (integer_zerop (*number_of_iterations))
1520 if (dump_enabled_p ())
1521 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1522 "not vectorized: number of iterations = 0.\n");
1523 return false;
1526 return true;
1529 /* Analyze LOOP form and return a loop_vec_info if it is of suitable form. */
1531 loop_vec_info
1532 vect_analyze_loop_form (struct loop *loop)
1534 tree assumptions, number_of_iterations, number_of_iterationsm1;
1535 gcond *loop_cond, *inner_loop_cond = NULL;
1537 if (! vect_analyze_loop_form_1 (loop, &loop_cond,
1538 &assumptions, &number_of_iterationsm1,
1539 &number_of_iterations, &inner_loop_cond))
1540 return NULL;
1542 loop_vec_info loop_vinfo = new_loop_vec_info (loop);
1543 LOOP_VINFO_NITERSM1 (loop_vinfo) = number_of_iterationsm1;
1544 LOOP_VINFO_NITERS (loop_vinfo) = number_of_iterations;
1545 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = number_of_iterations;
1546 if (!integer_onep (assumptions))
1548 /* We consider to vectorize this loop by versioning it under
1549 some assumptions. In order to do this, we need to clear
1550 existing information computed by scev and niter analyzer. */
1551 scev_reset_htab ();
1552 free_numbers_of_iterations_estimates_loop (loop);
1553 /* Also set flag for this loop so that following scev and niter
1554 analysis are done under the assumptions. */
1555 loop_constraint_set (loop, LOOP_C_FINITE);
1556 /* Also record the assumptions for versioning. */
1557 LOOP_VINFO_NITERS_ASSUMPTIONS (loop_vinfo) = assumptions;
1560 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
1562 if (dump_enabled_p ())
1564 dump_printf_loc (MSG_NOTE, vect_location,
1565 "Symbolic number of iterations is ");
1566 dump_generic_expr (MSG_NOTE, TDF_DETAILS, number_of_iterations);
1567 dump_printf (MSG_NOTE, "\n");
1571 STMT_VINFO_TYPE (vinfo_for_stmt (loop_cond)) = loop_exit_ctrl_vec_info_type;
1572 if (inner_loop_cond)
1573 STMT_VINFO_TYPE (vinfo_for_stmt (inner_loop_cond))
1574 = loop_exit_ctrl_vec_info_type;
1576 gcc_assert (!loop->aux);
1577 loop->aux = loop_vinfo;
1578 return loop_vinfo;
1583 /* Scan the loop stmts and dependent on whether there are any (non-)SLP
1584 statements update the vectorization factor. */
1586 static void
1587 vect_update_vf_for_slp (loop_vec_info loop_vinfo)
1589 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1590 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1591 int nbbs = loop->num_nodes;
1592 unsigned int vectorization_factor;
1593 int i;
1595 if (dump_enabled_p ())
1596 dump_printf_loc (MSG_NOTE, vect_location,
1597 "=== vect_update_vf_for_slp ===\n");
1599 vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1600 gcc_assert (vectorization_factor != 0);
1602 /* If all the stmts in the loop can be SLPed, we perform only SLP, and
1603 vectorization factor of the loop is the unrolling factor required by
1604 the SLP instances. If that unrolling factor is 1, we say, that we
1605 perform pure SLP on loop - cross iteration parallelism is not
1606 exploited. */
1607 bool only_slp_in_loop = true;
1608 for (i = 0; i < nbbs; i++)
1610 basic_block bb = bbs[i];
1611 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
1612 gsi_next (&si))
1614 gimple *stmt = gsi_stmt (si);
1615 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
1616 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
1617 && STMT_VINFO_RELATED_STMT (stmt_info))
1619 stmt = STMT_VINFO_RELATED_STMT (stmt_info);
1620 stmt_info = vinfo_for_stmt (stmt);
1622 if ((STMT_VINFO_RELEVANT_P (stmt_info)
1623 || VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
1624 && !PURE_SLP_STMT (stmt_info))
1625 /* STMT needs both SLP and loop-based vectorization. */
1626 only_slp_in_loop = false;
1630 if (only_slp_in_loop)
1631 vectorization_factor = LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo);
1632 else
1633 vectorization_factor
1634 = least_common_multiple (vectorization_factor,
1635 LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo));
1637 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
1638 if (dump_enabled_p ())
1639 dump_printf_loc (MSG_NOTE, vect_location,
1640 "Updating vectorization factor to %d\n",
1641 vectorization_factor);
1644 /* Function vect_analyze_loop_operations.
1646 Scan the loop stmts and make sure they are all vectorizable. */
1648 static bool
1649 vect_analyze_loop_operations (loop_vec_info loop_vinfo)
1651 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1652 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1653 int nbbs = loop->num_nodes;
1654 int i;
1655 stmt_vec_info stmt_info;
1656 bool need_to_vectorize = false;
1657 bool ok;
1659 if (dump_enabled_p ())
1660 dump_printf_loc (MSG_NOTE, vect_location,
1661 "=== vect_analyze_loop_operations ===\n");
1663 for (i = 0; i < nbbs; i++)
1665 basic_block bb = bbs[i];
1667 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
1668 gsi_next (&si))
1670 gphi *phi = si.phi ();
1671 ok = true;
1673 stmt_info = vinfo_for_stmt (phi);
1674 if (dump_enabled_p ())
1676 dump_printf_loc (MSG_NOTE, vect_location, "examining phi: ");
1677 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
1679 if (virtual_operand_p (gimple_phi_result (phi)))
1680 continue;
1682 /* Inner-loop loop-closed exit phi in outer-loop vectorization
1683 (i.e., a phi in the tail of the outer-loop). */
1684 if (! is_loop_header_bb_p (bb))
1686 /* FORNOW: we currently don't support the case that these phis
1687 are not used in the outerloop (unless it is double reduction,
1688 i.e., this phi is vect_reduction_def), cause this case
1689 requires to actually do something here. */
1690 if ((!STMT_VINFO_RELEVANT_P (stmt_info)
1691 || STMT_VINFO_LIVE_P (stmt_info))
1692 && STMT_VINFO_DEF_TYPE (stmt_info)
1693 != vect_double_reduction_def)
1695 if (dump_enabled_p ())
1696 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1697 "Unsupported loop-closed phi in "
1698 "outer-loop.\n");
1699 return false;
1702 /* If PHI is used in the outer loop, we check that its operand
1703 is defined in the inner loop. */
1704 if (STMT_VINFO_RELEVANT_P (stmt_info))
1706 tree phi_op;
1707 gimple *op_def_stmt;
1709 if (gimple_phi_num_args (phi) != 1)
1710 return false;
1712 phi_op = PHI_ARG_DEF (phi, 0);
1713 if (TREE_CODE (phi_op) != SSA_NAME)
1714 return false;
1716 op_def_stmt = SSA_NAME_DEF_STMT (phi_op);
1717 if (gimple_nop_p (op_def_stmt)
1718 || !flow_bb_inside_loop_p (loop, gimple_bb (op_def_stmt))
1719 || !vinfo_for_stmt (op_def_stmt))
1720 return false;
1722 if (STMT_VINFO_RELEVANT (vinfo_for_stmt (op_def_stmt))
1723 != vect_used_in_outer
1724 && STMT_VINFO_RELEVANT (vinfo_for_stmt (op_def_stmt))
1725 != vect_used_in_outer_by_reduction)
1726 return false;
1729 continue;
1732 gcc_assert (stmt_info);
1734 if ((STMT_VINFO_RELEVANT (stmt_info) == vect_used_in_scope
1735 || STMT_VINFO_LIVE_P (stmt_info))
1736 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_induction_def)
1738 /* A scalar-dependence cycle that we don't support. */
1739 if (dump_enabled_p ())
1740 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1741 "not vectorized: scalar dependence cycle.\n");
1742 return false;
1745 if (STMT_VINFO_RELEVANT_P (stmt_info))
1747 need_to_vectorize = true;
1748 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def)
1749 ok = vectorizable_induction (phi, NULL, NULL);
1752 if (ok && STMT_VINFO_LIVE_P (stmt_info))
1753 ok = vectorizable_live_operation (phi, NULL, NULL, -1, NULL);
1755 if (!ok)
1757 if (dump_enabled_p ())
1759 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1760 "not vectorized: relevant phi not "
1761 "supported: ");
1762 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, phi, 0);
1764 return false;
1768 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
1769 gsi_next (&si))
1771 gimple *stmt = gsi_stmt (si);
1772 if (!gimple_clobber_p (stmt)
1773 && !vect_analyze_stmt (stmt, &need_to_vectorize, NULL))
1774 return false;
1776 } /* bbs */
1778 /* All operations in the loop are either irrelevant (deal with loop
1779 control, or dead), or only used outside the loop and can be moved
1780 out of the loop (e.g. invariants, inductions). The loop can be
1781 optimized away by scalar optimizations. We're better off not
1782 touching this loop. */
1783 if (!need_to_vectorize)
1785 if (dump_enabled_p ())
1786 dump_printf_loc (MSG_NOTE, vect_location,
1787 "All the computation can be taken out of the loop.\n");
1788 if (dump_enabled_p ())
1789 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1790 "not vectorized: redundant loop. no profit to "
1791 "vectorize.\n");
1792 return false;
1795 return true;
1799 /* Function vect_analyze_loop_2.
1801 Apply a set of analyses on LOOP, and create a loop_vec_info struct
1802 for it. The different analyses will record information in the
1803 loop_vec_info struct. */
1804 static bool
1805 vect_analyze_loop_2 (loop_vec_info loop_vinfo, bool &fatal)
1807 bool ok;
1808 int max_vf = MAX_VECTORIZATION_FACTOR;
1809 int min_vf = 2;
1810 unsigned int n_stmts = 0;
1812 /* The first group of checks is independent of the vector size. */
1813 fatal = true;
1815 /* Find all data references in the loop (which correspond to vdefs/vuses)
1816 and analyze their evolution in the loop. */
1818 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1820 loop_p loop = LOOP_VINFO_LOOP (loop_vinfo);
1821 if (!find_loop_nest (loop, &LOOP_VINFO_LOOP_NEST (loop_vinfo)))
1823 if (dump_enabled_p ())
1824 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1825 "not vectorized: loop nest containing two "
1826 "or more consecutive inner loops cannot be "
1827 "vectorized\n");
1828 return false;
1831 for (unsigned i = 0; i < loop->num_nodes; i++)
1832 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
1833 !gsi_end_p (gsi); gsi_next (&gsi))
1835 gimple *stmt = gsi_stmt (gsi);
1836 if (is_gimple_debug (stmt))
1837 continue;
1838 ++n_stmts;
1839 if (!find_data_references_in_stmt (loop, stmt,
1840 &LOOP_VINFO_DATAREFS (loop_vinfo)))
1842 if (is_gimple_call (stmt) && loop->safelen)
1844 tree fndecl = gimple_call_fndecl (stmt), op;
1845 if (fndecl != NULL_TREE)
1847 cgraph_node *node = cgraph_node::get (fndecl);
1848 if (node != NULL && node->simd_clones != NULL)
1850 unsigned int j, n = gimple_call_num_args (stmt);
1851 for (j = 0; j < n; j++)
1853 op = gimple_call_arg (stmt, j);
1854 if (DECL_P (op)
1855 || (REFERENCE_CLASS_P (op)
1856 && get_base_address (op)))
1857 break;
1859 op = gimple_call_lhs (stmt);
1860 /* Ignore #pragma omp declare simd functions
1861 if they don't have data references in the
1862 call stmt itself. */
1863 if (j == n
1864 && !(op
1865 && (DECL_P (op)
1866 || (REFERENCE_CLASS_P (op)
1867 && get_base_address (op)))))
1868 continue;
1872 if (dump_enabled_p ())
1873 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1874 "not vectorized: loop contains function "
1875 "calls or data references that cannot "
1876 "be analyzed\n");
1877 return false;
1881 /* Analyze the data references and also adjust the minimal
1882 vectorization factor according to the loads and stores. */
1884 ok = vect_analyze_data_refs (loop_vinfo, &min_vf);
1885 if (!ok)
1887 if (dump_enabled_p ())
1888 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1889 "bad data references.\n");
1890 return false;
1893 /* Classify all cross-iteration scalar data-flow cycles.
1894 Cross-iteration cycles caused by virtual phis are analyzed separately. */
1895 vect_analyze_scalar_cycles (loop_vinfo);
1897 vect_pattern_recog (loop_vinfo);
1899 vect_fixup_scalar_cycles_with_patterns (loop_vinfo);
1901 /* Analyze the access patterns of the data-refs in the loop (consecutive,
1902 complex, etc.). FORNOW: Only handle consecutive access pattern. */
1904 ok = vect_analyze_data_ref_accesses (loop_vinfo);
1905 if (!ok)
1907 if (dump_enabled_p ())
1908 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1909 "bad data access.\n");
1910 return false;
1913 /* Data-flow analysis to detect stmts that do not need to be vectorized. */
1915 ok = vect_mark_stmts_to_be_vectorized (loop_vinfo);
1916 if (!ok)
1918 if (dump_enabled_p ())
1919 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1920 "unexpected pattern.\n");
1921 return false;
1924 /* While the rest of the analysis below depends on it in some way. */
1925 fatal = false;
1927 /* Analyze data dependences between the data-refs in the loop
1928 and adjust the maximum vectorization factor according to
1929 the dependences.
1930 FORNOW: fail at the first data dependence that we encounter. */
1932 ok = vect_analyze_data_ref_dependences (loop_vinfo, &max_vf);
1933 if (!ok
1934 || max_vf < min_vf)
1936 if (dump_enabled_p ())
1937 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1938 "bad data dependence.\n");
1939 return false;
1942 ok = vect_determine_vectorization_factor (loop_vinfo);
1943 if (!ok)
1945 if (dump_enabled_p ())
1946 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1947 "can't determine vectorization factor.\n");
1948 return false;
1950 if (max_vf < LOOP_VINFO_VECT_FACTOR (loop_vinfo))
1952 if (dump_enabled_p ())
1953 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1954 "bad data dependence.\n");
1955 return false;
1958 /* Compute the scalar iteration cost. */
1959 vect_compute_single_scalar_iteration_cost (loop_vinfo);
1961 int saved_vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1962 HOST_WIDE_INT estimated_niter;
1963 unsigned th;
1964 int min_scalar_loop_bound;
1966 /* Check the SLP opportunities in the loop, analyze and build SLP trees. */
1967 ok = vect_analyze_slp (loop_vinfo, n_stmts);
1968 if (!ok)
1969 return false;
1971 /* If there are any SLP instances mark them as pure_slp. */
1972 bool slp = vect_make_slp_decision (loop_vinfo);
1973 if (slp)
1975 /* Find stmts that need to be both vectorized and SLPed. */
1976 vect_detect_hybrid_slp (loop_vinfo);
1978 /* Update the vectorization factor based on the SLP decision. */
1979 vect_update_vf_for_slp (loop_vinfo);
1982 /* This is the point where we can re-start analysis with SLP forced off. */
1983 start_over:
1985 /* Now the vectorization factor is final. */
1986 unsigned vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1987 gcc_assert (vectorization_factor != 0);
1989 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && dump_enabled_p ())
1990 dump_printf_loc (MSG_NOTE, vect_location,
1991 "vectorization_factor = %d, niters = "
1992 HOST_WIDE_INT_PRINT_DEC "\n", vectorization_factor,
1993 LOOP_VINFO_INT_NITERS (loop_vinfo));
1995 HOST_WIDE_INT max_niter
1996 = likely_max_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
1997 if ((LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
1998 && (LOOP_VINFO_INT_NITERS (loop_vinfo) < vectorization_factor))
1999 || (max_niter != -1
2000 && (unsigned HOST_WIDE_INT) max_niter < vectorization_factor))
2002 if (dump_enabled_p ())
2003 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2004 "not vectorized: iteration count smaller than "
2005 "vectorization factor.\n");
2006 return false;
2009 /* Analyze the alignment of the data-refs in the loop.
2010 Fail if a data reference is found that cannot be vectorized. */
2012 ok = vect_analyze_data_refs_alignment (loop_vinfo);
2013 if (!ok)
2015 if (dump_enabled_p ())
2016 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2017 "bad data alignment.\n");
2018 return false;
2021 /* Prune the list of ddrs to be tested at run-time by versioning for alias.
2022 It is important to call pruning after vect_analyze_data_ref_accesses,
2023 since we use grouping information gathered by interleaving analysis. */
2024 ok = vect_prune_runtime_alias_test_list (loop_vinfo);
2025 if (!ok)
2026 return false;
2028 /* This pass will decide on using loop versioning and/or loop peeling in
2029 order to enhance the alignment of data references in the loop. */
2030 ok = vect_enhance_data_refs_alignment (loop_vinfo);
2031 if (!ok)
2033 if (dump_enabled_p ())
2034 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2035 "bad data alignment.\n");
2036 return false;
2039 if (slp)
2041 /* Analyze operations in the SLP instances. Note this may
2042 remove unsupported SLP instances which makes the above
2043 SLP kind detection invalid. */
2044 unsigned old_size = LOOP_VINFO_SLP_INSTANCES (loop_vinfo).length ();
2045 vect_slp_analyze_operations (LOOP_VINFO_SLP_INSTANCES (loop_vinfo),
2046 LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
2047 if (LOOP_VINFO_SLP_INSTANCES (loop_vinfo).length () != old_size)
2048 goto again;
2051 /* Scan all the remaining operations in the loop that are not subject
2052 to SLP and make sure they are vectorizable. */
2053 ok = vect_analyze_loop_operations (loop_vinfo);
2054 if (!ok)
2056 if (dump_enabled_p ())
2057 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2058 "bad operation or unsupported loop bound.\n");
2059 return false;
2062 /* If epilog loop is required because of data accesses with gaps,
2063 one additional iteration needs to be peeled. Check if there is
2064 enough iterations for vectorization. */
2065 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
2066 && LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
2068 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2069 tree scalar_niters = LOOP_VINFO_NITERSM1 (loop_vinfo);
2071 if (wi::to_widest (scalar_niters) < vf)
2073 if (dump_enabled_p ())
2074 dump_printf_loc (MSG_NOTE, vect_location,
2075 "loop has no enough iterations to support"
2076 " peeling for gaps.\n");
2077 return false;
2081 /* Analyze cost. Decide if worth while to vectorize. */
2082 int min_profitable_estimate, min_profitable_iters;
2083 vect_estimate_min_profitable_iters (loop_vinfo, &min_profitable_iters,
2084 &min_profitable_estimate);
2086 if (min_profitable_iters < 0)
2088 if (dump_enabled_p ())
2089 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2090 "not vectorized: vectorization not profitable.\n");
2091 if (dump_enabled_p ())
2092 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2093 "not vectorized: vector version will never be "
2094 "profitable.\n");
2095 goto again;
2098 min_scalar_loop_bound = ((PARAM_VALUE (PARAM_MIN_VECT_LOOP_BOUND)
2099 * vectorization_factor) - 1);
2101 /* Use the cost model only if it is more conservative than user specified
2102 threshold. */
2103 th = (unsigned) min_scalar_loop_bound;
2104 if (min_profitable_iters
2105 && (!min_scalar_loop_bound
2106 || min_profitable_iters > min_scalar_loop_bound))
2107 th = (unsigned) min_profitable_iters;
2109 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = th;
2111 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2112 && LOOP_VINFO_INT_NITERS (loop_vinfo) <= th)
2114 if (dump_enabled_p ())
2115 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2116 "not vectorized: vectorization not profitable.\n");
2117 if (dump_enabled_p ())
2118 dump_printf_loc (MSG_NOTE, vect_location,
2119 "not vectorized: iteration count smaller than user "
2120 "specified loop bound parameter or minimum profitable "
2121 "iterations (whichever is more conservative).\n");
2122 goto again;
2125 estimated_niter
2126 = estimated_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
2127 if (estimated_niter == -1)
2128 estimated_niter = max_niter;
2129 if (estimated_niter != -1
2130 && ((unsigned HOST_WIDE_INT) estimated_niter
2131 <= MAX (th, (unsigned)min_profitable_estimate)))
2133 if (dump_enabled_p ())
2134 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2135 "not vectorized: estimated iteration count too "
2136 "small.\n");
2137 if (dump_enabled_p ())
2138 dump_printf_loc (MSG_NOTE, vect_location,
2139 "not vectorized: estimated iteration count smaller "
2140 "than specified loop bound parameter or minimum "
2141 "profitable iterations (whichever is more "
2142 "conservative).\n");
2143 goto again;
2146 /* Decide whether we need to create an epilogue loop to handle
2147 remaining scalar iterations. */
2148 th = ((LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) + 1)
2149 / LOOP_VINFO_VECT_FACTOR (loop_vinfo))
2150 * LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2152 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2153 && LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) > 0)
2155 if (ctz_hwi (LOOP_VINFO_INT_NITERS (loop_vinfo)
2156 - LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo))
2157 < exact_log2 (LOOP_VINFO_VECT_FACTOR (loop_vinfo)))
2158 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = true;
2160 else if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
2161 || (tree_ctz (LOOP_VINFO_NITERS (loop_vinfo))
2162 < (unsigned)exact_log2 (LOOP_VINFO_VECT_FACTOR (loop_vinfo))
2163 /* In case of versioning, check if the maximum number of
2164 iterations is greater than th. If they are identical,
2165 the epilogue is unnecessary. */
2166 && (!LOOP_REQUIRES_VERSIONING (loop_vinfo)
2167 || (unsigned HOST_WIDE_INT) max_niter > th)))
2168 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = true;
2170 /* If an epilogue loop is required make sure we can create one. */
2171 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
2172 || LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo))
2174 if (dump_enabled_p ())
2175 dump_printf_loc (MSG_NOTE, vect_location, "epilog loop required\n");
2176 if (!vect_can_advance_ivs_p (loop_vinfo)
2177 || !slpeel_can_duplicate_loop_p (LOOP_VINFO_LOOP (loop_vinfo),
2178 single_exit (LOOP_VINFO_LOOP
2179 (loop_vinfo))))
2181 if (dump_enabled_p ())
2182 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2183 "not vectorized: can't create required "
2184 "epilog loop\n");
2185 goto again;
2189 gcc_assert (vectorization_factor
2190 == (unsigned)LOOP_VINFO_VECT_FACTOR (loop_vinfo));
2192 /* Ok to vectorize! */
2193 return true;
2195 again:
2196 /* Try again with SLP forced off but if we didn't do any SLP there is
2197 no point in re-trying. */
2198 if (!slp)
2199 return false;
2201 /* If there are reduction chains re-trying will fail anyway. */
2202 if (! LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo).is_empty ())
2203 return false;
2205 /* Likewise if the grouped loads or stores in the SLP cannot be handled
2206 via interleaving or lane instructions. */
2207 slp_instance instance;
2208 slp_tree node;
2209 unsigned i, j;
2210 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
2212 stmt_vec_info vinfo;
2213 vinfo = vinfo_for_stmt
2214 (SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (instance))[0]);
2215 if (! STMT_VINFO_GROUPED_ACCESS (vinfo))
2216 continue;
2217 vinfo = vinfo_for_stmt (STMT_VINFO_GROUP_FIRST_ELEMENT (vinfo));
2218 unsigned int size = STMT_VINFO_GROUP_SIZE (vinfo);
2219 tree vectype = STMT_VINFO_VECTYPE (vinfo);
2220 if (! vect_store_lanes_supported (vectype, size)
2221 && ! vect_grouped_store_supported (vectype, size))
2222 return false;
2223 FOR_EACH_VEC_ELT (SLP_INSTANCE_LOADS (instance), j, node)
2225 vinfo = vinfo_for_stmt (SLP_TREE_SCALAR_STMTS (node)[0]);
2226 vinfo = vinfo_for_stmt (STMT_VINFO_GROUP_FIRST_ELEMENT (vinfo));
2227 bool single_element_p = !STMT_VINFO_GROUP_NEXT_ELEMENT (vinfo);
2228 size = STMT_VINFO_GROUP_SIZE (vinfo);
2229 vectype = STMT_VINFO_VECTYPE (vinfo);
2230 if (! vect_load_lanes_supported (vectype, size)
2231 && ! vect_grouped_load_supported (vectype, single_element_p,
2232 size))
2233 return false;
2237 if (dump_enabled_p ())
2238 dump_printf_loc (MSG_NOTE, vect_location,
2239 "re-trying with SLP disabled\n");
2241 /* Roll back state appropriately. No SLP this time. */
2242 slp = false;
2243 /* Restore vectorization factor as it were without SLP. */
2244 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = saved_vectorization_factor;
2245 /* Free the SLP instances. */
2246 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), j, instance)
2247 vect_free_slp_instance (instance);
2248 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
2249 /* Reset SLP type to loop_vect on all stmts. */
2250 for (i = 0; i < LOOP_VINFO_LOOP (loop_vinfo)->num_nodes; ++i)
2252 basic_block bb = LOOP_VINFO_BBS (loop_vinfo)[i];
2253 for (gimple_stmt_iterator si = gsi_start_bb (bb);
2254 !gsi_end_p (si); gsi_next (&si))
2256 stmt_vec_info stmt_info = vinfo_for_stmt (gsi_stmt (si));
2257 STMT_SLP_TYPE (stmt_info) = loop_vect;
2258 if (STMT_VINFO_IN_PATTERN_P (stmt_info))
2260 stmt_info = vinfo_for_stmt (STMT_VINFO_RELATED_STMT (stmt_info));
2261 STMT_SLP_TYPE (stmt_info) = loop_vect;
2262 for (gimple_stmt_iterator pi
2263 = gsi_start (STMT_VINFO_PATTERN_DEF_SEQ (stmt_info));
2264 !gsi_end_p (pi); gsi_next (&pi))
2266 gimple *pstmt = gsi_stmt (pi);
2267 STMT_SLP_TYPE (vinfo_for_stmt (pstmt)) = loop_vect;
2272 /* Free optimized alias test DDRS. */
2273 LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).release ();
2274 /* Reset target cost data. */
2275 destroy_cost_data (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
2276 LOOP_VINFO_TARGET_COST_DATA (loop_vinfo)
2277 = init_cost (LOOP_VINFO_LOOP (loop_vinfo));
2278 /* Reset assorted flags. */
2279 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = false;
2280 LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) = false;
2281 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = 0;
2283 goto start_over;
2286 /* Function vect_analyze_loop.
2288 Apply a set of analyses on LOOP, and create a loop_vec_info struct
2289 for it. The different analyses will record information in the
2290 loop_vec_info struct. */
2291 loop_vec_info
2292 vect_analyze_loop (struct loop *loop)
2294 loop_vec_info loop_vinfo;
2295 unsigned int vector_sizes;
2297 /* Autodetect first vector size we try. */
2298 current_vector_size = 0;
2299 vector_sizes = targetm.vectorize.autovectorize_vector_sizes ();
2301 if (dump_enabled_p ())
2302 dump_printf_loc (MSG_NOTE, vect_location,
2303 "===== analyze_loop_nest =====\n");
2305 if (loop_outer (loop)
2306 && loop_vec_info_for_loop (loop_outer (loop))
2307 && LOOP_VINFO_VECTORIZABLE_P (loop_vec_info_for_loop (loop_outer (loop))))
2309 if (dump_enabled_p ())
2310 dump_printf_loc (MSG_NOTE, vect_location,
2311 "outer-loop already vectorized.\n");
2312 return NULL;
2315 while (1)
2317 /* Check the CFG characteristics of the loop (nesting, entry/exit). */
2318 loop_vinfo = vect_analyze_loop_form (loop);
2319 if (!loop_vinfo)
2321 if (dump_enabled_p ())
2322 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2323 "bad loop form.\n");
2324 return NULL;
2327 bool fatal = false;
2328 if (vect_analyze_loop_2 (loop_vinfo, fatal))
2330 LOOP_VINFO_VECTORIZABLE_P (loop_vinfo) = 1;
2332 return loop_vinfo;
2335 destroy_loop_vec_info (loop_vinfo, true);
2337 vector_sizes &= ~current_vector_size;
2338 if (fatal
2339 || vector_sizes == 0
2340 || current_vector_size == 0)
2341 return NULL;
2343 /* Try the next biggest vector size. */
2344 current_vector_size = 1 << floor_log2 (vector_sizes);
2345 if (dump_enabled_p ())
2346 dump_printf_loc (MSG_NOTE, vect_location,
2347 "***** Re-trying analysis with "
2348 "vector size %d\n", current_vector_size);
2353 /* Function reduction_code_for_scalar_code
2355 Input:
2356 CODE - tree_code of a reduction operations.
2358 Output:
2359 REDUC_CODE - the corresponding tree-code to be used to reduce the
2360 vector of partial results into a single scalar result, or ERROR_MARK
2361 if the operation is a supported reduction operation, but does not have
2362 such a tree-code.
2364 Return FALSE if CODE currently cannot be vectorized as reduction. */
2366 static bool
2367 reduction_code_for_scalar_code (enum tree_code code,
2368 enum tree_code *reduc_code)
2370 switch (code)
2372 case MAX_EXPR:
2373 *reduc_code = REDUC_MAX_EXPR;
2374 return true;
2376 case MIN_EXPR:
2377 *reduc_code = REDUC_MIN_EXPR;
2378 return true;
2380 case PLUS_EXPR:
2381 *reduc_code = REDUC_PLUS_EXPR;
2382 return true;
2384 case MULT_EXPR:
2385 case MINUS_EXPR:
2386 case BIT_IOR_EXPR:
2387 case BIT_XOR_EXPR:
2388 case BIT_AND_EXPR:
2389 *reduc_code = ERROR_MARK;
2390 return true;
2392 default:
2393 return false;
2398 /* Error reporting helper for vect_is_simple_reduction below. GIMPLE statement
2399 STMT is printed with a message MSG. */
2401 static void
2402 report_vect_op (int msg_type, gimple *stmt, const char *msg)
2404 dump_printf_loc (msg_type, vect_location, "%s", msg);
2405 dump_gimple_stmt (msg_type, TDF_SLIM, stmt, 0);
2409 /* Detect SLP reduction of the form:
2411 #a1 = phi <a5, a0>
2412 a2 = operation (a1)
2413 a3 = operation (a2)
2414 a4 = operation (a3)
2415 a5 = operation (a4)
2417 #a = phi <a5>
2419 PHI is the reduction phi node (#a1 = phi <a5, a0> above)
2420 FIRST_STMT is the first reduction stmt in the chain
2421 (a2 = operation (a1)).
2423 Return TRUE if a reduction chain was detected. */
2425 static bool
2426 vect_is_slp_reduction (loop_vec_info loop_info, gimple *phi,
2427 gimple *first_stmt)
2429 struct loop *loop = (gimple_bb (phi))->loop_father;
2430 struct loop *vect_loop = LOOP_VINFO_LOOP (loop_info);
2431 enum tree_code code;
2432 gimple *current_stmt = NULL, *loop_use_stmt = NULL, *first, *next_stmt;
2433 stmt_vec_info use_stmt_info, current_stmt_info;
2434 tree lhs;
2435 imm_use_iterator imm_iter;
2436 use_operand_p use_p;
2437 int nloop_uses, size = 0, n_out_of_loop_uses;
2438 bool found = false;
2440 if (loop != vect_loop)
2441 return false;
2443 lhs = PHI_RESULT (phi);
2444 code = gimple_assign_rhs_code (first_stmt);
2445 while (1)
2447 nloop_uses = 0;
2448 n_out_of_loop_uses = 0;
2449 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
2451 gimple *use_stmt = USE_STMT (use_p);
2452 if (is_gimple_debug (use_stmt))
2453 continue;
2455 /* Check if we got back to the reduction phi. */
2456 if (use_stmt == phi)
2458 loop_use_stmt = use_stmt;
2459 found = true;
2460 break;
2463 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2465 loop_use_stmt = use_stmt;
2466 nloop_uses++;
2468 else
2469 n_out_of_loop_uses++;
2471 /* There are can be either a single use in the loop or two uses in
2472 phi nodes. */
2473 if (nloop_uses > 1 || (n_out_of_loop_uses && nloop_uses))
2474 return false;
2477 if (found)
2478 break;
2480 /* We reached a statement with no loop uses. */
2481 if (nloop_uses == 0)
2482 return false;
2484 /* This is a loop exit phi, and we haven't reached the reduction phi. */
2485 if (gimple_code (loop_use_stmt) == GIMPLE_PHI)
2486 return false;
2488 if (!is_gimple_assign (loop_use_stmt)
2489 || code != gimple_assign_rhs_code (loop_use_stmt)
2490 || !flow_bb_inside_loop_p (loop, gimple_bb (loop_use_stmt)))
2491 return false;
2493 /* Insert USE_STMT into reduction chain. */
2494 use_stmt_info = vinfo_for_stmt (loop_use_stmt);
2495 if (current_stmt)
2497 current_stmt_info = vinfo_for_stmt (current_stmt);
2498 GROUP_NEXT_ELEMENT (current_stmt_info) = loop_use_stmt;
2499 GROUP_FIRST_ELEMENT (use_stmt_info)
2500 = GROUP_FIRST_ELEMENT (current_stmt_info);
2502 else
2503 GROUP_FIRST_ELEMENT (use_stmt_info) = loop_use_stmt;
2505 lhs = gimple_assign_lhs (loop_use_stmt);
2506 current_stmt = loop_use_stmt;
2507 size++;
2510 if (!found || loop_use_stmt != phi || size < 2)
2511 return false;
2513 /* Swap the operands, if needed, to make the reduction operand be the second
2514 operand. */
2515 lhs = PHI_RESULT (phi);
2516 next_stmt = GROUP_FIRST_ELEMENT (vinfo_for_stmt (current_stmt));
2517 while (next_stmt)
2519 if (gimple_assign_rhs2 (next_stmt) == lhs)
2521 tree op = gimple_assign_rhs1 (next_stmt);
2522 gimple *def_stmt = NULL;
2524 if (TREE_CODE (op) == SSA_NAME)
2525 def_stmt = SSA_NAME_DEF_STMT (op);
2527 /* Check that the other def is either defined in the loop
2528 ("vect_internal_def"), or it's an induction (defined by a
2529 loop-header phi-node). */
2530 if (def_stmt
2531 && gimple_bb (def_stmt)
2532 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2533 && (is_gimple_assign (def_stmt)
2534 || is_gimple_call (def_stmt)
2535 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2536 == vect_induction_def
2537 || (gimple_code (def_stmt) == GIMPLE_PHI
2538 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2539 == vect_internal_def
2540 && !is_loop_header_bb_p (gimple_bb (def_stmt)))))
2542 lhs = gimple_assign_lhs (next_stmt);
2543 next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
2544 continue;
2547 return false;
2549 else
2551 tree op = gimple_assign_rhs2 (next_stmt);
2552 gimple *def_stmt = NULL;
2554 if (TREE_CODE (op) == SSA_NAME)
2555 def_stmt = SSA_NAME_DEF_STMT (op);
2557 /* Check that the other def is either defined in the loop
2558 ("vect_internal_def"), or it's an induction (defined by a
2559 loop-header phi-node). */
2560 if (def_stmt
2561 && gimple_bb (def_stmt)
2562 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2563 && (is_gimple_assign (def_stmt)
2564 || is_gimple_call (def_stmt)
2565 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2566 == vect_induction_def
2567 || (gimple_code (def_stmt) == GIMPLE_PHI
2568 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2569 == vect_internal_def
2570 && !is_loop_header_bb_p (gimple_bb (def_stmt)))))
2572 if (dump_enabled_p ())
2574 dump_printf_loc (MSG_NOTE, vect_location, "swapping oprnds: ");
2575 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, next_stmt, 0);
2578 swap_ssa_operands (next_stmt,
2579 gimple_assign_rhs1_ptr (next_stmt),
2580 gimple_assign_rhs2_ptr (next_stmt));
2581 update_stmt (next_stmt);
2583 if (CONSTANT_CLASS_P (gimple_assign_rhs1 (next_stmt)))
2584 LOOP_VINFO_OPERANDS_SWAPPED (loop_info) = true;
2586 else
2587 return false;
2590 lhs = gimple_assign_lhs (next_stmt);
2591 next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
2594 /* Save the chain for further analysis in SLP detection. */
2595 first = GROUP_FIRST_ELEMENT (vinfo_for_stmt (current_stmt));
2596 LOOP_VINFO_REDUCTION_CHAINS (loop_info).safe_push (first);
2597 GROUP_SIZE (vinfo_for_stmt (first)) = size;
2599 return true;
2603 /* Function vect_is_simple_reduction_1
2605 (1) Detect a cross-iteration def-use cycle that represents a simple
2606 reduction computation. We look for the following pattern:
2608 loop_header:
2609 a1 = phi < a0, a2 >
2610 a3 = ...
2611 a2 = operation (a3, a1)
2615 a3 = ...
2616 loop_header:
2617 a1 = phi < a0, a2 >
2618 a2 = operation (a3, a1)
2620 such that:
2621 1. operation is commutative and associative and it is safe to
2622 change the order of the computation (if CHECK_REDUCTION is true)
2623 2. no uses for a2 in the loop (a2 is used out of the loop)
2624 3. no uses of a1 in the loop besides the reduction operation
2625 4. no uses of a1 outside the loop.
2627 Conditions 1,4 are tested here.
2628 Conditions 2,3 are tested in vect_mark_stmts_to_be_vectorized.
2630 (2) Detect a cross-iteration def-use cycle in nested loops, i.e.,
2631 nested cycles, if CHECK_REDUCTION is false.
2633 (3) Detect cycles of phi nodes in outer-loop vectorization, i.e., double
2634 reductions:
2636 a1 = phi < a0, a2 >
2637 inner loop (def of a3)
2638 a2 = phi < a3 >
2640 (4) Detect condition expressions, ie:
2641 for (int i = 0; i < N; i++)
2642 if (a[i] < val)
2643 ret_val = a[i];
2647 static gimple *
2648 vect_is_simple_reduction (loop_vec_info loop_info, gimple *phi,
2649 bool check_reduction, bool *double_reduc,
2650 bool need_wrapping_integral_overflow,
2651 enum vect_reduction_type *v_reduc_type)
2653 struct loop *loop = (gimple_bb (phi))->loop_father;
2654 struct loop *vect_loop = LOOP_VINFO_LOOP (loop_info);
2655 edge latch_e = loop_latch_edge (loop);
2656 tree loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
2657 gimple *def_stmt, *def1 = NULL, *def2 = NULL, *phi_use_stmt = NULL;
2658 enum tree_code orig_code, code;
2659 tree op1, op2, op3 = NULL_TREE, op4 = NULL_TREE;
2660 tree type;
2661 int nloop_uses;
2662 tree name;
2663 imm_use_iterator imm_iter;
2664 use_operand_p use_p;
2665 bool phi_def;
2667 *double_reduc = false;
2668 *v_reduc_type = TREE_CODE_REDUCTION;
2670 /* If CHECK_REDUCTION is true, we assume inner-most loop vectorization,
2671 otherwise, we assume outer loop vectorization. */
2672 gcc_assert ((check_reduction && loop == vect_loop)
2673 || (!check_reduction && flow_loop_nested_p (vect_loop, loop)));
2675 name = PHI_RESULT (phi);
2676 /* ??? If there are no uses of the PHI result the inner loop reduction
2677 won't be detected as possibly double-reduction by vectorizable_reduction
2678 because that tries to walk the PHI arg from the preheader edge which
2679 can be constant. See PR60382. */
2680 if (has_zero_uses (name))
2681 return NULL;
2682 nloop_uses = 0;
2683 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, name)
2685 gimple *use_stmt = USE_STMT (use_p);
2686 if (is_gimple_debug (use_stmt))
2687 continue;
2689 if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2691 if (dump_enabled_p ())
2692 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2693 "intermediate value used outside loop.\n");
2695 return NULL;
2698 nloop_uses++;
2699 if (nloop_uses > 1)
2701 if (dump_enabled_p ())
2702 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2703 "reduction used in loop.\n");
2704 return NULL;
2707 phi_use_stmt = use_stmt;
2710 if (TREE_CODE (loop_arg) != SSA_NAME)
2712 if (dump_enabled_p ())
2714 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2715 "reduction: not ssa_name: ");
2716 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, loop_arg);
2717 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
2719 return NULL;
2722 def_stmt = SSA_NAME_DEF_STMT (loop_arg);
2723 if (!def_stmt)
2725 if (dump_enabled_p ())
2726 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2727 "reduction: no def_stmt.\n");
2728 return NULL;
2731 if (!is_gimple_assign (def_stmt) && gimple_code (def_stmt) != GIMPLE_PHI)
2733 if (dump_enabled_p ())
2734 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, def_stmt, 0);
2735 return NULL;
2738 if (is_gimple_assign (def_stmt))
2740 name = gimple_assign_lhs (def_stmt);
2741 phi_def = false;
2743 else
2745 name = PHI_RESULT (def_stmt);
2746 phi_def = true;
2749 nloop_uses = 0;
2750 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, name)
2752 gimple *use_stmt = USE_STMT (use_p);
2753 if (is_gimple_debug (use_stmt))
2754 continue;
2755 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2756 nloop_uses++;
2757 if (nloop_uses > 1)
2759 if (dump_enabled_p ())
2760 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2761 "reduction used in loop.\n");
2762 return NULL;
2766 /* If DEF_STMT is a phi node itself, we expect it to have a single argument
2767 defined in the inner loop. */
2768 if (phi_def)
2770 op1 = PHI_ARG_DEF (def_stmt, 0);
2772 if (gimple_phi_num_args (def_stmt) != 1
2773 || TREE_CODE (op1) != SSA_NAME)
2775 if (dump_enabled_p ())
2776 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2777 "unsupported phi node definition.\n");
2779 return NULL;
2782 def1 = SSA_NAME_DEF_STMT (op1);
2783 if (gimple_bb (def1)
2784 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2785 && loop->inner
2786 && flow_bb_inside_loop_p (loop->inner, gimple_bb (def1))
2787 && is_gimple_assign (def1)
2788 && flow_bb_inside_loop_p (loop->inner, gimple_bb (phi_use_stmt)))
2790 if (dump_enabled_p ())
2791 report_vect_op (MSG_NOTE, def_stmt,
2792 "detected double reduction: ");
2794 *double_reduc = true;
2795 return def_stmt;
2798 return NULL;
2801 code = orig_code = gimple_assign_rhs_code (def_stmt);
2803 /* We can handle "res -= x[i]", which is non-associative by
2804 simply rewriting this into "res += -x[i]". Avoid changing
2805 gimple instruction for the first simple tests and only do this
2806 if we're allowed to change code at all. */
2807 if (code == MINUS_EXPR
2808 && (op1 = gimple_assign_rhs1 (def_stmt))
2809 && TREE_CODE (op1) == SSA_NAME
2810 && SSA_NAME_DEF_STMT (op1) == phi)
2811 code = PLUS_EXPR;
2813 if (code == COND_EXPR)
2815 if (check_reduction)
2816 *v_reduc_type = COND_REDUCTION;
2818 else if (!commutative_tree_code (code) || !associative_tree_code (code))
2820 if (dump_enabled_p ())
2821 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2822 "reduction: not commutative/associative: ");
2823 return NULL;
2826 if (get_gimple_rhs_class (code) != GIMPLE_BINARY_RHS)
2828 if (code != COND_EXPR)
2830 if (dump_enabled_p ())
2831 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2832 "reduction: not binary operation: ");
2834 return NULL;
2837 op3 = gimple_assign_rhs1 (def_stmt);
2838 if (COMPARISON_CLASS_P (op3))
2840 op4 = TREE_OPERAND (op3, 1);
2841 op3 = TREE_OPERAND (op3, 0);
2844 op1 = gimple_assign_rhs2 (def_stmt);
2845 op2 = gimple_assign_rhs3 (def_stmt);
2847 if (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op2) != SSA_NAME)
2849 if (dump_enabled_p ())
2850 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2851 "reduction: uses not ssa_names: ");
2853 return NULL;
2856 else
2858 op1 = gimple_assign_rhs1 (def_stmt);
2859 op2 = gimple_assign_rhs2 (def_stmt);
2861 if (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op2) != SSA_NAME)
2863 if (dump_enabled_p ())
2864 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2865 "reduction: uses not ssa_names: ");
2867 return NULL;
2871 type = TREE_TYPE (gimple_assign_lhs (def_stmt));
2872 if ((TREE_CODE (op1) == SSA_NAME
2873 && !types_compatible_p (type,TREE_TYPE (op1)))
2874 || (TREE_CODE (op2) == SSA_NAME
2875 && !types_compatible_p (type, TREE_TYPE (op2)))
2876 || (op3 && TREE_CODE (op3) == SSA_NAME
2877 && !types_compatible_p (type, TREE_TYPE (op3)))
2878 || (op4 && TREE_CODE (op4) == SSA_NAME
2879 && !types_compatible_p (type, TREE_TYPE (op4))))
2881 if (dump_enabled_p ())
2883 dump_printf_loc (MSG_NOTE, vect_location,
2884 "reduction: multiple types: operation type: ");
2885 dump_generic_expr (MSG_NOTE, TDF_SLIM, type);
2886 dump_printf (MSG_NOTE, ", operands types: ");
2887 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2888 TREE_TYPE (op1));
2889 dump_printf (MSG_NOTE, ",");
2890 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2891 TREE_TYPE (op2));
2892 if (op3)
2894 dump_printf (MSG_NOTE, ",");
2895 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2896 TREE_TYPE (op3));
2899 if (op4)
2901 dump_printf (MSG_NOTE, ",");
2902 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2903 TREE_TYPE (op4));
2905 dump_printf (MSG_NOTE, "\n");
2908 return NULL;
2911 /* Check that it's ok to change the order of the computation.
2912 Generally, when vectorizing a reduction we change the order of the
2913 computation. This may change the behavior of the program in some
2914 cases, so we need to check that this is ok. One exception is when
2915 vectorizing an outer-loop: the inner-loop is executed sequentially,
2916 and therefore vectorizing reductions in the inner-loop during
2917 outer-loop vectorization is safe. */
2919 if (*v_reduc_type != COND_REDUCTION
2920 && check_reduction)
2922 /* CHECKME: check for !flag_finite_math_only too? */
2923 if (SCALAR_FLOAT_TYPE_P (type) && !flag_associative_math)
2925 /* Changing the order of operations changes the semantics. */
2926 if (dump_enabled_p ())
2927 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2928 "reduction: unsafe fp math optimization: ");
2929 return NULL;
2931 else if (INTEGRAL_TYPE_P (type))
2933 if (!operation_no_trapping_overflow (type, code))
2935 /* Changing the order of operations changes the semantics. */
2936 if (dump_enabled_p ())
2937 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2938 "reduction: unsafe int math optimization"
2939 " (overflow traps): ");
2940 return NULL;
2942 if (need_wrapping_integral_overflow
2943 && !TYPE_OVERFLOW_WRAPS (type)
2944 && operation_can_overflow (code))
2946 /* Changing the order of operations changes the semantics. */
2947 if (dump_enabled_p ())
2948 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2949 "reduction: unsafe int math optimization"
2950 " (overflow doesn't wrap): ");
2951 return NULL;
2954 else if (SAT_FIXED_POINT_TYPE_P (type))
2956 /* Changing the order of operations changes the semantics. */
2957 if (dump_enabled_p ())
2958 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2959 "reduction: unsafe fixed-point math optimization: ");
2960 return NULL;
2964 /* Reduction is safe. We're dealing with one of the following:
2965 1) integer arithmetic and no trapv
2966 2) floating point arithmetic, and special flags permit this optimization
2967 3) nested cycle (i.e., outer loop vectorization). */
2968 if (TREE_CODE (op1) == SSA_NAME)
2969 def1 = SSA_NAME_DEF_STMT (op1);
2971 if (TREE_CODE (op2) == SSA_NAME)
2972 def2 = SSA_NAME_DEF_STMT (op2);
2974 if (code != COND_EXPR
2975 && ((!def1 || gimple_nop_p (def1)) && (!def2 || gimple_nop_p (def2))))
2977 if (dump_enabled_p ())
2978 report_vect_op (MSG_NOTE, def_stmt, "reduction: no defs for operands: ");
2979 return NULL;
2982 /* Check that one def is the reduction def, defined by PHI,
2983 the other def is either defined in the loop ("vect_internal_def"),
2984 or it's an induction (defined by a loop-header phi-node). */
2986 if (def2 && def2 == phi
2987 && (code == COND_EXPR
2988 || !def1 || gimple_nop_p (def1)
2989 || !flow_bb_inside_loop_p (loop, gimple_bb (def1))
2990 || (def1 && flow_bb_inside_loop_p (loop, gimple_bb (def1))
2991 && (is_gimple_assign (def1)
2992 || is_gimple_call (def1)
2993 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def1))
2994 == vect_induction_def
2995 || (gimple_code (def1) == GIMPLE_PHI
2996 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def1))
2997 == vect_internal_def
2998 && !is_loop_header_bb_p (gimple_bb (def1)))))))
3000 if (dump_enabled_p ())
3001 report_vect_op (MSG_NOTE, def_stmt, "detected reduction: ");
3002 return def_stmt;
3005 if (def1 && def1 == phi
3006 && (code == COND_EXPR
3007 || !def2 || gimple_nop_p (def2)
3008 || !flow_bb_inside_loop_p (loop, gimple_bb (def2))
3009 || (def2 && flow_bb_inside_loop_p (loop, gimple_bb (def2))
3010 && (is_gimple_assign (def2)
3011 || is_gimple_call (def2)
3012 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def2))
3013 == vect_induction_def
3014 || (gimple_code (def2) == GIMPLE_PHI
3015 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def2))
3016 == vect_internal_def
3017 && !is_loop_header_bb_p (gimple_bb (def2)))))))
3019 if (check_reduction
3020 && orig_code != MINUS_EXPR)
3022 if (code == COND_EXPR)
3024 /* No current known use where this case would be useful. */
3025 if (dump_enabled_p ())
3026 report_vect_op (MSG_NOTE, def_stmt,
3027 "detected reduction: cannot currently swap "
3028 "operands for cond_expr");
3029 return NULL;
3032 /* Swap operands (just for simplicity - so that the rest of the code
3033 can assume that the reduction variable is always the last (second)
3034 argument). */
3035 if (dump_enabled_p ())
3036 report_vect_op (MSG_NOTE, def_stmt,
3037 "detected reduction: need to swap operands: ");
3039 swap_ssa_operands (def_stmt, gimple_assign_rhs1_ptr (def_stmt),
3040 gimple_assign_rhs2_ptr (def_stmt));
3042 if (CONSTANT_CLASS_P (gimple_assign_rhs1 (def_stmt)))
3043 LOOP_VINFO_OPERANDS_SWAPPED (loop_info) = true;
3045 else
3047 if (dump_enabled_p ())
3048 report_vect_op (MSG_NOTE, def_stmt, "detected reduction: ");
3051 return def_stmt;
3054 /* Try to find SLP reduction chain. */
3055 if (check_reduction && code != COND_EXPR
3056 && vect_is_slp_reduction (loop_info, phi, def_stmt))
3058 if (dump_enabled_p ())
3059 report_vect_op (MSG_NOTE, def_stmt,
3060 "reduction: detected reduction chain: ");
3062 return def_stmt;
3065 if (dump_enabled_p ())
3066 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
3067 "reduction: unknown pattern: ");
3069 return NULL;
3072 /* Wrapper around vect_is_simple_reduction_1, which will modify code
3073 in-place if it enables detection of more reductions. Arguments
3074 as there. */
3076 gimple *
3077 vect_force_simple_reduction (loop_vec_info loop_info, gimple *phi,
3078 bool check_reduction, bool *double_reduc,
3079 bool need_wrapping_integral_overflow)
3081 enum vect_reduction_type v_reduc_type;
3082 return vect_is_simple_reduction (loop_info, phi, check_reduction,
3083 double_reduc,
3084 need_wrapping_integral_overflow,
3085 &v_reduc_type);
3088 /* Calculate cost of peeling the loop PEEL_ITERS_PROLOGUE times. */
3090 vect_get_known_peeling_cost (loop_vec_info loop_vinfo, int peel_iters_prologue,
3091 int *peel_iters_epilogue,
3092 stmt_vector_for_cost *scalar_cost_vec,
3093 stmt_vector_for_cost *prologue_cost_vec,
3094 stmt_vector_for_cost *epilogue_cost_vec)
3096 int retval = 0;
3097 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3099 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
3101 *peel_iters_epilogue = vf/2;
3102 if (dump_enabled_p ())
3103 dump_printf_loc (MSG_NOTE, vect_location,
3104 "cost model: epilogue peel iters set to vf/2 "
3105 "because loop iterations are unknown .\n");
3107 /* If peeled iterations are known but number of scalar loop
3108 iterations are unknown, count a taken branch per peeled loop. */
3109 retval = record_stmt_cost (prologue_cost_vec, 1, cond_branch_taken,
3110 NULL, 0, vect_prologue);
3111 retval = record_stmt_cost (prologue_cost_vec, 1, cond_branch_taken,
3112 NULL, 0, vect_epilogue);
3114 else
3116 int niters = LOOP_VINFO_INT_NITERS (loop_vinfo);
3117 peel_iters_prologue = niters < peel_iters_prologue ?
3118 niters : peel_iters_prologue;
3119 *peel_iters_epilogue = (niters - peel_iters_prologue) % vf;
3120 /* If we need to peel for gaps, but no peeling is required, we have to
3121 peel VF iterations. */
3122 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) && !*peel_iters_epilogue)
3123 *peel_iters_epilogue = vf;
3126 stmt_info_for_cost *si;
3127 int j;
3128 if (peel_iters_prologue)
3129 FOR_EACH_VEC_ELT (*scalar_cost_vec, j, si)
3130 retval += record_stmt_cost (prologue_cost_vec,
3131 si->count * peel_iters_prologue,
3132 si->kind, NULL, si->misalign,
3133 vect_prologue);
3134 if (*peel_iters_epilogue)
3135 FOR_EACH_VEC_ELT (*scalar_cost_vec, j, si)
3136 retval += record_stmt_cost (epilogue_cost_vec,
3137 si->count * *peel_iters_epilogue,
3138 si->kind, NULL, si->misalign,
3139 vect_epilogue);
3141 return retval;
3144 /* Function vect_estimate_min_profitable_iters
3146 Return the number of iterations required for the vector version of the
3147 loop to be profitable relative to the cost of the scalar version of the
3148 loop.
3150 *RET_MIN_PROFITABLE_NITERS is a cost model profitability threshold
3151 of iterations for vectorization. -1 value means loop vectorization
3152 is not profitable. This returned value may be used for dynamic
3153 profitability check.
3155 *RET_MIN_PROFITABLE_ESTIMATE is a profitability threshold to be used
3156 for static check against estimated number of iterations. */
3158 static void
3159 vect_estimate_min_profitable_iters (loop_vec_info loop_vinfo,
3160 int *ret_min_profitable_niters,
3161 int *ret_min_profitable_estimate)
3163 int min_profitable_iters;
3164 int min_profitable_estimate;
3165 int peel_iters_prologue;
3166 int peel_iters_epilogue;
3167 unsigned vec_inside_cost = 0;
3168 int vec_outside_cost = 0;
3169 unsigned vec_prologue_cost = 0;
3170 unsigned vec_epilogue_cost = 0;
3171 int scalar_single_iter_cost = 0;
3172 int scalar_outside_cost = 0;
3173 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3174 int npeel = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
3175 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3177 /* Cost model disabled. */
3178 if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
3180 dump_printf_loc (MSG_NOTE, vect_location, "cost model disabled.\n");
3181 *ret_min_profitable_niters = 0;
3182 *ret_min_profitable_estimate = 0;
3183 return;
3186 /* Requires loop versioning tests to handle misalignment. */
3187 if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo))
3189 /* FIXME: Make cost depend on complexity of individual check. */
3190 unsigned len = LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).length ();
3191 (void) add_stmt_cost (target_cost_data, len, vector_stmt, NULL, 0,
3192 vect_prologue);
3193 dump_printf (MSG_NOTE,
3194 "cost model: Adding cost of checks for loop "
3195 "versioning to treat misalignment.\n");
3198 /* Requires loop versioning with alias checks. */
3199 if (LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
3201 /* FIXME: Make cost depend on complexity of individual check. */
3202 unsigned len = LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).length ();
3203 (void) add_stmt_cost (target_cost_data, len, vector_stmt, NULL, 0,
3204 vect_prologue);
3205 dump_printf (MSG_NOTE,
3206 "cost model: Adding cost of checks for loop "
3207 "versioning aliasing.\n");
3210 /* Requires loop versioning with niter checks. */
3211 if (LOOP_REQUIRES_VERSIONING_FOR_NITERS (loop_vinfo))
3213 /* FIXME: Make cost depend on complexity of individual check. */
3214 (void) add_stmt_cost (target_cost_data, 1, vector_stmt, NULL, 0,
3215 vect_prologue);
3216 dump_printf (MSG_NOTE,
3217 "cost model: Adding cost of checks for loop "
3218 "versioning niters.\n");
3221 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
3222 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken, NULL, 0,
3223 vect_prologue);
3225 /* Count statements in scalar loop. Using this as scalar cost for a single
3226 iteration for now.
3228 TODO: Add outer loop support.
3230 TODO: Consider assigning different costs to different scalar
3231 statements. */
3233 scalar_single_iter_cost
3234 = LOOP_VINFO_SINGLE_SCALAR_ITERATION_COST (loop_vinfo);
3236 /* Add additional cost for the peeled instructions in prologue and epilogue
3237 loop.
3239 FORNOW: If we don't know the value of peel_iters for prologue or epilogue
3240 at compile-time - we assume it's vf/2 (the worst would be vf-1).
3242 TODO: Build an expression that represents peel_iters for prologue and
3243 epilogue to be used in a run-time test. */
3245 if (npeel < 0)
3247 peel_iters_prologue = vf/2;
3248 dump_printf (MSG_NOTE, "cost model: "
3249 "prologue peel iters set to vf/2.\n");
3251 /* If peeling for alignment is unknown, loop bound of main loop becomes
3252 unknown. */
3253 peel_iters_epilogue = vf/2;
3254 dump_printf (MSG_NOTE, "cost model: "
3255 "epilogue peel iters set to vf/2 because "
3256 "peeling for alignment is unknown.\n");
3258 /* If peeled iterations are unknown, count a taken branch and a not taken
3259 branch per peeled loop. Even if scalar loop iterations are known,
3260 vector iterations are not known since peeled prologue iterations are
3261 not known. Hence guards remain the same. */
3262 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
3263 NULL, 0, vect_prologue);
3264 (void) add_stmt_cost (target_cost_data, 1, cond_branch_not_taken,
3265 NULL, 0, vect_prologue);
3266 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
3267 NULL, 0, vect_epilogue);
3268 (void) add_stmt_cost (target_cost_data, 1, cond_branch_not_taken,
3269 NULL, 0, vect_epilogue);
3270 stmt_info_for_cost *si;
3271 int j;
3272 FOR_EACH_VEC_ELT (LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo), j, si)
3274 struct _stmt_vec_info *stmt_info
3275 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3276 (void) add_stmt_cost (target_cost_data,
3277 si->count * peel_iters_prologue,
3278 si->kind, stmt_info, si->misalign,
3279 vect_prologue);
3280 (void) add_stmt_cost (target_cost_data,
3281 si->count * peel_iters_epilogue,
3282 si->kind, stmt_info, si->misalign,
3283 vect_epilogue);
3286 else
3288 stmt_vector_for_cost prologue_cost_vec, epilogue_cost_vec;
3289 stmt_info_for_cost *si;
3290 int j;
3291 void *data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3293 prologue_cost_vec.create (2);
3294 epilogue_cost_vec.create (2);
3295 peel_iters_prologue = npeel;
3297 (void) vect_get_known_peeling_cost (loop_vinfo, peel_iters_prologue,
3298 &peel_iters_epilogue,
3299 &LOOP_VINFO_SCALAR_ITERATION_COST
3300 (loop_vinfo),
3301 &prologue_cost_vec,
3302 &epilogue_cost_vec);
3304 FOR_EACH_VEC_ELT (prologue_cost_vec, j, si)
3306 struct _stmt_vec_info *stmt_info
3307 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3308 (void) add_stmt_cost (data, si->count, si->kind, stmt_info,
3309 si->misalign, vect_prologue);
3312 FOR_EACH_VEC_ELT (epilogue_cost_vec, j, si)
3314 struct _stmt_vec_info *stmt_info
3315 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3316 (void) add_stmt_cost (data, si->count, si->kind, stmt_info,
3317 si->misalign, vect_epilogue);
3320 prologue_cost_vec.release ();
3321 epilogue_cost_vec.release ();
3324 /* FORNOW: The scalar outside cost is incremented in one of the
3325 following ways:
3327 1. The vectorizer checks for alignment and aliasing and generates
3328 a condition that allows dynamic vectorization. A cost model
3329 check is ANDED with the versioning condition. Hence scalar code
3330 path now has the added cost of the versioning check.
3332 if (cost > th & versioning_check)
3333 jmp to vector code
3335 Hence run-time scalar is incremented by not-taken branch cost.
3337 2. The vectorizer then checks if a prologue is required. If the
3338 cost model check was not done before during versioning, it has to
3339 be done before the prologue check.
3341 if (cost <= th)
3342 prologue = scalar_iters
3343 if (prologue == 0)
3344 jmp to vector code
3345 else
3346 execute prologue
3347 if (prologue == num_iters)
3348 go to exit
3350 Hence the run-time scalar cost is incremented by a taken branch,
3351 plus a not-taken branch, plus a taken branch cost.
3353 3. The vectorizer then checks if an epilogue is required. If the
3354 cost model check was not done before during prologue check, it
3355 has to be done with the epilogue check.
3357 if (prologue == 0)
3358 jmp to vector code
3359 else
3360 execute prologue
3361 if (prologue == num_iters)
3362 go to exit
3363 vector code:
3364 if ((cost <= th) | (scalar_iters-prologue-epilogue == 0))
3365 jmp to epilogue
3367 Hence the run-time scalar cost should be incremented by 2 taken
3368 branches.
3370 TODO: The back end may reorder the BBS's differently and reverse
3371 conditions/branch directions. Change the estimates below to
3372 something more reasonable. */
3374 /* If the number of iterations is known and we do not do versioning, we can
3375 decide whether to vectorize at compile time. Hence the scalar version
3376 do not carry cost model guard costs. */
3377 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
3378 || LOOP_REQUIRES_VERSIONING (loop_vinfo))
3380 /* Cost model check occurs at versioning. */
3381 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
3382 scalar_outside_cost += vect_get_stmt_cost (cond_branch_not_taken);
3383 else
3385 /* Cost model check occurs at prologue generation. */
3386 if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
3387 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken)
3388 + vect_get_stmt_cost (cond_branch_not_taken);
3389 /* Cost model check occurs at epilogue generation. */
3390 else
3391 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken);
3395 /* Complete the target-specific cost calculations. */
3396 finish_cost (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo), &vec_prologue_cost,
3397 &vec_inside_cost, &vec_epilogue_cost);
3399 vec_outside_cost = (int)(vec_prologue_cost + vec_epilogue_cost);
3401 if (dump_enabled_p ())
3403 dump_printf_loc (MSG_NOTE, vect_location, "Cost model analysis: \n");
3404 dump_printf (MSG_NOTE, " Vector inside of loop cost: %d\n",
3405 vec_inside_cost);
3406 dump_printf (MSG_NOTE, " Vector prologue cost: %d\n",
3407 vec_prologue_cost);
3408 dump_printf (MSG_NOTE, " Vector epilogue cost: %d\n",
3409 vec_epilogue_cost);
3410 dump_printf (MSG_NOTE, " Scalar iteration cost: %d\n",
3411 scalar_single_iter_cost);
3412 dump_printf (MSG_NOTE, " Scalar outside cost: %d\n",
3413 scalar_outside_cost);
3414 dump_printf (MSG_NOTE, " Vector outside cost: %d\n",
3415 vec_outside_cost);
3416 dump_printf (MSG_NOTE, " prologue iterations: %d\n",
3417 peel_iters_prologue);
3418 dump_printf (MSG_NOTE, " epilogue iterations: %d\n",
3419 peel_iters_epilogue);
3422 /* Calculate number of iterations required to make the vector version
3423 profitable, relative to the loop bodies only. The following condition
3424 must hold true:
3425 SIC * niters + SOC > VIC * ((niters-PL_ITERS-EP_ITERS)/VF) + VOC
3426 where
3427 SIC = scalar iteration cost, VIC = vector iteration cost,
3428 VOC = vector outside cost, VF = vectorization factor,
3429 PL_ITERS = prologue iterations, EP_ITERS= epilogue iterations
3430 SOC = scalar outside cost for run time cost model check. */
3432 if ((scalar_single_iter_cost * vf) > (int) vec_inside_cost)
3434 if (vec_outside_cost <= 0)
3435 min_profitable_iters = 1;
3436 else
3438 min_profitable_iters = ((vec_outside_cost - scalar_outside_cost) * vf
3439 - vec_inside_cost * peel_iters_prologue
3440 - vec_inside_cost * peel_iters_epilogue)
3441 / ((scalar_single_iter_cost * vf)
3442 - vec_inside_cost);
3444 if ((scalar_single_iter_cost * vf * min_profitable_iters)
3445 <= (((int) vec_inside_cost * min_profitable_iters)
3446 + (((int) vec_outside_cost - scalar_outside_cost) * vf)))
3447 min_profitable_iters++;
3450 /* vector version will never be profitable. */
3451 else
3453 if (LOOP_VINFO_LOOP (loop_vinfo)->force_vectorize)
3454 warning_at (vect_location, OPT_Wopenmp_simd, "vectorization "
3455 "did not happen for a simd loop");
3457 if (dump_enabled_p ())
3458 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3459 "cost model: the vector iteration cost = %d "
3460 "divided by the scalar iteration cost = %d "
3461 "is greater or equal to the vectorization factor = %d"
3462 ".\n",
3463 vec_inside_cost, scalar_single_iter_cost, vf);
3464 *ret_min_profitable_niters = -1;
3465 *ret_min_profitable_estimate = -1;
3466 return;
3469 dump_printf (MSG_NOTE,
3470 " Calculated minimum iters for profitability: %d\n",
3471 min_profitable_iters);
3473 min_profitable_iters =
3474 min_profitable_iters < vf ? vf : min_profitable_iters;
3476 /* Because the condition we create is:
3477 if (niters <= min_profitable_iters)
3478 then skip the vectorized loop. */
3479 min_profitable_iters--;
3481 if (dump_enabled_p ())
3482 dump_printf_loc (MSG_NOTE, vect_location,
3483 " Runtime profitability threshold = %d\n",
3484 min_profitable_iters);
3486 *ret_min_profitable_niters = min_profitable_iters;
3488 /* Calculate number of iterations required to make the vector version
3489 profitable, relative to the loop bodies only.
3491 Non-vectorized variant is SIC * niters and it must win over vector
3492 variant on the expected loop trip count. The following condition must hold true:
3493 SIC * niters > VIC * ((niters-PL_ITERS-EP_ITERS)/VF) + VOC + SOC */
3495 if (vec_outside_cost <= 0)
3496 min_profitable_estimate = 1;
3497 else
3499 min_profitable_estimate = ((vec_outside_cost + scalar_outside_cost) * vf
3500 - vec_inside_cost * peel_iters_prologue
3501 - vec_inside_cost * peel_iters_epilogue)
3502 / ((scalar_single_iter_cost * vf)
3503 - vec_inside_cost);
3505 min_profitable_estimate --;
3506 min_profitable_estimate = MAX (min_profitable_estimate, min_profitable_iters);
3507 if (dump_enabled_p ())
3508 dump_printf_loc (MSG_NOTE, vect_location,
3509 " Static estimate profitability threshold = %d\n",
3510 min_profitable_estimate);
3512 *ret_min_profitable_estimate = min_profitable_estimate;
3515 /* Writes into SEL a mask for a vec_perm, equivalent to a vec_shr by OFFSET
3516 vector elements (not bits) for a vector of mode MODE. */
3517 static void
3518 calc_vec_perm_mask_for_shift (enum machine_mode mode, unsigned int offset,
3519 unsigned char *sel)
3521 unsigned int i, nelt = GET_MODE_NUNITS (mode);
3523 for (i = 0; i < nelt; i++)
3524 sel[i] = (i + offset) & (2*nelt - 1);
3527 /* Checks whether the target supports whole-vector shifts for vectors of mode
3528 MODE. This is the case if _either_ the platform handles vec_shr_optab, _or_
3529 it supports vec_perm_const with masks for all necessary shift amounts. */
3530 static bool
3531 have_whole_vector_shift (enum machine_mode mode)
3533 if (optab_handler (vec_shr_optab, mode) != CODE_FOR_nothing)
3534 return true;
3536 if (direct_optab_handler (vec_perm_const_optab, mode) == CODE_FOR_nothing)
3537 return false;
3539 unsigned int i, nelt = GET_MODE_NUNITS (mode);
3540 unsigned char *sel = XALLOCAVEC (unsigned char, nelt);
3542 for (i = nelt/2; i >= 1; i/=2)
3544 calc_vec_perm_mask_for_shift (mode, i, sel);
3545 if (!can_vec_perm_p (mode, false, sel))
3546 return false;
3548 return true;
3551 /* Return the reduction operand (with index REDUC_INDEX) of STMT. */
3553 static tree
3554 get_reduction_op (gimple *stmt, int reduc_index)
3556 switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
3558 case GIMPLE_SINGLE_RHS:
3559 gcc_assert (TREE_OPERAND_LENGTH (gimple_assign_rhs1 (stmt))
3560 == ternary_op);
3561 return TREE_OPERAND (gimple_assign_rhs1 (stmt), reduc_index);
3562 case GIMPLE_UNARY_RHS:
3563 return gimple_assign_rhs1 (stmt);
3564 case GIMPLE_BINARY_RHS:
3565 return (reduc_index
3566 ? gimple_assign_rhs2 (stmt) : gimple_assign_rhs1 (stmt));
3567 case GIMPLE_TERNARY_RHS:
3568 return gimple_op (stmt, reduc_index + 1);
3569 default:
3570 gcc_unreachable ();
3574 /* TODO: Close dependency between vect_model_*_cost and vectorizable_*
3575 functions. Design better to avoid maintenance issues. */
3577 /* Function vect_model_reduction_cost.
3579 Models cost for a reduction operation, including the vector ops
3580 generated within the strip-mine loop, the initial definition before
3581 the loop, and the epilogue code that must be generated. */
3583 static bool
3584 vect_model_reduction_cost (stmt_vec_info stmt_info, enum tree_code reduc_code,
3585 int ncopies, int reduc_index)
3587 int prologue_cost = 0, epilogue_cost = 0;
3588 enum tree_code code;
3589 optab optab;
3590 tree vectype;
3591 gimple *stmt, *orig_stmt;
3592 tree reduction_op;
3593 machine_mode mode;
3594 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3595 struct loop *loop = NULL;
3596 void *target_cost_data;
3598 if (loop_vinfo)
3600 loop = LOOP_VINFO_LOOP (loop_vinfo);
3601 target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3603 else
3604 target_cost_data = BB_VINFO_TARGET_COST_DATA (STMT_VINFO_BB_VINFO (stmt_info));
3606 /* Condition reductions generate two reductions in the loop. */
3607 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
3608 ncopies *= 2;
3610 /* Cost of reduction op inside loop. */
3611 unsigned inside_cost = add_stmt_cost (target_cost_data, ncopies, vector_stmt,
3612 stmt_info, 0, vect_body);
3613 stmt = STMT_VINFO_STMT (stmt_info);
3615 reduction_op = get_reduction_op (stmt, reduc_index);
3617 vectype = get_vectype_for_scalar_type (TREE_TYPE (reduction_op));
3618 if (!vectype)
3620 if (dump_enabled_p ())
3622 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3623 "unsupported data-type ");
3624 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
3625 TREE_TYPE (reduction_op));
3626 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
3628 return false;
3631 mode = TYPE_MODE (vectype);
3632 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
3634 if (!orig_stmt)
3635 orig_stmt = STMT_VINFO_STMT (stmt_info);
3637 code = gimple_assign_rhs_code (orig_stmt);
3639 /* Add in cost for initial definition.
3640 For cond reduction we have four vectors: initial index, step, initial
3641 result of the data reduction, initial value of the index reduction. */
3642 int prologue_stmts = STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
3643 == COND_REDUCTION ? 4 : 1;
3644 prologue_cost += add_stmt_cost (target_cost_data, prologue_stmts,
3645 scalar_to_vec, stmt_info, 0,
3646 vect_prologue);
3648 /* Determine cost of epilogue code.
3650 We have a reduction operator that will reduce the vector in one statement.
3651 Also requires scalar extract. */
3653 if (!loop || !nested_in_vect_loop_p (loop, orig_stmt))
3655 if (reduc_code != ERROR_MARK)
3657 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
3659 /* An EQ stmt and an COND_EXPR stmt. */
3660 epilogue_cost += add_stmt_cost (target_cost_data, 2,
3661 vector_stmt, stmt_info, 0,
3662 vect_epilogue);
3663 /* Reduction of the max index and a reduction of the found
3664 values. */
3665 epilogue_cost += add_stmt_cost (target_cost_data, 2,
3666 vec_to_scalar, stmt_info, 0,
3667 vect_epilogue);
3668 /* A broadcast of the max value. */
3669 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3670 scalar_to_vec, stmt_info, 0,
3671 vect_epilogue);
3673 else
3675 epilogue_cost += add_stmt_cost (target_cost_data, 1, vector_stmt,
3676 stmt_info, 0, vect_epilogue);
3677 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3678 vec_to_scalar, stmt_info, 0,
3679 vect_epilogue);
3682 else
3684 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
3685 tree bitsize =
3686 TYPE_SIZE (TREE_TYPE (gimple_assign_lhs (orig_stmt)));
3687 int element_bitsize = tree_to_uhwi (bitsize);
3688 int nelements = vec_size_in_bits / element_bitsize;
3690 optab = optab_for_tree_code (code, vectype, optab_default);
3692 /* We have a whole vector shift available. */
3693 if (VECTOR_MODE_P (mode)
3694 && optab_handler (optab, mode) != CODE_FOR_nothing
3695 && have_whole_vector_shift (mode))
3697 /* Final reduction via vector shifts and the reduction operator.
3698 Also requires scalar extract. */
3699 epilogue_cost += add_stmt_cost (target_cost_data,
3700 exact_log2 (nelements) * 2,
3701 vector_stmt, stmt_info, 0,
3702 vect_epilogue);
3703 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3704 vec_to_scalar, stmt_info, 0,
3705 vect_epilogue);
3707 else
3708 /* Use extracts and reduction op for final reduction. For N
3709 elements, we have N extracts and N-1 reduction ops. */
3710 epilogue_cost += add_stmt_cost (target_cost_data,
3711 nelements + nelements - 1,
3712 vector_stmt, stmt_info, 0,
3713 vect_epilogue);
3717 if (dump_enabled_p ())
3718 dump_printf (MSG_NOTE,
3719 "vect_model_reduction_cost: inside_cost = %d, "
3720 "prologue_cost = %d, epilogue_cost = %d .\n", inside_cost,
3721 prologue_cost, epilogue_cost);
3723 return true;
3727 /* Function vect_model_induction_cost.
3729 Models cost for induction operations. */
3731 static void
3732 vect_model_induction_cost (stmt_vec_info stmt_info, int ncopies)
3734 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3735 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3736 unsigned inside_cost, prologue_cost;
3738 /* loop cost for vec_loop. */
3739 inside_cost = add_stmt_cost (target_cost_data, ncopies, vector_stmt,
3740 stmt_info, 0, vect_body);
3742 /* prologue cost for vec_init and vec_step. */
3743 prologue_cost = add_stmt_cost (target_cost_data, 2, scalar_to_vec,
3744 stmt_info, 0, vect_prologue);
3746 if (dump_enabled_p ())
3747 dump_printf_loc (MSG_NOTE, vect_location,
3748 "vect_model_induction_cost: inside_cost = %d, "
3749 "prologue_cost = %d .\n", inside_cost, prologue_cost);
3753 /* Function get_initial_def_for_induction
3755 Input:
3756 STMT - a stmt that performs an induction operation in the loop.
3757 IV_PHI - the initial value of the induction variable
3759 Output:
3760 Return a vector variable, initialized with the first VF values of
3761 the induction variable. E.g., for an iv with IV_PHI='X' and
3762 evolution S, for a vector of 4 units, we want to return:
3763 [X, X + S, X + 2*S, X + 3*S]. */
3765 static tree
3766 get_initial_def_for_induction (gimple *iv_phi)
3768 stmt_vec_info stmt_vinfo = vinfo_for_stmt (iv_phi);
3769 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
3770 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
3771 tree vectype;
3772 int nunits;
3773 edge pe = loop_preheader_edge (loop);
3774 struct loop *iv_loop;
3775 basic_block new_bb;
3776 tree new_vec, vec_init, vec_step, t;
3777 tree new_name;
3778 gimple *new_stmt;
3779 gphi *induction_phi;
3780 tree induc_def, vec_def, vec_dest;
3781 tree init_expr, step_expr;
3782 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3783 int i;
3784 int ncopies;
3785 tree expr;
3786 stmt_vec_info phi_info = vinfo_for_stmt (iv_phi);
3787 bool nested_in_vect_loop = false;
3788 gimple_seq stmts;
3789 imm_use_iterator imm_iter;
3790 use_operand_p use_p;
3791 gimple *exit_phi;
3792 edge latch_e;
3793 tree loop_arg;
3794 gimple_stmt_iterator si;
3795 basic_block bb = gimple_bb (iv_phi);
3796 tree stepvectype;
3797 tree resvectype;
3799 /* Is phi in an inner-loop, while vectorizing an enclosing outer-loop? */
3800 if (nested_in_vect_loop_p (loop, iv_phi))
3802 nested_in_vect_loop = true;
3803 iv_loop = loop->inner;
3805 else
3806 iv_loop = loop;
3807 gcc_assert (iv_loop == (gimple_bb (iv_phi))->loop_father);
3809 latch_e = loop_latch_edge (iv_loop);
3810 loop_arg = PHI_ARG_DEF_FROM_EDGE (iv_phi, latch_e);
3812 step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (phi_info);
3813 gcc_assert (step_expr != NULL_TREE);
3815 pe = loop_preheader_edge (iv_loop);
3816 init_expr = PHI_ARG_DEF_FROM_EDGE (iv_phi,
3817 loop_preheader_edge (iv_loop));
3819 vectype = get_vectype_for_scalar_type (TREE_TYPE (init_expr));
3820 resvectype = get_vectype_for_scalar_type (TREE_TYPE (PHI_RESULT (iv_phi)));
3821 gcc_assert (vectype);
3822 nunits = TYPE_VECTOR_SUBPARTS (vectype);
3823 ncopies = vf / nunits;
3825 gcc_assert (phi_info);
3826 gcc_assert (ncopies >= 1);
3828 /* Convert the step to the desired type. */
3829 stmts = NULL;
3830 step_expr = gimple_convert (&stmts, TREE_TYPE (vectype), step_expr);
3831 if (stmts)
3833 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
3834 gcc_assert (!new_bb);
3837 /* Find the first insertion point in the BB. */
3838 si = gsi_after_labels (bb);
3840 /* Create the vector that holds the initial_value of the induction. */
3841 if (nested_in_vect_loop)
3843 /* iv_loop is nested in the loop to be vectorized. init_expr had already
3844 been created during vectorization of previous stmts. We obtain it
3845 from the STMT_VINFO_VEC_STMT of the defining stmt. */
3846 vec_init = vect_get_vec_def_for_operand (init_expr, iv_phi);
3847 /* If the initial value is not of proper type, convert it. */
3848 if (!useless_type_conversion_p (vectype, TREE_TYPE (vec_init)))
3850 new_stmt
3851 = gimple_build_assign (vect_get_new_ssa_name (vectype,
3852 vect_simple_var,
3853 "vec_iv_"),
3854 VIEW_CONVERT_EXPR,
3855 build1 (VIEW_CONVERT_EXPR, vectype,
3856 vec_init));
3857 vec_init = gimple_assign_lhs (new_stmt);
3858 new_bb = gsi_insert_on_edge_immediate (loop_preheader_edge (iv_loop),
3859 new_stmt);
3860 gcc_assert (!new_bb);
3861 set_vinfo_for_stmt (new_stmt,
3862 new_stmt_vec_info (new_stmt, loop_vinfo));
3865 else
3867 vec<constructor_elt, va_gc> *v;
3869 /* iv_loop is the loop to be vectorized. Create:
3870 vec_init = [X, X+S, X+2*S, X+3*S] (S = step_expr, X = init_expr) */
3871 stmts = NULL;
3872 new_name = gimple_convert (&stmts, TREE_TYPE (vectype), init_expr);
3874 vec_alloc (v, nunits);
3875 bool constant_p = is_gimple_min_invariant (new_name);
3876 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, new_name);
3877 for (i = 1; i < nunits; i++)
3879 /* Create: new_name_i = new_name + step_expr */
3880 new_name = gimple_build (&stmts, PLUS_EXPR, TREE_TYPE (new_name),
3881 new_name, step_expr);
3882 if (!is_gimple_min_invariant (new_name))
3883 constant_p = false;
3884 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, new_name);
3886 if (stmts)
3888 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
3889 gcc_assert (!new_bb);
3892 /* Create a vector from [new_name_0, new_name_1, ..., new_name_nunits-1] */
3893 if (constant_p)
3894 new_vec = build_vector_from_ctor (vectype, v);
3895 else
3896 new_vec = build_constructor (vectype, v);
3897 vec_init = vect_init_vector (iv_phi, new_vec, vectype, NULL);
3901 /* Create the vector that holds the step of the induction. */
3902 if (nested_in_vect_loop)
3903 /* iv_loop is nested in the loop to be vectorized. Generate:
3904 vec_step = [S, S, S, S] */
3905 new_name = step_expr;
3906 else
3908 /* iv_loop is the loop to be vectorized. Generate:
3909 vec_step = [VF*S, VF*S, VF*S, VF*S] */
3910 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
3912 expr = build_int_cst (integer_type_node, vf);
3913 expr = fold_convert (TREE_TYPE (step_expr), expr);
3915 else
3916 expr = build_int_cst (TREE_TYPE (step_expr), vf);
3917 new_name = fold_build2 (MULT_EXPR, TREE_TYPE (step_expr),
3918 expr, step_expr);
3919 if (TREE_CODE (step_expr) == SSA_NAME)
3920 new_name = vect_init_vector (iv_phi, new_name,
3921 TREE_TYPE (step_expr), NULL);
3924 t = unshare_expr (new_name);
3925 gcc_assert (CONSTANT_CLASS_P (new_name)
3926 || TREE_CODE (new_name) == SSA_NAME);
3927 stepvectype = get_vectype_for_scalar_type (TREE_TYPE (new_name));
3928 gcc_assert (stepvectype);
3929 new_vec = build_vector_from_val (stepvectype, t);
3930 vec_step = vect_init_vector (iv_phi, new_vec, stepvectype, NULL);
3933 /* Create the following def-use cycle:
3934 loop prolog:
3935 vec_init = ...
3936 vec_step = ...
3937 loop:
3938 vec_iv = PHI <vec_init, vec_loop>
3940 STMT
3942 vec_loop = vec_iv + vec_step; */
3944 /* Create the induction-phi that defines the induction-operand. */
3945 vec_dest = vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_");
3946 induction_phi = create_phi_node (vec_dest, iv_loop->header);
3947 set_vinfo_for_stmt (induction_phi,
3948 new_stmt_vec_info (induction_phi, loop_vinfo));
3949 induc_def = PHI_RESULT (induction_phi);
3951 /* Create the iv update inside the loop */
3952 new_stmt = gimple_build_assign (vec_dest, PLUS_EXPR, induc_def, vec_step);
3953 vec_def = make_ssa_name (vec_dest, new_stmt);
3954 gimple_assign_set_lhs (new_stmt, vec_def);
3955 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
3956 set_vinfo_for_stmt (new_stmt, new_stmt_vec_info (new_stmt, loop_vinfo));
3958 /* Set the arguments of the phi node: */
3959 add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
3960 add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
3961 UNKNOWN_LOCATION);
3964 /* In case that vectorization factor (VF) is bigger than the number
3965 of elements that we can fit in a vectype (nunits), we have to generate
3966 more than one vector stmt - i.e - we need to "unroll" the
3967 vector stmt by a factor VF/nunits. For more details see documentation
3968 in vectorizable_operation. */
3970 if (ncopies > 1)
3972 stmt_vec_info prev_stmt_vinfo;
3973 /* FORNOW. This restriction should be relaxed. */
3974 gcc_assert (!nested_in_vect_loop);
3976 /* Create the vector that holds the step of the induction. */
3977 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
3979 expr = build_int_cst (integer_type_node, nunits);
3980 expr = fold_convert (TREE_TYPE (step_expr), expr);
3982 else
3983 expr = build_int_cst (TREE_TYPE (step_expr), nunits);
3984 new_name = fold_build2 (MULT_EXPR, TREE_TYPE (step_expr),
3985 expr, step_expr);
3986 if (TREE_CODE (step_expr) == SSA_NAME)
3987 new_name = vect_init_vector (iv_phi, new_name,
3988 TREE_TYPE (step_expr), NULL);
3989 t = unshare_expr (new_name);
3990 gcc_assert (CONSTANT_CLASS_P (new_name)
3991 || TREE_CODE (new_name) == SSA_NAME);
3992 new_vec = build_vector_from_val (stepvectype, t);
3993 vec_step = vect_init_vector (iv_phi, new_vec, stepvectype, NULL);
3995 vec_def = induc_def;
3996 prev_stmt_vinfo = vinfo_for_stmt (induction_phi);
3997 for (i = 1; i < ncopies; i++)
3999 /* vec_i = vec_prev + vec_step */
4000 new_stmt = gimple_build_assign (vec_dest, PLUS_EXPR,
4001 vec_def, vec_step);
4002 vec_def = make_ssa_name (vec_dest, new_stmt);
4003 gimple_assign_set_lhs (new_stmt, vec_def);
4005 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
4006 if (!useless_type_conversion_p (resvectype, vectype))
4008 new_stmt
4009 = gimple_build_assign
4010 (vect_get_new_vect_var (resvectype, vect_simple_var,
4011 "vec_iv_"),
4012 VIEW_CONVERT_EXPR,
4013 build1 (VIEW_CONVERT_EXPR, resvectype,
4014 gimple_assign_lhs (new_stmt)));
4015 gimple_assign_set_lhs (new_stmt,
4016 make_ssa_name
4017 (gimple_assign_lhs (new_stmt), new_stmt));
4018 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
4020 set_vinfo_for_stmt (new_stmt,
4021 new_stmt_vec_info (new_stmt, loop_vinfo));
4022 STMT_VINFO_RELATED_STMT (prev_stmt_vinfo) = new_stmt;
4023 prev_stmt_vinfo = vinfo_for_stmt (new_stmt);
4027 if (nested_in_vect_loop)
4029 /* Find the loop-closed exit-phi of the induction, and record
4030 the final vector of induction results: */
4031 exit_phi = NULL;
4032 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
4034 gimple *use_stmt = USE_STMT (use_p);
4035 if (is_gimple_debug (use_stmt))
4036 continue;
4038 if (!flow_bb_inside_loop_p (iv_loop, gimple_bb (use_stmt)))
4040 exit_phi = use_stmt;
4041 break;
4044 if (exit_phi)
4046 stmt_vec_info stmt_vinfo = vinfo_for_stmt (exit_phi);
4047 /* FORNOW. Currently not supporting the case that an inner-loop induction
4048 is not used in the outer-loop (i.e. only outside the outer-loop). */
4049 gcc_assert (STMT_VINFO_RELEVANT_P (stmt_vinfo)
4050 && !STMT_VINFO_LIVE_P (stmt_vinfo));
4052 STMT_VINFO_VEC_STMT (stmt_vinfo) = new_stmt;
4053 if (dump_enabled_p ())
4055 dump_printf_loc (MSG_NOTE, vect_location,
4056 "vector of inductions after inner-loop:");
4057 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, new_stmt, 0);
4063 if (dump_enabled_p ())
4065 dump_printf_loc (MSG_NOTE, vect_location,
4066 "transform induction: created def-use cycle: ");
4067 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, induction_phi, 0);
4068 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
4069 SSA_NAME_DEF_STMT (vec_def), 0);
4072 STMT_VINFO_VEC_STMT (phi_info) = induction_phi;
4073 if (!useless_type_conversion_p (resvectype, vectype))
4075 new_stmt = gimple_build_assign (vect_get_new_vect_var (resvectype,
4076 vect_simple_var,
4077 "vec_iv_"),
4078 VIEW_CONVERT_EXPR,
4079 build1 (VIEW_CONVERT_EXPR, resvectype,
4080 induc_def));
4081 induc_def = make_ssa_name (gimple_assign_lhs (new_stmt), new_stmt);
4082 gimple_assign_set_lhs (new_stmt, induc_def);
4083 si = gsi_after_labels (bb);
4084 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
4085 set_vinfo_for_stmt (new_stmt,
4086 new_stmt_vec_info (new_stmt, loop_vinfo));
4087 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (new_stmt))
4088 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (induction_phi));
4091 return induc_def;
4095 /* Function get_initial_def_for_reduction
4097 Input:
4098 STMT - a stmt that performs a reduction operation in the loop.
4099 INIT_VAL - the initial value of the reduction variable
4101 Output:
4102 ADJUSTMENT_DEF - a tree that holds a value to be added to the final result
4103 of the reduction (used for adjusting the epilog - see below).
4104 Return a vector variable, initialized according to the operation that STMT
4105 performs. This vector will be used as the initial value of the
4106 vector of partial results.
4108 Option1 (adjust in epilog): Initialize the vector as follows:
4109 add/bit or/xor: [0,0,...,0,0]
4110 mult/bit and: [1,1,...,1,1]
4111 min/max/cond_expr: [init_val,init_val,..,init_val,init_val]
4112 and when necessary (e.g. add/mult case) let the caller know
4113 that it needs to adjust the result by init_val.
4115 Option2: Initialize the vector as follows:
4116 add/bit or/xor: [init_val,0,0,...,0]
4117 mult/bit and: [init_val,1,1,...,1]
4118 min/max/cond_expr: [init_val,init_val,...,init_val]
4119 and no adjustments are needed.
4121 For example, for the following code:
4123 s = init_val;
4124 for (i=0;i<n;i++)
4125 s = s + a[i];
4127 STMT is 's = s + a[i]', and the reduction variable is 's'.
4128 For a vector of 4 units, we want to return either [0,0,0,init_val],
4129 or [0,0,0,0] and let the caller know that it needs to adjust
4130 the result at the end by 'init_val'.
4132 FORNOW, we are using the 'adjust in epilog' scheme, because this way the
4133 initialization vector is simpler (same element in all entries), if
4134 ADJUSTMENT_DEF is not NULL, and Option2 otherwise.
4136 A cost model should help decide between these two schemes. */
4138 tree
4139 get_initial_def_for_reduction (gimple *stmt, tree init_val,
4140 tree *adjustment_def)
4142 stmt_vec_info stmt_vinfo = vinfo_for_stmt (stmt);
4143 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
4144 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
4145 tree scalar_type = TREE_TYPE (init_val);
4146 tree vectype = get_vectype_for_scalar_type (scalar_type);
4147 int nunits;
4148 enum tree_code code = gimple_assign_rhs_code (stmt);
4149 tree def_for_init;
4150 tree init_def;
4151 tree *elts;
4152 int i;
4153 bool nested_in_vect_loop = false;
4154 REAL_VALUE_TYPE real_init_val = dconst0;
4155 int int_init_val = 0;
4156 gimple *def_stmt = NULL;
4157 gimple_seq stmts = NULL;
4159 gcc_assert (vectype);
4160 nunits = TYPE_VECTOR_SUBPARTS (vectype);
4162 gcc_assert (POINTER_TYPE_P (scalar_type) || INTEGRAL_TYPE_P (scalar_type)
4163 || SCALAR_FLOAT_TYPE_P (scalar_type));
4165 if (nested_in_vect_loop_p (loop, stmt))
4166 nested_in_vect_loop = true;
4167 else
4168 gcc_assert (loop == (gimple_bb (stmt))->loop_father);
4170 /* In case of double reduction we only create a vector variable to be put
4171 in the reduction phi node. The actual statement creation is done in
4172 vect_create_epilog_for_reduction. */
4173 if (adjustment_def && nested_in_vect_loop
4174 && TREE_CODE (init_val) == SSA_NAME
4175 && (def_stmt = SSA_NAME_DEF_STMT (init_val))
4176 && gimple_code (def_stmt) == GIMPLE_PHI
4177 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
4178 && vinfo_for_stmt (def_stmt)
4179 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
4180 == vect_double_reduction_def)
4182 *adjustment_def = NULL;
4183 return vect_create_destination_var (init_val, vectype);
4186 /* In case of a nested reduction do not use an adjustment def as
4187 that case is not supported by the epilogue generation correctly
4188 if ncopies is not one. */
4189 if (adjustment_def && nested_in_vect_loop)
4191 *adjustment_def = NULL;
4192 return vect_get_vec_def_for_operand (init_val, stmt);
4195 switch (code)
4197 case WIDEN_SUM_EXPR:
4198 case DOT_PROD_EXPR:
4199 case SAD_EXPR:
4200 case PLUS_EXPR:
4201 case MINUS_EXPR:
4202 case BIT_IOR_EXPR:
4203 case BIT_XOR_EXPR:
4204 case MULT_EXPR:
4205 case BIT_AND_EXPR:
4206 /* ADJUSMENT_DEF is NULL when called from
4207 vect_create_epilog_for_reduction to vectorize double reduction. */
4208 if (adjustment_def)
4209 *adjustment_def = init_val;
4211 if (code == MULT_EXPR)
4213 real_init_val = dconst1;
4214 int_init_val = 1;
4217 if (code == BIT_AND_EXPR)
4218 int_init_val = -1;
4220 if (SCALAR_FLOAT_TYPE_P (scalar_type))
4221 def_for_init = build_real (scalar_type, real_init_val);
4222 else
4223 def_for_init = build_int_cst (scalar_type, int_init_val);
4225 /* Create a vector of '0' or '1' except the first element. */
4226 elts = XALLOCAVEC (tree, nunits);
4227 for (i = nunits - 2; i >= 0; --i)
4228 elts[i + 1] = def_for_init;
4230 /* Option1: the first element is '0' or '1' as well. */
4231 if (adjustment_def)
4233 elts[0] = def_for_init;
4234 init_def = build_vector (vectype, elts);
4235 break;
4238 /* Option2: the first element is INIT_VAL. */
4239 elts[0] = init_val;
4240 if (TREE_CONSTANT (init_val))
4241 init_def = build_vector (vectype, elts);
4242 else
4244 vec<constructor_elt, va_gc> *v;
4245 vec_alloc (v, nunits);
4246 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init_val);
4247 for (i = 1; i < nunits; ++i)
4248 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, elts[i]);
4249 init_def = build_constructor (vectype, v);
4252 break;
4254 case MIN_EXPR:
4255 case MAX_EXPR:
4256 case COND_EXPR:
4257 if (adjustment_def)
4259 *adjustment_def = NULL_TREE;
4260 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_vinfo) != COND_REDUCTION)
4262 init_def = vect_get_vec_def_for_operand (init_val, stmt);
4263 break;
4266 init_val = gimple_convert (&stmts, TREE_TYPE (vectype), init_val);
4267 if (! gimple_seq_empty_p (stmts))
4268 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
4269 init_def = build_vector_from_val (vectype, init_val);
4270 break;
4272 default:
4273 gcc_unreachable ();
4276 return init_def;
4279 /* Function vect_create_epilog_for_reduction
4281 Create code at the loop-epilog to finalize the result of a reduction
4282 computation.
4284 VECT_DEFS is list of vector of partial results, i.e., the lhs's of vector
4285 reduction statements.
4286 STMT is the scalar reduction stmt that is being vectorized.
4287 NCOPIES is > 1 in case the vectorization factor (VF) is bigger than the
4288 number of elements that we can fit in a vectype (nunits). In this case
4289 we have to generate more than one vector stmt - i.e - we need to "unroll"
4290 the vector stmt by a factor VF/nunits. For more details see documentation
4291 in vectorizable_operation.
4292 REDUC_CODE is the tree-code for the epilog reduction.
4293 REDUCTION_PHIS is a list of the phi-nodes that carry the reduction
4294 computation.
4295 REDUC_INDEX is the index of the operand in the right hand side of the
4296 statement that is defined by REDUCTION_PHI.
4297 DOUBLE_REDUC is TRUE if double reduction phi nodes should be handled.
4298 SLP_NODE is an SLP node containing a group of reduction statements. The
4299 first one in this group is STMT.
4300 INDUCTION_INDEX is the index of the loop for condition reductions.
4301 Otherwise it is undefined.
4303 This function:
4304 1. Creates the reduction def-use cycles: sets the arguments for
4305 REDUCTION_PHIS:
4306 The loop-entry argument is the vectorized initial-value of the reduction.
4307 The loop-latch argument is taken from VECT_DEFS - the vector of partial
4308 sums.
4309 2. "Reduces" each vector of partial results VECT_DEFS into a single result,
4310 by applying the operation specified by REDUC_CODE if available, or by
4311 other means (whole-vector shifts or a scalar loop).
4312 The function also creates a new phi node at the loop exit to preserve
4313 loop-closed form, as illustrated below.
4315 The flow at the entry to this function:
4317 loop:
4318 vec_def = phi <null, null> # REDUCTION_PHI
4319 VECT_DEF = vector_stmt # vectorized form of STMT
4320 s_loop = scalar_stmt # (scalar) STMT
4321 loop_exit:
4322 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
4323 use <s_out0>
4324 use <s_out0>
4326 The above is transformed by this function into:
4328 loop:
4329 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
4330 VECT_DEF = vector_stmt # vectorized form of STMT
4331 s_loop = scalar_stmt # (scalar) STMT
4332 loop_exit:
4333 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
4334 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
4335 v_out2 = reduce <v_out1>
4336 s_out3 = extract_field <v_out2, 0>
4337 s_out4 = adjust_result <s_out3>
4338 use <s_out4>
4339 use <s_out4>
4342 static void
4343 vect_create_epilog_for_reduction (vec<tree> vect_defs, gimple *stmt,
4344 int ncopies, enum tree_code reduc_code,
4345 vec<gimple *> reduction_phis,
4346 int reduc_index, bool double_reduc,
4347 slp_tree slp_node, tree induction_index)
4349 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
4350 stmt_vec_info prev_phi_info;
4351 tree vectype;
4352 machine_mode mode;
4353 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
4354 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo), *outer_loop = NULL;
4355 basic_block exit_bb;
4356 tree scalar_dest;
4357 tree scalar_type;
4358 gimple *new_phi = NULL, *phi;
4359 gimple_stmt_iterator exit_gsi;
4360 tree vec_dest;
4361 tree new_temp = NULL_TREE, new_dest, new_name, new_scalar_dest;
4362 gimple *epilog_stmt = NULL;
4363 enum tree_code code = gimple_assign_rhs_code (stmt);
4364 gimple *exit_phi;
4365 tree bitsize;
4366 tree adjustment_def = NULL;
4367 tree vec_initial_def = NULL;
4368 tree reduction_op, expr, def, initial_def = NULL;
4369 tree orig_name, scalar_result;
4370 imm_use_iterator imm_iter, phi_imm_iter;
4371 use_operand_p use_p, phi_use_p;
4372 gimple *use_stmt, *orig_stmt, *reduction_phi = NULL;
4373 bool nested_in_vect_loop = false;
4374 auto_vec<gimple *> new_phis;
4375 auto_vec<gimple *> inner_phis;
4376 enum vect_def_type dt = vect_unknown_def_type;
4377 int j, i;
4378 auto_vec<tree> scalar_results;
4379 unsigned int group_size = 1, k, ratio;
4380 auto_vec<tree> vec_initial_defs;
4381 auto_vec<gimple *> phis;
4382 bool slp_reduc = false;
4383 tree new_phi_result;
4384 gimple *inner_phi = NULL;
4386 if (slp_node)
4387 group_size = SLP_TREE_SCALAR_STMTS (slp_node).length ();
4389 if (nested_in_vect_loop_p (loop, stmt))
4391 outer_loop = loop;
4392 loop = loop->inner;
4393 nested_in_vect_loop = true;
4394 gcc_assert (!slp_node);
4397 reduction_op = get_reduction_op (stmt, reduc_index);
4399 vectype = get_vectype_for_scalar_type (TREE_TYPE (reduction_op));
4400 gcc_assert (vectype);
4401 mode = TYPE_MODE (vectype);
4403 /* 1. Create the reduction def-use cycle:
4404 Set the arguments of REDUCTION_PHIS, i.e., transform
4406 loop:
4407 vec_def = phi <null, null> # REDUCTION_PHI
4408 VECT_DEF = vector_stmt # vectorized form of STMT
4411 into:
4413 loop:
4414 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
4415 VECT_DEF = vector_stmt # vectorized form of STMT
4418 (in case of SLP, do it for all the phis). */
4420 /* Get the loop-entry arguments. */
4421 enum vect_def_type initial_def_dt = vect_unknown_def_type;
4422 if (slp_node)
4423 vect_get_vec_defs (reduction_op, NULL_TREE, stmt, &vec_initial_defs,
4424 NULL, slp_node, reduc_index);
4425 else
4427 /* Get at the scalar def before the loop, that defines the initial value
4428 of the reduction variable. */
4429 gimple *def_stmt = SSA_NAME_DEF_STMT (reduction_op);
4430 initial_def = PHI_ARG_DEF_FROM_EDGE (def_stmt,
4431 loop_preheader_edge (loop));
4432 vect_is_simple_use (initial_def, loop_vinfo, &def_stmt, &initial_def_dt);
4433 vec_initial_def = get_initial_def_for_reduction (stmt, initial_def,
4434 &adjustment_def);
4435 vec_initial_defs.create (1);
4436 vec_initial_defs.quick_push (vec_initial_def);
4439 /* Set phi nodes arguments. */
4440 FOR_EACH_VEC_ELT (reduction_phis, i, phi)
4442 tree vec_init_def, def;
4443 gimple_seq stmts;
4444 vec_init_def = force_gimple_operand (vec_initial_defs[i], &stmts,
4445 true, NULL_TREE);
4446 if (stmts)
4447 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
4449 def = vect_defs[i];
4450 for (j = 0; j < ncopies; j++)
4452 if (j != 0)
4454 phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi));
4455 if (nested_in_vect_loop)
4456 vec_init_def
4457 = vect_get_vec_def_for_stmt_copy (initial_def_dt,
4458 vec_init_def);
4461 /* Set the loop-entry arg of the reduction-phi. */
4463 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
4464 == INTEGER_INDUC_COND_REDUCTION)
4466 /* Initialise the reduction phi to zero. This prevents initial
4467 values of non-zero interferring with the reduction op. */
4468 gcc_assert (ncopies == 1);
4469 gcc_assert (i == 0);
4471 tree vec_init_def_type = TREE_TYPE (vec_init_def);
4472 tree zero_vec = build_zero_cst (vec_init_def_type);
4474 add_phi_arg (as_a <gphi *> (phi), zero_vec,
4475 loop_preheader_edge (loop), UNKNOWN_LOCATION);
4477 else
4478 add_phi_arg (as_a <gphi *> (phi), vec_init_def,
4479 loop_preheader_edge (loop), UNKNOWN_LOCATION);
4481 /* Set the loop-latch arg for the reduction-phi. */
4482 if (j > 0)
4483 def = vect_get_vec_def_for_stmt_copy (vect_unknown_def_type, def);
4485 add_phi_arg (as_a <gphi *> (phi), def, loop_latch_edge (loop),
4486 UNKNOWN_LOCATION);
4488 if (dump_enabled_p ())
4490 dump_printf_loc (MSG_NOTE, vect_location,
4491 "transform reduction: created def-use cycle: ");
4492 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
4493 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, SSA_NAME_DEF_STMT (def), 0);
4498 /* 2. Create epilog code.
4499 The reduction epilog code operates across the elements of the vector
4500 of partial results computed by the vectorized loop.
4501 The reduction epilog code consists of:
4503 step 1: compute the scalar result in a vector (v_out2)
4504 step 2: extract the scalar result (s_out3) from the vector (v_out2)
4505 step 3: adjust the scalar result (s_out3) if needed.
4507 Step 1 can be accomplished using one the following three schemes:
4508 (scheme 1) using reduc_code, if available.
4509 (scheme 2) using whole-vector shifts, if available.
4510 (scheme 3) using a scalar loop. In this case steps 1+2 above are
4511 combined.
4513 The overall epilog code looks like this:
4515 s_out0 = phi <s_loop> # original EXIT_PHI
4516 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
4517 v_out2 = reduce <v_out1> # step 1
4518 s_out3 = extract_field <v_out2, 0> # step 2
4519 s_out4 = adjust_result <s_out3> # step 3
4521 (step 3 is optional, and steps 1 and 2 may be combined).
4522 Lastly, the uses of s_out0 are replaced by s_out4. */
4525 /* 2.1 Create new loop-exit-phis to preserve loop-closed form:
4526 v_out1 = phi <VECT_DEF>
4527 Store them in NEW_PHIS. */
4529 exit_bb = single_exit (loop)->dest;
4530 prev_phi_info = NULL;
4531 new_phis.create (vect_defs.length ());
4532 FOR_EACH_VEC_ELT (vect_defs, i, def)
4534 for (j = 0; j < ncopies; j++)
4536 tree new_def = copy_ssa_name (def);
4537 phi = create_phi_node (new_def, exit_bb);
4538 set_vinfo_for_stmt (phi, new_stmt_vec_info (phi, loop_vinfo));
4539 if (j == 0)
4540 new_phis.quick_push (phi);
4541 else
4543 def = vect_get_vec_def_for_stmt_copy (dt, def);
4544 STMT_VINFO_RELATED_STMT (prev_phi_info) = phi;
4547 SET_PHI_ARG_DEF (phi, single_exit (loop)->dest_idx, def);
4548 prev_phi_info = vinfo_for_stmt (phi);
4552 /* The epilogue is created for the outer-loop, i.e., for the loop being
4553 vectorized. Create exit phis for the outer loop. */
4554 if (double_reduc)
4556 loop = outer_loop;
4557 exit_bb = single_exit (loop)->dest;
4558 inner_phis.create (vect_defs.length ());
4559 FOR_EACH_VEC_ELT (new_phis, i, phi)
4561 tree new_result = copy_ssa_name (PHI_RESULT (phi));
4562 gphi *outer_phi = create_phi_node (new_result, exit_bb);
4563 SET_PHI_ARG_DEF (outer_phi, single_exit (loop)->dest_idx,
4564 PHI_RESULT (phi));
4565 set_vinfo_for_stmt (outer_phi, new_stmt_vec_info (outer_phi,
4566 loop_vinfo));
4567 inner_phis.quick_push (phi);
4568 new_phis[i] = outer_phi;
4569 prev_phi_info = vinfo_for_stmt (outer_phi);
4570 while (STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi)))
4572 phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi));
4573 new_result = copy_ssa_name (PHI_RESULT (phi));
4574 outer_phi = create_phi_node (new_result, exit_bb);
4575 SET_PHI_ARG_DEF (outer_phi, single_exit (loop)->dest_idx,
4576 PHI_RESULT (phi));
4577 set_vinfo_for_stmt (outer_phi, new_stmt_vec_info (outer_phi,
4578 loop_vinfo));
4579 STMT_VINFO_RELATED_STMT (prev_phi_info) = outer_phi;
4580 prev_phi_info = vinfo_for_stmt (outer_phi);
4585 exit_gsi = gsi_after_labels (exit_bb);
4587 /* 2.2 Get the relevant tree-code to use in the epilog for schemes 2,3
4588 (i.e. when reduc_code is not available) and in the final adjustment
4589 code (if needed). Also get the original scalar reduction variable as
4590 defined in the loop. In case STMT is a "pattern-stmt" (i.e. - it
4591 represents a reduction pattern), the tree-code and scalar-def are
4592 taken from the original stmt that the pattern-stmt (STMT) replaces.
4593 Otherwise (it is a regular reduction) - the tree-code and scalar-def
4594 are taken from STMT. */
4596 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
4597 if (!orig_stmt)
4599 /* Regular reduction */
4600 orig_stmt = stmt;
4602 else
4604 /* Reduction pattern */
4605 stmt_vec_info stmt_vinfo = vinfo_for_stmt (orig_stmt);
4606 gcc_assert (STMT_VINFO_IN_PATTERN_P (stmt_vinfo));
4607 gcc_assert (STMT_VINFO_RELATED_STMT (stmt_vinfo) == stmt);
4610 code = gimple_assign_rhs_code (orig_stmt);
4611 /* For MINUS_EXPR the initial vector is [init_val,0,...,0], therefore,
4612 partial results are added and not subtracted. */
4613 if (code == MINUS_EXPR)
4614 code = PLUS_EXPR;
4616 scalar_dest = gimple_assign_lhs (orig_stmt);
4617 scalar_type = TREE_TYPE (scalar_dest);
4618 scalar_results.create (group_size);
4619 new_scalar_dest = vect_create_destination_var (scalar_dest, NULL);
4620 bitsize = TYPE_SIZE (scalar_type);
4622 /* In case this is a reduction in an inner-loop while vectorizing an outer
4623 loop - we don't need to extract a single scalar result at the end of the
4624 inner-loop (unless it is double reduction, i.e., the use of reduction is
4625 outside the outer-loop). The final vector of partial results will be used
4626 in the vectorized outer-loop, or reduced to a scalar result at the end of
4627 the outer-loop. */
4628 if (nested_in_vect_loop && !double_reduc)
4629 goto vect_finalize_reduction;
4631 /* SLP reduction without reduction chain, e.g.,
4632 # a1 = phi <a2, a0>
4633 # b1 = phi <b2, b0>
4634 a2 = operation (a1)
4635 b2 = operation (b1) */
4636 slp_reduc = (slp_node && !GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)));
4638 /* In case of reduction chain, e.g.,
4639 # a1 = phi <a3, a0>
4640 a2 = operation (a1)
4641 a3 = operation (a2),
4643 we may end up with more than one vector result. Here we reduce them to
4644 one vector. */
4645 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
4647 tree first_vect = PHI_RESULT (new_phis[0]);
4648 tree tmp;
4649 gassign *new_vec_stmt = NULL;
4651 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4652 for (k = 1; k < new_phis.length (); k++)
4654 gimple *next_phi = new_phis[k];
4655 tree second_vect = PHI_RESULT (next_phi);
4657 tmp = build2 (code, vectype, first_vect, second_vect);
4658 new_vec_stmt = gimple_build_assign (vec_dest, tmp);
4659 first_vect = make_ssa_name (vec_dest, new_vec_stmt);
4660 gimple_assign_set_lhs (new_vec_stmt, first_vect);
4661 gsi_insert_before (&exit_gsi, new_vec_stmt, GSI_SAME_STMT);
4664 new_phi_result = first_vect;
4665 if (new_vec_stmt)
4667 new_phis.truncate (0);
4668 new_phis.safe_push (new_vec_stmt);
4671 else
4672 new_phi_result = PHI_RESULT (new_phis[0]);
4674 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
4676 /* For condition reductions, we have a vector (NEW_PHI_RESULT) containing
4677 various data values where the condition matched and another vector
4678 (INDUCTION_INDEX) containing all the indexes of those matches. We
4679 need to extract the last matching index (which will be the index with
4680 highest value) and use this to index into the data vector.
4681 For the case where there were no matches, the data vector will contain
4682 all default values and the index vector will be all zeros. */
4684 /* Get various versions of the type of the vector of indexes. */
4685 tree index_vec_type = TREE_TYPE (induction_index);
4686 gcc_checking_assert (TYPE_UNSIGNED (index_vec_type));
4687 tree index_scalar_type = TREE_TYPE (index_vec_type);
4688 tree index_vec_cmp_type = build_same_sized_truth_vector_type
4689 (index_vec_type);
4691 /* Get an unsigned integer version of the type of the data vector. */
4692 int scalar_precision = GET_MODE_PRECISION (TYPE_MODE (scalar_type));
4693 tree scalar_type_unsigned = make_unsigned_type (scalar_precision);
4694 tree vectype_unsigned = build_vector_type
4695 (scalar_type_unsigned, TYPE_VECTOR_SUBPARTS (vectype));
4697 /* First we need to create a vector (ZERO_VEC) of zeros and another
4698 vector (MAX_INDEX_VEC) filled with the last matching index, which we
4699 can create using a MAX reduction and then expanding.
4700 In the case where the loop never made any matches, the max index will
4701 be zero. */
4703 /* Vector of {0, 0, 0,...}. */
4704 tree zero_vec = make_ssa_name (vectype);
4705 tree zero_vec_rhs = build_zero_cst (vectype);
4706 gimple *zero_vec_stmt = gimple_build_assign (zero_vec, zero_vec_rhs);
4707 gsi_insert_before (&exit_gsi, zero_vec_stmt, GSI_SAME_STMT);
4709 /* Find maximum value from the vector of found indexes. */
4710 tree max_index = make_ssa_name (index_scalar_type);
4711 gimple *max_index_stmt = gimple_build_assign (max_index, REDUC_MAX_EXPR,
4712 induction_index);
4713 gsi_insert_before (&exit_gsi, max_index_stmt, GSI_SAME_STMT);
4715 /* Vector of {max_index, max_index, max_index,...}. */
4716 tree max_index_vec = make_ssa_name (index_vec_type);
4717 tree max_index_vec_rhs = build_vector_from_val (index_vec_type,
4718 max_index);
4719 gimple *max_index_vec_stmt = gimple_build_assign (max_index_vec,
4720 max_index_vec_rhs);
4721 gsi_insert_before (&exit_gsi, max_index_vec_stmt, GSI_SAME_STMT);
4723 /* Next we compare the new vector (MAX_INDEX_VEC) full of max indexes
4724 with the vector (INDUCTION_INDEX) of found indexes, choosing values
4725 from the data vector (NEW_PHI_RESULT) for matches, 0 (ZERO_VEC)
4726 otherwise. Only one value should match, resulting in a vector
4727 (VEC_COND) with one data value and the rest zeros.
4728 In the case where the loop never made any matches, every index will
4729 match, resulting in a vector with all data values (which will all be
4730 the default value). */
4732 /* Compare the max index vector to the vector of found indexes to find
4733 the position of the max value. */
4734 tree vec_compare = make_ssa_name (index_vec_cmp_type);
4735 gimple *vec_compare_stmt = gimple_build_assign (vec_compare, EQ_EXPR,
4736 induction_index,
4737 max_index_vec);
4738 gsi_insert_before (&exit_gsi, vec_compare_stmt, GSI_SAME_STMT);
4740 /* Use the compare to choose either values from the data vector or
4741 zero. */
4742 tree vec_cond = make_ssa_name (vectype);
4743 gimple *vec_cond_stmt = gimple_build_assign (vec_cond, VEC_COND_EXPR,
4744 vec_compare, new_phi_result,
4745 zero_vec);
4746 gsi_insert_before (&exit_gsi, vec_cond_stmt, GSI_SAME_STMT);
4748 /* Finally we need to extract the data value from the vector (VEC_COND)
4749 into a scalar (MATCHED_DATA_REDUC). Logically we want to do a OR
4750 reduction, but because this doesn't exist, we can use a MAX reduction
4751 instead. The data value might be signed or a float so we need to cast
4752 it first.
4753 In the case where the loop never made any matches, the data values are
4754 all identical, and so will reduce down correctly. */
4756 /* Make the matched data values unsigned. */
4757 tree vec_cond_cast = make_ssa_name (vectype_unsigned);
4758 tree vec_cond_cast_rhs = build1 (VIEW_CONVERT_EXPR, vectype_unsigned,
4759 vec_cond);
4760 gimple *vec_cond_cast_stmt = gimple_build_assign (vec_cond_cast,
4761 VIEW_CONVERT_EXPR,
4762 vec_cond_cast_rhs);
4763 gsi_insert_before (&exit_gsi, vec_cond_cast_stmt, GSI_SAME_STMT);
4765 /* Reduce down to a scalar value. */
4766 tree data_reduc = make_ssa_name (scalar_type_unsigned);
4767 optab ot = optab_for_tree_code (REDUC_MAX_EXPR, vectype_unsigned,
4768 optab_default);
4769 gcc_assert (optab_handler (ot, TYPE_MODE (vectype_unsigned))
4770 != CODE_FOR_nothing);
4771 gimple *data_reduc_stmt = gimple_build_assign (data_reduc,
4772 REDUC_MAX_EXPR,
4773 vec_cond_cast);
4774 gsi_insert_before (&exit_gsi, data_reduc_stmt, GSI_SAME_STMT);
4776 /* Convert the reduced value back to the result type and set as the
4777 result. */
4778 tree data_reduc_cast = build1 (VIEW_CONVERT_EXPR, scalar_type,
4779 data_reduc);
4780 epilog_stmt = gimple_build_assign (new_scalar_dest, data_reduc_cast);
4781 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4782 gimple_assign_set_lhs (epilog_stmt, new_temp);
4783 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4784 scalar_results.safe_push (new_temp);
4787 /* 2.3 Create the reduction code, using one of the three schemes described
4788 above. In SLP we simply need to extract all the elements from the
4789 vector (without reducing them), so we use scalar shifts. */
4790 else if (reduc_code != ERROR_MARK && !slp_reduc)
4792 tree tmp;
4793 tree vec_elem_type;
4795 /*** Case 1: Create:
4796 v_out2 = reduc_expr <v_out1> */
4798 if (dump_enabled_p ())
4799 dump_printf_loc (MSG_NOTE, vect_location,
4800 "Reduce using direct vector reduction.\n");
4802 vec_elem_type = TREE_TYPE (TREE_TYPE (new_phi_result));
4803 if (!useless_type_conversion_p (scalar_type, vec_elem_type))
4805 tree tmp_dest =
4806 vect_create_destination_var (scalar_dest, vec_elem_type);
4807 tmp = build1 (reduc_code, vec_elem_type, new_phi_result);
4808 epilog_stmt = gimple_build_assign (tmp_dest, tmp);
4809 new_temp = make_ssa_name (tmp_dest, epilog_stmt);
4810 gimple_assign_set_lhs (epilog_stmt, new_temp);
4811 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4813 tmp = build1 (NOP_EXPR, scalar_type, new_temp);
4815 else
4816 tmp = build1 (reduc_code, scalar_type, new_phi_result);
4818 epilog_stmt = gimple_build_assign (new_scalar_dest, tmp);
4819 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4820 gimple_assign_set_lhs (epilog_stmt, new_temp);
4821 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4823 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
4824 == INTEGER_INDUC_COND_REDUCTION)
4826 /* Earlier we set the initial value to be zero. Check the result
4827 and if it is zero then replace with the original initial
4828 value. */
4829 tree zero = build_zero_cst (scalar_type);
4830 tree zcompare = build2 (EQ_EXPR, boolean_type_node, new_temp, zero);
4832 tmp = make_ssa_name (new_scalar_dest);
4833 epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
4834 initial_def, new_temp);
4835 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4836 new_temp = tmp;
4839 scalar_results.safe_push (new_temp);
4841 else
4843 bool reduce_with_shift = have_whole_vector_shift (mode);
4844 int element_bitsize = tree_to_uhwi (bitsize);
4845 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
4846 tree vec_temp;
4848 /* Regardless of whether we have a whole vector shift, if we're
4849 emulating the operation via tree-vect-generic, we don't want
4850 to use it. Only the first round of the reduction is likely
4851 to still be profitable via emulation. */
4852 /* ??? It might be better to emit a reduction tree code here, so that
4853 tree-vect-generic can expand the first round via bit tricks. */
4854 if (!VECTOR_MODE_P (mode))
4855 reduce_with_shift = false;
4856 else
4858 optab optab = optab_for_tree_code (code, vectype, optab_default);
4859 if (optab_handler (optab, mode) == CODE_FOR_nothing)
4860 reduce_with_shift = false;
4863 if (reduce_with_shift && !slp_reduc)
4865 int nelements = vec_size_in_bits / element_bitsize;
4866 unsigned char *sel = XALLOCAVEC (unsigned char, nelements);
4868 int elt_offset;
4870 tree zero_vec = build_zero_cst (vectype);
4871 /*** Case 2: Create:
4872 for (offset = nelements/2; offset >= 1; offset/=2)
4874 Create: va' = vec_shift <va, offset>
4875 Create: va = vop <va, va'>
4876 } */
4878 tree rhs;
4880 if (dump_enabled_p ())
4881 dump_printf_loc (MSG_NOTE, vect_location,
4882 "Reduce using vector shifts\n");
4884 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4885 new_temp = new_phi_result;
4886 for (elt_offset = nelements / 2;
4887 elt_offset >= 1;
4888 elt_offset /= 2)
4890 calc_vec_perm_mask_for_shift (mode, elt_offset, sel);
4891 tree mask = vect_gen_perm_mask_any (vectype, sel);
4892 epilog_stmt = gimple_build_assign (vec_dest, VEC_PERM_EXPR,
4893 new_temp, zero_vec, mask);
4894 new_name = make_ssa_name (vec_dest, epilog_stmt);
4895 gimple_assign_set_lhs (epilog_stmt, new_name);
4896 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4898 epilog_stmt = gimple_build_assign (vec_dest, code, new_name,
4899 new_temp);
4900 new_temp = make_ssa_name (vec_dest, epilog_stmt);
4901 gimple_assign_set_lhs (epilog_stmt, new_temp);
4902 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4905 /* 2.4 Extract the final scalar result. Create:
4906 s_out3 = extract_field <v_out2, bitpos> */
4908 if (dump_enabled_p ())
4909 dump_printf_loc (MSG_NOTE, vect_location,
4910 "extract scalar result\n");
4912 rhs = build3 (BIT_FIELD_REF, scalar_type, new_temp,
4913 bitsize, bitsize_zero_node);
4914 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4915 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4916 gimple_assign_set_lhs (epilog_stmt, new_temp);
4917 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4918 scalar_results.safe_push (new_temp);
4920 else
4922 /*** Case 3: Create:
4923 s = extract_field <v_out2, 0>
4924 for (offset = element_size;
4925 offset < vector_size;
4926 offset += element_size;)
4928 Create: s' = extract_field <v_out2, offset>
4929 Create: s = op <s, s'> // For non SLP cases
4930 } */
4932 if (dump_enabled_p ())
4933 dump_printf_loc (MSG_NOTE, vect_location,
4934 "Reduce using scalar code.\n");
4936 vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
4937 FOR_EACH_VEC_ELT (new_phis, i, new_phi)
4939 int bit_offset;
4940 if (gimple_code (new_phi) == GIMPLE_PHI)
4941 vec_temp = PHI_RESULT (new_phi);
4942 else
4943 vec_temp = gimple_assign_lhs (new_phi);
4944 tree rhs = build3 (BIT_FIELD_REF, scalar_type, vec_temp, bitsize,
4945 bitsize_zero_node);
4946 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4947 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4948 gimple_assign_set_lhs (epilog_stmt, new_temp);
4949 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4951 /* In SLP we don't need to apply reduction operation, so we just
4952 collect s' values in SCALAR_RESULTS. */
4953 if (slp_reduc)
4954 scalar_results.safe_push (new_temp);
4956 for (bit_offset = element_bitsize;
4957 bit_offset < vec_size_in_bits;
4958 bit_offset += element_bitsize)
4960 tree bitpos = bitsize_int (bit_offset);
4961 tree rhs = build3 (BIT_FIELD_REF, scalar_type, vec_temp,
4962 bitsize, bitpos);
4964 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4965 new_name = make_ssa_name (new_scalar_dest, epilog_stmt);
4966 gimple_assign_set_lhs (epilog_stmt, new_name);
4967 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4969 if (slp_reduc)
4971 /* In SLP we don't need to apply reduction operation, so
4972 we just collect s' values in SCALAR_RESULTS. */
4973 new_temp = new_name;
4974 scalar_results.safe_push (new_name);
4976 else
4978 epilog_stmt = gimple_build_assign (new_scalar_dest, code,
4979 new_name, new_temp);
4980 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4981 gimple_assign_set_lhs (epilog_stmt, new_temp);
4982 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4987 /* The only case where we need to reduce scalar results in SLP, is
4988 unrolling. If the size of SCALAR_RESULTS is greater than
4989 GROUP_SIZE, we reduce them combining elements modulo
4990 GROUP_SIZE. */
4991 if (slp_reduc)
4993 tree res, first_res, new_res;
4994 gimple *new_stmt;
4996 /* Reduce multiple scalar results in case of SLP unrolling. */
4997 for (j = group_size; scalar_results.iterate (j, &res);
4998 j++)
5000 first_res = scalar_results[j % group_size];
5001 new_stmt = gimple_build_assign (new_scalar_dest, code,
5002 first_res, res);
5003 new_res = make_ssa_name (new_scalar_dest, new_stmt);
5004 gimple_assign_set_lhs (new_stmt, new_res);
5005 gsi_insert_before (&exit_gsi, new_stmt, GSI_SAME_STMT);
5006 scalar_results[j % group_size] = new_res;
5009 else
5010 /* Not SLP - we have one scalar to keep in SCALAR_RESULTS. */
5011 scalar_results.safe_push (new_temp);
5015 vect_finalize_reduction:
5017 if (double_reduc)
5018 loop = loop->inner;
5020 /* 2.5 Adjust the final result by the initial value of the reduction
5021 variable. (When such adjustment is not needed, then
5022 'adjustment_def' is zero). For example, if code is PLUS we create:
5023 new_temp = loop_exit_def + adjustment_def */
5025 if (adjustment_def)
5027 gcc_assert (!slp_reduc);
5028 if (nested_in_vect_loop)
5030 new_phi = new_phis[0];
5031 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) == VECTOR_TYPE);
5032 expr = build2 (code, vectype, PHI_RESULT (new_phi), adjustment_def);
5033 new_dest = vect_create_destination_var (scalar_dest, vectype);
5035 else
5037 new_temp = scalar_results[0];
5038 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) != VECTOR_TYPE);
5039 expr = build2 (code, scalar_type, new_temp, adjustment_def);
5040 new_dest = vect_create_destination_var (scalar_dest, scalar_type);
5043 epilog_stmt = gimple_build_assign (new_dest, expr);
5044 new_temp = make_ssa_name (new_dest, epilog_stmt);
5045 gimple_assign_set_lhs (epilog_stmt, new_temp);
5046 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5047 if (nested_in_vect_loop)
5049 set_vinfo_for_stmt (epilog_stmt,
5050 new_stmt_vec_info (epilog_stmt, loop_vinfo));
5051 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (epilog_stmt)) =
5052 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (new_phi));
5054 if (!double_reduc)
5055 scalar_results.quick_push (new_temp);
5056 else
5057 scalar_results[0] = new_temp;
5059 else
5060 scalar_results[0] = new_temp;
5062 new_phis[0] = epilog_stmt;
5065 /* 2.6 Handle the loop-exit phis. Replace the uses of scalar loop-exit
5066 phis with new adjusted scalar results, i.e., replace use <s_out0>
5067 with use <s_out4>.
5069 Transform:
5070 loop_exit:
5071 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
5072 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
5073 v_out2 = reduce <v_out1>
5074 s_out3 = extract_field <v_out2, 0>
5075 s_out4 = adjust_result <s_out3>
5076 use <s_out0>
5077 use <s_out0>
5079 into:
5081 loop_exit:
5082 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
5083 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
5084 v_out2 = reduce <v_out1>
5085 s_out3 = extract_field <v_out2, 0>
5086 s_out4 = adjust_result <s_out3>
5087 use <s_out4>
5088 use <s_out4> */
5091 /* In SLP reduction chain we reduce vector results into one vector if
5092 necessary, hence we set here GROUP_SIZE to 1. SCALAR_DEST is the LHS of
5093 the last stmt in the reduction chain, since we are looking for the loop
5094 exit phi node. */
5095 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
5097 gimple *dest_stmt = SLP_TREE_SCALAR_STMTS (slp_node)[group_size - 1];
5098 /* Handle reduction patterns. */
5099 if (STMT_VINFO_RELATED_STMT (vinfo_for_stmt (dest_stmt)))
5100 dest_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (dest_stmt));
5102 scalar_dest = gimple_assign_lhs (dest_stmt);
5103 group_size = 1;
5106 /* In SLP we may have several statements in NEW_PHIS and REDUCTION_PHIS (in
5107 case that GROUP_SIZE is greater than vectorization factor). Therefore, we
5108 need to match SCALAR_RESULTS with corresponding statements. The first
5109 (GROUP_SIZE / number of new vector stmts) scalar results correspond to
5110 the first vector stmt, etc.
5111 (RATIO is equal to (GROUP_SIZE / number of new vector stmts)). */
5112 if (group_size > new_phis.length ())
5114 ratio = group_size / new_phis.length ();
5115 gcc_assert (!(group_size % new_phis.length ()));
5117 else
5118 ratio = 1;
5120 for (k = 0; k < group_size; k++)
5122 if (k % ratio == 0)
5124 epilog_stmt = new_phis[k / ratio];
5125 reduction_phi = reduction_phis[k / ratio];
5126 if (double_reduc)
5127 inner_phi = inner_phis[k / ratio];
5130 if (slp_reduc)
5132 gimple *current_stmt = SLP_TREE_SCALAR_STMTS (slp_node)[k];
5134 orig_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (current_stmt));
5135 /* SLP statements can't participate in patterns. */
5136 gcc_assert (!orig_stmt);
5137 scalar_dest = gimple_assign_lhs (current_stmt);
5140 phis.create (3);
5141 /* Find the loop-closed-use at the loop exit of the original scalar
5142 result. (The reduction result is expected to have two immediate uses -
5143 one at the latch block, and one at the loop exit). */
5144 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
5145 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p)))
5146 && !is_gimple_debug (USE_STMT (use_p)))
5147 phis.safe_push (USE_STMT (use_p));
5149 /* While we expect to have found an exit_phi because of loop-closed-ssa
5150 form we can end up without one if the scalar cycle is dead. */
5152 FOR_EACH_VEC_ELT (phis, i, exit_phi)
5154 if (outer_loop)
5156 stmt_vec_info exit_phi_vinfo = vinfo_for_stmt (exit_phi);
5157 gphi *vect_phi;
5159 /* FORNOW. Currently not supporting the case that an inner-loop
5160 reduction is not used in the outer-loop (but only outside the
5161 outer-loop), unless it is double reduction. */
5162 gcc_assert ((STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
5163 && !STMT_VINFO_LIVE_P (exit_phi_vinfo))
5164 || double_reduc);
5166 if (double_reduc)
5167 STMT_VINFO_VEC_STMT (exit_phi_vinfo) = inner_phi;
5168 else
5169 STMT_VINFO_VEC_STMT (exit_phi_vinfo) = epilog_stmt;
5170 if (!double_reduc
5171 || STMT_VINFO_DEF_TYPE (exit_phi_vinfo)
5172 != vect_double_reduction_def)
5173 continue;
5175 /* Handle double reduction:
5177 stmt1: s1 = phi <s0, s2> - double reduction phi (outer loop)
5178 stmt2: s3 = phi <s1, s4> - (regular) reduc phi (inner loop)
5179 stmt3: s4 = use (s3) - (regular) reduc stmt (inner loop)
5180 stmt4: s2 = phi <s4> - double reduction stmt (outer loop)
5182 At that point the regular reduction (stmt2 and stmt3) is
5183 already vectorized, as well as the exit phi node, stmt4.
5184 Here we vectorize the phi node of double reduction, stmt1, and
5185 update all relevant statements. */
5187 /* Go through all the uses of s2 to find double reduction phi
5188 node, i.e., stmt1 above. */
5189 orig_name = PHI_RESULT (exit_phi);
5190 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
5192 stmt_vec_info use_stmt_vinfo;
5193 stmt_vec_info new_phi_vinfo;
5194 tree vect_phi_init, preheader_arg, vect_phi_res, init_def;
5195 basic_block bb = gimple_bb (use_stmt);
5196 gimple *use;
5198 /* Check that USE_STMT is really double reduction phi
5199 node. */
5200 if (gimple_code (use_stmt) != GIMPLE_PHI
5201 || gimple_phi_num_args (use_stmt) != 2
5202 || bb->loop_father != outer_loop)
5203 continue;
5204 use_stmt_vinfo = vinfo_for_stmt (use_stmt);
5205 if (!use_stmt_vinfo
5206 || STMT_VINFO_DEF_TYPE (use_stmt_vinfo)
5207 != vect_double_reduction_def)
5208 continue;
5210 /* Create vector phi node for double reduction:
5211 vs1 = phi <vs0, vs2>
5212 vs1 was created previously in this function by a call to
5213 vect_get_vec_def_for_operand and is stored in
5214 vec_initial_def;
5215 vs2 is defined by INNER_PHI, the vectorized EXIT_PHI;
5216 vs0 is created here. */
5218 /* Create vector phi node. */
5219 vect_phi = create_phi_node (vec_initial_def, bb);
5220 new_phi_vinfo = new_stmt_vec_info (vect_phi,
5221 loop_vec_info_for_loop (outer_loop));
5222 set_vinfo_for_stmt (vect_phi, new_phi_vinfo);
5224 /* Create vs0 - initial def of the double reduction phi. */
5225 preheader_arg = PHI_ARG_DEF_FROM_EDGE (use_stmt,
5226 loop_preheader_edge (outer_loop));
5227 init_def = get_initial_def_for_reduction (stmt,
5228 preheader_arg, NULL);
5229 vect_phi_init = vect_init_vector (use_stmt, init_def,
5230 vectype, NULL);
5232 /* Update phi node arguments with vs0 and vs2. */
5233 add_phi_arg (vect_phi, vect_phi_init,
5234 loop_preheader_edge (outer_loop),
5235 UNKNOWN_LOCATION);
5236 add_phi_arg (vect_phi, PHI_RESULT (inner_phi),
5237 loop_latch_edge (outer_loop), UNKNOWN_LOCATION);
5238 if (dump_enabled_p ())
5240 dump_printf_loc (MSG_NOTE, vect_location,
5241 "created double reduction phi node: ");
5242 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, vect_phi, 0);
5245 vect_phi_res = PHI_RESULT (vect_phi);
5247 /* Replace the use, i.e., set the correct vs1 in the regular
5248 reduction phi node. FORNOW, NCOPIES is always 1, so the
5249 loop is redundant. */
5250 use = reduction_phi;
5251 for (j = 0; j < ncopies; j++)
5253 edge pr_edge = loop_preheader_edge (loop);
5254 SET_PHI_ARG_DEF (use, pr_edge->dest_idx, vect_phi_res);
5255 use = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (use));
5261 phis.release ();
5262 if (nested_in_vect_loop)
5264 if (double_reduc)
5265 loop = outer_loop;
5266 else
5267 continue;
5270 phis.create (3);
5271 /* Find the loop-closed-use at the loop exit of the original scalar
5272 result. (The reduction result is expected to have two immediate uses,
5273 one at the latch block, and one at the loop exit). For double
5274 reductions we are looking for exit phis of the outer loop. */
5275 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
5277 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
5279 if (!is_gimple_debug (USE_STMT (use_p)))
5280 phis.safe_push (USE_STMT (use_p));
5282 else
5284 if (double_reduc && gimple_code (USE_STMT (use_p)) == GIMPLE_PHI)
5286 tree phi_res = PHI_RESULT (USE_STMT (use_p));
5288 FOR_EACH_IMM_USE_FAST (phi_use_p, phi_imm_iter, phi_res)
5290 if (!flow_bb_inside_loop_p (loop,
5291 gimple_bb (USE_STMT (phi_use_p)))
5292 && !is_gimple_debug (USE_STMT (phi_use_p)))
5293 phis.safe_push (USE_STMT (phi_use_p));
5299 FOR_EACH_VEC_ELT (phis, i, exit_phi)
5301 /* Replace the uses: */
5302 orig_name = PHI_RESULT (exit_phi);
5303 scalar_result = scalar_results[k];
5304 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
5305 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
5306 SET_USE (use_p, scalar_result);
5309 phis.release ();
5314 /* Function is_nonwrapping_integer_induction.
5316 Check if STMT (which is part of loop LOOP) both increments and
5317 does not cause overflow. */
5319 static bool
5320 is_nonwrapping_integer_induction (gimple *stmt, struct loop *loop)
5322 stmt_vec_info stmt_vinfo = vinfo_for_stmt (stmt);
5323 tree base = STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo);
5324 tree step = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo);
5325 tree lhs_type = TREE_TYPE (gimple_phi_result (stmt));
5326 widest_int ni, max_loop_value, lhs_max;
5327 bool overflow = false;
5329 /* Make sure the loop is integer based. */
5330 if (TREE_CODE (base) != INTEGER_CST
5331 || TREE_CODE (step) != INTEGER_CST)
5332 return false;
5334 /* Check that the induction increments. */
5335 if (tree_int_cst_sgn (step) == -1)
5336 return false;
5338 /* Check that the max size of the loop will not wrap. */
5340 if (TYPE_OVERFLOW_UNDEFINED (lhs_type))
5341 return true;
5343 if (! max_stmt_executions (loop, &ni))
5344 return false;
5346 max_loop_value = wi::mul (wi::to_widest (step), ni, TYPE_SIGN (lhs_type),
5347 &overflow);
5348 if (overflow)
5349 return false;
5351 max_loop_value = wi::add (wi::to_widest (base), max_loop_value,
5352 TYPE_SIGN (lhs_type), &overflow);
5353 if (overflow)
5354 return false;
5356 return (wi::min_precision (max_loop_value, TYPE_SIGN (lhs_type))
5357 <= TYPE_PRECISION (lhs_type));
5360 /* Function vectorizable_reduction.
5362 Check if STMT performs a reduction operation that can be vectorized.
5363 If VEC_STMT is also passed, vectorize the STMT: create a vectorized
5364 stmt to replace it, put it in VEC_STMT, and insert it at GSI.
5365 Return FALSE if not a vectorizable STMT, TRUE otherwise.
5367 This function also handles reduction idioms (patterns) that have been
5368 recognized in advance during vect_pattern_recog. In this case, STMT may be
5369 of this form:
5370 X = pattern_expr (arg0, arg1, ..., X)
5371 and it's STMT_VINFO_RELATED_STMT points to the last stmt in the original
5372 sequence that had been detected and replaced by the pattern-stmt (STMT).
5374 This function also handles reduction of condition expressions, for example:
5375 for (int i = 0; i < N; i++)
5376 if (a[i] < value)
5377 last = a[i];
5378 This is handled by vectorising the loop and creating an additional vector
5379 containing the loop indexes for which "a[i] < value" was true. In the
5380 function epilogue this is reduced to a single max value and then used to
5381 index into the vector of results.
5383 In some cases of reduction patterns, the type of the reduction variable X is
5384 different than the type of the other arguments of STMT.
5385 In such cases, the vectype that is used when transforming STMT into a vector
5386 stmt is different than the vectype that is used to determine the
5387 vectorization factor, because it consists of a different number of elements
5388 than the actual number of elements that are being operated upon in parallel.
5390 For example, consider an accumulation of shorts into an int accumulator.
5391 On some targets it's possible to vectorize this pattern operating on 8
5392 shorts at a time (hence, the vectype for purposes of determining the
5393 vectorization factor should be V8HI); on the other hand, the vectype that
5394 is used to create the vector form is actually V4SI (the type of the result).
5396 Upon entry to this function, STMT_VINFO_VECTYPE records the vectype that
5397 indicates what is the actual level of parallelism (V8HI in the example), so
5398 that the right vectorization factor would be derived. This vectype
5399 corresponds to the type of arguments to the reduction stmt, and should *NOT*
5400 be used to create the vectorized stmt. The right vectype for the vectorized
5401 stmt is obtained from the type of the result X:
5402 get_vectype_for_scalar_type (TREE_TYPE (X))
5404 This means that, contrary to "regular" reductions (or "regular" stmts in
5405 general), the following equation:
5406 STMT_VINFO_VECTYPE == get_vectype_for_scalar_type (TREE_TYPE (X))
5407 does *NOT* necessarily hold for reduction patterns. */
5409 bool
5410 vectorizable_reduction (gimple *stmt, gimple_stmt_iterator *gsi,
5411 gimple **vec_stmt, slp_tree slp_node)
5413 tree vec_dest;
5414 tree scalar_dest;
5415 tree loop_vec_def0 = NULL_TREE, loop_vec_def1 = NULL_TREE;
5416 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
5417 tree vectype_out = STMT_VINFO_VECTYPE (stmt_info);
5418 tree vectype_in = NULL_TREE;
5419 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
5420 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
5421 enum tree_code code, orig_code, epilog_reduc_code;
5422 machine_mode vec_mode;
5423 int op_type;
5424 optab optab, reduc_optab;
5425 tree new_temp = NULL_TREE;
5426 gimple *def_stmt;
5427 enum vect_def_type dt, cond_reduc_dt = vect_unknown_def_type;
5428 gphi *new_phi = NULL;
5429 tree scalar_type;
5430 bool is_simple_use;
5431 gimple *orig_stmt;
5432 stmt_vec_info orig_stmt_info;
5433 tree expr = NULL_TREE;
5434 int i;
5435 int ncopies;
5436 int epilog_copies;
5437 stmt_vec_info prev_stmt_info, prev_phi_info;
5438 bool single_defuse_cycle = false;
5439 tree reduc_def = NULL_TREE;
5440 gimple *new_stmt = NULL;
5441 int j;
5442 tree ops[3];
5443 bool nested_cycle = false, found_nested_cycle_def = false;
5444 gimple *reduc_def_stmt = NULL;
5445 bool double_reduc = false, dummy;
5446 basic_block def_bb;
5447 struct loop * def_stmt_loop, *outer_loop = NULL;
5448 tree def_arg;
5449 gimple *def_arg_stmt;
5450 auto_vec<tree> vec_oprnds0;
5451 auto_vec<tree> vec_oprnds1;
5452 auto_vec<tree> vect_defs;
5453 auto_vec<gimple *> phis;
5454 int vec_num;
5455 tree def0, def1, tem, op1 = NULL_TREE;
5456 bool first_p = true;
5457 tree cr_index_scalar_type = NULL_TREE, cr_index_vector_type = NULL_TREE;
5458 tree cond_reduc_val = NULL_TREE;
5460 /* In case of reduction chain we switch to the first stmt in the chain, but
5461 we don't update STMT_INFO, since only the last stmt is marked as reduction
5462 and has reduction properties. */
5463 if (GROUP_FIRST_ELEMENT (stmt_info)
5464 && GROUP_FIRST_ELEMENT (stmt_info) != stmt)
5466 stmt = GROUP_FIRST_ELEMENT (stmt_info);
5467 first_p = false;
5470 if (nested_in_vect_loop_p (loop, stmt))
5472 outer_loop = loop;
5473 loop = loop->inner;
5474 nested_cycle = true;
5477 /* 1. Is vectorizable reduction? */
5478 /* Not supportable if the reduction variable is used in the loop, unless
5479 it's a reduction chain. */
5480 if (STMT_VINFO_RELEVANT (stmt_info) > vect_used_in_outer
5481 && !GROUP_FIRST_ELEMENT (stmt_info))
5482 return false;
5484 /* Reductions that are not used even in an enclosing outer-loop,
5485 are expected to be "live" (used out of the loop). */
5486 if (STMT_VINFO_RELEVANT (stmt_info) == vect_unused_in_scope
5487 && !STMT_VINFO_LIVE_P (stmt_info))
5488 return false;
5490 /* Make sure it was already recognized as a reduction computation. */
5491 if (STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmt)) != vect_reduction_def
5492 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmt)) != vect_nested_cycle)
5493 return false;
5495 /* 2. Has this been recognized as a reduction pattern?
5497 Check if STMT represents a pattern that has been recognized
5498 in earlier analysis stages. For stmts that represent a pattern,
5499 the STMT_VINFO_RELATED_STMT field records the last stmt in
5500 the original sequence that constitutes the pattern. */
5502 orig_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
5503 if (orig_stmt)
5505 orig_stmt_info = vinfo_for_stmt (orig_stmt);
5506 gcc_assert (STMT_VINFO_IN_PATTERN_P (orig_stmt_info));
5507 gcc_assert (!STMT_VINFO_IN_PATTERN_P (stmt_info));
5510 /* 3. Check the operands of the operation. The first operands are defined
5511 inside the loop body. The last operand is the reduction variable,
5512 which is defined by the loop-header-phi. */
5514 gcc_assert (is_gimple_assign (stmt));
5516 /* Flatten RHS. */
5517 switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
5519 case GIMPLE_SINGLE_RHS:
5520 op_type = TREE_OPERAND_LENGTH (gimple_assign_rhs1 (stmt));
5521 if (op_type == ternary_op)
5523 tree rhs = gimple_assign_rhs1 (stmt);
5524 ops[0] = TREE_OPERAND (rhs, 0);
5525 ops[1] = TREE_OPERAND (rhs, 1);
5526 ops[2] = TREE_OPERAND (rhs, 2);
5527 code = TREE_CODE (rhs);
5529 else
5530 return false;
5531 break;
5533 case GIMPLE_BINARY_RHS:
5534 code = gimple_assign_rhs_code (stmt);
5535 op_type = TREE_CODE_LENGTH (code);
5536 gcc_assert (op_type == binary_op);
5537 ops[0] = gimple_assign_rhs1 (stmt);
5538 ops[1] = gimple_assign_rhs2 (stmt);
5539 break;
5541 case GIMPLE_TERNARY_RHS:
5542 code = gimple_assign_rhs_code (stmt);
5543 op_type = TREE_CODE_LENGTH (code);
5544 gcc_assert (op_type == ternary_op);
5545 ops[0] = gimple_assign_rhs1 (stmt);
5546 ops[1] = gimple_assign_rhs2 (stmt);
5547 ops[2] = gimple_assign_rhs3 (stmt);
5548 break;
5550 case GIMPLE_UNARY_RHS:
5551 return false;
5553 default:
5554 gcc_unreachable ();
5556 /* The default is that the reduction variable is the last in statement. */
5557 int reduc_index = op_type - 1;
5558 if (code == MINUS_EXPR)
5559 reduc_index = 0;
5561 if (code == COND_EXPR && slp_node)
5562 return false;
5564 scalar_dest = gimple_assign_lhs (stmt);
5565 scalar_type = TREE_TYPE (scalar_dest);
5566 if (!POINTER_TYPE_P (scalar_type) && !INTEGRAL_TYPE_P (scalar_type)
5567 && !SCALAR_FLOAT_TYPE_P (scalar_type))
5568 return false;
5570 /* Do not try to vectorize bit-precision reductions. */
5571 if ((TYPE_PRECISION (scalar_type)
5572 != GET_MODE_PRECISION (TYPE_MODE (scalar_type))))
5573 return false;
5575 /* All uses but the last are expected to be defined in the loop.
5576 The last use is the reduction variable. In case of nested cycle this
5577 assumption is not true: we use reduc_index to record the index of the
5578 reduction variable. */
5579 for (i = 0; i < op_type; i++)
5581 if (i == reduc_index)
5582 continue;
5584 /* The condition of COND_EXPR is checked in vectorizable_condition(). */
5585 if (i == 0 && code == COND_EXPR)
5586 continue;
5588 is_simple_use = vect_is_simple_use (ops[i], loop_vinfo,
5589 &def_stmt, &dt, &tem);
5590 if (!vectype_in)
5591 vectype_in = tem;
5592 gcc_assert (is_simple_use);
5594 if (dt != vect_internal_def
5595 && dt != vect_external_def
5596 && dt != vect_constant_def
5597 && dt != vect_induction_def
5598 && !(dt == vect_nested_cycle && nested_cycle))
5599 return false;
5601 if (dt == vect_nested_cycle)
5603 found_nested_cycle_def = true;
5604 reduc_def_stmt = def_stmt;
5605 reduc_index = i;
5608 if (i == 1 && code == COND_EXPR)
5610 /* Record how value of COND_EXPR is defined. */
5611 if (dt == vect_constant_def)
5613 cond_reduc_dt = dt;
5614 cond_reduc_val = ops[i];
5616 if (dt == vect_induction_def && def_stmt != NULL
5617 && is_nonwrapping_integer_induction (def_stmt, loop))
5618 cond_reduc_dt = dt;
5622 is_simple_use = vect_is_simple_use (ops[reduc_index], loop_vinfo,
5623 &def_stmt, &dt, &tem);
5624 if (!vectype_in)
5625 vectype_in = tem;
5626 gcc_assert (is_simple_use);
5627 if (!found_nested_cycle_def)
5628 reduc_def_stmt = def_stmt;
5630 if (reduc_def_stmt && gimple_code (reduc_def_stmt) != GIMPLE_PHI)
5631 return false;
5633 if (!(dt == vect_reduction_def
5634 || dt == vect_nested_cycle
5635 || ((dt == vect_internal_def || dt == vect_external_def
5636 || dt == vect_constant_def || dt == vect_induction_def)
5637 && nested_cycle && found_nested_cycle_def)))
5639 /* For pattern recognized stmts, orig_stmt might be a reduction,
5640 but some helper statements for the pattern might not, or
5641 might be COND_EXPRs with reduction uses in the condition. */
5642 gcc_assert (orig_stmt);
5643 return false;
5646 enum vect_reduction_type v_reduc_type;
5647 gimple *tmp = vect_is_simple_reduction (loop_vinfo, reduc_def_stmt,
5648 !nested_cycle, &dummy, false,
5649 &v_reduc_type);
5651 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) = v_reduc_type;
5652 /* If we have a condition reduction, see if we can simplify it further. */
5653 if (v_reduc_type == COND_REDUCTION)
5655 if (cond_reduc_dt == vect_induction_def)
5657 if (dump_enabled_p ())
5658 dump_printf_loc (MSG_NOTE, vect_location,
5659 "condition expression based on "
5660 "integer induction.\n");
5661 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5662 = INTEGER_INDUC_COND_REDUCTION;
5665 /* Loop peeling modifies initial value of reduction PHI, which
5666 makes the reduction stmt to be transformed different to the
5667 original stmt analyzed. We need to record reduction code for
5668 CONST_COND_REDUCTION type reduction at analyzing stage, thus
5669 it can be used directly at transform stage. */
5670 if (STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info) == MAX_EXPR
5671 || STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info) == MIN_EXPR)
5673 /* Also set the reduction type to CONST_COND_REDUCTION. */
5674 gcc_assert (cond_reduc_dt == vect_constant_def);
5675 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) = CONST_COND_REDUCTION;
5677 else if (cond_reduc_dt == vect_constant_def)
5679 enum vect_def_type cond_initial_dt;
5680 gimple *def_stmt = SSA_NAME_DEF_STMT (ops[reduc_index]);
5681 tree cond_initial_val
5682 = PHI_ARG_DEF_FROM_EDGE (def_stmt, loop_preheader_edge (loop));
5684 gcc_assert (cond_reduc_val != NULL_TREE);
5685 vect_is_simple_use (cond_initial_val, loop_vinfo,
5686 &def_stmt, &cond_initial_dt);
5687 if (cond_initial_dt == vect_constant_def
5688 && types_compatible_p (TREE_TYPE (cond_initial_val),
5689 TREE_TYPE (cond_reduc_val)))
5691 tree e = fold_build2 (LE_EXPR, boolean_type_node,
5692 cond_initial_val, cond_reduc_val);
5693 if (e && (integer_onep (e) || integer_zerop (e)))
5695 if (dump_enabled_p ())
5696 dump_printf_loc (MSG_NOTE, vect_location,
5697 "condition expression based on "
5698 "compile time constant.\n");
5699 /* Record reduction code at analysis stage. */
5700 STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info)
5701 = integer_onep (e) ? MAX_EXPR : MIN_EXPR;
5702 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5703 = CONST_COND_REDUCTION;
5709 if (orig_stmt)
5710 gcc_assert (tmp == orig_stmt
5711 || GROUP_FIRST_ELEMENT (vinfo_for_stmt (tmp)) == orig_stmt);
5712 else
5713 /* We changed STMT to be the first stmt in reduction chain, hence we
5714 check that in this case the first element in the chain is STMT. */
5715 gcc_assert (stmt == tmp
5716 || GROUP_FIRST_ELEMENT (vinfo_for_stmt (tmp)) == stmt);
5718 if (STMT_VINFO_LIVE_P (vinfo_for_stmt (reduc_def_stmt)))
5719 return false;
5721 if (slp_node)
5722 ncopies = 1;
5723 else
5724 ncopies = (LOOP_VINFO_VECT_FACTOR (loop_vinfo)
5725 / TYPE_VECTOR_SUBPARTS (vectype_in));
5727 gcc_assert (ncopies >= 1);
5729 vec_mode = TYPE_MODE (vectype_in);
5731 if (code == COND_EXPR)
5733 /* Only call during the analysis stage, otherwise we'll lose
5734 STMT_VINFO_TYPE. */
5735 if (!vec_stmt && !vectorizable_condition (stmt, gsi, NULL,
5736 ops[reduc_index], 0, NULL))
5738 if (dump_enabled_p ())
5739 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5740 "unsupported condition in reduction\n");
5741 return false;
5744 else
5746 /* 4. Supportable by target? */
5748 if (code == LSHIFT_EXPR || code == RSHIFT_EXPR
5749 || code == LROTATE_EXPR || code == RROTATE_EXPR)
5751 /* Shifts and rotates are only supported by vectorizable_shifts,
5752 not vectorizable_reduction. */
5753 if (dump_enabled_p ())
5754 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5755 "unsupported shift or rotation.\n");
5756 return false;
5759 /* 4.1. check support for the operation in the loop */
5760 optab = optab_for_tree_code (code, vectype_in, optab_default);
5761 if (!optab)
5763 if (dump_enabled_p ())
5764 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5765 "no optab.\n");
5767 return false;
5770 if (optab_handler (optab, vec_mode) == CODE_FOR_nothing)
5772 if (dump_enabled_p ())
5773 dump_printf (MSG_NOTE, "op not supported by target.\n");
5775 if (GET_MODE_SIZE (vec_mode) != UNITS_PER_WORD
5776 || LOOP_VINFO_VECT_FACTOR (loop_vinfo)
5777 < vect_min_worthwhile_factor (code))
5778 return false;
5780 if (dump_enabled_p ())
5781 dump_printf (MSG_NOTE, "proceeding using word mode.\n");
5784 /* Worthwhile without SIMD support? */
5785 if (!VECTOR_MODE_P (TYPE_MODE (vectype_in))
5786 && LOOP_VINFO_VECT_FACTOR (loop_vinfo)
5787 < vect_min_worthwhile_factor (code))
5789 if (dump_enabled_p ())
5790 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5791 "not worthwhile without SIMD support.\n");
5793 return false;
5797 /* 4.2. Check support for the epilog operation.
5799 If STMT represents a reduction pattern, then the type of the
5800 reduction variable may be different than the type of the rest
5801 of the arguments. For example, consider the case of accumulation
5802 of shorts into an int accumulator; The original code:
5803 S1: int_a = (int) short_a;
5804 orig_stmt-> S2: int_acc = plus <int_a ,int_acc>;
5806 was replaced with:
5807 STMT: int_acc = widen_sum <short_a, int_acc>
5809 This means that:
5810 1. The tree-code that is used to create the vector operation in the
5811 epilog code (that reduces the partial results) is not the
5812 tree-code of STMT, but is rather the tree-code of the original
5813 stmt from the pattern that STMT is replacing. I.e, in the example
5814 above we want to use 'widen_sum' in the loop, but 'plus' in the
5815 epilog.
5816 2. The type (mode) we use to check available target support
5817 for the vector operation to be created in the *epilog*, is
5818 determined by the type of the reduction variable (in the example
5819 above we'd check this: optab_handler (plus_optab, vect_int_mode])).
5820 However the type (mode) we use to check available target support
5821 for the vector operation to be created *inside the loop*, is
5822 determined by the type of the other arguments to STMT (in the
5823 example we'd check this: optab_handler (widen_sum_optab,
5824 vect_short_mode)).
5826 This is contrary to "regular" reductions, in which the types of all
5827 the arguments are the same as the type of the reduction variable.
5828 For "regular" reductions we can therefore use the same vector type
5829 (and also the same tree-code) when generating the epilog code and
5830 when generating the code inside the loop. */
5832 if (orig_stmt)
5834 /* This is a reduction pattern: get the vectype from the type of the
5835 reduction variable, and get the tree-code from orig_stmt. */
5836 gcc_assert (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5837 == TREE_CODE_REDUCTION);
5838 orig_code = gimple_assign_rhs_code (orig_stmt);
5839 gcc_assert (vectype_out);
5840 vec_mode = TYPE_MODE (vectype_out);
5842 else
5844 /* Regular reduction: use the same vectype and tree-code as used for
5845 the vector code inside the loop can be used for the epilog code. */
5846 orig_code = code;
5848 if (code == MINUS_EXPR)
5849 orig_code = PLUS_EXPR;
5851 /* For simple condition reductions, replace with the actual expression
5852 we want to base our reduction around. */
5853 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == CONST_COND_REDUCTION)
5855 orig_code = STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info);
5856 gcc_assert (orig_code == MAX_EXPR || orig_code == MIN_EXPR);
5858 else if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5859 == INTEGER_INDUC_COND_REDUCTION)
5860 orig_code = MAX_EXPR;
5863 if (nested_cycle)
5865 def_bb = gimple_bb (reduc_def_stmt);
5866 def_stmt_loop = def_bb->loop_father;
5867 def_arg = PHI_ARG_DEF_FROM_EDGE (reduc_def_stmt,
5868 loop_preheader_edge (def_stmt_loop));
5869 if (TREE_CODE (def_arg) == SSA_NAME
5870 && (def_arg_stmt = SSA_NAME_DEF_STMT (def_arg))
5871 && gimple_code (def_arg_stmt) == GIMPLE_PHI
5872 && flow_bb_inside_loop_p (outer_loop, gimple_bb (def_arg_stmt))
5873 && vinfo_for_stmt (def_arg_stmt)
5874 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_arg_stmt))
5875 == vect_double_reduction_def)
5876 double_reduc = true;
5879 epilog_reduc_code = ERROR_MARK;
5881 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) != COND_REDUCTION)
5883 if (reduction_code_for_scalar_code (orig_code, &epilog_reduc_code))
5885 reduc_optab = optab_for_tree_code (epilog_reduc_code, vectype_out,
5886 optab_default);
5887 if (!reduc_optab)
5889 if (dump_enabled_p ())
5890 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5891 "no optab for reduction.\n");
5893 epilog_reduc_code = ERROR_MARK;
5895 else if (optab_handler (reduc_optab, vec_mode) == CODE_FOR_nothing)
5897 if (dump_enabled_p ())
5898 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5899 "reduc op not supported by target.\n");
5901 epilog_reduc_code = ERROR_MARK;
5904 /* When epilog_reduc_code is ERROR_MARK then a reduction will be
5905 generated in the epilog using multiple expressions. This does not
5906 work for condition reductions. */
5907 if (epilog_reduc_code == ERROR_MARK
5908 && (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5909 == INTEGER_INDUC_COND_REDUCTION
5910 || STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5911 == CONST_COND_REDUCTION))
5913 if (dump_enabled_p ())
5914 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5915 "no reduc code for scalar code.\n");
5916 return false;
5919 else
5921 if (!nested_cycle || double_reduc)
5923 if (dump_enabled_p ())
5924 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5925 "no reduc code for scalar code.\n");
5927 return false;
5931 else
5933 int scalar_precision = GET_MODE_PRECISION (TYPE_MODE (scalar_type));
5934 cr_index_scalar_type = make_unsigned_type (scalar_precision);
5935 cr_index_vector_type = build_vector_type
5936 (cr_index_scalar_type, TYPE_VECTOR_SUBPARTS (vectype_out));
5938 epilog_reduc_code = REDUC_MAX_EXPR;
5939 optab = optab_for_tree_code (REDUC_MAX_EXPR, cr_index_vector_type,
5940 optab_default);
5941 if (optab_handler (optab, TYPE_MODE (cr_index_vector_type))
5942 == CODE_FOR_nothing)
5944 if (dump_enabled_p ())
5945 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5946 "reduc max op not supported by target.\n");
5947 return false;
5951 if ((double_reduc
5952 || STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) != TREE_CODE_REDUCTION)
5953 && ncopies > 1)
5955 if (dump_enabled_p ())
5956 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5957 "multiple types in double reduction or condition "
5958 "reduction.\n");
5959 return false;
5962 /* In case of widenning multiplication by a constant, we update the type
5963 of the constant to be the type of the other operand. We check that the
5964 constant fits the type in the pattern recognition pass. */
5965 if (code == DOT_PROD_EXPR
5966 && !types_compatible_p (TREE_TYPE (ops[0]), TREE_TYPE (ops[1])))
5968 if (TREE_CODE (ops[0]) == INTEGER_CST)
5969 ops[0] = fold_convert (TREE_TYPE (ops[1]), ops[0]);
5970 else if (TREE_CODE (ops[1]) == INTEGER_CST)
5971 ops[1] = fold_convert (TREE_TYPE (ops[0]), ops[1]);
5972 else
5974 if (dump_enabled_p ())
5975 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5976 "invalid types in dot-prod\n");
5978 return false;
5982 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
5984 widest_int ni;
5986 if (! max_loop_iterations (loop, &ni))
5988 if (dump_enabled_p ())
5989 dump_printf_loc (MSG_NOTE, vect_location,
5990 "loop count not known, cannot create cond "
5991 "reduction.\n");
5992 return false;
5994 /* Convert backedges to iterations. */
5995 ni += 1;
5997 /* The additional index will be the same type as the condition. Check
5998 that the loop can fit into this less one (because we'll use up the
5999 zero slot for when there are no matches). */
6000 tree max_index = TYPE_MAX_VALUE (cr_index_scalar_type);
6001 if (wi::geu_p (ni, wi::to_widest (max_index)))
6003 if (dump_enabled_p ())
6004 dump_printf_loc (MSG_NOTE, vect_location,
6005 "loop size is greater than data size.\n");
6006 return false;
6010 if (!vec_stmt) /* transformation not required. */
6012 if (first_p
6013 && !vect_model_reduction_cost (stmt_info, epilog_reduc_code, ncopies,
6014 reduc_index))
6015 return false;
6016 STMT_VINFO_TYPE (stmt_info) = reduc_vec_info_type;
6017 return true;
6020 /** Transform. **/
6022 if (dump_enabled_p ())
6023 dump_printf_loc (MSG_NOTE, vect_location, "transform reduction.\n");
6025 /* FORNOW: Multiple types are not supported for condition. */
6026 if (code == COND_EXPR)
6027 gcc_assert (ncopies == 1);
6029 /* Create the destination vector */
6030 vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
6032 /* In case the vectorization factor (VF) is bigger than the number
6033 of elements that we can fit in a vectype (nunits), we have to generate
6034 more than one vector stmt - i.e - we need to "unroll" the
6035 vector stmt by a factor VF/nunits. For more details see documentation
6036 in vectorizable_operation. */
6038 /* If the reduction is used in an outer loop we need to generate
6039 VF intermediate results, like so (e.g. for ncopies=2):
6040 r0 = phi (init, r0)
6041 r1 = phi (init, r1)
6042 r0 = x0 + r0;
6043 r1 = x1 + r1;
6044 (i.e. we generate VF results in 2 registers).
6045 In this case we have a separate def-use cycle for each copy, and therefore
6046 for each copy we get the vector def for the reduction variable from the
6047 respective phi node created for this copy.
6049 Otherwise (the reduction is unused in the loop nest), we can combine
6050 together intermediate results, like so (e.g. for ncopies=2):
6051 r = phi (init, r)
6052 r = x0 + r;
6053 r = x1 + r;
6054 (i.e. we generate VF/2 results in a single register).
6055 In this case for each copy we get the vector def for the reduction variable
6056 from the vectorized reduction operation generated in the previous iteration.
6059 if (STMT_VINFO_RELEVANT (stmt_info) <= vect_used_only_live)
6061 single_defuse_cycle = true;
6062 epilog_copies = 1;
6064 else
6065 epilog_copies = ncopies;
6067 prev_stmt_info = NULL;
6068 prev_phi_info = NULL;
6069 if (slp_node)
6070 vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
6071 else
6073 vec_num = 1;
6074 vec_oprnds0.create (1);
6075 if (op_type == ternary_op)
6076 vec_oprnds1.create (1);
6079 phis.create (vec_num);
6080 vect_defs.create (vec_num);
6081 if (!slp_node)
6082 vect_defs.quick_push (NULL_TREE);
6084 for (j = 0; j < ncopies; j++)
6086 if (j == 0 || !single_defuse_cycle)
6088 for (i = 0; i < vec_num; i++)
6090 /* Create the reduction-phi that defines the reduction
6091 operand. */
6092 new_phi = create_phi_node (vec_dest, loop->header);
6093 set_vinfo_for_stmt (new_phi,
6094 new_stmt_vec_info (new_phi, loop_vinfo));
6095 if (j == 0 || slp_node)
6096 phis.quick_push (new_phi);
6100 if (code == COND_EXPR)
6102 gcc_assert (!slp_node);
6103 vectorizable_condition (stmt, gsi, vec_stmt,
6104 PHI_RESULT (phis[0]),
6105 reduc_index, NULL);
6106 /* Multiple types are not supported for condition. */
6107 break;
6110 /* Handle uses. */
6111 if (j == 0)
6113 if (slp_node)
6115 /* Get vec defs for all the operands except the reduction index,
6116 ensuring the ordering of the ops in the vector is kept. */
6117 auto_vec<tree, 3> slp_ops;
6118 auto_vec<vec<tree>, 3> vec_defs;
6120 slp_ops.quick_push ((reduc_index == 0) ? NULL : ops[0]);
6121 slp_ops.quick_push ((reduc_index == 1) ? NULL : ops[1]);
6122 if (op_type == ternary_op)
6123 slp_ops.quick_push ((reduc_index == 2) ? NULL : ops[2]);
6125 vect_get_slp_defs (slp_ops, slp_node, &vec_defs, -1);
6127 vec_oprnds0.safe_splice (vec_defs[(reduc_index == 0) ? 1 : 0]);
6128 if (op_type == ternary_op)
6129 vec_oprnds1.safe_splice (vec_defs[(reduc_index == 2) ? 1 : 2]);
6131 else
6133 loop_vec_def0 = vect_get_vec_def_for_operand (ops[!reduc_index],
6134 stmt);
6135 vec_oprnds0.quick_push (loop_vec_def0);
6136 if (op_type == ternary_op)
6138 op1 = (reduc_index == 0) ? ops[2] : ops[1];
6139 loop_vec_def1 = vect_get_vec_def_for_operand (op1, stmt);
6140 vec_oprnds1.quick_push (loop_vec_def1);
6144 else
6146 if (!slp_node)
6148 enum vect_def_type dt;
6149 gimple *dummy_stmt;
6151 vect_is_simple_use (ops[!reduc_index], loop_vinfo,
6152 &dummy_stmt, &dt);
6153 loop_vec_def0 = vect_get_vec_def_for_stmt_copy (dt,
6154 loop_vec_def0);
6155 vec_oprnds0[0] = loop_vec_def0;
6156 if (op_type == ternary_op)
6158 vect_is_simple_use (op1, loop_vinfo, &dummy_stmt, &dt);
6159 loop_vec_def1 = vect_get_vec_def_for_stmt_copy (dt,
6160 loop_vec_def1);
6161 vec_oprnds1[0] = loop_vec_def1;
6165 if (single_defuse_cycle)
6166 reduc_def = gimple_assign_lhs (new_stmt);
6168 STMT_VINFO_RELATED_STMT (prev_phi_info) = new_phi;
6171 FOR_EACH_VEC_ELT (vec_oprnds0, i, def0)
6173 if (slp_node)
6174 reduc_def = PHI_RESULT (phis[i]);
6175 else
6177 if (!single_defuse_cycle || j == 0)
6178 reduc_def = PHI_RESULT (new_phi);
6181 def1 = ((op_type == ternary_op)
6182 ? vec_oprnds1[i] : NULL);
6183 if (op_type == binary_op)
6185 if (reduc_index == 0)
6186 expr = build2 (code, vectype_out, reduc_def, def0);
6187 else
6188 expr = build2 (code, vectype_out, def0, reduc_def);
6190 else
6192 if (reduc_index == 0)
6193 expr = build3 (code, vectype_out, reduc_def, def0, def1);
6194 else
6196 if (reduc_index == 1)
6197 expr = build3 (code, vectype_out, def0, reduc_def, def1);
6198 else
6199 expr = build3 (code, vectype_out, def0, def1, reduc_def);
6203 new_stmt = gimple_build_assign (vec_dest, expr);
6204 new_temp = make_ssa_name (vec_dest, new_stmt);
6205 gimple_assign_set_lhs (new_stmt, new_temp);
6206 vect_finish_stmt_generation (stmt, new_stmt, gsi);
6208 if (slp_node)
6210 SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt);
6211 vect_defs.quick_push (new_temp);
6213 else
6214 vect_defs[0] = new_temp;
6217 if (slp_node)
6218 continue;
6220 if (j == 0)
6221 STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt;
6222 else
6223 STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt;
6225 prev_stmt_info = vinfo_for_stmt (new_stmt);
6226 prev_phi_info = vinfo_for_stmt (new_phi);
6229 tree indx_before_incr, indx_after_incr, cond_name = NULL;
6231 /* Finalize the reduction-phi (set its arguments) and create the
6232 epilog reduction code. */
6233 if ((!single_defuse_cycle || code == COND_EXPR) && !slp_node)
6235 new_temp = gimple_assign_lhs (*vec_stmt);
6236 vect_defs[0] = new_temp;
6238 /* For cond reductions we want to create a new vector (INDEX_COND_EXPR)
6239 which is updated with the current index of the loop for every match of
6240 the original loop's cond_expr (VEC_STMT). This results in a vector
6241 containing the last time the condition passed for that vector lane.
6242 The first match will be a 1 to allow 0 to be used for non-matching
6243 indexes. If there are no matches at all then the vector will be all
6244 zeroes. */
6245 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
6247 int nunits_out = TYPE_VECTOR_SUBPARTS (vectype_out);
6248 int k;
6250 gcc_assert (gimple_assign_rhs_code (*vec_stmt) == VEC_COND_EXPR);
6252 /* First we create a simple vector induction variable which starts
6253 with the values {1,2,3,...} (SERIES_VECT) and increments by the
6254 vector size (STEP). */
6256 /* Create a {1,2,3,...} vector. */
6257 tree *vtemp = XALLOCAVEC (tree, nunits_out);
6258 for (k = 0; k < nunits_out; ++k)
6259 vtemp[k] = build_int_cst (cr_index_scalar_type, k + 1);
6260 tree series_vect = build_vector (cr_index_vector_type, vtemp);
6262 /* Create a vector of the step value. */
6263 tree step = build_int_cst (cr_index_scalar_type, nunits_out);
6264 tree vec_step = build_vector_from_val (cr_index_vector_type, step);
6266 /* Create an induction variable. */
6267 gimple_stmt_iterator incr_gsi;
6268 bool insert_after;
6269 standard_iv_increment_position (loop, &incr_gsi, &insert_after);
6270 create_iv (series_vect, vec_step, NULL_TREE, loop, &incr_gsi,
6271 insert_after, &indx_before_incr, &indx_after_incr);
6273 /* Next create a new phi node vector (NEW_PHI_TREE) which starts
6274 filled with zeros (VEC_ZERO). */
6276 /* Create a vector of 0s. */
6277 tree zero = build_zero_cst (cr_index_scalar_type);
6278 tree vec_zero = build_vector_from_val (cr_index_vector_type, zero);
6280 /* Create a vector phi node. */
6281 tree new_phi_tree = make_ssa_name (cr_index_vector_type);
6282 new_phi = create_phi_node (new_phi_tree, loop->header);
6283 set_vinfo_for_stmt (new_phi,
6284 new_stmt_vec_info (new_phi, loop_vinfo));
6285 add_phi_arg (new_phi, vec_zero, loop_preheader_edge (loop),
6286 UNKNOWN_LOCATION);
6288 /* Now take the condition from the loops original cond_expr
6289 (VEC_STMT) and produce a new cond_expr (INDEX_COND_EXPR) which for
6290 every match uses values from the induction variable
6291 (INDEX_BEFORE_INCR) otherwise uses values from the phi node
6292 (NEW_PHI_TREE).
6293 Finally, we update the phi (NEW_PHI_TREE) to take the value of
6294 the new cond_expr (INDEX_COND_EXPR). */
6296 /* Duplicate the condition from vec_stmt. */
6297 tree ccompare = unshare_expr (gimple_assign_rhs1 (*vec_stmt));
6299 /* Create a conditional, where the condition is taken from vec_stmt
6300 (CCOMPARE), then is the induction index (INDEX_BEFORE_INCR) and
6301 else is the phi (NEW_PHI_TREE). */
6302 tree index_cond_expr = build3 (VEC_COND_EXPR, cr_index_vector_type,
6303 ccompare, indx_before_incr,
6304 new_phi_tree);
6305 cond_name = make_ssa_name (cr_index_vector_type);
6306 gimple *index_condition = gimple_build_assign (cond_name,
6307 index_cond_expr);
6308 gsi_insert_before (&incr_gsi, index_condition, GSI_SAME_STMT);
6309 stmt_vec_info index_vec_info = new_stmt_vec_info (index_condition,
6310 loop_vinfo);
6311 STMT_VINFO_VECTYPE (index_vec_info) = cr_index_vector_type;
6312 set_vinfo_for_stmt (index_condition, index_vec_info);
6314 /* Update the phi with the vec cond. */
6315 add_phi_arg (new_phi, cond_name, loop_latch_edge (loop),
6316 UNKNOWN_LOCATION);
6320 vect_create_epilog_for_reduction (vect_defs, stmt, epilog_copies,
6321 epilog_reduc_code, phis, reduc_index,
6322 double_reduc, slp_node, cond_name);
6324 return true;
6327 /* Function vect_min_worthwhile_factor.
6329 For a loop where we could vectorize the operation indicated by CODE,
6330 return the minimum vectorization factor that makes it worthwhile
6331 to use generic vectors. */
6333 vect_min_worthwhile_factor (enum tree_code code)
6335 switch (code)
6337 case PLUS_EXPR:
6338 case MINUS_EXPR:
6339 case NEGATE_EXPR:
6340 return 4;
6342 case BIT_AND_EXPR:
6343 case BIT_IOR_EXPR:
6344 case BIT_XOR_EXPR:
6345 case BIT_NOT_EXPR:
6346 return 2;
6348 default:
6349 return INT_MAX;
6354 /* Function vectorizable_induction
6356 Check if PHI performs an induction computation that can be vectorized.
6357 If VEC_STMT is also passed, vectorize the induction PHI: create a vectorized
6358 phi to replace it, put it in VEC_STMT, and add it to the same basic block.
6359 Return FALSE if not a vectorizable STMT, TRUE otherwise. */
6361 bool
6362 vectorizable_induction (gimple *phi,
6363 gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
6364 gimple **vec_stmt)
6366 stmt_vec_info stmt_info = vinfo_for_stmt (phi);
6367 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
6368 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
6369 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6370 int nunits = TYPE_VECTOR_SUBPARTS (vectype);
6371 int ncopies = LOOP_VINFO_VECT_FACTOR (loop_vinfo) / nunits;
6372 tree vec_def;
6374 gcc_assert (ncopies >= 1);
6375 /* FORNOW. These restrictions should be relaxed. */
6376 if (nested_in_vect_loop_p (loop, phi))
6378 imm_use_iterator imm_iter;
6379 use_operand_p use_p;
6380 gimple *exit_phi;
6381 edge latch_e;
6382 tree loop_arg;
6384 if (ncopies > 1)
6386 if (dump_enabled_p ())
6387 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6388 "multiple types in nested loop.\n");
6389 return false;
6392 exit_phi = NULL;
6393 latch_e = loop_latch_edge (loop->inner);
6394 loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
6395 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
6397 gimple *use_stmt = USE_STMT (use_p);
6398 if (is_gimple_debug (use_stmt))
6399 continue;
6401 if (!flow_bb_inside_loop_p (loop->inner, gimple_bb (use_stmt)))
6403 exit_phi = use_stmt;
6404 break;
6407 if (exit_phi)
6409 stmt_vec_info exit_phi_vinfo = vinfo_for_stmt (exit_phi);
6410 if (!(STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
6411 && !STMT_VINFO_LIVE_P (exit_phi_vinfo)))
6413 if (dump_enabled_p ())
6414 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6415 "inner-loop induction only used outside "
6416 "of the outer vectorized loop.\n");
6417 return false;
6422 if (!STMT_VINFO_RELEVANT_P (stmt_info))
6423 return false;
6425 /* FORNOW: SLP not supported. */
6426 if (STMT_SLP_TYPE (stmt_info))
6427 return false;
6429 gcc_assert (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def);
6431 if (gimple_code (phi) != GIMPLE_PHI)
6432 return false;
6434 if (!vec_stmt) /* transformation not required. */
6436 STMT_VINFO_TYPE (stmt_info) = induc_vec_info_type;
6437 if (dump_enabled_p ())
6438 dump_printf_loc (MSG_NOTE, vect_location,
6439 "=== vectorizable_induction ===\n");
6440 vect_model_induction_cost (stmt_info, ncopies);
6441 return true;
6444 /** Transform. **/
6446 if (dump_enabled_p ())
6447 dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
6449 vec_def = get_initial_def_for_induction (phi);
6450 *vec_stmt = SSA_NAME_DEF_STMT (vec_def);
6451 return true;
6454 /* Function vectorizable_live_operation.
6456 STMT computes a value that is used outside the loop. Check if
6457 it can be supported. */
6459 bool
6460 vectorizable_live_operation (gimple *stmt,
6461 gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
6462 slp_tree slp_node, int slp_index,
6463 gimple **vec_stmt)
6465 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
6466 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
6467 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6468 imm_use_iterator imm_iter;
6469 tree lhs, lhs_type, bitsize, vec_bitsize;
6470 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
6471 int nunits = TYPE_VECTOR_SUBPARTS (vectype);
6472 int ncopies = LOOP_VINFO_VECT_FACTOR (loop_vinfo) / nunits;
6473 gimple *use_stmt;
6474 auto_vec<tree> vec_oprnds;
6476 gcc_assert (STMT_VINFO_LIVE_P (stmt_info));
6478 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def)
6479 return false;
6481 /* FORNOW. CHECKME. */
6482 if (nested_in_vect_loop_p (loop, stmt))
6483 return false;
6485 /* If STMT is not relevant and it is a simple assignment and its inputs are
6486 invariant then it can remain in place, unvectorized. The original last
6487 scalar value that it computes will be used. */
6488 if (!STMT_VINFO_RELEVANT_P (stmt_info))
6490 gcc_assert (is_simple_and_all_uses_invariant (stmt, loop_vinfo));
6491 if (dump_enabled_p ())
6492 dump_printf_loc (MSG_NOTE, vect_location,
6493 "statement is simple and uses invariant. Leaving in "
6494 "place.\n");
6495 return true;
6498 if (!vec_stmt)
6499 /* No transformation required. */
6500 return true;
6502 /* If stmt has a related stmt, then use that for getting the lhs. */
6503 if (is_pattern_stmt_p (stmt_info))
6504 stmt = STMT_VINFO_RELATED_STMT (stmt_info);
6506 lhs = (is_a <gphi *> (stmt)) ? gimple_phi_result (stmt)
6507 : gimple_get_lhs (stmt);
6508 lhs_type = TREE_TYPE (lhs);
6510 bitsize = TYPE_SIZE (TREE_TYPE (vectype));
6511 vec_bitsize = TYPE_SIZE (vectype);
6513 /* Get the vectorized lhs of STMT and the lane to use (counted in bits). */
6514 tree vec_lhs, bitstart;
6515 if (slp_node)
6517 gcc_assert (slp_index >= 0);
6519 int num_scalar = SLP_TREE_SCALAR_STMTS (slp_node).length ();
6520 int num_vec = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
6522 /* Get the last occurrence of the scalar index from the concatenation of
6523 all the slp vectors. Calculate which slp vector it is and the index
6524 within. */
6525 int pos = (num_vec * nunits) - num_scalar + slp_index;
6526 int vec_entry = pos / nunits;
6527 int vec_index = pos % nunits;
6529 /* Get the correct slp vectorized stmt. */
6530 vec_lhs = gimple_get_lhs (SLP_TREE_VEC_STMTS (slp_node)[vec_entry]);
6532 /* Get entry to use. */
6533 bitstart = build_int_cst (unsigned_type_node, vec_index);
6534 bitstart = int_const_binop (MULT_EXPR, bitsize, bitstart);
6536 else
6538 enum vect_def_type dt = STMT_VINFO_DEF_TYPE (stmt_info);
6539 vec_lhs = vect_get_vec_def_for_operand_1 (stmt, dt);
6541 /* For multiple copies, get the last copy. */
6542 for (int i = 1; i < ncopies; ++i)
6543 vec_lhs = vect_get_vec_def_for_stmt_copy (vect_unknown_def_type,
6544 vec_lhs);
6546 /* Get the last lane in the vector. */
6547 bitstart = int_const_binop (MINUS_EXPR, vec_bitsize, bitsize);
6550 /* Create a new vectorized stmt for the uses of STMT and insert outside the
6551 loop. */
6552 gimple_seq stmts = NULL;
6553 tree new_tree = build3 (BIT_FIELD_REF, TREE_TYPE (vectype), vec_lhs, bitsize,
6554 bitstart);
6555 new_tree = force_gimple_operand (fold_convert (lhs_type, new_tree), &stmts,
6556 true, NULL_TREE);
6557 if (stmts)
6558 gsi_insert_seq_on_edge_immediate (single_exit (loop), stmts);
6560 /* Replace use of lhs with newly computed result. If the use stmt is a
6561 single arg PHI, just replace all uses of PHI result. It's necessary
6562 because lcssa PHI defining lhs may be before newly inserted stmt. */
6563 use_operand_p use_p;
6564 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
6565 if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt))
6566 && !is_gimple_debug (use_stmt))
6568 if (gimple_code (use_stmt) == GIMPLE_PHI
6569 && gimple_phi_num_args (use_stmt) == 1)
6571 replace_uses_by (gimple_phi_result (use_stmt), new_tree);
6573 else
6575 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
6576 SET_USE (use_p, new_tree);
6578 update_stmt (use_stmt);
6581 return true;
6584 /* Kill any debug uses outside LOOP of SSA names defined in STMT. */
6586 static void
6587 vect_loop_kill_debug_uses (struct loop *loop, gimple *stmt)
6589 ssa_op_iter op_iter;
6590 imm_use_iterator imm_iter;
6591 def_operand_p def_p;
6592 gimple *ustmt;
6594 FOR_EACH_PHI_OR_STMT_DEF (def_p, stmt, op_iter, SSA_OP_DEF)
6596 FOR_EACH_IMM_USE_STMT (ustmt, imm_iter, DEF_FROM_PTR (def_p))
6598 basic_block bb;
6600 if (!is_gimple_debug (ustmt))
6601 continue;
6603 bb = gimple_bb (ustmt);
6605 if (!flow_bb_inside_loop_p (loop, bb))
6607 if (gimple_debug_bind_p (ustmt))
6609 if (dump_enabled_p ())
6610 dump_printf_loc (MSG_NOTE, vect_location,
6611 "killing debug use\n");
6613 gimple_debug_bind_reset_value (ustmt);
6614 update_stmt (ustmt);
6616 else
6617 gcc_unreachable ();
6623 /* Given loop represented by LOOP_VINFO, return true if computation of
6624 LOOP_VINFO_NITERS (= LOOP_VINFO_NITERSM1 + 1) doesn't overflow, false
6625 otherwise. */
6627 static bool
6628 loop_niters_no_overflow (loop_vec_info loop_vinfo)
6630 /* Constant case. */
6631 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6633 tree cst_niters = LOOP_VINFO_NITERS (loop_vinfo);
6634 tree cst_nitersm1 = LOOP_VINFO_NITERSM1 (loop_vinfo);
6636 gcc_assert (TREE_CODE (cst_niters) == INTEGER_CST);
6637 gcc_assert (TREE_CODE (cst_nitersm1) == INTEGER_CST);
6638 if (wi::to_widest (cst_nitersm1) < wi::to_widest (cst_niters))
6639 return true;
6642 widest_int max;
6643 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6644 /* Check the upper bound of loop niters. */
6645 if (get_max_loop_iterations (loop, &max))
6647 tree type = TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo));
6648 signop sgn = TYPE_SIGN (type);
6649 widest_int type_max = widest_int::from (wi::max_value (type), sgn);
6650 if (max < type_max)
6651 return true;
6653 return false;
6656 /* Function vect_transform_loop.
6658 The analysis phase has determined that the loop is vectorizable.
6659 Vectorize the loop - created vectorized stmts to replace the scalar
6660 stmts in the loop, and update the loop exit condition. */
6662 void
6663 vect_transform_loop (loop_vec_info loop_vinfo)
6665 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6666 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
6667 int nbbs = loop->num_nodes;
6668 int i;
6669 tree niters_vector = NULL;
6670 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
6671 bool grouped_store;
6672 bool slp_scheduled = false;
6673 gimple *stmt, *pattern_stmt;
6674 gimple_seq pattern_def_seq = NULL;
6675 gimple_stmt_iterator pattern_def_si = gsi_none ();
6676 bool transform_pattern_stmt = false;
6677 bool check_profitability = false;
6678 int th;
6679 /* Record number of iterations before we started tampering with the profile. */
6680 gcov_type expected_iterations = expected_loop_iterations_unbounded (loop);
6682 if (dump_enabled_p ())
6683 dump_printf_loc (MSG_NOTE, vect_location, "=== vec_transform_loop ===\n");
6685 /* If profile is inprecise, we have chance to fix it up. */
6686 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6687 expected_iterations = LOOP_VINFO_INT_NITERS (loop_vinfo);
6689 /* Use the more conservative vectorization threshold. If the number
6690 of iterations is constant assume the cost check has been performed
6691 by our caller. If the threshold makes all loops profitable that
6692 run at least the vectorization factor number of times checking
6693 is pointless, too. */
6694 th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
6695 if (th >= LOOP_VINFO_VECT_FACTOR (loop_vinfo) - 1
6696 && !LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6698 if (dump_enabled_p ())
6699 dump_printf_loc (MSG_NOTE, vect_location,
6700 "Profitability threshold is %d loop iterations.\n",
6701 th);
6702 check_profitability = true;
6705 /* Make sure there exists a single-predecessor exit bb. Do this before
6706 versioning. */
6707 edge e = single_exit (loop);
6708 if (! single_pred_p (e->dest))
6710 split_loop_exit_edge (e);
6711 if (dump_enabled_p ())
6712 dump_printf (MSG_NOTE, "split exit edge\n");
6715 /* Version the loop first, if required, so the profitability check
6716 comes first. */
6718 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
6720 vect_loop_versioning (loop_vinfo, th, check_profitability);
6721 check_profitability = false;
6724 /* Make sure there exists a single-predecessor exit bb also on the
6725 scalar loop copy. Do this after versioning but before peeling
6726 so CFG structure is fine for both scalar and if-converted loop
6727 to make slpeel_duplicate_current_defs_from_edges face matched
6728 loop closed PHI nodes on the exit. */
6729 if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))
6731 e = single_exit (LOOP_VINFO_SCALAR_LOOP (loop_vinfo));
6732 if (! single_pred_p (e->dest))
6734 split_loop_exit_edge (e);
6735 if (dump_enabled_p ())
6736 dump_printf (MSG_NOTE, "split exit edge of scalar loop\n");
6740 tree niters = vect_build_loop_niters (loop_vinfo);
6741 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = niters;
6742 tree nitersm1 = unshare_expr (LOOP_VINFO_NITERSM1 (loop_vinfo));
6743 bool niters_no_overflow = loop_niters_no_overflow (loop_vinfo);
6744 vect_do_peeling (loop_vinfo, niters, nitersm1, &niters_vector, th,
6745 check_profitability, niters_no_overflow);
6746 if (niters_vector == NULL_TREE)
6748 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6749 niters_vector
6750 = build_int_cst (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)),
6751 LOOP_VINFO_INT_NITERS (loop_vinfo) / vf);
6752 else
6753 vect_gen_vector_loop_niters (loop_vinfo, niters, &niters_vector,
6754 niters_no_overflow);
6757 /* 1) Make sure the loop header has exactly two entries
6758 2) Make sure we have a preheader basic block. */
6760 gcc_assert (EDGE_COUNT (loop->header->preds) == 2);
6762 split_edge (loop_preheader_edge (loop));
6764 /* FORNOW: the vectorizer supports only loops which body consist
6765 of one basic block (header + empty latch). When the vectorizer will
6766 support more involved loop forms, the order by which the BBs are
6767 traversed need to be reconsidered. */
6769 for (i = 0; i < nbbs; i++)
6771 basic_block bb = bbs[i];
6772 stmt_vec_info stmt_info;
6774 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6775 gsi_next (&si))
6777 gphi *phi = si.phi ();
6778 if (dump_enabled_p ())
6780 dump_printf_loc (MSG_NOTE, vect_location,
6781 "------>vectorizing phi: ");
6782 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
6784 stmt_info = vinfo_for_stmt (phi);
6785 if (!stmt_info)
6786 continue;
6788 if (MAY_HAVE_DEBUG_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
6789 vect_loop_kill_debug_uses (loop, phi);
6791 if (!STMT_VINFO_RELEVANT_P (stmt_info)
6792 && !STMT_VINFO_LIVE_P (stmt_info))
6793 continue;
6795 if (STMT_VINFO_VECTYPE (stmt_info)
6796 && (TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info))
6797 != (unsigned HOST_WIDE_INT) vf)
6798 && dump_enabled_p ())
6799 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
6801 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def)
6803 if (dump_enabled_p ())
6804 dump_printf_loc (MSG_NOTE, vect_location, "transform phi.\n");
6805 vect_transform_stmt (phi, NULL, NULL, NULL, NULL);
6809 pattern_stmt = NULL;
6810 for (gimple_stmt_iterator si = gsi_start_bb (bb);
6811 !gsi_end_p (si) || transform_pattern_stmt;)
6813 bool is_store;
6815 if (transform_pattern_stmt)
6816 stmt = pattern_stmt;
6817 else
6819 stmt = gsi_stmt (si);
6820 /* During vectorization remove existing clobber stmts. */
6821 if (gimple_clobber_p (stmt))
6823 unlink_stmt_vdef (stmt);
6824 gsi_remove (&si, true);
6825 release_defs (stmt);
6826 continue;
6830 if (dump_enabled_p ())
6832 dump_printf_loc (MSG_NOTE, vect_location,
6833 "------>vectorizing statement: ");
6834 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
6837 stmt_info = vinfo_for_stmt (stmt);
6839 /* vector stmts created in the outer-loop during vectorization of
6840 stmts in an inner-loop may not have a stmt_info, and do not
6841 need to be vectorized. */
6842 if (!stmt_info)
6844 gsi_next (&si);
6845 continue;
6848 if (MAY_HAVE_DEBUG_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
6849 vect_loop_kill_debug_uses (loop, stmt);
6851 if (!STMT_VINFO_RELEVANT_P (stmt_info)
6852 && !STMT_VINFO_LIVE_P (stmt_info))
6854 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
6855 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
6856 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
6857 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
6859 stmt = pattern_stmt;
6860 stmt_info = vinfo_for_stmt (stmt);
6862 else
6864 gsi_next (&si);
6865 continue;
6868 else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
6869 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
6870 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
6871 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
6872 transform_pattern_stmt = true;
6874 /* If pattern statement has def stmts, vectorize them too. */
6875 if (is_pattern_stmt_p (stmt_info))
6877 if (pattern_def_seq == NULL)
6879 pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
6880 pattern_def_si = gsi_start (pattern_def_seq);
6882 else if (!gsi_end_p (pattern_def_si))
6883 gsi_next (&pattern_def_si);
6884 if (pattern_def_seq != NULL)
6886 gimple *pattern_def_stmt = NULL;
6887 stmt_vec_info pattern_def_stmt_info = NULL;
6889 while (!gsi_end_p (pattern_def_si))
6891 pattern_def_stmt = gsi_stmt (pattern_def_si);
6892 pattern_def_stmt_info
6893 = vinfo_for_stmt (pattern_def_stmt);
6894 if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
6895 || STMT_VINFO_LIVE_P (pattern_def_stmt_info))
6896 break;
6897 gsi_next (&pattern_def_si);
6900 if (!gsi_end_p (pattern_def_si))
6902 if (dump_enabled_p ())
6904 dump_printf_loc (MSG_NOTE, vect_location,
6905 "==> vectorizing pattern def "
6906 "stmt: ");
6907 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
6908 pattern_def_stmt, 0);
6911 stmt = pattern_def_stmt;
6912 stmt_info = pattern_def_stmt_info;
6914 else
6916 pattern_def_si = gsi_none ();
6917 transform_pattern_stmt = false;
6920 else
6921 transform_pattern_stmt = false;
6924 if (STMT_VINFO_VECTYPE (stmt_info))
6926 unsigned int nunits
6927 = (unsigned int)
6928 TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info));
6929 if (!STMT_SLP_TYPE (stmt_info)
6930 && nunits != (unsigned int) vf
6931 && dump_enabled_p ())
6932 /* For SLP VF is set according to unrolling factor, and not
6933 to vector size, hence for SLP this print is not valid. */
6934 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
6937 /* SLP. Schedule all the SLP instances when the first SLP stmt is
6938 reached. */
6939 if (STMT_SLP_TYPE (stmt_info))
6941 if (!slp_scheduled)
6943 slp_scheduled = true;
6945 if (dump_enabled_p ())
6946 dump_printf_loc (MSG_NOTE, vect_location,
6947 "=== scheduling SLP instances ===\n");
6949 vect_schedule_slp (loop_vinfo);
6952 /* Hybrid SLP stmts must be vectorized in addition to SLP. */
6953 if (!vinfo_for_stmt (stmt) || PURE_SLP_STMT (stmt_info))
6955 if (!transform_pattern_stmt && gsi_end_p (pattern_def_si))
6957 pattern_def_seq = NULL;
6958 gsi_next (&si);
6960 continue;
6964 /* -------- vectorize statement ------------ */
6965 if (dump_enabled_p ())
6966 dump_printf_loc (MSG_NOTE, vect_location, "transform statement.\n");
6968 grouped_store = false;
6969 is_store = vect_transform_stmt (stmt, &si, &grouped_store, NULL, NULL);
6970 if (is_store)
6972 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
6974 /* Interleaving. If IS_STORE is TRUE, the vectorization of the
6975 interleaving chain was completed - free all the stores in
6976 the chain. */
6977 gsi_next (&si);
6978 vect_remove_stores (GROUP_FIRST_ELEMENT (stmt_info));
6980 else
6982 /* Free the attached stmt_vec_info and remove the stmt. */
6983 gimple *store = gsi_stmt (si);
6984 free_stmt_vec_info (store);
6985 unlink_stmt_vdef (store);
6986 gsi_remove (&si, true);
6987 release_defs (store);
6990 /* Stores can only appear at the end of pattern statements. */
6991 gcc_assert (!transform_pattern_stmt);
6992 pattern_def_seq = NULL;
6994 else if (!transform_pattern_stmt && gsi_end_p (pattern_def_si))
6996 pattern_def_seq = NULL;
6997 gsi_next (&si);
6999 } /* stmts in BB */
7000 } /* BBs in loop */
7002 slpeel_make_loop_iterate_ntimes (loop, niters_vector);
7004 /* Reduce loop iterations by the vectorization factor. */
7005 scale_loop_profile (loop, GCOV_COMPUTE_SCALE (1, vf),
7006 expected_iterations / vf);
7007 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
7009 if (loop->nb_iterations_upper_bound != 0)
7010 loop->nb_iterations_upper_bound = loop->nb_iterations_upper_bound - 1;
7011 if (loop->nb_iterations_likely_upper_bound != 0)
7012 loop->nb_iterations_likely_upper_bound
7013 = loop->nb_iterations_likely_upper_bound - 1;
7015 loop->nb_iterations_upper_bound
7016 = wi::udiv_floor (loop->nb_iterations_upper_bound + 1, vf) - 1;
7017 loop->nb_iterations_likely_upper_bound
7018 = wi::udiv_floor (loop->nb_iterations_likely_upper_bound + 1, vf) - 1;
7020 if (loop->any_estimate)
7022 loop->nb_iterations_estimate
7023 = wi::udiv_floor (loop->nb_iterations_estimate, vf);
7024 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
7025 && loop->nb_iterations_estimate != 0)
7026 loop->nb_iterations_estimate = loop->nb_iterations_estimate - 1;
7029 if (dump_enabled_p ())
7031 dump_printf_loc (MSG_NOTE, vect_location,
7032 "LOOP VECTORIZED\n");
7033 if (loop->inner)
7034 dump_printf_loc (MSG_NOTE, vect_location,
7035 "OUTER LOOP VECTORIZED\n");
7036 dump_printf (MSG_NOTE, "\n");
7039 /* Free SLP instances here because otherwise stmt reference counting
7040 won't work. */
7041 slp_instance instance;
7042 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
7043 vect_free_slp_instance (instance);
7044 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
7045 /* Clear-up safelen field since its value is invalid after vectorization
7046 since vectorized loop can have loop-carried dependencies. */
7047 loop->safelen = 0;
7050 /* The code below is trying to perform simple optimization - revert
7051 if-conversion for masked stores, i.e. if the mask of a store is zero
7052 do not perform it and all stored value producers also if possible.
7053 For example,
7054 for (i=0; i<n; i++)
7055 if (c[i])
7057 p1[i] += 1;
7058 p2[i] = p3[i] +2;
7060 this transformation will produce the following semi-hammock:
7062 if (!mask__ifc__42.18_165 == { 0, 0, 0, 0, 0, 0, 0, 0 })
7064 vect__11.19_170 = MASK_LOAD (vectp_p1.20_168, 0B, mask__ifc__42.18_165);
7065 vect__12.22_172 = vect__11.19_170 + vect_cst__171;
7066 MASK_STORE (vectp_p1.23_175, 0B, mask__ifc__42.18_165, vect__12.22_172);
7067 vect__18.25_182 = MASK_LOAD (vectp_p3.26_180, 0B, mask__ifc__42.18_165);
7068 vect__19.28_184 = vect__18.25_182 + vect_cst__183;
7069 MASK_STORE (vectp_p2.29_187, 0B, mask__ifc__42.18_165, vect__19.28_184);
7073 void
7074 optimize_mask_stores (struct loop *loop)
7076 basic_block *bbs = get_loop_body (loop);
7077 unsigned nbbs = loop->num_nodes;
7078 unsigned i;
7079 basic_block bb;
7080 gimple_stmt_iterator gsi;
7081 gimple *stmt;
7082 auto_vec<gimple *> worklist;
7084 vect_location = find_loop_location (loop);
7085 /* Pick up all masked stores in loop if any. */
7086 for (i = 0; i < nbbs; i++)
7088 bb = bbs[i];
7089 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
7090 gsi_next (&gsi))
7092 stmt = gsi_stmt (gsi);
7093 if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
7094 worklist.safe_push (stmt);
7098 free (bbs);
7099 if (worklist.is_empty ())
7100 return;
7102 /* Loop has masked stores. */
7103 while (!worklist.is_empty ())
7105 gimple *last, *last_store;
7106 edge e, efalse;
7107 tree mask;
7108 basic_block store_bb, join_bb;
7109 gimple_stmt_iterator gsi_to;
7110 tree vdef, new_vdef;
7111 gphi *phi;
7112 tree vectype;
7113 tree zero;
7115 last = worklist.pop ();
7116 mask = gimple_call_arg (last, 2);
7117 bb = gimple_bb (last);
7118 /* Create new bb. */
7119 e = split_block (bb, last);
7120 join_bb = e->dest;
7121 store_bb = create_empty_bb (bb);
7122 add_bb_to_loop (store_bb, loop);
7123 e->flags = EDGE_TRUE_VALUE;
7124 efalse = make_edge (bb, store_bb, EDGE_FALSE_VALUE);
7125 /* Put STORE_BB to likely part. */
7126 efalse->probability = PROB_UNLIKELY;
7127 store_bb->frequency = PROB_ALWAYS - EDGE_FREQUENCY (efalse);
7128 make_edge (store_bb, join_bb, EDGE_FALLTHRU);
7129 if (dom_info_available_p (CDI_DOMINATORS))
7130 set_immediate_dominator (CDI_DOMINATORS, store_bb, bb);
7131 if (dump_enabled_p ())
7132 dump_printf_loc (MSG_NOTE, vect_location,
7133 "Create new block %d to sink mask stores.",
7134 store_bb->index);
7135 /* Create vector comparison with boolean result. */
7136 vectype = TREE_TYPE (mask);
7137 zero = build_zero_cst (vectype);
7138 stmt = gimple_build_cond (EQ_EXPR, mask, zero, NULL_TREE, NULL_TREE);
7139 gsi = gsi_last_bb (bb);
7140 gsi_insert_after (&gsi, stmt, GSI_SAME_STMT);
7141 /* Create new PHI node for vdef of the last masked store:
7142 .MEM_2 = VDEF <.MEM_1>
7143 will be converted to
7144 .MEM.3 = VDEF <.MEM_1>
7145 and new PHI node will be created in join bb
7146 .MEM_2 = PHI <.MEM_1, .MEM_3>
7148 vdef = gimple_vdef (last);
7149 new_vdef = make_ssa_name (gimple_vop (cfun), last);
7150 gimple_set_vdef (last, new_vdef);
7151 phi = create_phi_node (vdef, join_bb);
7152 add_phi_arg (phi, new_vdef, EDGE_SUCC (store_bb, 0), UNKNOWN_LOCATION);
7154 /* Put all masked stores with the same mask to STORE_BB if possible. */
7155 while (true)
7157 gimple_stmt_iterator gsi_from;
7158 gimple *stmt1 = NULL;
7160 /* Move masked store to STORE_BB. */
7161 last_store = last;
7162 gsi = gsi_for_stmt (last);
7163 gsi_from = gsi;
7164 /* Shift GSI to the previous stmt for further traversal. */
7165 gsi_prev (&gsi);
7166 gsi_to = gsi_start_bb (store_bb);
7167 gsi_move_before (&gsi_from, &gsi_to);
7168 /* Setup GSI_TO to the non-empty block start. */
7169 gsi_to = gsi_start_bb (store_bb);
7170 if (dump_enabled_p ())
7172 dump_printf_loc (MSG_NOTE, vect_location,
7173 "Move stmt to created bb\n");
7174 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, last, 0);
7176 /* Move all stored value producers if possible. */
7177 while (!gsi_end_p (gsi))
7179 tree lhs;
7180 imm_use_iterator imm_iter;
7181 use_operand_p use_p;
7182 bool res;
7184 /* Skip debug statements. */
7185 if (is_gimple_debug (gsi_stmt (gsi)))
7187 gsi_prev (&gsi);
7188 continue;
7190 stmt1 = gsi_stmt (gsi);
7191 /* Do not consider statements writing to memory or having
7192 volatile operand. */
7193 if (gimple_vdef (stmt1)
7194 || gimple_has_volatile_ops (stmt1))
7195 break;
7196 gsi_from = gsi;
7197 gsi_prev (&gsi);
7198 lhs = gimple_get_lhs (stmt1);
7199 if (!lhs)
7200 break;
7202 /* LHS of vectorized stmt must be SSA_NAME. */
7203 if (TREE_CODE (lhs) != SSA_NAME)
7204 break;
7206 if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
7208 /* Remove dead scalar statement. */
7209 if (has_zero_uses (lhs))
7211 gsi_remove (&gsi_from, true);
7212 continue;
7216 /* Check that LHS does not have uses outside of STORE_BB. */
7217 res = true;
7218 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
7220 gimple *use_stmt;
7221 use_stmt = USE_STMT (use_p);
7222 if (is_gimple_debug (use_stmt))
7223 continue;
7224 if (gimple_bb (use_stmt) != store_bb)
7226 res = false;
7227 break;
7230 if (!res)
7231 break;
7233 if (gimple_vuse (stmt1)
7234 && gimple_vuse (stmt1) != gimple_vuse (last_store))
7235 break;
7237 /* Can move STMT1 to STORE_BB. */
7238 if (dump_enabled_p ())
7240 dump_printf_loc (MSG_NOTE, vect_location,
7241 "Move stmt to created bb\n");
7242 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt1, 0);
7244 gsi_move_before (&gsi_from, &gsi_to);
7245 /* Shift GSI_TO for further insertion. */
7246 gsi_prev (&gsi_to);
7248 /* Put other masked stores with the same mask to STORE_BB. */
7249 if (worklist.is_empty ()
7250 || gimple_call_arg (worklist.last (), 2) != mask
7251 || worklist.last () != stmt1)
7252 break;
7253 last = worklist.pop ();
7255 add_phi_arg (phi, gimple_vuse (last_store), e, UNKNOWN_LOCATION);