* lto-partition.c (add_symbol_to_partition_1,
[official-gcc.git] / gcc / tree-vect-loop.c
blob838803ebe520ef883ef28f422548020bd1339353
1 /* Loop Vectorization
2 Copyright (C) 2003-2014 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 "dumpfile.h"
26 #include "tm.h"
27 #include "tree.h"
28 #include "stor-layout.h"
29 #include "basic-block.h"
30 #include "gimple-pretty-print.h"
31 #include "tree-ssa-alias.h"
32 #include "internal-fn.h"
33 #include "gimple-expr.h"
34 #include "is-a.h"
35 #include "gimple.h"
36 #include "gimplify.h"
37 #include "gimple-iterator.h"
38 #include "gimplify-me.h"
39 #include "gimple-ssa.h"
40 #include "tree-phinodes.h"
41 #include "ssa-iterators.h"
42 #include "stringpool.h"
43 #include "tree-ssanames.h"
44 #include "tree-ssa-loop-ivopts.h"
45 #include "tree-ssa-loop-manip.h"
46 #include "tree-ssa-loop-niter.h"
47 #include "tree-pass.h"
48 #include "cfgloop.h"
49 #include "expr.h"
50 #include "recog.h"
51 #include "optabs.h"
52 #include "params.h"
53 #include "diagnostic-core.h"
54 #include "tree-chrec.h"
55 #include "tree-scalar-evolution.h"
56 #include "tree-vectorizer.h"
57 #include "target.h"
59 /* Loop Vectorization Pass.
61 This pass tries to vectorize loops.
63 For example, the vectorizer transforms the following simple loop:
65 short a[N]; short b[N]; short c[N]; int i;
67 for (i=0; i<N; i++){
68 a[i] = b[i] + c[i];
71 as if it was manually vectorized by rewriting the source code into:
73 typedef int __attribute__((mode(V8HI))) v8hi;
74 short a[N]; short b[N]; short c[N]; int i;
75 v8hi *pa = (v8hi*)a, *pb = (v8hi*)b, *pc = (v8hi*)c;
76 v8hi va, vb, vc;
78 for (i=0; i<N/8; i++){
79 vb = pb[i];
80 vc = pc[i];
81 va = vb + vc;
82 pa[i] = va;
85 The main entry to this pass is vectorize_loops(), in which
86 the vectorizer applies a set of analyses on a given set of loops,
87 followed by the actual vectorization transformation for the loops that
88 had successfully passed the analysis phase.
89 Throughout this pass we make a distinction between two types of
90 data: scalars (which are represented by SSA_NAMES), and memory references
91 ("data-refs"). These two types of data require different handling both
92 during analysis and transformation. The types of data-refs that the
93 vectorizer currently supports are ARRAY_REFS which base is an array DECL
94 (not a pointer), and INDIRECT_REFS through pointers; both array and pointer
95 accesses are required to have a simple (consecutive) access pattern.
97 Analysis phase:
98 ===============
99 The driver for the analysis phase is vect_analyze_loop().
100 It applies a set of analyses, some of which rely on the scalar evolution
101 analyzer (scev) developed by Sebastian Pop.
103 During the analysis phase the vectorizer records some information
104 per stmt in a "stmt_vec_info" struct which is attached to each stmt in the
105 loop, as well as general information about the loop as a whole, which is
106 recorded in a "loop_vec_info" struct attached to each loop.
108 Transformation phase:
109 =====================
110 The loop transformation phase scans all the stmts in the loop, and
111 creates a vector stmt (or a sequence of stmts) for each scalar stmt S in
112 the loop that needs to be vectorized. It inserts the vector code sequence
113 just before the scalar stmt S, and records a pointer to the vector code
114 in STMT_VINFO_VEC_STMT (stmt_info) (stmt_info is the stmt_vec_info struct
115 attached to S). This pointer will be used for the vectorization of following
116 stmts which use the def of stmt S. Stmt S is removed if it writes to memory;
117 otherwise, we rely on dead code elimination for removing it.
119 For example, say stmt S1 was vectorized into stmt VS1:
121 VS1: vb = px[i];
122 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
123 S2: a = b;
125 To vectorize stmt S2, the vectorizer first finds the stmt that defines
126 the operand 'b' (S1), and gets the relevant vector def 'vb' from the
127 vector stmt VS1 pointed to by STMT_VINFO_VEC_STMT (stmt_info (S1)). The
128 resulting sequence would be:
130 VS1: vb = px[i];
131 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
132 VS2: va = vb;
133 S2: a = b; STMT_VINFO_VEC_STMT (stmt_info (S2)) = VS2
135 Operands that are not SSA_NAMEs, are data-refs that appear in
136 load/store operations (like 'x[i]' in S1), and are handled differently.
138 Target modeling:
139 =================
140 Currently the only target specific information that is used is the
141 size of the vector (in bytes) - "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD".
142 Targets that can support different sizes of vectors, for now will need
143 to specify one value for "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD". More
144 flexibility will be added in the future.
146 Since we only vectorize operations which vector form can be
147 expressed using existing tree codes, to verify that an operation is
148 supported, the vectorizer checks the relevant optab at the relevant
149 machine_mode (e.g, optab_handler (add_optab, V8HImode)). If
150 the value found is CODE_FOR_nothing, then there's no target support, and
151 we can't vectorize the stmt.
153 For additional information on this project see:
154 http://gcc.gnu.org/projects/tree-ssa/vectorization.html
157 static void vect_estimate_min_profitable_iters (loop_vec_info, int *, int *);
159 /* Function vect_determine_vectorization_factor
161 Determine the vectorization factor (VF). VF is the number of data elements
162 that are operated upon in parallel in a single iteration of the vectorized
163 loop. For example, when vectorizing a loop that operates on 4byte elements,
164 on a target with vector size (VS) 16byte, the VF is set to 4, since 4
165 elements can fit in a single vector register.
167 We currently support vectorization of loops in which all types operated upon
168 are of the same size. Therefore this function currently sets VF according to
169 the size of the types operated upon, and fails if there are multiple sizes
170 in the loop.
172 VF is also the factor by which the loop iterations are strip-mined, e.g.:
173 original loop:
174 for (i=0; i<N; i++){
175 a[i] = b[i] + c[i];
178 vectorized loop:
179 for (i=0; i<N; i+=VF){
180 a[i:VF] = b[i:VF] + c[i:VF];
184 static bool
185 vect_determine_vectorization_factor (loop_vec_info loop_vinfo)
187 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
188 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
189 int nbbs = loop->num_nodes;
190 gimple_stmt_iterator si;
191 unsigned int vectorization_factor = 0;
192 tree scalar_type;
193 gimple phi;
194 tree vectype;
195 unsigned int nunits;
196 stmt_vec_info stmt_info;
197 int i;
198 HOST_WIDE_INT dummy;
199 gimple stmt, pattern_stmt = NULL;
200 gimple_seq pattern_def_seq = NULL;
201 gimple_stmt_iterator pattern_def_si = gsi_none ();
202 bool analyze_pattern_stmt = false;
204 if (dump_enabled_p ())
205 dump_printf_loc (MSG_NOTE, vect_location,
206 "=== vect_determine_vectorization_factor ===\n");
208 for (i = 0; i < nbbs; i++)
210 basic_block bb = bbs[i];
212 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
214 phi = gsi_stmt (si);
215 stmt_info = vinfo_for_stmt (phi);
216 if (dump_enabled_p ())
218 dump_printf_loc (MSG_NOTE, vect_location, "==> examining phi: ");
219 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
220 dump_printf (MSG_NOTE, "\n");
223 gcc_assert (stmt_info);
225 if (STMT_VINFO_RELEVANT_P (stmt_info))
227 gcc_assert (!STMT_VINFO_VECTYPE (stmt_info));
228 scalar_type = TREE_TYPE (PHI_RESULT (phi));
230 if (dump_enabled_p ())
232 dump_printf_loc (MSG_NOTE, vect_location,
233 "get vectype for scalar type: ");
234 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
235 dump_printf (MSG_NOTE, "\n");
238 vectype = get_vectype_for_scalar_type (scalar_type);
239 if (!vectype)
241 if (dump_enabled_p ())
243 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
244 "not vectorized: unsupported "
245 "data-type ");
246 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
247 scalar_type);
248 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
250 return false;
252 STMT_VINFO_VECTYPE (stmt_info) = vectype;
254 if (dump_enabled_p ())
256 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
257 dump_generic_expr (MSG_NOTE, TDF_SLIM, vectype);
258 dump_printf (MSG_NOTE, "\n");
261 nunits = TYPE_VECTOR_SUBPARTS (vectype);
262 if (dump_enabled_p ())
263 dump_printf_loc (MSG_NOTE, vect_location, "nunits = %d\n",
264 nunits);
266 if (!vectorization_factor
267 || (nunits > vectorization_factor))
268 vectorization_factor = nunits;
272 for (si = gsi_start_bb (bb); !gsi_end_p (si) || analyze_pattern_stmt;)
274 tree vf_vectype;
276 if (analyze_pattern_stmt)
277 stmt = pattern_stmt;
278 else
279 stmt = gsi_stmt (si);
281 stmt_info = vinfo_for_stmt (stmt);
283 if (dump_enabled_p ())
285 dump_printf_loc (MSG_NOTE, vect_location,
286 "==> examining statement: ");
287 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
288 dump_printf (MSG_NOTE, "\n");
291 gcc_assert (stmt_info);
293 /* Skip stmts which do not need to be vectorized. */
294 if ((!STMT_VINFO_RELEVANT_P (stmt_info)
295 && !STMT_VINFO_LIVE_P (stmt_info))
296 || gimple_clobber_p (stmt))
298 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
299 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
300 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
301 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
303 stmt = pattern_stmt;
304 stmt_info = vinfo_for_stmt (pattern_stmt);
305 if (dump_enabled_p ())
307 dump_printf_loc (MSG_NOTE, vect_location,
308 "==> examining pattern statement: ");
309 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
310 dump_printf (MSG_NOTE, "\n");
313 else
315 if (dump_enabled_p ())
316 dump_printf_loc (MSG_NOTE, vect_location, "skip.\n");
317 gsi_next (&si);
318 continue;
321 else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
322 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
323 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
324 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
325 analyze_pattern_stmt = true;
327 /* If a pattern statement has def stmts, analyze them too. */
328 if (is_pattern_stmt_p (stmt_info))
330 if (pattern_def_seq == NULL)
332 pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
333 pattern_def_si = gsi_start (pattern_def_seq);
335 else if (!gsi_end_p (pattern_def_si))
336 gsi_next (&pattern_def_si);
337 if (pattern_def_seq != NULL)
339 gimple pattern_def_stmt = NULL;
340 stmt_vec_info pattern_def_stmt_info = NULL;
342 while (!gsi_end_p (pattern_def_si))
344 pattern_def_stmt = gsi_stmt (pattern_def_si);
345 pattern_def_stmt_info
346 = vinfo_for_stmt (pattern_def_stmt);
347 if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
348 || STMT_VINFO_LIVE_P (pattern_def_stmt_info))
349 break;
350 gsi_next (&pattern_def_si);
353 if (!gsi_end_p (pattern_def_si))
355 if (dump_enabled_p ())
357 dump_printf_loc (MSG_NOTE, vect_location,
358 "==> examining pattern def stmt: ");
359 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
360 pattern_def_stmt, 0);
361 dump_printf (MSG_NOTE, "\n");
364 stmt = pattern_def_stmt;
365 stmt_info = pattern_def_stmt_info;
367 else
369 pattern_def_si = gsi_none ();
370 analyze_pattern_stmt = false;
373 else
374 analyze_pattern_stmt = false;
377 if (gimple_get_lhs (stmt) == NULL_TREE
378 /* MASK_STORE has no lhs, but is ok. */
379 && (!is_gimple_call (stmt)
380 || !gimple_call_internal_p (stmt)
381 || gimple_call_internal_fn (stmt) != IFN_MASK_STORE))
383 if (is_gimple_call (stmt))
385 /* Ignore calls with no lhs. These must be calls to
386 #pragma omp simd functions, and what vectorization factor
387 it really needs can't be determined until
388 vectorizable_simd_clone_call. */
389 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
391 pattern_def_seq = NULL;
392 gsi_next (&si);
394 continue;
396 if (dump_enabled_p ())
398 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
399 "not vectorized: irregular stmt.");
400 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
402 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
404 return false;
407 if (VECTOR_MODE_P (TYPE_MODE (gimple_expr_type (stmt))))
409 if (dump_enabled_p ())
411 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
412 "not vectorized: vector stmt in loop:");
413 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
414 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
416 return false;
419 if (STMT_VINFO_VECTYPE (stmt_info))
421 /* The only case when a vectype had been already set is for stmts
422 that contain a dataref, or for "pattern-stmts" (stmts
423 generated by the vectorizer to represent/replace a certain
424 idiom). */
425 gcc_assert (STMT_VINFO_DATA_REF (stmt_info)
426 || is_pattern_stmt_p (stmt_info)
427 || !gsi_end_p (pattern_def_si));
428 vectype = STMT_VINFO_VECTYPE (stmt_info);
430 else
432 gcc_assert (!STMT_VINFO_DATA_REF (stmt_info));
433 if (is_gimple_call (stmt)
434 && gimple_call_internal_p (stmt)
435 && gimple_call_internal_fn (stmt) == IFN_MASK_STORE)
436 scalar_type = TREE_TYPE (gimple_call_arg (stmt, 3));
437 else
438 scalar_type = TREE_TYPE (gimple_get_lhs (stmt));
439 if (dump_enabled_p ())
441 dump_printf_loc (MSG_NOTE, vect_location,
442 "get vectype for scalar type: ");
443 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
444 dump_printf (MSG_NOTE, "\n");
446 vectype = get_vectype_for_scalar_type (scalar_type);
447 if (!vectype)
449 if (dump_enabled_p ())
451 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
452 "not vectorized: unsupported "
453 "data-type ");
454 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
455 scalar_type);
456 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
458 return false;
461 STMT_VINFO_VECTYPE (stmt_info) = vectype;
463 if (dump_enabled_p ())
465 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
466 dump_generic_expr (MSG_NOTE, TDF_SLIM, vectype);
467 dump_printf (MSG_NOTE, "\n");
471 /* The vectorization factor is according to the smallest
472 scalar type (or the largest vector size, but we only
473 support one vector size per loop). */
474 scalar_type = vect_get_smallest_scalar_type (stmt, &dummy,
475 &dummy);
476 if (dump_enabled_p ())
478 dump_printf_loc (MSG_NOTE, vect_location,
479 "get vectype for scalar type: ");
480 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
481 dump_printf (MSG_NOTE, "\n");
483 vf_vectype = get_vectype_for_scalar_type (scalar_type);
484 if (!vf_vectype)
486 if (dump_enabled_p ())
488 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
489 "not vectorized: unsupported data-type ");
490 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
491 scalar_type);
492 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
494 return false;
497 if ((GET_MODE_SIZE (TYPE_MODE (vectype))
498 != GET_MODE_SIZE (TYPE_MODE (vf_vectype))))
500 if (dump_enabled_p ())
502 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
503 "not vectorized: different sized vector "
504 "types in statement, ");
505 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
506 vectype);
507 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
508 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
509 vf_vectype);
510 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
512 return false;
515 if (dump_enabled_p ())
517 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
518 dump_generic_expr (MSG_NOTE, TDF_SLIM, vf_vectype);
519 dump_printf (MSG_NOTE, "\n");
522 nunits = TYPE_VECTOR_SUBPARTS (vf_vectype);
523 if (dump_enabled_p ())
524 dump_printf_loc (MSG_NOTE, vect_location, "nunits = %d\n", nunits);
525 if (!vectorization_factor
526 || (nunits > vectorization_factor))
527 vectorization_factor = nunits;
529 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
531 pattern_def_seq = NULL;
532 gsi_next (&si);
537 /* TODO: Analyze cost. Decide if worth while to vectorize. */
538 if (dump_enabled_p ())
539 dump_printf_loc (MSG_NOTE, vect_location, "vectorization factor = %d\n",
540 vectorization_factor);
541 if (vectorization_factor <= 1)
543 if (dump_enabled_p ())
544 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
545 "not vectorized: unsupported data-type\n");
546 return false;
548 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
550 return true;
554 /* Function vect_is_simple_iv_evolution.
556 FORNOW: A simple evolution of an induction variables in the loop is
557 considered a polynomial evolution. */
559 static bool
560 vect_is_simple_iv_evolution (unsigned loop_nb, tree access_fn, tree * init,
561 tree * step)
563 tree init_expr;
564 tree step_expr;
565 tree evolution_part = evolution_part_in_loop_num (access_fn, loop_nb);
566 basic_block bb;
568 /* When there is no evolution in this loop, the evolution function
569 is not "simple". */
570 if (evolution_part == NULL_TREE)
571 return false;
573 /* When the evolution is a polynomial of degree >= 2
574 the evolution function is not "simple". */
575 if (tree_is_chrec (evolution_part))
576 return false;
578 step_expr = evolution_part;
579 init_expr = unshare_expr (initial_condition_in_loop_num (access_fn, loop_nb));
581 if (dump_enabled_p ())
583 dump_printf_loc (MSG_NOTE, vect_location, "step: ");
584 dump_generic_expr (MSG_NOTE, TDF_SLIM, step_expr);
585 dump_printf (MSG_NOTE, ", init: ");
586 dump_generic_expr (MSG_NOTE, TDF_SLIM, init_expr);
587 dump_printf (MSG_NOTE, "\n");
590 *init = init_expr;
591 *step = step_expr;
593 if (TREE_CODE (step_expr) != INTEGER_CST
594 && (TREE_CODE (step_expr) != SSA_NAME
595 || ((bb = gimple_bb (SSA_NAME_DEF_STMT (step_expr)))
596 && flow_bb_inside_loop_p (get_loop (cfun, loop_nb), bb))
597 || (!INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
598 && (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr))
599 || !flag_associative_math)))
600 && (TREE_CODE (step_expr) != REAL_CST
601 || !flag_associative_math))
603 if (dump_enabled_p ())
604 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
605 "step unknown.\n");
606 return false;
609 return true;
612 /* Function vect_analyze_scalar_cycles_1.
614 Examine the cross iteration def-use cycles of scalar variables
615 in LOOP. LOOP_VINFO represents the loop that is now being
616 considered for vectorization (can be LOOP, or an outer-loop
617 enclosing LOOP). */
619 static void
620 vect_analyze_scalar_cycles_1 (loop_vec_info loop_vinfo, struct loop *loop)
622 basic_block bb = loop->header;
623 tree init, step;
624 auto_vec<gimple, 64> worklist;
625 gimple_stmt_iterator gsi;
626 bool double_reduc;
628 if (dump_enabled_p ())
629 dump_printf_loc (MSG_NOTE, vect_location,
630 "=== vect_analyze_scalar_cycles ===\n");
632 /* First - identify all inductions. Reduction detection assumes that all the
633 inductions have been identified, therefore, this order must not be
634 changed. */
635 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
637 gimple phi = gsi_stmt (gsi);
638 tree access_fn = NULL;
639 tree def = PHI_RESULT (phi);
640 stmt_vec_info stmt_vinfo = vinfo_for_stmt (phi);
642 if (dump_enabled_p ())
644 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: ");
645 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
646 dump_printf (MSG_NOTE, "\n");
649 /* Skip virtual phi's. The data dependences that are associated with
650 virtual defs/uses (i.e., memory accesses) are analyzed elsewhere. */
651 if (virtual_operand_p (def))
652 continue;
654 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_unknown_def_type;
656 /* Analyze the evolution function. */
657 access_fn = analyze_scalar_evolution (loop, def);
658 if (access_fn)
660 STRIP_NOPS (access_fn);
661 if (dump_enabled_p ())
663 dump_printf_loc (MSG_NOTE, vect_location,
664 "Access function of PHI: ");
665 dump_generic_expr (MSG_NOTE, TDF_SLIM, access_fn);
666 dump_printf (MSG_NOTE, "\n");
668 STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo)
669 = evolution_part_in_loop_num (access_fn, loop->num);
672 if (!access_fn
673 || !vect_is_simple_iv_evolution (loop->num, access_fn, &init, &step)
674 || (LOOP_VINFO_LOOP (loop_vinfo) != loop
675 && TREE_CODE (step) != INTEGER_CST))
677 worklist.safe_push (phi);
678 continue;
681 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo) != NULL_TREE);
683 if (dump_enabled_p ())
684 dump_printf_loc (MSG_NOTE, vect_location, "Detected induction.\n");
685 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_induction_def;
689 /* Second - identify all reductions and nested cycles. */
690 while (worklist.length () > 0)
692 gimple phi = worklist.pop ();
693 tree def = PHI_RESULT (phi);
694 stmt_vec_info stmt_vinfo = vinfo_for_stmt (phi);
695 gimple reduc_stmt;
696 bool nested_cycle;
698 if (dump_enabled_p ())
700 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: ");
701 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
702 dump_printf (MSG_NOTE, "\n");
705 gcc_assert (!virtual_operand_p (def)
706 && STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_unknown_def_type);
708 nested_cycle = (loop != LOOP_VINFO_LOOP (loop_vinfo));
709 reduc_stmt = vect_force_simple_reduction (loop_vinfo, phi, !nested_cycle,
710 &double_reduc);
711 if (reduc_stmt)
713 if (double_reduc)
715 if (dump_enabled_p ())
716 dump_printf_loc (MSG_NOTE, vect_location,
717 "Detected double reduction.\n");
719 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_double_reduction_def;
720 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
721 vect_double_reduction_def;
723 else
725 if (nested_cycle)
727 if (dump_enabled_p ())
728 dump_printf_loc (MSG_NOTE, vect_location,
729 "Detected vectorizable nested cycle.\n");
731 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_nested_cycle;
732 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
733 vect_nested_cycle;
735 else
737 if (dump_enabled_p ())
738 dump_printf_loc (MSG_NOTE, vect_location,
739 "Detected reduction.\n");
741 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_reduction_def;
742 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
743 vect_reduction_def;
744 /* Store the reduction cycles for possible vectorization in
745 loop-aware SLP. */
746 LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push (reduc_stmt);
750 else
751 if (dump_enabled_p ())
752 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
753 "Unknown def-use cycle pattern.\n");
758 /* Function vect_analyze_scalar_cycles.
760 Examine the cross iteration def-use cycles of scalar variables, by
761 analyzing the loop-header PHIs of scalar variables. Classify each
762 cycle as one of the following: invariant, induction, reduction, unknown.
763 We do that for the loop represented by LOOP_VINFO, and also to its
764 inner-loop, if exists.
765 Examples for scalar cycles:
767 Example1: reduction:
769 loop1:
770 for (i=0; i<N; i++)
771 sum += a[i];
773 Example2: induction:
775 loop2:
776 for (i=0; i<N; i++)
777 a[i] = i; */
779 static void
780 vect_analyze_scalar_cycles (loop_vec_info loop_vinfo)
782 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
784 vect_analyze_scalar_cycles_1 (loop_vinfo, loop);
786 /* When vectorizing an outer-loop, the inner-loop is executed sequentially.
787 Reductions in such inner-loop therefore have different properties than
788 the reductions in the nest that gets vectorized:
789 1. When vectorized, they are executed in the same order as in the original
790 scalar loop, so we can't change the order of computation when
791 vectorizing them.
792 2. FIXME: Inner-loop reductions can be used in the inner-loop, so the
793 current checks are too strict. */
795 if (loop->inner)
796 vect_analyze_scalar_cycles_1 (loop_vinfo, loop->inner);
800 /* Function vect_get_loop_niters.
802 Determine how many iterations the loop is executed and place it
803 in NUMBER_OF_ITERATIONS. Place the number of latch iterations
804 in NUMBER_OF_ITERATIONSM1.
806 Return the loop exit condition. */
808 static gimple
809 vect_get_loop_niters (struct loop *loop, tree *number_of_iterations,
810 tree *number_of_iterationsm1)
812 tree niters;
814 if (dump_enabled_p ())
815 dump_printf_loc (MSG_NOTE, vect_location,
816 "=== get_loop_niters ===\n");
818 niters = number_of_latch_executions (loop);
819 *number_of_iterationsm1 = niters;
821 /* We want the number of loop header executions which is the number
822 of latch executions plus one.
823 ??? For UINT_MAX latch executions this number overflows to zero
824 for loops like do { n++; } while (n != 0); */
825 if (niters && !chrec_contains_undetermined (niters))
826 niters = fold_build2 (PLUS_EXPR, TREE_TYPE (niters), unshare_expr (niters),
827 build_int_cst (TREE_TYPE (niters), 1));
828 *number_of_iterations = niters;
830 return get_loop_exit_condition (loop);
834 /* Function bb_in_loop_p
836 Used as predicate for dfs order traversal of the loop bbs. */
838 static bool
839 bb_in_loop_p (const_basic_block bb, const void *data)
841 const struct loop *const loop = (const struct loop *)data;
842 if (flow_bb_inside_loop_p (loop, bb))
843 return true;
844 return false;
848 /* Function new_loop_vec_info.
850 Create and initialize a new loop_vec_info struct for LOOP, as well as
851 stmt_vec_info structs for all the stmts in LOOP. */
853 static loop_vec_info
854 new_loop_vec_info (struct loop *loop)
856 loop_vec_info res;
857 basic_block *bbs;
858 gimple_stmt_iterator si;
859 unsigned int i, nbbs;
861 res = (loop_vec_info) xcalloc (1, sizeof (struct _loop_vec_info));
862 LOOP_VINFO_LOOP (res) = loop;
864 bbs = get_loop_body (loop);
866 /* Create/Update stmt_info for all stmts in the loop. */
867 for (i = 0; i < loop->num_nodes; i++)
869 basic_block bb = bbs[i];
871 /* BBs in a nested inner-loop will have been already processed (because
872 we will have called vect_analyze_loop_form for any nested inner-loop).
873 Therefore, for stmts in an inner-loop we just want to update the
874 STMT_VINFO_LOOP_VINFO field of their stmt_info to point to the new
875 loop_info of the outer-loop we are currently considering to vectorize
876 (instead of the loop_info of the inner-loop).
877 For stmts in other BBs we need to create a stmt_info from scratch. */
878 if (bb->loop_father != loop)
880 /* Inner-loop bb. */
881 gcc_assert (loop->inner && bb->loop_father == loop->inner);
882 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
884 gimple phi = gsi_stmt (si);
885 stmt_vec_info stmt_info = vinfo_for_stmt (phi);
886 loop_vec_info inner_loop_vinfo =
887 STMT_VINFO_LOOP_VINFO (stmt_info);
888 gcc_assert (loop->inner == LOOP_VINFO_LOOP (inner_loop_vinfo));
889 STMT_VINFO_LOOP_VINFO (stmt_info) = res;
891 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
893 gimple stmt = gsi_stmt (si);
894 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
895 loop_vec_info inner_loop_vinfo =
896 STMT_VINFO_LOOP_VINFO (stmt_info);
897 gcc_assert (loop->inner == LOOP_VINFO_LOOP (inner_loop_vinfo));
898 STMT_VINFO_LOOP_VINFO (stmt_info) = res;
901 else
903 /* bb in current nest. */
904 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
906 gimple phi = gsi_stmt (si);
907 gimple_set_uid (phi, 0);
908 set_vinfo_for_stmt (phi, new_stmt_vec_info (phi, res, NULL));
911 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
913 gimple stmt = gsi_stmt (si);
914 gimple_set_uid (stmt, 0);
915 set_vinfo_for_stmt (stmt, new_stmt_vec_info (stmt, res, NULL));
920 /* CHECKME: We want to visit all BBs before their successors (except for
921 latch blocks, for which this assertion wouldn't hold). In the simple
922 case of the loop forms we allow, a dfs order of the BBs would the same
923 as reversed postorder traversal, so we are safe. */
925 free (bbs);
926 bbs = XCNEWVEC (basic_block, loop->num_nodes);
927 nbbs = dfs_enumerate_from (loop->header, 0, bb_in_loop_p,
928 bbs, loop->num_nodes, loop);
929 gcc_assert (nbbs == loop->num_nodes);
931 LOOP_VINFO_BBS (res) = bbs;
932 LOOP_VINFO_NITERSM1 (res) = NULL;
933 LOOP_VINFO_NITERS (res) = NULL;
934 LOOP_VINFO_NITERS_UNCHANGED (res) = NULL;
935 LOOP_VINFO_COST_MODEL_MIN_ITERS (res) = 0;
936 LOOP_VINFO_VECTORIZABLE_P (res) = 0;
937 LOOP_VINFO_PEELING_FOR_ALIGNMENT (res) = 0;
938 LOOP_VINFO_VECT_FACTOR (res) = 0;
939 LOOP_VINFO_LOOP_NEST (res).create (3);
940 LOOP_VINFO_DATAREFS (res).create (10);
941 LOOP_VINFO_DDRS (res).create (10 * 10);
942 LOOP_VINFO_UNALIGNED_DR (res) = NULL;
943 LOOP_VINFO_MAY_MISALIGN_STMTS (res).create (
944 PARAM_VALUE (PARAM_VECT_MAX_VERSION_FOR_ALIGNMENT_CHECKS));
945 LOOP_VINFO_MAY_ALIAS_DDRS (res).create (
946 PARAM_VALUE (PARAM_VECT_MAX_VERSION_FOR_ALIAS_CHECKS));
947 LOOP_VINFO_GROUPED_STORES (res).create (10);
948 LOOP_VINFO_REDUCTIONS (res).create (10);
949 LOOP_VINFO_REDUCTION_CHAINS (res).create (10);
950 LOOP_VINFO_SLP_INSTANCES (res).create (10);
951 LOOP_VINFO_SLP_UNROLLING_FACTOR (res) = 1;
952 LOOP_VINFO_TARGET_COST_DATA (res) = init_cost (loop);
953 LOOP_VINFO_PEELING_FOR_GAPS (res) = false;
954 LOOP_VINFO_PEELING_FOR_NITER (res) = false;
955 LOOP_VINFO_OPERANDS_SWAPPED (res) = false;
957 return res;
961 /* Function destroy_loop_vec_info.
963 Free LOOP_VINFO struct, as well as all the stmt_vec_info structs of all the
964 stmts in the loop. */
966 void
967 destroy_loop_vec_info (loop_vec_info loop_vinfo, bool clean_stmts)
969 struct loop *loop;
970 basic_block *bbs;
971 int nbbs;
972 gimple_stmt_iterator si;
973 int j;
974 vec<slp_instance> slp_instances;
975 slp_instance instance;
976 bool swapped;
978 if (!loop_vinfo)
979 return;
981 loop = LOOP_VINFO_LOOP (loop_vinfo);
983 bbs = LOOP_VINFO_BBS (loop_vinfo);
984 nbbs = clean_stmts ? loop->num_nodes : 0;
985 swapped = LOOP_VINFO_OPERANDS_SWAPPED (loop_vinfo);
987 for (j = 0; j < nbbs; j++)
989 basic_block bb = bbs[j];
990 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
991 free_stmt_vec_info (gsi_stmt (si));
993 for (si = gsi_start_bb (bb); !gsi_end_p (si); )
995 gimple stmt = gsi_stmt (si);
997 /* We may have broken canonical form by moving a constant
998 into RHS1 of a commutative op. Fix such occurrences. */
999 if (swapped && is_gimple_assign (stmt))
1001 enum tree_code code = gimple_assign_rhs_code (stmt);
1003 if ((code == PLUS_EXPR
1004 || code == POINTER_PLUS_EXPR
1005 || code == MULT_EXPR)
1006 && CONSTANT_CLASS_P (gimple_assign_rhs1 (stmt)))
1007 swap_ssa_operands (stmt,
1008 gimple_assign_rhs1_ptr (stmt),
1009 gimple_assign_rhs2_ptr (stmt));
1012 /* Free stmt_vec_info. */
1013 free_stmt_vec_info (stmt);
1014 gsi_next (&si);
1018 free (LOOP_VINFO_BBS (loop_vinfo));
1019 vect_destroy_datarefs (loop_vinfo, NULL);
1020 free_dependence_relations (LOOP_VINFO_DDRS (loop_vinfo));
1021 LOOP_VINFO_LOOP_NEST (loop_vinfo).release ();
1022 LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).release ();
1023 LOOP_VINFO_MAY_ALIAS_DDRS (loop_vinfo).release ();
1024 slp_instances = LOOP_VINFO_SLP_INSTANCES (loop_vinfo);
1025 FOR_EACH_VEC_ELT (slp_instances, j, instance)
1026 vect_free_slp_instance (instance);
1028 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
1029 LOOP_VINFO_GROUPED_STORES (loop_vinfo).release ();
1030 LOOP_VINFO_REDUCTIONS (loop_vinfo).release ();
1031 LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo).release ();
1033 if (LOOP_VINFO_PEELING_HTAB (loop_vinfo).is_created ())
1034 LOOP_VINFO_PEELING_HTAB (loop_vinfo).dispose ();
1036 destroy_cost_data (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
1038 free (loop_vinfo);
1039 loop->aux = NULL;
1043 /* Function vect_analyze_loop_1.
1045 Apply a set of analyses on LOOP, and create a loop_vec_info struct
1046 for it. The different analyses will record information in the
1047 loop_vec_info struct. This is a subset of the analyses applied in
1048 vect_analyze_loop, to be applied on an inner-loop nested in the loop
1049 that is now considered for (outer-loop) vectorization. */
1051 static loop_vec_info
1052 vect_analyze_loop_1 (struct loop *loop)
1054 loop_vec_info loop_vinfo;
1056 if (dump_enabled_p ())
1057 dump_printf_loc (MSG_NOTE, vect_location,
1058 "===== analyze_loop_nest_1 =====\n");
1060 /* Check the CFG characteristics of the loop (nesting, entry/exit, etc. */
1062 loop_vinfo = vect_analyze_loop_form (loop);
1063 if (!loop_vinfo)
1065 if (dump_enabled_p ())
1066 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1067 "bad inner-loop form.\n");
1068 return NULL;
1071 return loop_vinfo;
1075 /* Function vect_analyze_loop_form.
1077 Verify that certain CFG restrictions hold, including:
1078 - the loop has a pre-header
1079 - the loop has a single entry and exit
1080 - the loop exit condition is simple enough, and the number of iterations
1081 can be analyzed (a countable loop). */
1083 loop_vec_info
1084 vect_analyze_loop_form (struct loop *loop)
1086 loop_vec_info loop_vinfo;
1087 gimple loop_cond;
1088 tree number_of_iterations = NULL, number_of_iterationsm1 = NULL;
1089 loop_vec_info inner_loop_vinfo = NULL;
1091 if (dump_enabled_p ())
1092 dump_printf_loc (MSG_NOTE, vect_location,
1093 "=== vect_analyze_loop_form ===\n");
1095 /* Different restrictions apply when we are considering an inner-most loop,
1096 vs. an outer (nested) loop.
1097 (FORNOW. May want to relax some of these restrictions in the future). */
1099 if (!loop->inner)
1101 /* Inner-most loop. We currently require that the number of BBs is
1102 exactly 2 (the header and latch). Vectorizable inner-most loops
1103 look like this:
1105 (pre-header)
1107 header <--------+
1108 | | |
1109 | +--> latch --+
1111 (exit-bb) */
1113 if (loop->num_nodes != 2)
1115 if (dump_enabled_p ())
1116 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1117 "not vectorized: control flow in loop.\n");
1118 return NULL;
1121 if (empty_block_p (loop->header))
1123 if (dump_enabled_p ())
1124 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1125 "not vectorized: empty loop.\n");
1126 return NULL;
1129 else
1131 struct loop *innerloop = loop->inner;
1132 edge entryedge;
1134 /* Nested loop. We currently require that the loop is doubly-nested,
1135 contains a single inner loop, and the number of BBs is exactly 5.
1136 Vectorizable outer-loops look like this:
1138 (pre-header)
1140 header <---+
1142 inner-loop |
1144 tail ------+
1146 (exit-bb)
1148 The inner-loop has the properties expected of inner-most loops
1149 as described above. */
1151 if ((loop->inner)->inner || (loop->inner)->next)
1153 if (dump_enabled_p ())
1154 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1155 "not vectorized: multiple nested loops.\n");
1156 return NULL;
1159 /* Analyze the inner-loop. */
1160 inner_loop_vinfo = vect_analyze_loop_1 (loop->inner);
1161 if (!inner_loop_vinfo)
1163 if (dump_enabled_p ())
1164 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1165 "not vectorized: Bad inner loop.\n");
1166 return NULL;
1169 if (!expr_invariant_in_loop_p (loop,
1170 LOOP_VINFO_NITERS (inner_loop_vinfo)))
1172 if (dump_enabled_p ())
1173 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1174 "not vectorized: inner-loop count not"
1175 " invariant.\n");
1176 destroy_loop_vec_info (inner_loop_vinfo, true);
1177 return NULL;
1180 if (loop->num_nodes != 5)
1182 if (dump_enabled_p ())
1183 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1184 "not vectorized: control flow in loop.\n");
1185 destroy_loop_vec_info (inner_loop_vinfo, true);
1186 return NULL;
1189 gcc_assert (EDGE_COUNT (innerloop->header->preds) == 2);
1190 entryedge = EDGE_PRED (innerloop->header, 0);
1191 if (EDGE_PRED (innerloop->header, 0)->src == innerloop->latch)
1192 entryedge = EDGE_PRED (innerloop->header, 1);
1194 if (entryedge->src != loop->header
1195 || !single_exit (innerloop)
1196 || single_exit (innerloop)->dest != EDGE_PRED (loop->latch, 0)->src)
1198 if (dump_enabled_p ())
1199 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1200 "not vectorized: unsupported outerloop form.\n");
1201 destroy_loop_vec_info (inner_loop_vinfo, true);
1202 return NULL;
1205 if (dump_enabled_p ())
1206 dump_printf_loc (MSG_NOTE, vect_location,
1207 "Considering outer-loop vectorization.\n");
1210 if (!single_exit (loop)
1211 || EDGE_COUNT (loop->header->preds) != 2)
1213 if (dump_enabled_p ())
1215 if (!single_exit (loop))
1216 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1217 "not vectorized: multiple exits.\n");
1218 else if (EDGE_COUNT (loop->header->preds) != 2)
1219 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1220 "not vectorized: too many incoming edges.\n");
1222 if (inner_loop_vinfo)
1223 destroy_loop_vec_info (inner_loop_vinfo, true);
1224 return NULL;
1227 /* We assume that the loop exit condition is at the end of the loop. i.e,
1228 that the loop is represented as a do-while (with a proper if-guard
1229 before the loop if needed), where the loop header contains all the
1230 executable statements, and the latch is empty. */
1231 if (!empty_block_p (loop->latch)
1232 || !gimple_seq_empty_p (phi_nodes (loop->latch)))
1234 if (dump_enabled_p ())
1235 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1236 "not vectorized: latch block not empty.\n");
1237 if (inner_loop_vinfo)
1238 destroy_loop_vec_info (inner_loop_vinfo, true);
1239 return NULL;
1242 /* Make sure there exists a single-predecessor exit bb: */
1243 if (!single_pred_p (single_exit (loop)->dest))
1245 edge e = single_exit (loop);
1246 if (!(e->flags & EDGE_ABNORMAL))
1248 split_loop_exit_edge (e);
1249 if (dump_enabled_p ())
1250 dump_printf (MSG_NOTE, "split exit edge.\n");
1252 else
1254 if (dump_enabled_p ())
1255 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1256 "not vectorized: abnormal loop exit edge.\n");
1257 if (inner_loop_vinfo)
1258 destroy_loop_vec_info (inner_loop_vinfo, true);
1259 return NULL;
1263 loop_cond = vect_get_loop_niters (loop, &number_of_iterations,
1264 &number_of_iterationsm1);
1265 if (!loop_cond)
1267 if (dump_enabled_p ())
1268 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1269 "not vectorized: complicated exit condition.\n");
1270 if (inner_loop_vinfo)
1271 destroy_loop_vec_info (inner_loop_vinfo, true);
1272 return NULL;
1275 if (!number_of_iterations
1276 || chrec_contains_undetermined (number_of_iterations))
1278 if (dump_enabled_p ())
1279 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1280 "not vectorized: number of iterations cannot be "
1281 "computed.\n");
1282 if (inner_loop_vinfo)
1283 destroy_loop_vec_info (inner_loop_vinfo, true);
1284 return NULL;
1287 if (integer_zerop (number_of_iterations))
1289 if (dump_enabled_p ())
1290 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1291 "not vectorized: number of iterations = 0.\n");
1292 if (inner_loop_vinfo)
1293 destroy_loop_vec_info (inner_loop_vinfo, true);
1294 return NULL;
1297 loop_vinfo = new_loop_vec_info (loop);
1298 LOOP_VINFO_NITERSM1 (loop_vinfo) = number_of_iterationsm1;
1299 LOOP_VINFO_NITERS (loop_vinfo) = number_of_iterations;
1300 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = number_of_iterations;
1302 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
1304 if (dump_enabled_p ())
1306 dump_printf_loc (MSG_NOTE, vect_location,
1307 "Symbolic number of iterations is ");
1308 dump_generic_expr (MSG_NOTE, TDF_DETAILS, number_of_iterations);
1309 dump_printf (MSG_NOTE, "\n");
1313 STMT_VINFO_TYPE (vinfo_for_stmt (loop_cond)) = loop_exit_ctrl_vec_info_type;
1315 /* CHECKME: May want to keep it around it in the future. */
1316 if (inner_loop_vinfo)
1317 destroy_loop_vec_info (inner_loop_vinfo, false);
1319 gcc_assert (!loop->aux);
1320 loop->aux = loop_vinfo;
1321 return loop_vinfo;
1325 /* Function vect_analyze_loop_operations.
1327 Scan the loop stmts and make sure they are all vectorizable. */
1329 static bool
1330 vect_analyze_loop_operations (loop_vec_info loop_vinfo, bool slp)
1332 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1333 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1334 int nbbs = loop->num_nodes;
1335 gimple_stmt_iterator si;
1336 unsigned int vectorization_factor = 0;
1337 int i;
1338 gimple phi;
1339 stmt_vec_info stmt_info;
1340 bool need_to_vectorize = false;
1341 int min_profitable_iters;
1342 int min_scalar_loop_bound;
1343 unsigned int th;
1344 bool only_slp_in_loop = true, ok;
1345 HOST_WIDE_INT max_niter;
1346 HOST_WIDE_INT estimated_niter;
1347 int min_profitable_estimate;
1349 if (dump_enabled_p ())
1350 dump_printf_loc (MSG_NOTE, vect_location,
1351 "=== vect_analyze_loop_operations ===\n");
1353 gcc_assert (LOOP_VINFO_VECT_FACTOR (loop_vinfo));
1354 vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1355 if (slp)
1357 /* If all the stmts in the loop can be SLPed, we perform only SLP, and
1358 vectorization factor of the loop is the unrolling factor required by
1359 the SLP instances. If that unrolling factor is 1, we say, that we
1360 perform pure SLP on loop - cross iteration parallelism is not
1361 exploited. */
1362 for (i = 0; i < nbbs; i++)
1364 basic_block bb = bbs[i];
1365 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1367 gimple stmt = gsi_stmt (si);
1368 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
1369 gcc_assert (stmt_info);
1370 if ((STMT_VINFO_RELEVANT_P (stmt_info)
1371 || VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
1372 && !PURE_SLP_STMT (stmt_info))
1373 /* STMT needs both SLP and loop-based vectorization. */
1374 only_slp_in_loop = false;
1378 if (only_slp_in_loop)
1379 vectorization_factor = LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo);
1380 else
1381 vectorization_factor = least_common_multiple (vectorization_factor,
1382 LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo));
1384 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
1385 if (dump_enabled_p ())
1386 dump_printf_loc (MSG_NOTE, vect_location,
1387 "Updating vectorization factor to %d\n",
1388 vectorization_factor);
1391 for (i = 0; i < nbbs; i++)
1393 basic_block bb = bbs[i];
1395 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
1397 phi = gsi_stmt (si);
1398 ok = true;
1400 stmt_info = vinfo_for_stmt (phi);
1401 if (dump_enabled_p ())
1403 dump_printf_loc (MSG_NOTE, vect_location, "examining phi: ");
1404 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
1405 dump_printf (MSG_NOTE, "\n");
1408 /* Inner-loop loop-closed exit phi in outer-loop vectorization
1409 (i.e., a phi in the tail of the outer-loop). */
1410 if (! is_loop_header_bb_p (bb))
1412 /* FORNOW: we currently don't support the case that these phis
1413 are not used in the outerloop (unless it is double reduction,
1414 i.e., this phi is vect_reduction_def), cause this case
1415 requires to actually do something here. */
1416 if ((!STMT_VINFO_RELEVANT_P (stmt_info)
1417 || STMT_VINFO_LIVE_P (stmt_info))
1418 && STMT_VINFO_DEF_TYPE (stmt_info)
1419 != vect_double_reduction_def)
1421 if (dump_enabled_p ())
1422 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1423 "Unsupported loop-closed phi in "
1424 "outer-loop.\n");
1425 return false;
1428 /* If PHI is used in the outer loop, we check that its operand
1429 is defined in the inner loop. */
1430 if (STMT_VINFO_RELEVANT_P (stmt_info))
1432 tree phi_op;
1433 gimple op_def_stmt;
1435 if (gimple_phi_num_args (phi) != 1)
1436 return false;
1438 phi_op = PHI_ARG_DEF (phi, 0);
1439 if (TREE_CODE (phi_op) != SSA_NAME)
1440 return false;
1442 op_def_stmt = SSA_NAME_DEF_STMT (phi_op);
1443 if (gimple_nop_p (op_def_stmt)
1444 || !flow_bb_inside_loop_p (loop, gimple_bb (op_def_stmt))
1445 || !vinfo_for_stmt (op_def_stmt))
1446 return false;
1448 if (STMT_VINFO_RELEVANT (vinfo_for_stmt (op_def_stmt))
1449 != vect_used_in_outer
1450 && STMT_VINFO_RELEVANT (vinfo_for_stmt (op_def_stmt))
1451 != vect_used_in_outer_by_reduction)
1452 return false;
1455 continue;
1458 gcc_assert (stmt_info);
1460 if (STMT_VINFO_LIVE_P (stmt_info))
1462 /* FORNOW: not yet supported. */
1463 if (dump_enabled_p ())
1464 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1465 "not vectorized: value used after loop.\n");
1466 return false;
1469 if (STMT_VINFO_RELEVANT (stmt_info) == vect_used_in_scope
1470 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_induction_def)
1472 /* A scalar-dependence cycle that we don't support. */
1473 if (dump_enabled_p ())
1474 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1475 "not vectorized: scalar dependence cycle.\n");
1476 return false;
1479 if (STMT_VINFO_RELEVANT_P (stmt_info))
1481 need_to_vectorize = true;
1482 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def)
1483 ok = vectorizable_induction (phi, NULL, NULL);
1486 if (!ok)
1488 if (dump_enabled_p ())
1490 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1491 "not vectorized: relevant phi not "
1492 "supported: ");
1493 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, phi, 0);
1494 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
1496 return false;
1500 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1502 gimple stmt = gsi_stmt (si);
1503 if (!gimple_clobber_p (stmt)
1504 && !vect_analyze_stmt (stmt, &need_to_vectorize, NULL))
1505 return false;
1507 } /* bbs */
1509 /* All operations in the loop are either irrelevant (deal with loop
1510 control, or dead), or only used outside the loop and can be moved
1511 out of the loop (e.g. invariants, inductions). The loop can be
1512 optimized away by scalar optimizations. We're better off not
1513 touching this loop. */
1514 if (!need_to_vectorize)
1516 if (dump_enabled_p ())
1517 dump_printf_loc (MSG_NOTE, vect_location,
1518 "All the computation can be taken out of the loop.\n");
1519 if (dump_enabled_p ())
1520 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1521 "not vectorized: redundant loop. no profit to "
1522 "vectorize.\n");
1523 return false;
1526 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && dump_enabled_p ())
1527 dump_printf_loc (MSG_NOTE, vect_location,
1528 "vectorization_factor = %d, niters = "
1529 HOST_WIDE_INT_PRINT_DEC "\n", vectorization_factor,
1530 LOOP_VINFO_INT_NITERS (loop_vinfo));
1532 if ((LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
1533 && (LOOP_VINFO_INT_NITERS (loop_vinfo) < vectorization_factor))
1534 || ((max_niter = max_stmt_executions_int (loop)) != -1
1535 && (unsigned HOST_WIDE_INT) max_niter < vectorization_factor))
1537 if (dump_enabled_p ())
1538 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1539 "not vectorized: iteration count too small.\n");
1540 if (dump_enabled_p ())
1541 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1542 "not vectorized: iteration count smaller than "
1543 "vectorization factor.\n");
1544 return false;
1547 /* Analyze cost. Decide if worth while to vectorize. */
1549 /* Once VF is set, SLP costs should be updated since the number of created
1550 vector stmts depends on VF. */
1551 vect_update_slp_costs_according_to_vf (loop_vinfo);
1553 vect_estimate_min_profitable_iters (loop_vinfo, &min_profitable_iters,
1554 &min_profitable_estimate);
1555 LOOP_VINFO_COST_MODEL_MIN_ITERS (loop_vinfo) = min_profitable_iters;
1557 if (min_profitable_iters < 0)
1559 if (dump_enabled_p ())
1560 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1561 "not vectorized: vectorization not profitable.\n");
1562 if (dump_enabled_p ())
1563 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1564 "not vectorized: vector version will never be "
1565 "profitable.\n");
1566 return false;
1569 min_scalar_loop_bound = ((PARAM_VALUE (PARAM_MIN_VECT_LOOP_BOUND)
1570 * vectorization_factor) - 1);
1573 /* Use the cost model only if it is more conservative than user specified
1574 threshold. */
1576 th = (unsigned) min_scalar_loop_bound;
1577 if (min_profitable_iters
1578 && (!min_scalar_loop_bound
1579 || min_profitable_iters > min_scalar_loop_bound))
1580 th = (unsigned) min_profitable_iters;
1582 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
1583 && LOOP_VINFO_INT_NITERS (loop_vinfo) <= th)
1585 if (dump_enabled_p ())
1586 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1587 "not vectorized: vectorization not profitable.\n");
1588 if (dump_enabled_p ())
1589 dump_printf_loc (MSG_NOTE, vect_location,
1590 "not vectorized: iteration count smaller than user "
1591 "specified loop bound parameter or minimum profitable "
1592 "iterations (whichever is more conservative).\n");
1593 return false;
1596 if ((estimated_niter = estimated_stmt_executions_int (loop)) != -1
1597 && ((unsigned HOST_WIDE_INT) estimated_niter
1598 <= MAX (th, (unsigned)min_profitable_estimate)))
1600 if (dump_enabled_p ())
1601 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1602 "not vectorized: estimated iteration count too "
1603 "small.\n");
1604 if (dump_enabled_p ())
1605 dump_printf_loc (MSG_NOTE, vect_location,
1606 "not vectorized: estimated iteration count smaller "
1607 "than specified loop bound parameter or minimum "
1608 "profitable iterations (whichever is more "
1609 "conservative).\n");
1610 return false;
1613 return true;
1617 /* Function vect_analyze_loop_2.
1619 Apply a set of analyses on LOOP, and create a loop_vec_info struct
1620 for it. The different analyses will record information in the
1621 loop_vec_info struct. */
1622 static bool
1623 vect_analyze_loop_2 (loop_vec_info loop_vinfo)
1625 bool ok, slp = false;
1626 int max_vf = MAX_VECTORIZATION_FACTOR;
1627 int min_vf = 2;
1629 /* Find all data references in the loop (which correspond to vdefs/vuses)
1630 and analyze their evolution in the loop. Also adjust the minimal
1631 vectorization factor according to the loads and stores.
1633 FORNOW: Handle only simple, array references, which
1634 alignment can be forced, and aligned pointer-references. */
1636 ok = vect_analyze_data_refs (loop_vinfo, NULL, &min_vf);
1637 if (!ok)
1639 if (dump_enabled_p ())
1640 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1641 "bad data references.\n");
1642 return false;
1645 /* Analyze the access patterns of the data-refs in the loop (consecutive,
1646 complex, etc.). FORNOW: Only handle consecutive access pattern. */
1648 ok = vect_analyze_data_ref_accesses (loop_vinfo, NULL);
1649 if (!ok)
1651 if (dump_enabled_p ())
1652 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1653 "bad data access.\n");
1654 return false;
1657 /* Classify all cross-iteration scalar data-flow cycles.
1658 Cross-iteration cycles caused by virtual phis are analyzed separately. */
1660 vect_analyze_scalar_cycles (loop_vinfo);
1662 vect_pattern_recog (loop_vinfo, NULL);
1664 /* Data-flow analysis to detect stmts that do not need to be vectorized. */
1666 ok = vect_mark_stmts_to_be_vectorized (loop_vinfo);
1667 if (!ok)
1669 if (dump_enabled_p ())
1670 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1671 "unexpected pattern.\n");
1672 return false;
1675 /* Analyze data dependences between the data-refs in the loop
1676 and adjust the maximum vectorization factor according to
1677 the dependences.
1678 FORNOW: fail at the first data dependence that we encounter. */
1680 ok = vect_analyze_data_ref_dependences (loop_vinfo, &max_vf);
1681 if (!ok
1682 || max_vf < min_vf)
1684 if (dump_enabled_p ())
1685 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1686 "bad data dependence.\n");
1687 return false;
1690 ok = vect_determine_vectorization_factor (loop_vinfo);
1691 if (!ok)
1693 if (dump_enabled_p ())
1694 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1695 "can't determine vectorization factor.\n");
1696 return false;
1698 if (max_vf < LOOP_VINFO_VECT_FACTOR (loop_vinfo))
1700 if (dump_enabled_p ())
1701 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1702 "bad data dependence.\n");
1703 return false;
1706 /* Analyze the alignment of the data-refs in the loop.
1707 Fail if a data reference is found that cannot be vectorized. */
1709 ok = vect_analyze_data_refs_alignment (loop_vinfo, NULL);
1710 if (!ok)
1712 if (dump_enabled_p ())
1713 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1714 "bad data alignment.\n");
1715 return false;
1718 /* Prune the list of ddrs to be tested at run-time by versioning for alias.
1719 It is important to call pruning after vect_analyze_data_ref_accesses,
1720 since we use grouping information gathered by interleaving analysis. */
1721 ok = vect_prune_runtime_alias_test_list (loop_vinfo);
1722 if (!ok)
1724 if (dump_enabled_p ())
1725 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1726 "number of versioning for alias "
1727 "run-time tests exceeds %d "
1728 "(--param vect-max-version-for-alias-checks)\n",
1729 PARAM_VALUE (PARAM_VECT_MAX_VERSION_FOR_ALIAS_CHECKS));
1730 return false;
1733 /* This pass will decide on using loop versioning and/or loop peeling in
1734 order to enhance the alignment of data references in the loop. */
1736 ok = vect_enhance_data_refs_alignment (loop_vinfo);
1737 if (!ok)
1739 if (dump_enabled_p ())
1740 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1741 "bad data alignment.\n");
1742 return false;
1745 /* Check the SLP opportunities in the loop, analyze and build SLP trees. */
1746 ok = vect_analyze_slp (loop_vinfo, NULL);
1747 if (ok)
1749 /* Decide which possible SLP instances to SLP. */
1750 slp = vect_make_slp_decision (loop_vinfo);
1752 /* Find stmts that need to be both vectorized and SLPed. */
1753 vect_detect_hybrid_slp (loop_vinfo);
1755 else
1756 return false;
1758 /* Scan all the operations in the loop and make sure they are
1759 vectorizable. */
1761 ok = vect_analyze_loop_operations (loop_vinfo, slp);
1762 if (!ok)
1764 if (dump_enabled_p ())
1765 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1766 "bad operation or unsupported loop bound.\n");
1767 return false;
1770 /* Decide whether we need to create an epilogue loop to handle
1771 remaining scalar iterations. */
1772 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
1773 && LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) > 0)
1775 if (ctz_hwi (LOOP_VINFO_INT_NITERS (loop_vinfo)
1776 - LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo))
1777 < exact_log2 (LOOP_VINFO_VECT_FACTOR (loop_vinfo)))
1778 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = true;
1780 else if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
1781 || (tree_ctz (LOOP_VINFO_NITERS (loop_vinfo))
1782 < (unsigned)exact_log2 (LOOP_VINFO_VECT_FACTOR (loop_vinfo))))
1783 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = true;
1785 /* If an epilogue loop is required make sure we can create one. */
1786 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
1787 || LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo))
1789 if (dump_enabled_p ())
1790 dump_printf_loc (MSG_NOTE, vect_location, "epilog loop required\n");
1791 if (!vect_can_advance_ivs_p (loop_vinfo)
1792 || !slpeel_can_duplicate_loop_p (LOOP_VINFO_LOOP (loop_vinfo),
1793 single_exit (LOOP_VINFO_LOOP
1794 (loop_vinfo))))
1796 if (dump_enabled_p ())
1797 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1798 "not vectorized: can't create required "
1799 "epilog loop\n");
1800 return false;
1804 return true;
1807 /* Function vect_analyze_loop.
1809 Apply a set of analyses on LOOP, and create a loop_vec_info struct
1810 for it. The different analyses will record information in the
1811 loop_vec_info struct. */
1812 loop_vec_info
1813 vect_analyze_loop (struct loop *loop)
1815 loop_vec_info loop_vinfo;
1816 unsigned int vector_sizes;
1818 /* Autodetect first vector size we try. */
1819 current_vector_size = 0;
1820 vector_sizes = targetm.vectorize.autovectorize_vector_sizes ();
1822 if (dump_enabled_p ())
1823 dump_printf_loc (MSG_NOTE, vect_location,
1824 "===== analyze_loop_nest =====\n");
1826 if (loop_outer (loop)
1827 && loop_vec_info_for_loop (loop_outer (loop))
1828 && LOOP_VINFO_VECTORIZABLE_P (loop_vec_info_for_loop (loop_outer (loop))))
1830 if (dump_enabled_p ())
1831 dump_printf_loc (MSG_NOTE, vect_location,
1832 "outer-loop already vectorized.\n");
1833 return NULL;
1836 while (1)
1838 /* Check the CFG characteristics of the loop (nesting, entry/exit). */
1839 loop_vinfo = vect_analyze_loop_form (loop);
1840 if (!loop_vinfo)
1842 if (dump_enabled_p ())
1843 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1844 "bad loop form.\n");
1845 return NULL;
1848 if (vect_analyze_loop_2 (loop_vinfo))
1850 LOOP_VINFO_VECTORIZABLE_P (loop_vinfo) = 1;
1852 return loop_vinfo;
1855 destroy_loop_vec_info (loop_vinfo, true);
1857 vector_sizes &= ~current_vector_size;
1858 if (vector_sizes == 0
1859 || current_vector_size == 0)
1860 return NULL;
1862 /* Try the next biggest vector size. */
1863 current_vector_size = 1 << floor_log2 (vector_sizes);
1864 if (dump_enabled_p ())
1865 dump_printf_loc (MSG_NOTE, vect_location,
1866 "***** Re-trying analysis with "
1867 "vector size %d\n", current_vector_size);
1872 /* Function reduction_code_for_scalar_code
1874 Input:
1875 CODE - tree_code of a reduction operations.
1877 Output:
1878 REDUC_CODE - the corresponding tree-code to be used to reduce the
1879 vector of partial results into a single scalar result (which
1880 will also reside in a vector) or ERROR_MARK if the operation is
1881 a supported reduction operation, but does not have such tree-code.
1883 Return FALSE if CODE currently cannot be vectorized as reduction. */
1885 static bool
1886 reduction_code_for_scalar_code (enum tree_code code,
1887 enum tree_code *reduc_code)
1889 switch (code)
1891 case MAX_EXPR:
1892 *reduc_code = REDUC_MAX_EXPR;
1893 return true;
1895 case MIN_EXPR:
1896 *reduc_code = REDUC_MIN_EXPR;
1897 return true;
1899 case PLUS_EXPR:
1900 *reduc_code = REDUC_PLUS_EXPR;
1901 return true;
1903 case MULT_EXPR:
1904 case MINUS_EXPR:
1905 case BIT_IOR_EXPR:
1906 case BIT_XOR_EXPR:
1907 case BIT_AND_EXPR:
1908 *reduc_code = ERROR_MARK;
1909 return true;
1911 default:
1912 return false;
1917 /* Error reporting helper for vect_is_simple_reduction below. GIMPLE statement
1918 STMT is printed with a message MSG. */
1920 static void
1921 report_vect_op (int msg_type, gimple stmt, const char *msg)
1923 dump_printf_loc (msg_type, vect_location, "%s", msg);
1924 dump_gimple_stmt (msg_type, TDF_SLIM, stmt, 0);
1925 dump_printf (msg_type, "\n");
1929 /* Detect SLP reduction of the form:
1931 #a1 = phi <a5, a0>
1932 a2 = operation (a1)
1933 a3 = operation (a2)
1934 a4 = operation (a3)
1935 a5 = operation (a4)
1937 #a = phi <a5>
1939 PHI is the reduction phi node (#a1 = phi <a5, a0> above)
1940 FIRST_STMT is the first reduction stmt in the chain
1941 (a2 = operation (a1)).
1943 Return TRUE if a reduction chain was detected. */
1945 static bool
1946 vect_is_slp_reduction (loop_vec_info loop_info, gimple phi, gimple first_stmt)
1948 struct loop *loop = (gimple_bb (phi))->loop_father;
1949 struct loop *vect_loop = LOOP_VINFO_LOOP (loop_info);
1950 enum tree_code code;
1951 gimple current_stmt = NULL, loop_use_stmt = NULL, first, next_stmt;
1952 stmt_vec_info use_stmt_info, current_stmt_info;
1953 tree lhs;
1954 imm_use_iterator imm_iter;
1955 use_operand_p use_p;
1956 int nloop_uses, size = 0, n_out_of_loop_uses;
1957 bool found = false;
1959 if (loop != vect_loop)
1960 return false;
1962 lhs = PHI_RESULT (phi);
1963 code = gimple_assign_rhs_code (first_stmt);
1964 while (1)
1966 nloop_uses = 0;
1967 n_out_of_loop_uses = 0;
1968 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
1970 gimple use_stmt = USE_STMT (use_p);
1971 if (is_gimple_debug (use_stmt))
1972 continue;
1974 /* Check if we got back to the reduction phi. */
1975 if (use_stmt == phi)
1977 loop_use_stmt = use_stmt;
1978 found = true;
1979 break;
1982 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
1984 if (vinfo_for_stmt (use_stmt)
1985 && !STMT_VINFO_IN_PATTERN_P (vinfo_for_stmt (use_stmt)))
1987 loop_use_stmt = use_stmt;
1988 nloop_uses++;
1991 else
1992 n_out_of_loop_uses++;
1994 /* There are can be either a single use in the loop or two uses in
1995 phi nodes. */
1996 if (nloop_uses > 1 || (n_out_of_loop_uses && nloop_uses))
1997 return false;
2000 if (found)
2001 break;
2003 /* We reached a statement with no loop uses. */
2004 if (nloop_uses == 0)
2005 return false;
2007 /* This is a loop exit phi, and we haven't reached the reduction phi. */
2008 if (gimple_code (loop_use_stmt) == GIMPLE_PHI)
2009 return false;
2011 if (!is_gimple_assign (loop_use_stmt)
2012 || code != gimple_assign_rhs_code (loop_use_stmt)
2013 || !flow_bb_inside_loop_p (loop, gimple_bb (loop_use_stmt)))
2014 return false;
2016 /* Insert USE_STMT into reduction chain. */
2017 use_stmt_info = vinfo_for_stmt (loop_use_stmt);
2018 if (current_stmt)
2020 current_stmt_info = vinfo_for_stmt (current_stmt);
2021 GROUP_NEXT_ELEMENT (current_stmt_info) = loop_use_stmt;
2022 GROUP_FIRST_ELEMENT (use_stmt_info)
2023 = GROUP_FIRST_ELEMENT (current_stmt_info);
2025 else
2026 GROUP_FIRST_ELEMENT (use_stmt_info) = loop_use_stmt;
2028 lhs = gimple_assign_lhs (loop_use_stmt);
2029 current_stmt = loop_use_stmt;
2030 size++;
2033 if (!found || loop_use_stmt != phi || size < 2)
2034 return false;
2036 /* Swap the operands, if needed, to make the reduction operand be the second
2037 operand. */
2038 lhs = PHI_RESULT (phi);
2039 next_stmt = GROUP_FIRST_ELEMENT (vinfo_for_stmt (current_stmt));
2040 while (next_stmt)
2042 if (gimple_assign_rhs2 (next_stmt) == lhs)
2044 tree op = gimple_assign_rhs1 (next_stmt);
2045 gimple def_stmt = NULL;
2047 if (TREE_CODE (op) == SSA_NAME)
2048 def_stmt = SSA_NAME_DEF_STMT (op);
2050 /* Check that the other def is either defined in the loop
2051 ("vect_internal_def"), or it's an induction (defined by a
2052 loop-header phi-node). */
2053 if (def_stmt
2054 && gimple_bb (def_stmt)
2055 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2056 && (is_gimple_assign (def_stmt)
2057 || is_gimple_call (def_stmt)
2058 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2059 == vect_induction_def
2060 || (gimple_code (def_stmt) == GIMPLE_PHI
2061 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2062 == vect_internal_def
2063 && !is_loop_header_bb_p (gimple_bb (def_stmt)))))
2065 lhs = gimple_assign_lhs (next_stmt);
2066 next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
2067 continue;
2070 return false;
2072 else
2074 tree op = gimple_assign_rhs2 (next_stmt);
2075 gimple def_stmt = NULL;
2077 if (TREE_CODE (op) == SSA_NAME)
2078 def_stmt = SSA_NAME_DEF_STMT (op);
2080 /* Check that the other def is either defined in the loop
2081 ("vect_internal_def"), or it's an induction (defined by a
2082 loop-header phi-node). */
2083 if (def_stmt
2084 && gimple_bb (def_stmt)
2085 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2086 && (is_gimple_assign (def_stmt)
2087 || is_gimple_call (def_stmt)
2088 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2089 == vect_induction_def
2090 || (gimple_code (def_stmt) == GIMPLE_PHI
2091 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2092 == vect_internal_def
2093 && !is_loop_header_bb_p (gimple_bb (def_stmt)))))
2095 if (dump_enabled_p ())
2097 dump_printf_loc (MSG_NOTE, vect_location, "swapping oprnds: ");
2098 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, next_stmt, 0);
2099 dump_printf (MSG_NOTE, "\n");
2102 swap_ssa_operands (next_stmt,
2103 gimple_assign_rhs1_ptr (next_stmt),
2104 gimple_assign_rhs2_ptr (next_stmt));
2105 update_stmt (next_stmt);
2107 if (CONSTANT_CLASS_P (gimple_assign_rhs1 (next_stmt)))
2108 LOOP_VINFO_OPERANDS_SWAPPED (loop_info) = true;
2110 else
2111 return false;
2114 lhs = gimple_assign_lhs (next_stmt);
2115 next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
2118 /* Save the chain for further analysis in SLP detection. */
2119 first = GROUP_FIRST_ELEMENT (vinfo_for_stmt (current_stmt));
2120 LOOP_VINFO_REDUCTION_CHAINS (loop_info).safe_push (first);
2121 GROUP_SIZE (vinfo_for_stmt (first)) = size;
2123 return true;
2127 /* Function vect_is_simple_reduction_1
2129 (1) Detect a cross-iteration def-use cycle that represents a simple
2130 reduction computation. We look for the following pattern:
2132 loop_header:
2133 a1 = phi < a0, a2 >
2134 a3 = ...
2135 a2 = operation (a3, a1)
2139 a3 = ...
2140 loop_header:
2141 a1 = phi < a0, a2 >
2142 a2 = operation (a3, a1)
2144 such that:
2145 1. operation is commutative and associative and it is safe to
2146 change the order of the computation (if CHECK_REDUCTION is true)
2147 2. no uses for a2 in the loop (a2 is used out of the loop)
2148 3. no uses of a1 in the loop besides the reduction operation
2149 4. no uses of a1 outside the loop.
2151 Conditions 1,4 are tested here.
2152 Conditions 2,3 are tested in vect_mark_stmts_to_be_vectorized.
2154 (2) Detect a cross-iteration def-use cycle in nested loops, i.e.,
2155 nested cycles, if CHECK_REDUCTION is false.
2157 (3) Detect cycles of phi nodes in outer-loop vectorization, i.e., double
2158 reductions:
2160 a1 = phi < a0, a2 >
2161 inner loop (def of a3)
2162 a2 = phi < a3 >
2164 If MODIFY is true it tries also to rework the code in-place to enable
2165 detection of more reduction patterns. For the time being we rewrite
2166 "res -= RHS" into "rhs += -RHS" when it seems worthwhile.
2169 static gimple
2170 vect_is_simple_reduction_1 (loop_vec_info loop_info, gimple phi,
2171 bool check_reduction, bool *double_reduc,
2172 bool modify)
2174 struct loop *loop = (gimple_bb (phi))->loop_father;
2175 struct loop *vect_loop = LOOP_VINFO_LOOP (loop_info);
2176 edge latch_e = loop_latch_edge (loop);
2177 tree loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
2178 gimple def_stmt, def1 = NULL, def2 = NULL;
2179 enum tree_code orig_code, code;
2180 tree op1, op2, op3 = NULL_TREE, op4 = NULL_TREE;
2181 tree type;
2182 int nloop_uses;
2183 tree name;
2184 imm_use_iterator imm_iter;
2185 use_operand_p use_p;
2186 bool phi_def;
2188 *double_reduc = false;
2190 /* If CHECK_REDUCTION is true, we assume inner-most loop vectorization,
2191 otherwise, we assume outer loop vectorization. */
2192 gcc_assert ((check_reduction && loop == vect_loop)
2193 || (!check_reduction && flow_loop_nested_p (vect_loop, loop)));
2195 name = PHI_RESULT (phi);
2196 nloop_uses = 0;
2197 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, name)
2199 gimple use_stmt = USE_STMT (use_p);
2200 if (is_gimple_debug (use_stmt))
2201 continue;
2203 if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2205 if (dump_enabled_p ())
2206 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2207 "intermediate value used outside loop.\n");
2209 return NULL;
2212 if (vinfo_for_stmt (use_stmt)
2213 && !is_pattern_stmt_p (vinfo_for_stmt (use_stmt)))
2214 nloop_uses++;
2215 if (nloop_uses > 1)
2217 if (dump_enabled_p ())
2218 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2219 "reduction used in loop.\n");
2220 return NULL;
2224 if (TREE_CODE (loop_arg) != SSA_NAME)
2226 if (dump_enabled_p ())
2228 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2229 "reduction: not ssa_name: ");
2230 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, loop_arg);
2231 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
2233 return NULL;
2236 def_stmt = SSA_NAME_DEF_STMT (loop_arg);
2237 if (!def_stmt)
2239 if (dump_enabled_p ())
2240 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2241 "reduction: no def_stmt.\n");
2242 return NULL;
2245 if (!is_gimple_assign (def_stmt) && gimple_code (def_stmt) != GIMPLE_PHI)
2247 if (dump_enabled_p ())
2249 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, def_stmt, 0);
2250 dump_printf (MSG_NOTE, "\n");
2252 return NULL;
2255 if (is_gimple_assign (def_stmt))
2257 name = gimple_assign_lhs (def_stmt);
2258 phi_def = false;
2260 else
2262 name = PHI_RESULT (def_stmt);
2263 phi_def = true;
2266 nloop_uses = 0;
2267 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, name)
2269 gimple use_stmt = USE_STMT (use_p);
2270 if (is_gimple_debug (use_stmt))
2271 continue;
2272 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt))
2273 && vinfo_for_stmt (use_stmt)
2274 && !is_pattern_stmt_p (vinfo_for_stmt (use_stmt)))
2275 nloop_uses++;
2276 if (nloop_uses > 1)
2278 if (dump_enabled_p ())
2279 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2280 "reduction used in loop.\n");
2281 return NULL;
2285 /* If DEF_STMT is a phi node itself, we expect it to have a single argument
2286 defined in the inner loop. */
2287 if (phi_def)
2289 op1 = PHI_ARG_DEF (def_stmt, 0);
2291 if (gimple_phi_num_args (def_stmt) != 1
2292 || TREE_CODE (op1) != SSA_NAME)
2294 if (dump_enabled_p ())
2295 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2296 "unsupported phi node definition.\n");
2298 return NULL;
2301 def1 = SSA_NAME_DEF_STMT (op1);
2302 if (flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2303 && loop->inner
2304 && flow_bb_inside_loop_p (loop->inner, gimple_bb (def1))
2305 && is_gimple_assign (def1))
2307 if (dump_enabled_p ())
2308 report_vect_op (MSG_NOTE, def_stmt,
2309 "detected double reduction: ");
2311 *double_reduc = true;
2312 return def_stmt;
2315 return NULL;
2318 code = orig_code = gimple_assign_rhs_code (def_stmt);
2320 /* We can handle "res -= x[i]", which is non-associative by
2321 simply rewriting this into "res += -x[i]". Avoid changing
2322 gimple instruction for the first simple tests and only do this
2323 if we're allowed to change code at all. */
2324 if (code == MINUS_EXPR
2325 && modify
2326 && (op1 = gimple_assign_rhs1 (def_stmt))
2327 && TREE_CODE (op1) == SSA_NAME
2328 && SSA_NAME_DEF_STMT (op1) == phi)
2329 code = PLUS_EXPR;
2331 if (check_reduction
2332 && (!commutative_tree_code (code) || !associative_tree_code (code)))
2334 if (dump_enabled_p ())
2335 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2336 "reduction: not commutative/associative: ");
2337 return NULL;
2340 if (get_gimple_rhs_class (code) != GIMPLE_BINARY_RHS)
2342 if (code != COND_EXPR)
2344 if (dump_enabled_p ())
2345 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2346 "reduction: not binary operation: ");
2348 return NULL;
2351 op3 = gimple_assign_rhs1 (def_stmt);
2352 if (COMPARISON_CLASS_P (op3))
2354 op4 = TREE_OPERAND (op3, 1);
2355 op3 = TREE_OPERAND (op3, 0);
2358 op1 = gimple_assign_rhs2 (def_stmt);
2359 op2 = gimple_assign_rhs3 (def_stmt);
2361 if (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op2) != SSA_NAME)
2363 if (dump_enabled_p ())
2364 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2365 "reduction: uses not ssa_names: ");
2367 return NULL;
2370 else
2372 op1 = gimple_assign_rhs1 (def_stmt);
2373 op2 = gimple_assign_rhs2 (def_stmt);
2375 if (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op2) != SSA_NAME)
2377 if (dump_enabled_p ())
2378 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2379 "reduction: uses not ssa_names: ");
2381 return NULL;
2385 type = TREE_TYPE (gimple_assign_lhs (def_stmt));
2386 if ((TREE_CODE (op1) == SSA_NAME
2387 && !types_compatible_p (type,TREE_TYPE (op1)))
2388 || (TREE_CODE (op2) == SSA_NAME
2389 && !types_compatible_p (type, TREE_TYPE (op2)))
2390 || (op3 && TREE_CODE (op3) == SSA_NAME
2391 && !types_compatible_p (type, TREE_TYPE (op3)))
2392 || (op4 && TREE_CODE (op4) == SSA_NAME
2393 && !types_compatible_p (type, TREE_TYPE (op4))))
2395 if (dump_enabled_p ())
2397 dump_printf_loc (MSG_NOTE, vect_location,
2398 "reduction: multiple types: operation type: ");
2399 dump_generic_expr (MSG_NOTE, TDF_SLIM, type);
2400 dump_printf (MSG_NOTE, ", operands types: ");
2401 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2402 TREE_TYPE (op1));
2403 dump_printf (MSG_NOTE, ",");
2404 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2405 TREE_TYPE (op2));
2406 if (op3)
2408 dump_printf (MSG_NOTE, ",");
2409 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2410 TREE_TYPE (op3));
2413 if (op4)
2415 dump_printf (MSG_NOTE, ",");
2416 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2417 TREE_TYPE (op4));
2419 dump_printf (MSG_NOTE, "\n");
2422 return NULL;
2425 /* Check that it's ok to change the order of the computation.
2426 Generally, when vectorizing a reduction we change the order of the
2427 computation. This may change the behavior of the program in some
2428 cases, so we need to check that this is ok. One exception is when
2429 vectorizing an outer-loop: the inner-loop is executed sequentially,
2430 and therefore vectorizing reductions in the inner-loop during
2431 outer-loop vectorization is safe. */
2433 /* CHECKME: check for !flag_finite_math_only too? */
2434 if (SCALAR_FLOAT_TYPE_P (type) && !flag_associative_math
2435 && check_reduction)
2437 /* Changing the order of operations changes the semantics. */
2438 if (dump_enabled_p ())
2439 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2440 "reduction: unsafe fp math optimization: ");
2441 return NULL;
2443 else if (INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_TRAPS (type)
2444 && check_reduction)
2446 /* Changing the order of operations changes the semantics. */
2447 if (dump_enabled_p ())
2448 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2449 "reduction: unsafe int math optimization: ");
2450 return NULL;
2452 else if (SAT_FIXED_POINT_TYPE_P (type) && check_reduction)
2454 /* Changing the order of operations changes the semantics. */
2455 if (dump_enabled_p ())
2456 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2457 "reduction: unsafe fixed-point math optimization: ");
2458 return NULL;
2461 /* If we detected "res -= x[i]" earlier, rewrite it into
2462 "res += -x[i]" now. If this turns out to be useless reassoc
2463 will clean it up again. */
2464 if (orig_code == MINUS_EXPR)
2466 tree rhs = gimple_assign_rhs2 (def_stmt);
2467 tree negrhs = make_ssa_name (TREE_TYPE (rhs), NULL);
2468 gimple negate_stmt = gimple_build_assign_with_ops (NEGATE_EXPR, negrhs,
2469 rhs, NULL);
2470 gimple_stmt_iterator gsi = gsi_for_stmt (def_stmt);
2471 set_vinfo_for_stmt (negate_stmt, new_stmt_vec_info (negate_stmt,
2472 loop_info, NULL));
2473 gsi_insert_before (&gsi, negate_stmt, GSI_NEW_STMT);
2474 gimple_assign_set_rhs2 (def_stmt, negrhs);
2475 gimple_assign_set_rhs_code (def_stmt, PLUS_EXPR);
2476 update_stmt (def_stmt);
2479 /* Reduction is safe. We're dealing with one of the following:
2480 1) integer arithmetic and no trapv
2481 2) floating point arithmetic, and special flags permit this optimization
2482 3) nested cycle (i.e., outer loop vectorization). */
2483 if (TREE_CODE (op1) == SSA_NAME)
2484 def1 = SSA_NAME_DEF_STMT (op1);
2486 if (TREE_CODE (op2) == SSA_NAME)
2487 def2 = SSA_NAME_DEF_STMT (op2);
2489 if (code != COND_EXPR
2490 && ((!def1 || gimple_nop_p (def1)) && (!def2 || gimple_nop_p (def2))))
2492 if (dump_enabled_p ())
2493 report_vect_op (MSG_NOTE, def_stmt, "reduction: no defs for operands: ");
2494 return NULL;
2497 /* Check that one def is the reduction def, defined by PHI,
2498 the other def is either defined in the loop ("vect_internal_def"),
2499 or it's an induction (defined by a loop-header phi-node). */
2501 if (def2 && def2 == phi
2502 && (code == COND_EXPR
2503 || !def1 || gimple_nop_p (def1)
2504 || !flow_bb_inside_loop_p (loop, gimple_bb (def1))
2505 || (def1 && flow_bb_inside_loop_p (loop, gimple_bb (def1))
2506 && (is_gimple_assign (def1)
2507 || is_gimple_call (def1)
2508 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def1))
2509 == vect_induction_def
2510 || (gimple_code (def1) == GIMPLE_PHI
2511 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def1))
2512 == vect_internal_def
2513 && !is_loop_header_bb_p (gimple_bb (def1)))))))
2515 if (dump_enabled_p ())
2516 report_vect_op (MSG_NOTE, def_stmt, "detected reduction: ");
2517 return def_stmt;
2520 if (def1 && def1 == phi
2521 && (code == COND_EXPR
2522 || !def2 || gimple_nop_p (def2)
2523 || !flow_bb_inside_loop_p (loop, gimple_bb (def2))
2524 || (def2 && flow_bb_inside_loop_p (loop, gimple_bb (def2))
2525 && (is_gimple_assign (def2)
2526 || is_gimple_call (def2)
2527 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def2))
2528 == vect_induction_def
2529 || (gimple_code (def2) == GIMPLE_PHI
2530 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def2))
2531 == vect_internal_def
2532 && !is_loop_header_bb_p (gimple_bb (def2)))))))
2534 if (check_reduction)
2536 /* Swap operands (just for simplicity - so that the rest of the code
2537 can assume that the reduction variable is always the last (second)
2538 argument). */
2539 if (dump_enabled_p ())
2540 report_vect_op (MSG_NOTE, def_stmt,
2541 "detected reduction: need to swap operands: ");
2543 swap_ssa_operands (def_stmt, gimple_assign_rhs1_ptr (def_stmt),
2544 gimple_assign_rhs2_ptr (def_stmt));
2546 if (CONSTANT_CLASS_P (gimple_assign_rhs1 (def_stmt)))
2547 LOOP_VINFO_OPERANDS_SWAPPED (loop_info) = true;
2549 else
2551 if (dump_enabled_p ())
2552 report_vect_op (MSG_NOTE, def_stmt, "detected reduction: ");
2555 return def_stmt;
2558 /* Try to find SLP reduction chain. */
2559 if (check_reduction && vect_is_slp_reduction (loop_info, phi, def_stmt))
2561 if (dump_enabled_p ())
2562 report_vect_op (MSG_NOTE, def_stmt,
2563 "reduction: detected reduction chain: ");
2565 return def_stmt;
2568 if (dump_enabled_p ())
2569 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2570 "reduction: unknown pattern: ");
2572 return NULL;
2575 /* Wrapper around vect_is_simple_reduction_1, that won't modify code
2576 in-place. Arguments as there. */
2578 static gimple
2579 vect_is_simple_reduction (loop_vec_info loop_info, gimple phi,
2580 bool check_reduction, bool *double_reduc)
2582 return vect_is_simple_reduction_1 (loop_info, phi, check_reduction,
2583 double_reduc, false);
2586 /* Wrapper around vect_is_simple_reduction_1, which will modify code
2587 in-place if it enables detection of more reductions. Arguments
2588 as there. */
2590 gimple
2591 vect_force_simple_reduction (loop_vec_info loop_info, gimple phi,
2592 bool check_reduction, bool *double_reduc)
2594 return vect_is_simple_reduction_1 (loop_info, phi, check_reduction,
2595 double_reduc, true);
2598 /* Calculate the cost of one scalar iteration of the loop. */
2600 vect_get_single_scalar_iteration_cost (loop_vec_info loop_vinfo)
2602 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
2603 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
2604 int nbbs = loop->num_nodes, factor, scalar_single_iter_cost = 0;
2605 int innerloop_iters, i, stmt_cost;
2607 /* Count statements in scalar loop. Using this as scalar cost for a single
2608 iteration for now.
2610 TODO: Add outer loop support.
2612 TODO: Consider assigning different costs to different scalar
2613 statements. */
2615 /* FORNOW. */
2616 innerloop_iters = 1;
2617 if (loop->inner)
2618 innerloop_iters = 50; /* FIXME */
2620 for (i = 0; i < nbbs; i++)
2622 gimple_stmt_iterator si;
2623 basic_block bb = bbs[i];
2625 if (bb->loop_father == loop->inner)
2626 factor = innerloop_iters;
2627 else
2628 factor = 1;
2630 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
2632 gimple stmt = gsi_stmt (si);
2633 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
2635 if (!is_gimple_assign (stmt) && !is_gimple_call (stmt))
2636 continue;
2638 /* Skip stmts that are not vectorized inside the loop. */
2639 if (stmt_info
2640 && !STMT_VINFO_RELEVANT_P (stmt_info)
2641 && (!STMT_VINFO_LIVE_P (stmt_info)
2642 || !VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
2643 && !STMT_VINFO_IN_PATTERN_P (stmt_info))
2644 continue;
2646 if (STMT_VINFO_DATA_REF (vinfo_for_stmt (stmt)))
2648 if (DR_IS_READ (STMT_VINFO_DATA_REF (vinfo_for_stmt (stmt))))
2649 stmt_cost = vect_get_stmt_cost (scalar_load);
2650 else
2651 stmt_cost = vect_get_stmt_cost (scalar_store);
2653 else
2654 stmt_cost = vect_get_stmt_cost (scalar_stmt);
2656 scalar_single_iter_cost += stmt_cost * factor;
2659 return scalar_single_iter_cost;
2662 /* Calculate cost of peeling the loop PEEL_ITERS_PROLOGUE times. */
2664 vect_get_known_peeling_cost (loop_vec_info loop_vinfo, int peel_iters_prologue,
2665 int *peel_iters_epilogue,
2666 int scalar_single_iter_cost,
2667 stmt_vector_for_cost *prologue_cost_vec,
2668 stmt_vector_for_cost *epilogue_cost_vec)
2670 int retval = 0;
2671 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2673 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
2675 *peel_iters_epilogue = vf/2;
2676 if (dump_enabled_p ())
2677 dump_printf_loc (MSG_NOTE, vect_location,
2678 "cost model: epilogue peel iters set to vf/2 "
2679 "because loop iterations are unknown .\n");
2681 /* If peeled iterations are known but number of scalar loop
2682 iterations are unknown, count a taken branch per peeled loop. */
2683 retval = record_stmt_cost (prologue_cost_vec, 2, cond_branch_taken,
2684 NULL, 0, vect_prologue);
2686 else
2688 int niters = LOOP_VINFO_INT_NITERS (loop_vinfo);
2689 peel_iters_prologue = niters < peel_iters_prologue ?
2690 niters : peel_iters_prologue;
2691 *peel_iters_epilogue = (niters - peel_iters_prologue) % vf;
2692 /* If we need to peel for gaps, but no peeling is required, we have to
2693 peel VF iterations. */
2694 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) && !*peel_iters_epilogue)
2695 *peel_iters_epilogue = vf;
2698 if (peel_iters_prologue)
2699 retval += record_stmt_cost (prologue_cost_vec,
2700 peel_iters_prologue * scalar_single_iter_cost,
2701 scalar_stmt, NULL, 0, vect_prologue);
2702 if (*peel_iters_epilogue)
2703 retval += record_stmt_cost (epilogue_cost_vec,
2704 *peel_iters_epilogue * scalar_single_iter_cost,
2705 scalar_stmt, NULL, 0, vect_epilogue);
2706 return retval;
2709 /* Function vect_estimate_min_profitable_iters
2711 Return the number of iterations required for the vector version of the
2712 loop to be profitable relative to the cost of the scalar version of the
2713 loop. */
2715 static void
2716 vect_estimate_min_profitable_iters (loop_vec_info loop_vinfo,
2717 int *ret_min_profitable_niters,
2718 int *ret_min_profitable_estimate)
2720 int min_profitable_iters;
2721 int min_profitable_estimate;
2722 int peel_iters_prologue;
2723 int peel_iters_epilogue;
2724 unsigned vec_inside_cost = 0;
2725 int vec_outside_cost = 0;
2726 unsigned vec_prologue_cost = 0;
2727 unsigned vec_epilogue_cost = 0;
2728 int scalar_single_iter_cost = 0;
2729 int scalar_outside_cost = 0;
2730 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2731 int npeel = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
2732 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
2734 /* Cost model disabled. */
2735 if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
2737 dump_printf_loc (MSG_NOTE, vect_location, "cost model disabled.\n");
2738 *ret_min_profitable_niters = 0;
2739 *ret_min_profitable_estimate = 0;
2740 return;
2743 /* Requires loop versioning tests to handle misalignment. */
2744 if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo))
2746 /* FIXME: Make cost depend on complexity of individual check. */
2747 unsigned len = LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).length ();
2748 (void) add_stmt_cost (target_cost_data, len, vector_stmt, NULL, 0,
2749 vect_prologue);
2750 dump_printf (MSG_NOTE,
2751 "cost model: Adding cost of checks for loop "
2752 "versioning to treat misalignment.\n");
2755 /* Requires loop versioning with alias checks. */
2756 if (LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
2758 /* FIXME: Make cost depend on complexity of individual check. */
2759 unsigned len = LOOP_VINFO_MAY_ALIAS_DDRS (loop_vinfo).length ();
2760 (void) add_stmt_cost (target_cost_data, len, vector_stmt, NULL, 0,
2761 vect_prologue);
2762 dump_printf (MSG_NOTE,
2763 "cost model: Adding cost of checks for loop "
2764 "versioning aliasing.\n");
2767 if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo)
2768 || LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
2769 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken, NULL, 0,
2770 vect_prologue);
2772 /* Count statements in scalar loop. Using this as scalar cost for a single
2773 iteration for now.
2775 TODO: Add outer loop support.
2777 TODO: Consider assigning different costs to different scalar
2778 statements. */
2780 scalar_single_iter_cost = vect_get_single_scalar_iteration_cost (loop_vinfo);
2782 /* Add additional cost for the peeled instructions in prologue and epilogue
2783 loop.
2785 FORNOW: If we don't know the value of peel_iters for prologue or epilogue
2786 at compile-time - we assume it's vf/2 (the worst would be vf-1).
2788 TODO: Build an expression that represents peel_iters for prologue and
2789 epilogue to be used in a run-time test. */
2791 if (npeel < 0)
2793 peel_iters_prologue = vf/2;
2794 dump_printf (MSG_NOTE, "cost model: "
2795 "prologue peel iters set to vf/2.\n");
2797 /* If peeling for alignment is unknown, loop bound of main loop becomes
2798 unknown. */
2799 peel_iters_epilogue = vf/2;
2800 dump_printf (MSG_NOTE, "cost model: "
2801 "epilogue peel iters set to vf/2 because "
2802 "peeling for alignment is unknown.\n");
2804 /* If peeled iterations are unknown, count a taken branch and a not taken
2805 branch per peeled loop. Even if scalar loop iterations are known,
2806 vector iterations are not known since peeled prologue iterations are
2807 not known. Hence guards remain the same. */
2808 (void) add_stmt_cost (target_cost_data, 2, cond_branch_taken,
2809 NULL, 0, vect_prologue);
2810 (void) add_stmt_cost (target_cost_data, 2, cond_branch_not_taken,
2811 NULL, 0, vect_prologue);
2812 /* FORNOW: Don't attempt to pass individual scalar instructions to
2813 the model; just assume linear cost for scalar iterations. */
2814 (void) add_stmt_cost (target_cost_data,
2815 peel_iters_prologue * scalar_single_iter_cost,
2816 scalar_stmt, NULL, 0, vect_prologue);
2817 (void) add_stmt_cost (target_cost_data,
2818 peel_iters_epilogue * scalar_single_iter_cost,
2819 scalar_stmt, NULL, 0, vect_epilogue);
2821 else
2823 stmt_vector_for_cost prologue_cost_vec, epilogue_cost_vec;
2824 stmt_info_for_cost *si;
2825 int j;
2826 void *data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
2828 prologue_cost_vec.create (2);
2829 epilogue_cost_vec.create (2);
2830 peel_iters_prologue = npeel;
2832 (void) vect_get_known_peeling_cost (loop_vinfo, peel_iters_prologue,
2833 &peel_iters_epilogue,
2834 scalar_single_iter_cost,
2835 &prologue_cost_vec,
2836 &epilogue_cost_vec);
2838 FOR_EACH_VEC_ELT (prologue_cost_vec, j, si)
2840 struct _stmt_vec_info *stmt_info
2841 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
2842 (void) add_stmt_cost (data, si->count, si->kind, stmt_info,
2843 si->misalign, vect_prologue);
2846 FOR_EACH_VEC_ELT (epilogue_cost_vec, j, si)
2848 struct _stmt_vec_info *stmt_info
2849 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
2850 (void) add_stmt_cost (data, si->count, si->kind, stmt_info,
2851 si->misalign, vect_epilogue);
2854 prologue_cost_vec.release ();
2855 epilogue_cost_vec.release ();
2858 /* FORNOW: The scalar outside cost is incremented in one of the
2859 following ways:
2861 1. The vectorizer checks for alignment and aliasing and generates
2862 a condition that allows dynamic vectorization. A cost model
2863 check is ANDED with the versioning condition. Hence scalar code
2864 path now has the added cost of the versioning check.
2866 if (cost > th & versioning_check)
2867 jmp to vector code
2869 Hence run-time scalar is incremented by not-taken branch cost.
2871 2. The vectorizer then checks if a prologue is required. If the
2872 cost model check was not done before during versioning, it has to
2873 be done before the prologue check.
2875 if (cost <= th)
2876 prologue = scalar_iters
2877 if (prologue == 0)
2878 jmp to vector code
2879 else
2880 execute prologue
2881 if (prologue == num_iters)
2882 go to exit
2884 Hence the run-time scalar cost is incremented by a taken branch,
2885 plus a not-taken branch, plus a taken branch cost.
2887 3. The vectorizer then checks if an epilogue is required. If the
2888 cost model check was not done before during prologue check, it
2889 has to be done with the epilogue check.
2891 if (prologue == 0)
2892 jmp to vector code
2893 else
2894 execute prologue
2895 if (prologue == num_iters)
2896 go to exit
2897 vector code:
2898 if ((cost <= th) | (scalar_iters-prologue-epilogue == 0))
2899 jmp to epilogue
2901 Hence the run-time scalar cost should be incremented by 2 taken
2902 branches.
2904 TODO: The back end may reorder the BBS's differently and reverse
2905 conditions/branch directions. Change the estimates below to
2906 something more reasonable. */
2908 /* If the number of iterations is known and we do not do versioning, we can
2909 decide whether to vectorize at compile time. Hence the scalar version
2910 do not carry cost model guard costs. */
2911 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2912 || LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo)
2913 || LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
2915 /* Cost model check occurs at versioning. */
2916 if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo)
2917 || LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
2918 scalar_outside_cost += vect_get_stmt_cost (cond_branch_not_taken);
2919 else
2921 /* Cost model check occurs at prologue generation. */
2922 if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
2923 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken)
2924 + vect_get_stmt_cost (cond_branch_not_taken);
2925 /* Cost model check occurs at epilogue generation. */
2926 else
2927 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken);
2931 /* Complete the target-specific cost calculations. */
2932 finish_cost (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo), &vec_prologue_cost,
2933 &vec_inside_cost, &vec_epilogue_cost);
2935 vec_outside_cost = (int)(vec_prologue_cost + vec_epilogue_cost);
2937 /* Calculate number of iterations required to make the vector version
2938 profitable, relative to the loop bodies only. The following condition
2939 must hold true:
2940 SIC * niters + SOC > VIC * ((niters-PL_ITERS-EP_ITERS)/VF) + VOC
2941 where
2942 SIC = scalar iteration cost, VIC = vector iteration cost,
2943 VOC = vector outside cost, VF = vectorization factor,
2944 PL_ITERS = prologue iterations, EP_ITERS= epilogue iterations
2945 SOC = scalar outside cost for run time cost model check. */
2947 if ((scalar_single_iter_cost * vf) > (int) vec_inside_cost)
2949 if (vec_outside_cost <= 0)
2950 min_profitable_iters = 1;
2951 else
2953 min_profitable_iters = ((vec_outside_cost - scalar_outside_cost) * vf
2954 - vec_inside_cost * peel_iters_prologue
2955 - vec_inside_cost * peel_iters_epilogue)
2956 / ((scalar_single_iter_cost * vf)
2957 - vec_inside_cost);
2959 if ((scalar_single_iter_cost * vf * min_profitable_iters)
2960 <= (((int) vec_inside_cost * min_profitable_iters)
2961 + (((int) vec_outside_cost - scalar_outside_cost) * vf)))
2962 min_profitable_iters++;
2965 /* vector version will never be profitable. */
2966 else
2968 if (LOOP_VINFO_LOOP (loop_vinfo)->force_vect)
2969 warning_at (vect_location, OPT_Wopenmp_simd, "vectorization "
2970 "did not happen for a simd loop");
2972 if (dump_enabled_p ())
2973 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2974 "cost model: the vector iteration cost = %d "
2975 "divided by the scalar iteration cost = %d "
2976 "is greater or equal to the vectorization factor = %d"
2977 ".\n",
2978 vec_inside_cost, scalar_single_iter_cost, vf);
2979 *ret_min_profitable_niters = -1;
2980 *ret_min_profitable_estimate = -1;
2981 return;
2984 if (dump_enabled_p ())
2986 dump_printf_loc (MSG_NOTE, vect_location, "Cost model analysis: \n");
2987 dump_printf (MSG_NOTE, " Vector inside of loop cost: %d\n",
2988 vec_inside_cost);
2989 dump_printf (MSG_NOTE, " Vector prologue cost: %d\n",
2990 vec_prologue_cost);
2991 dump_printf (MSG_NOTE, " Vector epilogue cost: %d\n",
2992 vec_epilogue_cost);
2993 dump_printf (MSG_NOTE, " Scalar iteration cost: %d\n",
2994 scalar_single_iter_cost);
2995 dump_printf (MSG_NOTE, " Scalar outside cost: %d\n",
2996 scalar_outside_cost);
2997 dump_printf (MSG_NOTE, " Vector outside cost: %d\n",
2998 vec_outside_cost);
2999 dump_printf (MSG_NOTE, " prologue iterations: %d\n",
3000 peel_iters_prologue);
3001 dump_printf (MSG_NOTE, " epilogue iterations: %d\n",
3002 peel_iters_epilogue);
3003 dump_printf (MSG_NOTE,
3004 " Calculated minimum iters for profitability: %d\n",
3005 min_profitable_iters);
3006 dump_printf (MSG_NOTE, "\n");
3009 min_profitable_iters =
3010 min_profitable_iters < vf ? vf : min_profitable_iters;
3012 /* Because the condition we create is:
3013 if (niters <= min_profitable_iters)
3014 then skip the vectorized loop. */
3015 min_profitable_iters--;
3017 if (dump_enabled_p ())
3018 dump_printf_loc (MSG_NOTE, vect_location,
3019 " Runtime profitability threshold = %d\n",
3020 min_profitable_iters);
3022 *ret_min_profitable_niters = min_profitable_iters;
3024 /* Calculate number of iterations required to make the vector version
3025 profitable, relative to the loop bodies only.
3027 Non-vectorized variant is SIC * niters and it must win over vector
3028 variant on the expected loop trip count. The following condition must hold true:
3029 SIC * niters > VIC * ((niters-PL_ITERS-EP_ITERS)/VF) + VOC + SOC */
3031 if (vec_outside_cost <= 0)
3032 min_profitable_estimate = 1;
3033 else
3035 min_profitable_estimate = ((vec_outside_cost + scalar_outside_cost) * vf
3036 - vec_inside_cost * peel_iters_prologue
3037 - vec_inside_cost * peel_iters_epilogue)
3038 / ((scalar_single_iter_cost * vf)
3039 - vec_inside_cost);
3041 min_profitable_estimate --;
3042 min_profitable_estimate = MAX (min_profitable_estimate, min_profitable_iters);
3043 if (dump_enabled_p ())
3044 dump_printf_loc (MSG_NOTE, vect_location,
3045 " Static estimate profitability threshold = %d\n",
3046 min_profitable_iters);
3048 *ret_min_profitable_estimate = min_profitable_estimate;
3052 /* TODO: Close dependency between vect_model_*_cost and vectorizable_*
3053 functions. Design better to avoid maintenance issues. */
3055 /* Function vect_model_reduction_cost.
3057 Models cost for a reduction operation, including the vector ops
3058 generated within the strip-mine loop, the initial definition before
3059 the loop, and the epilogue code that must be generated. */
3061 static bool
3062 vect_model_reduction_cost (stmt_vec_info stmt_info, enum tree_code reduc_code,
3063 int ncopies)
3065 int prologue_cost = 0, epilogue_cost = 0;
3066 enum tree_code code;
3067 optab optab;
3068 tree vectype;
3069 gimple stmt, orig_stmt;
3070 tree reduction_op;
3071 enum machine_mode mode;
3072 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3073 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
3074 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3076 /* Cost of reduction op inside loop. */
3077 unsigned inside_cost = add_stmt_cost (target_cost_data, ncopies, vector_stmt,
3078 stmt_info, 0, vect_body);
3079 stmt = STMT_VINFO_STMT (stmt_info);
3081 switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
3083 case GIMPLE_SINGLE_RHS:
3084 gcc_assert (TREE_OPERAND_LENGTH (gimple_assign_rhs1 (stmt)) == ternary_op);
3085 reduction_op = TREE_OPERAND (gimple_assign_rhs1 (stmt), 2);
3086 break;
3087 case GIMPLE_UNARY_RHS:
3088 reduction_op = gimple_assign_rhs1 (stmt);
3089 break;
3090 case GIMPLE_BINARY_RHS:
3091 reduction_op = gimple_assign_rhs2 (stmt);
3092 break;
3093 case GIMPLE_TERNARY_RHS:
3094 reduction_op = gimple_assign_rhs3 (stmt);
3095 break;
3096 default:
3097 gcc_unreachable ();
3100 vectype = get_vectype_for_scalar_type (TREE_TYPE (reduction_op));
3101 if (!vectype)
3103 if (dump_enabled_p ())
3105 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3106 "unsupported data-type ");
3107 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
3108 TREE_TYPE (reduction_op));
3109 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
3111 return false;
3114 mode = TYPE_MODE (vectype);
3115 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
3117 if (!orig_stmt)
3118 orig_stmt = STMT_VINFO_STMT (stmt_info);
3120 code = gimple_assign_rhs_code (orig_stmt);
3122 /* Add in cost for initial definition. */
3123 prologue_cost += add_stmt_cost (target_cost_data, 1, scalar_to_vec,
3124 stmt_info, 0, vect_prologue);
3126 /* Determine cost of epilogue code.
3128 We have a reduction operator that will reduce the vector in one statement.
3129 Also requires scalar extract. */
3131 if (!nested_in_vect_loop_p (loop, orig_stmt))
3133 if (reduc_code != ERROR_MARK)
3135 epilogue_cost += add_stmt_cost (target_cost_data, 1, vector_stmt,
3136 stmt_info, 0, vect_epilogue);
3137 epilogue_cost += add_stmt_cost (target_cost_data, 1, vec_to_scalar,
3138 stmt_info, 0, vect_epilogue);
3140 else
3142 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
3143 tree bitsize =
3144 TYPE_SIZE (TREE_TYPE (gimple_assign_lhs (orig_stmt)));
3145 int element_bitsize = tree_to_uhwi (bitsize);
3146 int nelements = vec_size_in_bits / element_bitsize;
3148 optab = optab_for_tree_code (code, vectype, optab_default);
3150 /* We have a whole vector shift available. */
3151 if (VECTOR_MODE_P (mode)
3152 && optab_handler (optab, mode) != CODE_FOR_nothing
3153 && optab_handler (vec_shr_optab, mode) != CODE_FOR_nothing)
3155 /* Final reduction via vector shifts and the reduction operator.
3156 Also requires scalar extract. */
3157 epilogue_cost += add_stmt_cost (target_cost_data,
3158 exact_log2 (nelements) * 2,
3159 vector_stmt, stmt_info, 0,
3160 vect_epilogue);
3161 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3162 vec_to_scalar, stmt_info, 0,
3163 vect_epilogue);
3165 else
3166 /* Use extracts and reduction op for final reduction. For N
3167 elements, we have N extracts and N-1 reduction ops. */
3168 epilogue_cost += add_stmt_cost (target_cost_data,
3169 nelements + nelements - 1,
3170 vector_stmt, stmt_info, 0,
3171 vect_epilogue);
3175 if (dump_enabled_p ())
3176 dump_printf (MSG_NOTE,
3177 "vect_model_reduction_cost: inside_cost = %d, "
3178 "prologue_cost = %d, epilogue_cost = %d .\n", inside_cost,
3179 prologue_cost, epilogue_cost);
3181 return true;
3185 /* Function vect_model_induction_cost.
3187 Models cost for induction operations. */
3189 static void
3190 vect_model_induction_cost (stmt_vec_info stmt_info, int ncopies)
3192 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3193 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3194 unsigned inside_cost, prologue_cost;
3196 /* loop cost for vec_loop. */
3197 inside_cost = add_stmt_cost (target_cost_data, ncopies, vector_stmt,
3198 stmt_info, 0, vect_body);
3200 /* prologue cost for vec_init and vec_step. */
3201 prologue_cost = add_stmt_cost (target_cost_data, 2, scalar_to_vec,
3202 stmt_info, 0, vect_prologue);
3204 if (dump_enabled_p ())
3205 dump_printf_loc (MSG_NOTE, vect_location,
3206 "vect_model_induction_cost: inside_cost = %d, "
3207 "prologue_cost = %d .\n", inside_cost, prologue_cost);
3211 /* Function get_initial_def_for_induction
3213 Input:
3214 STMT - a stmt that performs an induction operation in the loop.
3215 IV_PHI - the initial value of the induction variable
3217 Output:
3218 Return a vector variable, initialized with the first VF values of
3219 the induction variable. E.g., for an iv with IV_PHI='X' and
3220 evolution S, for a vector of 4 units, we want to return:
3221 [X, X + S, X + 2*S, X + 3*S]. */
3223 static tree
3224 get_initial_def_for_induction (gimple iv_phi)
3226 stmt_vec_info stmt_vinfo = vinfo_for_stmt (iv_phi);
3227 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
3228 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
3229 tree vectype;
3230 int nunits;
3231 edge pe = loop_preheader_edge (loop);
3232 struct loop *iv_loop;
3233 basic_block new_bb;
3234 tree new_vec, vec_init, vec_step, t;
3235 tree new_var;
3236 tree new_name;
3237 gimple init_stmt, induction_phi, new_stmt;
3238 tree induc_def, vec_def, vec_dest;
3239 tree init_expr, step_expr;
3240 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3241 int i;
3242 int ncopies;
3243 tree expr;
3244 stmt_vec_info phi_info = vinfo_for_stmt (iv_phi);
3245 bool nested_in_vect_loop = false;
3246 gimple_seq stmts = NULL;
3247 imm_use_iterator imm_iter;
3248 use_operand_p use_p;
3249 gimple exit_phi;
3250 edge latch_e;
3251 tree loop_arg;
3252 gimple_stmt_iterator si;
3253 basic_block bb = gimple_bb (iv_phi);
3254 tree stepvectype;
3255 tree resvectype;
3257 /* Is phi in an inner-loop, while vectorizing an enclosing outer-loop? */
3258 if (nested_in_vect_loop_p (loop, iv_phi))
3260 nested_in_vect_loop = true;
3261 iv_loop = loop->inner;
3263 else
3264 iv_loop = loop;
3265 gcc_assert (iv_loop == (gimple_bb (iv_phi))->loop_father);
3267 latch_e = loop_latch_edge (iv_loop);
3268 loop_arg = PHI_ARG_DEF_FROM_EDGE (iv_phi, latch_e);
3270 step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (phi_info);
3271 gcc_assert (step_expr != NULL_TREE);
3273 pe = loop_preheader_edge (iv_loop);
3274 init_expr = PHI_ARG_DEF_FROM_EDGE (iv_phi,
3275 loop_preheader_edge (iv_loop));
3277 vectype = get_vectype_for_scalar_type (TREE_TYPE (init_expr));
3278 resvectype = get_vectype_for_scalar_type (TREE_TYPE (PHI_RESULT (iv_phi)));
3279 gcc_assert (vectype);
3280 nunits = TYPE_VECTOR_SUBPARTS (vectype);
3281 ncopies = vf / nunits;
3283 gcc_assert (phi_info);
3284 gcc_assert (ncopies >= 1);
3286 /* Convert the step to the desired type. */
3287 step_expr = force_gimple_operand (fold_convert (TREE_TYPE (vectype),
3288 step_expr),
3289 &stmts, true, NULL_TREE);
3290 if (stmts)
3292 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
3293 gcc_assert (!new_bb);
3296 /* Find the first insertion point in the BB. */
3297 si = gsi_after_labels (bb);
3299 /* Create the vector that holds the initial_value of the induction. */
3300 if (nested_in_vect_loop)
3302 /* iv_loop is nested in the loop to be vectorized. init_expr had already
3303 been created during vectorization of previous stmts. We obtain it
3304 from the STMT_VINFO_VEC_STMT of the defining stmt. */
3305 vec_init = vect_get_vec_def_for_operand (init_expr, iv_phi, NULL);
3306 /* If the initial value is not of proper type, convert it. */
3307 if (!useless_type_conversion_p (vectype, TREE_TYPE (vec_init)))
3309 new_stmt = gimple_build_assign_with_ops
3310 (VIEW_CONVERT_EXPR,
3311 vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_"),
3312 build1 (VIEW_CONVERT_EXPR, vectype, vec_init), NULL_TREE);
3313 vec_init = make_ssa_name (gimple_assign_lhs (new_stmt), new_stmt);
3314 gimple_assign_set_lhs (new_stmt, vec_init);
3315 new_bb = gsi_insert_on_edge_immediate (loop_preheader_edge (iv_loop),
3316 new_stmt);
3317 gcc_assert (!new_bb);
3318 set_vinfo_for_stmt (new_stmt,
3319 new_stmt_vec_info (new_stmt, loop_vinfo, NULL));
3322 else
3324 vec<constructor_elt, va_gc> *v;
3326 /* iv_loop is the loop to be vectorized. Create:
3327 vec_init = [X, X+S, X+2*S, X+3*S] (S = step_expr, X = init_expr) */
3328 new_var = vect_get_new_vect_var (TREE_TYPE (vectype),
3329 vect_scalar_var, "var_");
3330 new_name = force_gimple_operand (fold_convert (TREE_TYPE (vectype),
3331 init_expr),
3332 &stmts, false, new_var);
3333 if (stmts)
3335 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
3336 gcc_assert (!new_bb);
3339 vec_alloc (v, nunits);
3340 bool constant_p = is_gimple_min_invariant (new_name);
3341 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, new_name);
3342 for (i = 1; i < nunits; i++)
3344 /* Create: new_name_i = new_name + step_expr */
3345 new_name = fold_build2 (PLUS_EXPR, TREE_TYPE (new_name),
3346 new_name, step_expr);
3347 if (!is_gimple_min_invariant (new_name))
3349 init_stmt = gimple_build_assign (new_var, new_name);
3350 new_name = make_ssa_name (new_var, init_stmt);
3351 gimple_assign_set_lhs (init_stmt, new_name);
3352 new_bb = gsi_insert_on_edge_immediate (pe, init_stmt);
3353 gcc_assert (!new_bb);
3354 if (dump_enabled_p ())
3356 dump_printf_loc (MSG_NOTE, vect_location,
3357 "created new init_stmt: ");
3358 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, init_stmt, 0);
3359 dump_printf (MSG_NOTE, "\n");
3361 constant_p = false;
3363 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, new_name);
3365 /* Create a vector from [new_name_0, new_name_1, ..., new_name_nunits-1] */
3366 if (constant_p)
3367 new_vec = build_vector_from_ctor (vectype, v);
3368 else
3369 new_vec = build_constructor (vectype, v);
3370 vec_init = vect_init_vector (iv_phi, new_vec, vectype, NULL);
3374 /* Create the vector that holds the step of the induction. */
3375 if (nested_in_vect_loop)
3376 /* iv_loop is nested in the loop to be vectorized. Generate:
3377 vec_step = [S, S, S, S] */
3378 new_name = step_expr;
3379 else
3381 /* iv_loop is the loop to be vectorized. Generate:
3382 vec_step = [VF*S, VF*S, VF*S, VF*S] */
3383 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
3385 expr = build_int_cst (integer_type_node, vf);
3386 expr = fold_convert (TREE_TYPE (step_expr), expr);
3388 else
3389 expr = build_int_cst (TREE_TYPE (step_expr), vf);
3390 new_name = fold_build2 (MULT_EXPR, TREE_TYPE (step_expr),
3391 expr, step_expr);
3392 if (TREE_CODE (step_expr) == SSA_NAME)
3393 new_name = vect_init_vector (iv_phi, new_name,
3394 TREE_TYPE (step_expr), NULL);
3397 t = unshare_expr (new_name);
3398 gcc_assert (CONSTANT_CLASS_P (new_name)
3399 || TREE_CODE (new_name) == SSA_NAME);
3400 stepvectype = get_vectype_for_scalar_type (TREE_TYPE (new_name));
3401 gcc_assert (stepvectype);
3402 new_vec = build_vector_from_val (stepvectype, t);
3403 vec_step = vect_init_vector (iv_phi, new_vec, stepvectype, NULL);
3406 /* Create the following def-use cycle:
3407 loop prolog:
3408 vec_init = ...
3409 vec_step = ...
3410 loop:
3411 vec_iv = PHI <vec_init, vec_loop>
3413 STMT
3415 vec_loop = vec_iv + vec_step; */
3417 /* Create the induction-phi that defines the induction-operand. */
3418 vec_dest = vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_");
3419 induction_phi = create_phi_node (vec_dest, iv_loop->header);
3420 set_vinfo_for_stmt (induction_phi,
3421 new_stmt_vec_info (induction_phi, loop_vinfo, NULL));
3422 induc_def = PHI_RESULT (induction_phi);
3424 /* Create the iv update inside the loop */
3425 new_stmt = gimple_build_assign_with_ops (PLUS_EXPR, vec_dest,
3426 induc_def, vec_step);
3427 vec_def = make_ssa_name (vec_dest, new_stmt);
3428 gimple_assign_set_lhs (new_stmt, vec_def);
3429 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
3430 set_vinfo_for_stmt (new_stmt, new_stmt_vec_info (new_stmt, loop_vinfo,
3431 NULL));
3433 /* Set the arguments of the phi node: */
3434 add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
3435 add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
3436 UNKNOWN_LOCATION);
3439 /* In case that vectorization factor (VF) is bigger than the number
3440 of elements that we can fit in a vectype (nunits), we have to generate
3441 more than one vector stmt - i.e - we need to "unroll" the
3442 vector stmt by a factor VF/nunits. For more details see documentation
3443 in vectorizable_operation. */
3445 if (ncopies > 1)
3447 stmt_vec_info prev_stmt_vinfo;
3448 /* FORNOW. This restriction should be relaxed. */
3449 gcc_assert (!nested_in_vect_loop);
3451 /* Create the vector that holds the step of the induction. */
3452 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
3454 expr = build_int_cst (integer_type_node, nunits);
3455 expr = fold_convert (TREE_TYPE (step_expr), expr);
3457 else
3458 expr = build_int_cst (TREE_TYPE (step_expr), nunits);
3459 new_name = fold_build2 (MULT_EXPR, TREE_TYPE (step_expr),
3460 expr, step_expr);
3461 if (TREE_CODE (step_expr) == SSA_NAME)
3462 new_name = vect_init_vector (iv_phi, new_name,
3463 TREE_TYPE (step_expr), NULL);
3464 t = unshare_expr (new_name);
3465 gcc_assert (CONSTANT_CLASS_P (new_name)
3466 || TREE_CODE (new_name) == SSA_NAME);
3467 new_vec = build_vector_from_val (stepvectype, t);
3468 vec_step = vect_init_vector (iv_phi, new_vec, stepvectype, NULL);
3470 vec_def = induc_def;
3471 prev_stmt_vinfo = vinfo_for_stmt (induction_phi);
3472 for (i = 1; i < ncopies; i++)
3474 /* vec_i = vec_prev + vec_step */
3475 new_stmt = gimple_build_assign_with_ops (PLUS_EXPR, vec_dest,
3476 vec_def, vec_step);
3477 vec_def = make_ssa_name (vec_dest, new_stmt);
3478 gimple_assign_set_lhs (new_stmt, vec_def);
3480 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
3481 if (!useless_type_conversion_p (resvectype, vectype))
3483 new_stmt = gimple_build_assign_with_ops
3484 (VIEW_CONVERT_EXPR,
3485 vect_get_new_vect_var (resvectype, vect_simple_var,
3486 "vec_iv_"),
3487 build1 (VIEW_CONVERT_EXPR, resvectype,
3488 gimple_assign_lhs (new_stmt)), NULL_TREE);
3489 gimple_assign_set_lhs (new_stmt,
3490 make_ssa_name
3491 (gimple_assign_lhs (new_stmt), new_stmt));
3492 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
3494 set_vinfo_for_stmt (new_stmt,
3495 new_stmt_vec_info (new_stmt, loop_vinfo, NULL));
3496 STMT_VINFO_RELATED_STMT (prev_stmt_vinfo) = new_stmt;
3497 prev_stmt_vinfo = vinfo_for_stmt (new_stmt);
3501 if (nested_in_vect_loop)
3503 /* Find the loop-closed exit-phi of the induction, and record
3504 the final vector of induction results: */
3505 exit_phi = NULL;
3506 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
3508 gimple use_stmt = USE_STMT (use_p);
3509 if (is_gimple_debug (use_stmt))
3510 continue;
3512 if (!flow_bb_inside_loop_p (iv_loop, gimple_bb (use_stmt)))
3514 exit_phi = use_stmt;
3515 break;
3518 if (exit_phi)
3520 stmt_vec_info stmt_vinfo = vinfo_for_stmt (exit_phi);
3521 /* FORNOW. Currently not supporting the case that an inner-loop induction
3522 is not used in the outer-loop (i.e. only outside the outer-loop). */
3523 gcc_assert (STMT_VINFO_RELEVANT_P (stmt_vinfo)
3524 && !STMT_VINFO_LIVE_P (stmt_vinfo));
3526 STMT_VINFO_VEC_STMT (stmt_vinfo) = new_stmt;
3527 if (dump_enabled_p ())
3529 dump_printf_loc (MSG_NOTE, vect_location,
3530 "vector of inductions after inner-loop:");
3531 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, new_stmt, 0);
3532 dump_printf (MSG_NOTE, "\n");
3538 if (dump_enabled_p ())
3540 dump_printf_loc (MSG_NOTE, vect_location,
3541 "transform induction: created def-use cycle: ");
3542 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, induction_phi, 0);
3543 dump_printf (MSG_NOTE, "\n");
3544 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
3545 SSA_NAME_DEF_STMT (vec_def), 0);
3546 dump_printf (MSG_NOTE, "\n");
3549 STMT_VINFO_VEC_STMT (phi_info) = induction_phi;
3550 if (!useless_type_conversion_p (resvectype, vectype))
3552 new_stmt = gimple_build_assign_with_ops
3553 (VIEW_CONVERT_EXPR,
3554 vect_get_new_vect_var (resvectype, vect_simple_var, "vec_iv_"),
3555 build1 (VIEW_CONVERT_EXPR, resvectype, induc_def), NULL_TREE);
3556 induc_def = make_ssa_name (gimple_assign_lhs (new_stmt), new_stmt);
3557 gimple_assign_set_lhs (new_stmt, induc_def);
3558 si = gsi_after_labels (bb);
3559 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
3560 set_vinfo_for_stmt (new_stmt,
3561 new_stmt_vec_info (new_stmt, loop_vinfo, NULL));
3562 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (new_stmt))
3563 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (induction_phi));
3566 return induc_def;
3570 /* Function get_initial_def_for_reduction
3572 Input:
3573 STMT - a stmt that performs a reduction operation in the loop.
3574 INIT_VAL - the initial value of the reduction variable
3576 Output:
3577 ADJUSTMENT_DEF - a tree that holds a value to be added to the final result
3578 of the reduction (used for adjusting the epilog - see below).
3579 Return a vector variable, initialized according to the operation that STMT
3580 performs. This vector will be used as the initial value of the
3581 vector of partial results.
3583 Option1 (adjust in epilog): Initialize the vector as follows:
3584 add/bit or/xor: [0,0,...,0,0]
3585 mult/bit and: [1,1,...,1,1]
3586 min/max/cond_expr: [init_val,init_val,..,init_val,init_val]
3587 and when necessary (e.g. add/mult case) let the caller know
3588 that it needs to adjust the result by init_val.
3590 Option2: Initialize the vector as follows:
3591 add/bit or/xor: [init_val,0,0,...,0]
3592 mult/bit and: [init_val,1,1,...,1]
3593 min/max/cond_expr: [init_val,init_val,...,init_val]
3594 and no adjustments are needed.
3596 For example, for the following code:
3598 s = init_val;
3599 for (i=0;i<n;i++)
3600 s = s + a[i];
3602 STMT is 's = s + a[i]', and the reduction variable is 's'.
3603 For a vector of 4 units, we want to return either [0,0,0,init_val],
3604 or [0,0,0,0] and let the caller know that it needs to adjust
3605 the result at the end by 'init_val'.
3607 FORNOW, we are using the 'adjust in epilog' scheme, because this way the
3608 initialization vector is simpler (same element in all entries), if
3609 ADJUSTMENT_DEF is not NULL, and Option2 otherwise.
3611 A cost model should help decide between these two schemes. */
3613 tree
3614 get_initial_def_for_reduction (gimple stmt, tree init_val,
3615 tree *adjustment_def)
3617 stmt_vec_info stmt_vinfo = vinfo_for_stmt (stmt);
3618 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
3619 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
3620 tree scalar_type = TREE_TYPE (init_val);
3621 tree vectype = get_vectype_for_scalar_type (scalar_type);
3622 int nunits;
3623 enum tree_code code = gimple_assign_rhs_code (stmt);
3624 tree def_for_init;
3625 tree init_def;
3626 tree *elts;
3627 int i;
3628 bool nested_in_vect_loop = false;
3629 tree init_value;
3630 REAL_VALUE_TYPE real_init_val = dconst0;
3631 int int_init_val = 0;
3632 gimple def_stmt = NULL;
3634 gcc_assert (vectype);
3635 nunits = TYPE_VECTOR_SUBPARTS (vectype);
3637 gcc_assert (POINTER_TYPE_P (scalar_type) || INTEGRAL_TYPE_P (scalar_type)
3638 || SCALAR_FLOAT_TYPE_P (scalar_type));
3640 if (nested_in_vect_loop_p (loop, stmt))
3641 nested_in_vect_loop = true;
3642 else
3643 gcc_assert (loop == (gimple_bb (stmt))->loop_father);
3645 /* In case of double reduction we only create a vector variable to be put
3646 in the reduction phi node. The actual statement creation is done in
3647 vect_create_epilog_for_reduction. */
3648 if (adjustment_def && nested_in_vect_loop
3649 && TREE_CODE (init_val) == SSA_NAME
3650 && (def_stmt = SSA_NAME_DEF_STMT (init_val))
3651 && gimple_code (def_stmt) == GIMPLE_PHI
3652 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
3653 && vinfo_for_stmt (def_stmt)
3654 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
3655 == vect_double_reduction_def)
3657 *adjustment_def = NULL;
3658 return vect_create_destination_var (init_val, vectype);
3661 if (TREE_CONSTANT (init_val))
3663 if (SCALAR_FLOAT_TYPE_P (scalar_type))
3664 init_value = build_real (scalar_type, TREE_REAL_CST (init_val));
3665 else
3666 init_value = build_int_cst (scalar_type, TREE_INT_CST_LOW (init_val));
3668 else
3669 init_value = init_val;
3671 switch (code)
3673 case WIDEN_SUM_EXPR:
3674 case DOT_PROD_EXPR:
3675 case PLUS_EXPR:
3676 case MINUS_EXPR:
3677 case BIT_IOR_EXPR:
3678 case BIT_XOR_EXPR:
3679 case MULT_EXPR:
3680 case BIT_AND_EXPR:
3681 /* ADJUSMENT_DEF is NULL when called from
3682 vect_create_epilog_for_reduction to vectorize double reduction. */
3683 if (adjustment_def)
3685 if (nested_in_vect_loop)
3686 *adjustment_def = vect_get_vec_def_for_operand (init_val, stmt,
3687 NULL);
3688 else
3689 *adjustment_def = init_val;
3692 if (code == MULT_EXPR)
3694 real_init_val = dconst1;
3695 int_init_val = 1;
3698 if (code == BIT_AND_EXPR)
3699 int_init_val = -1;
3701 if (SCALAR_FLOAT_TYPE_P (scalar_type))
3702 def_for_init = build_real (scalar_type, real_init_val);
3703 else
3704 def_for_init = build_int_cst (scalar_type, int_init_val);
3706 /* Create a vector of '0' or '1' except the first element. */
3707 elts = XALLOCAVEC (tree, nunits);
3708 for (i = nunits - 2; i >= 0; --i)
3709 elts[i + 1] = def_for_init;
3711 /* Option1: the first element is '0' or '1' as well. */
3712 if (adjustment_def)
3714 elts[0] = def_for_init;
3715 init_def = build_vector (vectype, elts);
3716 break;
3719 /* Option2: the first element is INIT_VAL. */
3720 elts[0] = init_val;
3721 if (TREE_CONSTANT (init_val))
3722 init_def = build_vector (vectype, elts);
3723 else
3725 vec<constructor_elt, va_gc> *v;
3726 vec_alloc (v, nunits);
3727 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init_val);
3728 for (i = 1; i < nunits; ++i)
3729 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, elts[i]);
3730 init_def = build_constructor (vectype, v);
3733 break;
3735 case MIN_EXPR:
3736 case MAX_EXPR:
3737 case COND_EXPR:
3738 if (adjustment_def)
3740 *adjustment_def = NULL_TREE;
3741 init_def = vect_get_vec_def_for_operand (init_val, stmt, NULL);
3742 break;
3745 init_def = build_vector_from_val (vectype, init_value);
3746 break;
3748 default:
3749 gcc_unreachable ();
3752 return init_def;
3756 /* Function vect_create_epilog_for_reduction
3758 Create code at the loop-epilog to finalize the result of a reduction
3759 computation.
3761 VECT_DEFS is list of vector of partial results, i.e., the lhs's of vector
3762 reduction statements.
3763 STMT is the scalar reduction stmt that is being vectorized.
3764 NCOPIES is > 1 in case the vectorization factor (VF) is bigger than the
3765 number of elements that we can fit in a vectype (nunits). In this case
3766 we have to generate more than one vector stmt - i.e - we need to "unroll"
3767 the vector stmt by a factor VF/nunits. For more details see documentation
3768 in vectorizable_operation.
3769 REDUC_CODE is the tree-code for the epilog reduction.
3770 REDUCTION_PHIS is a list of the phi-nodes that carry the reduction
3771 computation.
3772 REDUC_INDEX is the index of the operand in the right hand side of the
3773 statement that is defined by REDUCTION_PHI.
3774 DOUBLE_REDUC is TRUE if double reduction phi nodes should be handled.
3775 SLP_NODE is an SLP node containing a group of reduction statements. The
3776 first one in this group is STMT.
3778 This function:
3779 1. Creates the reduction def-use cycles: sets the arguments for
3780 REDUCTION_PHIS:
3781 The loop-entry argument is the vectorized initial-value of the reduction.
3782 The loop-latch argument is taken from VECT_DEFS - the vector of partial
3783 sums.
3784 2. "Reduces" each vector of partial results VECT_DEFS into a single result,
3785 by applying the operation specified by REDUC_CODE if available, or by
3786 other means (whole-vector shifts or a scalar loop).
3787 The function also creates a new phi node at the loop exit to preserve
3788 loop-closed form, as illustrated below.
3790 The flow at the entry to this function:
3792 loop:
3793 vec_def = phi <null, null> # REDUCTION_PHI
3794 VECT_DEF = vector_stmt # vectorized form of STMT
3795 s_loop = scalar_stmt # (scalar) STMT
3796 loop_exit:
3797 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
3798 use <s_out0>
3799 use <s_out0>
3801 The above is transformed by this function into:
3803 loop:
3804 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
3805 VECT_DEF = vector_stmt # vectorized form of STMT
3806 s_loop = scalar_stmt # (scalar) STMT
3807 loop_exit:
3808 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
3809 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
3810 v_out2 = reduce <v_out1>
3811 s_out3 = extract_field <v_out2, 0>
3812 s_out4 = adjust_result <s_out3>
3813 use <s_out4>
3814 use <s_out4>
3817 static void
3818 vect_create_epilog_for_reduction (vec<tree> vect_defs, gimple stmt,
3819 int ncopies, enum tree_code reduc_code,
3820 vec<gimple> reduction_phis,
3821 int reduc_index, bool double_reduc,
3822 slp_tree slp_node)
3824 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
3825 stmt_vec_info prev_phi_info;
3826 tree vectype;
3827 enum machine_mode mode;
3828 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3829 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo), *outer_loop = NULL;
3830 basic_block exit_bb;
3831 tree scalar_dest;
3832 tree scalar_type;
3833 gimple new_phi = NULL, phi;
3834 gimple_stmt_iterator exit_gsi;
3835 tree vec_dest;
3836 tree new_temp = NULL_TREE, new_dest, new_name, new_scalar_dest;
3837 gimple epilog_stmt = NULL;
3838 enum tree_code code = gimple_assign_rhs_code (stmt);
3839 gimple exit_phi;
3840 tree bitsize, bitpos;
3841 tree adjustment_def = NULL;
3842 tree vec_initial_def = NULL;
3843 tree reduction_op, expr, def;
3844 tree orig_name, scalar_result;
3845 imm_use_iterator imm_iter, phi_imm_iter;
3846 use_operand_p use_p, phi_use_p;
3847 bool extract_scalar_result = false;
3848 gimple use_stmt, orig_stmt, reduction_phi = NULL;
3849 bool nested_in_vect_loop = false;
3850 auto_vec<gimple> new_phis;
3851 auto_vec<gimple> inner_phis;
3852 enum vect_def_type dt = vect_unknown_def_type;
3853 int j, i;
3854 auto_vec<tree> scalar_results;
3855 unsigned int group_size = 1, k, ratio;
3856 auto_vec<tree> vec_initial_defs;
3857 auto_vec<gimple> phis;
3858 bool slp_reduc = false;
3859 tree new_phi_result;
3860 gimple inner_phi = NULL;
3862 if (slp_node)
3863 group_size = SLP_TREE_SCALAR_STMTS (slp_node).length ();
3865 if (nested_in_vect_loop_p (loop, stmt))
3867 outer_loop = loop;
3868 loop = loop->inner;
3869 nested_in_vect_loop = true;
3870 gcc_assert (!slp_node);
3873 switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
3875 case GIMPLE_SINGLE_RHS:
3876 gcc_assert (TREE_OPERAND_LENGTH (gimple_assign_rhs1 (stmt))
3877 == ternary_op);
3878 reduction_op = TREE_OPERAND (gimple_assign_rhs1 (stmt), reduc_index);
3879 break;
3880 case GIMPLE_UNARY_RHS:
3881 reduction_op = gimple_assign_rhs1 (stmt);
3882 break;
3883 case GIMPLE_BINARY_RHS:
3884 reduction_op = reduc_index ?
3885 gimple_assign_rhs2 (stmt) : gimple_assign_rhs1 (stmt);
3886 break;
3887 case GIMPLE_TERNARY_RHS:
3888 reduction_op = gimple_op (stmt, reduc_index + 1);
3889 break;
3890 default:
3891 gcc_unreachable ();
3894 vectype = get_vectype_for_scalar_type (TREE_TYPE (reduction_op));
3895 gcc_assert (vectype);
3896 mode = TYPE_MODE (vectype);
3898 /* 1. Create the reduction def-use cycle:
3899 Set the arguments of REDUCTION_PHIS, i.e., transform
3901 loop:
3902 vec_def = phi <null, null> # REDUCTION_PHI
3903 VECT_DEF = vector_stmt # vectorized form of STMT
3906 into:
3908 loop:
3909 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
3910 VECT_DEF = vector_stmt # vectorized form of STMT
3913 (in case of SLP, do it for all the phis). */
3915 /* Get the loop-entry arguments. */
3916 if (slp_node)
3917 vect_get_vec_defs (reduction_op, NULL_TREE, stmt, &vec_initial_defs,
3918 NULL, slp_node, reduc_index);
3919 else
3921 vec_initial_defs.create (1);
3922 /* For the case of reduction, vect_get_vec_def_for_operand returns
3923 the scalar def before the loop, that defines the initial value
3924 of the reduction variable. */
3925 vec_initial_def = vect_get_vec_def_for_operand (reduction_op, stmt,
3926 &adjustment_def);
3927 vec_initial_defs.quick_push (vec_initial_def);
3930 /* Set phi nodes arguments. */
3931 FOR_EACH_VEC_ELT (reduction_phis, i, phi)
3933 tree vec_init_def = vec_initial_defs[i];
3934 tree def = vect_defs[i];
3935 for (j = 0; j < ncopies; j++)
3937 /* Set the loop-entry arg of the reduction-phi. */
3938 add_phi_arg (phi, vec_init_def, loop_preheader_edge (loop),
3939 UNKNOWN_LOCATION);
3941 /* Set the loop-latch arg for the reduction-phi. */
3942 if (j > 0)
3943 def = vect_get_vec_def_for_stmt_copy (vect_unknown_def_type, def);
3945 add_phi_arg (phi, def, loop_latch_edge (loop), UNKNOWN_LOCATION);
3947 if (dump_enabled_p ())
3949 dump_printf_loc (MSG_NOTE, vect_location,
3950 "transform reduction: created def-use cycle: ");
3951 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
3952 dump_printf (MSG_NOTE, "\n");
3953 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, SSA_NAME_DEF_STMT (def), 0);
3954 dump_printf (MSG_NOTE, "\n");
3957 phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi));
3961 /* 2. Create epilog code.
3962 The reduction epilog code operates across the elements of the vector
3963 of partial results computed by the vectorized loop.
3964 The reduction epilog code consists of:
3966 step 1: compute the scalar result in a vector (v_out2)
3967 step 2: extract the scalar result (s_out3) from the vector (v_out2)
3968 step 3: adjust the scalar result (s_out3) if needed.
3970 Step 1 can be accomplished using one the following three schemes:
3971 (scheme 1) using reduc_code, if available.
3972 (scheme 2) using whole-vector shifts, if available.
3973 (scheme 3) using a scalar loop. In this case steps 1+2 above are
3974 combined.
3976 The overall epilog code looks like this:
3978 s_out0 = phi <s_loop> # original EXIT_PHI
3979 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
3980 v_out2 = reduce <v_out1> # step 1
3981 s_out3 = extract_field <v_out2, 0> # step 2
3982 s_out4 = adjust_result <s_out3> # step 3
3984 (step 3 is optional, and steps 1 and 2 may be combined).
3985 Lastly, the uses of s_out0 are replaced by s_out4. */
3988 /* 2.1 Create new loop-exit-phis to preserve loop-closed form:
3989 v_out1 = phi <VECT_DEF>
3990 Store them in NEW_PHIS. */
3992 exit_bb = single_exit (loop)->dest;
3993 prev_phi_info = NULL;
3994 new_phis.create (vect_defs.length ());
3995 FOR_EACH_VEC_ELT (vect_defs, i, def)
3997 for (j = 0; j < ncopies; j++)
3999 tree new_def = copy_ssa_name (def, NULL);
4000 phi = create_phi_node (new_def, exit_bb);
4001 set_vinfo_for_stmt (phi, new_stmt_vec_info (phi, loop_vinfo, NULL));
4002 if (j == 0)
4003 new_phis.quick_push (phi);
4004 else
4006 def = vect_get_vec_def_for_stmt_copy (dt, def);
4007 STMT_VINFO_RELATED_STMT (prev_phi_info) = phi;
4010 SET_PHI_ARG_DEF (phi, single_exit (loop)->dest_idx, def);
4011 prev_phi_info = vinfo_for_stmt (phi);
4015 /* The epilogue is created for the outer-loop, i.e., for the loop being
4016 vectorized. Create exit phis for the outer loop. */
4017 if (double_reduc)
4019 loop = outer_loop;
4020 exit_bb = single_exit (loop)->dest;
4021 inner_phis.create (vect_defs.length ());
4022 FOR_EACH_VEC_ELT (new_phis, i, phi)
4024 tree new_result = copy_ssa_name (PHI_RESULT (phi), NULL);
4025 gimple outer_phi = create_phi_node (new_result, exit_bb);
4026 SET_PHI_ARG_DEF (outer_phi, single_exit (loop)->dest_idx,
4027 PHI_RESULT (phi));
4028 set_vinfo_for_stmt (outer_phi, new_stmt_vec_info (outer_phi,
4029 loop_vinfo, NULL));
4030 inner_phis.quick_push (phi);
4031 new_phis[i] = outer_phi;
4032 prev_phi_info = vinfo_for_stmt (outer_phi);
4033 while (STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi)))
4035 phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi));
4036 new_result = copy_ssa_name (PHI_RESULT (phi), NULL);
4037 outer_phi = create_phi_node (new_result, exit_bb);
4038 SET_PHI_ARG_DEF (outer_phi, single_exit (loop)->dest_idx,
4039 PHI_RESULT (phi));
4040 set_vinfo_for_stmt (outer_phi, new_stmt_vec_info (outer_phi,
4041 loop_vinfo, NULL));
4042 STMT_VINFO_RELATED_STMT (prev_phi_info) = outer_phi;
4043 prev_phi_info = vinfo_for_stmt (outer_phi);
4048 exit_gsi = gsi_after_labels (exit_bb);
4050 /* 2.2 Get the relevant tree-code to use in the epilog for schemes 2,3
4051 (i.e. when reduc_code is not available) and in the final adjustment
4052 code (if needed). Also get the original scalar reduction variable as
4053 defined in the loop. In case STMT is a "pattern-stmt" (i.e. - it
4054 represents a reduction pattern), the tree-code and scalar-def are
4055 taken from the original stmt that the pattern-stmt (STMT) replaces.
4056 Otherwise (it is a regular reduction) - the tree-code and scalar-def
4057 are taken from STMT. */
4059 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
4060 if (!orig_stmt)
4062 /* Regular reduction */
4063 orig_stmt = stmt;
4065 else
4067 /* Reduction pattern */
4068 stmt_vec_info stmt_vinfo = vinfo_for_stmt (orig_stmt);
4069 gcc_assert (STMT_VINFO_IN_PATTERN_P (stmt_vinfo));
4070 gcc_assert (STMT_VINFO_RELATED_STMT (stmt_vinfo) == stmt);
4073 code = gimple_assign_rhs_code (orig_stmt);
4074 /* For MINUS_EXPR the initial vector is [init_val,0,...,0], therefore,
4075 partial results are added and not subtracted. */
4076 if (code == MINUS_EXPR)
4077 code = PLUS_EXPR;
4079 scalar_dest = gimple_assign_lhs (orig_stmt);
4080 scalar_type = TREE_TYPE (scalar_dest);
4081 scalar_results.create (group_size);
4082 new_scalar_dest = vect_create_destination_var (scalar_dest, NULL);
4083 bitsize = TYPE_SIZE (scalar_type);
4085 /* In case this is a reduction in an inner-loop while vectorizing an outer
4086 loop - we don't need to extract a single scalar result at the end of the
4087 inner-loop (unless it is double reduction, i.e., the use of reduction is
4088 outside the outer-loop). The final vector of partial results will be used
4089 in the vectorized outer-loop, or reduced to a scalar result at the end of
4090 the outer-loop. */
4091 if (nested_in_vect_loop && !double_reduc)
4092 goto vect_finalize_reduction;
4094 /* SLP reduction without reduction chain, e.g.,
4095 # a1 = phi <a2, a0>
4096 # b1 = phi <b2, b0>
4097 a2 = operation (a1)
4098 b2 = operation (b1) */
4099 slp_reduc = (slp_node && !GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)));
4101 /* In case of reduction chain, e.g.,
4102 # a1 = phi <a3, a0>
4103 a2 = operation (a1)
4104 a3 = operation (a2),
4106 we may end up with more than one vector result. Here we reduce them to
4107 one vector. */
4108 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
4110 tree first_vect = PHI_RESULT (new_phis[0]);
4111 tree tmp;
4112 gimple new_vec_stmt = NULL;
4114 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4115 for (k = 1; k < new_phis.length (); k++)
4117 gimple next_phi = new_phis[k];
4118 tree second_vect = PHI_RESULT (next_phi);
4120 tmp = build2 (code, vectype, first_vect, second_vect);
4121 new_vec_stmt = gimple_build_assign (vec_dest, tmp);
4122 first_vect = make_ssa_name (vec_dest, new_vec_stmt);
4123 gimple_assign_set_lhs (new_vec_stmt, first_vect);
4124 gsi_insert_before (&exit_gsi, new_vec_stmt, GSI_SAME_STMT);
4127 new_phi_result = first_vect;
4128 if (new_vec_stmt)
4130 new_phis.truncate (0);
4131 new_phis.safe_push (new_vec_stmt);
4134 else
4135 new_phi_result = PHI_RESULT (new_phis[0]);
4137 /* 2.3 Create the reduction code, using one of the three schemes described
4138 above. In SLP we simply need to extract all the elements from the
4139 vector (without reducing them), so we use scalar shifts. */
4140 if (reduc_code != ERROR_MARK && !slp_reduc)
4142 tree tmp;
4144 /*** Case 1: Create:
4145 v_out2 = reduc_expr <v_out1> */
4147 if (dump_enabled_p ())
4148 dump_printf_loc (MSG_NOTE, vect_location,
4149 "Reduce using direct vector reduction.\n");
4151 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4152 tmp = build1 (reduc_code, vectype, new_phi_result);
4153 epilog_stmt = gimple_build_assign (vec_dest, tmp);
4154 new_temp = make_ssa_name (vec_dest, epilog_stmt);
4155 gimple_assign_set_lhs (epilog_stmt, new_temp);
4156 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4158 extract_scalar_result = true;
4160 else
4162 enum tree_code shift_code = ERROR_MARK;
4163 bool have_whole_vector_shift = true;
4164 int bit_offset;
4165 int element_bitsize = tree_to_uhwi (bitsize);
4166 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
4167 tree vec_temp;
4169 if (optab_handler (vec_shr_optab, mode) != CODE_FOR_nothing)
4170 shift_code = VEC_RSHIFT_EXPR;
4171 else
4172 have_whole_vector_shift = false;
4174 /* Regardless of whether we have a whole vector shift, if we're
4175 emulating the operation via tree-vect-generic, we don't want
4176 to use it. Only the first round of the reduction is likely
4177 to still be profitable via emulation. */
4178 /* ??? It might be better to emit a reduction tree code here, so that
4179 tree-vect-generic can expand the first round via bit tricks. */
4180 if (!VECTOR_MODE_P (mode))
4181 have_whole_vector_shift = false;
4182 else
4184 optab optab = optab_for_tree_code (code, vectype, optab_default);
4185 if (optab_handler (optab, mode) == CODE_FOR_nothing)
4186 have_whole_vector_shift = false;
4189 if (have_whole_vector_shift && !slp_reduc)
4191 /*** Case 2: Create:
4192 for (offset = VS/2; offset >= element_size; offset/=2)
4194 Create: va' = vec_shift <va, offset>
4195 Create: va = vop <va, va'>
4196 } */
4198 if (dump_enabled_p ())
4199 dump_printf_loc (MSG_NOTE, vect_location,
4200 "Reduce using vector shifts\n");
4202 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4203 new_temp = new_phi_result;
4204 for (bit_offset = vec_size_in_bits/2;
4205 bit_offset >= element_bitsize;
4206 bit_offset /= 2)
4208 tree bitpos = size_int (bit_offset);
4210 epilog_stmt = gimple_build_assign_with_ops (shift_code,
4211 vec_dest, new_temp, bitpos);
4212 new_name = make_ssa_name (vec_dest, epilog_stmt);
4213 gimple_assign_set_lhs (epilog_stmt, new_name);
4214 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4216 epilog_stmt = gimple_build_assign_with_ops (code, vec_dest,
4217 new_name, new_temp);
4218 new_temp = make_ssa_name (vec_dest, epilog_stmt);
4219 gimple_assign_set_lhs (epilog_stmt, new_temp);
4220 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4223 extract_scalar_result = true;
4225 else
4227 tree rhs;
4229 /*** Case 3: Create:
4230 s = extract_field <v_out2, 0>
4231 for (offset = element_size;
4232 offset < vector_size;
4233 offset += element_size;)
4235 Create: s' = extract_field <v_out2, offset>
4236 Create: s = op <s, s'> // For non SLP cases
4237 } */
4239 if (dump_enabled_p ())
4240 dump_printf_loc (MSG_NOTE, vect_location,
4241 "Reduce using scalar code.\n");
4243 vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
4244 FOR_EACH_VEC_ELT (new_phis, i, new_phi)
4246 if (gimple_code (new_phi) == GIMPLE_PHI)
4247 vec_temp = PHI_RESULT (new_phi);
4248 else
4249 vec_temp = gimple_assign_lhs (new_phi);
4250 rhs = build3 (BIT_FIELD_REF, scalar_type, vec_temp, bitsize,
4251 bitsize_zero_node);
4252 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4253 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4254 gimple_assign_set_lhs (epilog_stmt, new_temp);
4255 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4257 /* In SLP we don't need to apply reduction operation, so we just
4258 collect s' values in SCALAR_RESULTS. */
4259 if (slp_reduc)
4260 scalar_results.safe_push (new_temp);
4262 for (bit_offset = element_bitsize;
4263 bit_offset < vec_size_in_bits;
4264 bit_offset += element_bitsize)
4266 tree bitpos = bitsize_int (bit_offset);
4267 tree rhs = build3 (BIT_FIELD_REF, scalar_type, vec_temp,
4268 bitsize, bitpos);
4270 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4271 new_name = make_ssa_name (new_scalar_dest, epilog_stmt);
4272 gimple_assign_set_lhs (epilog_stmt, new_name);
4273 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4275 if (slp_reduc)
4277 /* In SLP we don't need to apply reduction operation, so
4278 we just collect s' values in SCALAR_RESULTS. */
4279 new_temp = new_name;
4280 scalar_results.safe_push (new_name);
4282 else
4284 epilog_stmt = gimple_build_assign_with_ops (code,
4285 new_scalar_dest, new_name, new_temp);
4286 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4287 gimple_assign_set_lhs (epilog_stmt, new_temp);
4288 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4293 /* The only case where we need to reduce scalar results in SLP, is
4294 unrolling. If the size of SCALAR_RESULTS is greater than
4295 GROUP_SIZE, we reduce them combining elements modulo
4296 GROUP_SIZE. */
4297 if (slp_reduc)
4299 tree res, first_res, new_res;
4300 gimple new_stmt;
4302 /* Reduce multiple scalar results in case of SLP unrolling. */
4303 for (j = group_size; scalar_results.iterate (j, &res);
4304 j++)
4306 first_res = scalar_results[j % group_size];
4307 new_stmt = gimple_build_assign_with_ops (code,
4308 new_scalar_dest, first_res, res);
4309 new_res = make_ssa_name (new_scalar_dest, new_stmt);
4310 gimple_assign_set_lhs (new_stmt, new_res);
4311 gsi_insert_before (&exit_gsi, new_stmt, GSI_SAME_STMT);
4312 scalar_results[j % group_size] = new_res;
4315 else
4316 /* Not SLP - we have one scalar to keep in SCALAR_RESULTS. */
4317 scalar_results.safe_push (new_temp);
4319 extract_scalar_result = false;
4323 /* 2.4 Extract the final scalar result. Create:
4324 s_out3 = extract_field <v_out2, bitpos> */
4326 if (extract_scalar_result)
4328 tree rhs;
4330 if (dump_enabled_p ())
4331 dump_printf_loc (MSG_NOTE, vect_location,
4332 "extract scalar result\n");
4334 if (BYTES_BIG_ENDIAN)
4335 bitpos = size_binop (MULT_EXPR,
4336 bitsize_int (TYPE_VECTOR_SUBPARTS (vectype) - 1),
4337 TYPE_SIZE (scalar_type));
4338 else
4339 bitpos = bitsize_zero_node;
4341 rhs = build3 (BIT_FIELD_REF, scalar_type, new_temp, bitsize, bitpos);
4342 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4343 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4344 gimple_assign_set_lhs (epilog_stmt, new_temp);
4345 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4346 scalar_results.safe_push (new_temp);
4349 vect_finalize_reduction:
4351 if (double_reduc)
4352 loop = loop->inner;
4354 /* 2.5 Adjust the final result by the initial value of the reduction
4355 variable. (When such adjustment is not needed, then
4356 'adjustment_def' is zero). For example, if code is PLUS we create:
4357 new_temp = loop_exit_def + adjustment_def */
4359 if (adjustment_def)
4361 gcc_assert (!slp_reduc);
4362 if (nested_in_vect_loop)
4364 new_phi = new_phis[0];
4365 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) == VECTOR_TYPE);
4366 expr = build2 (code, vectype, PHI_RESULT (new_phi), adjustment_def);
4367 new_dest = vect_create_destination_var (scalar_dest, vectype);
4369 else
4371 new_temp = scalar_results[0];
4372 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) != VECTOR_TYPE);
4373 expr = build2 (code, scalar_type, new_temp, adjustment_def);
4374 new_dest = vect_create_destination_var (scalar_dest, scalar_type);
4377 epilog_stmt = gimple_build_assign (new_dest, expr);
4378 new_temp = make_ssa_name (new_dest, epilog_stmt);
4379 gimple_assign_set_lhs (epilog_stmt, new_temp);
4380 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4381 if (nested_in_vect_loop)
4383 set_vinfo_for_stmt (epilog_stmt,
4384 new_stmt_vec_info (epilog_stmt, loop_vinfo,
4385 NULL));
4386 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (epilog_stmt)) =
4387 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (new_phi));
4389 if (!double_reduc)
4390 scalar_results.quick_push (new_temp);
4391 else
4392 scalar_results[0] = new_temp;
4394 else
4395 scalar_results[0] = new_temp;
4397 new_phis[0] = epilog_stmt;
4400 /* 2.6 Handle the loop-exit phis. Replace the uses of scalar loop-exit
4401 phis with new adjusted scalar results, i.e., replace use <s_out0>
4402 with use <s_out4>.
4404 Transform:
4405 loop_exit:
4406 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
4407 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
4408 v_out2 = reduce <v_out1>
4409 s_out3 = extract_field <v_out2, 0>
4410 s_out4 = adjust_result <s_out3>
4411 use <s_out0>
4412 use <s_out0>
4414 into:
4416 loop_exit:
4417 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
4418 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
4419 v_out2 = reduce <v_out1>
4420 s_out3 = extract_field <v_out2, 0>
4421 s_out4 = adjust_result <s_out3>
4422 use <s_out4>
4423 use <s_out4> */
4426 /* In SLP reduction chain we reduce vector results into one vector if
4427 necessary, hence we set here GROUP_SIZE to 1. SCALAR_DEST is the LHS of
4428 the last stmt in the reduction chain, since we are looking for the loop
4429 exit phi node. */
4430 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
4432 scalar_dest = gimple_assign_lhs (
4433 SLP_TREE_SCALAR_STMTS (slp_node)[group_size - 1]);
4434 group_size = 1;
4437 /* In SLP we may have several statements in NEW_PHIS and REDUCTION_PHIS (in
4438 case that GROUP_SIZE is greater than vectorization factor). Therefore, we
4439 need to match SCALAR_RESULTS with corresponding statements. The first
4440 (GROUP_SIZE / number of new vector stmts) scalar results correspond to
4441 the first vector stmt, etc.
4442 (RATIO is equal to (GROUP_SIZE / number of new vector stmts)). */
4443 if (group_size > new_phis.length ())
4445 ratio = group_size / new_phis.length ();
4446 gcc_assert (!(group_size % new_phis.length ()));
4448 else
4449 ratio = 1;
4451 for (k = 0; k < group_size; k++)
4453 if (k % ratio == 0)
4455 epilog_stmt = new_phis[k / ratio];
4456 reduction_phi = reduction_phis[k / ratio];
4457 if (double_reduc)
4458 inner_phi = inner_phis[k / ratio];
4461 if (slp_reduc)
4463 gimple current_stmt = SLP_TREE_SCALAR_STMTS (slp_node)[k];
4465 orig_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (current_stmt));
4466 /* SLP statements can't participate in patterns. */
4467 gcc_assert (!orig_stmt);
4468 scalar_dest = gimple_assign_lhs (current_stmt);
4471 phis.create (3);
4472 /* Find the loop-closed-use at the loop exit of the original scalar
4473 result. (The reduction result is expected to have two immediate uses -
4474 one at the latch block, and one at the loop exit). */
4475 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
4476 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p)))
4477 && !is_gimple_debug (USE_STMT (use_p)))
4478 phis.safe_push (USE_STMT (use_p));
4480 /* While we expect to have found an exit_phi because of loop-closed-ssa
4481 form we can end up without one if the scalar cycle is dead. */
4483 FOR_EACH_VEC_ELT (phis, i, exit_phi)
4485 if (outer_loop)
4487 stmt_vec_info exit_phi_vinfo = vinfo_for_stmt (exit_phi);
4488 gimple vect_phi;
4490 /* FORNOW. Currently not supporting the case that an inner-loop
4491 reduction is not used in the outer-loop (but only outside the
4492 outer-loop), unless it is double reduction. */
4493 gcc_assert ((STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
4494 && !STMT_VINFO_LIVE_P (exit_phi_vinfo))
4495 || double_reduc);
4497 STMT_VINFO_VEC_STMT (exit_phi_vinfo) = epilog_stmt;
4498 if (!double_reduc
4499 || STMT_VINFO_DEF_TYPE (exit_phi_vinfo)
4500 != vect_double_reduction_def)
4501 continue;
4503 /* Handle double reduction:
4505 stmt1: s1 = phi <s0, s2> - double reduction phi (outer loop)
4506 stmt2: s3 = phi <s1, s4> - (regular) reduc phi (inner loop)
4507 stmt3: s4 = use (s3) - (regular) reduc stmt (inner loop)
4508 stmt4: s2 = phi <s4> - double reduction stmt (outer loop)
4510 At that point the regular reduction (stmt2 and stmt3) is
4511 already vectorized, as well as the exit phi node, stmt4.
4512 Here we vectorize the phi node of double reduction, stmt1, and
4513 update all relevant statements. */
4515 /* Go through all the uses of s2 to find double reduction phi
4516 node, i.e., stmt1 above. */
4517 orig_name = PHI_RESULT (exit_phi);
4518 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
4520 stmt_vec_info use_stmt_vinfo;
4521 stmt_vec_info new_phi_vinfo;
4522 tree vect_phi_init, preheader_arg, vect_phi_res, init_def;
4523 basic_block bb = gimple_bb (use_stmt);
4524 gimple use;
4526 /* Check that USE_STMT is really double reduction phi
4527 node. */
4528 if (gimple_code (use_stmt) != GIMPLE_PHI
4529 || gimple_phi_num_args (use_stmt) != 2
4530 || bb->loop_father != outer_loop)
4531 continue;
4532 use_stmt_vinfo = vinfo_for_stmt (use_stmt);
4533 if (!use_stmt_vinfo
4534 || STMT_VINFO_DEF_TYPE (use_stmt_vinfo)
4535 != vect_double_reduction_def)
4536 continue;
4538 /* Create vector phi node for double reduction:
4539 vs1 = phi <vs0, vs2>
4540 vs1 was created previously in this function by a call to
4541 vect_get_vec_def_for_operand and is stored in
4542 vec_initial_def;
4543 vs2 is defined by INNER_PHI, the vectorized EXIT_PHI;
4544 vs0 is created here. */
4546 /* Create vector phi node. */
4547 vect_phi = create_phi_node (vec_initial_def, bb);
4548 new_phi_vinfo = new_stmt_vec_info (vect_phi,
4549 loop_vec_info_for_loop (outer_loop), NULL);
4550 set_vinfo_for_stmt (vect_phi, new_phi_vinfo);
4552 /* Create vs0 - initial def of the double reduction phi. */
4553 preheader_arg = PHI_ARG_DEF_FROM_EDGE (use_stmt,
4554 loop_preheader_edge (outer_loop));
4555 init_def = get_initial_def_for_reduction (stmt,
4556 preheader_arg, NULL);
4557 vect_phi_init = vect_init_vector (use_stmt, init_def,
4558 vectype, NULL);
4560 /* Update phi node arguments with vs0 and vs2. */
4561 add_phi_arg (vect_phi, vect_phi_init,
4562 loop_preheader_edge (outer_loop),
4563 UNKNOWN_LOCATION);
4564 add_phi_arg (vect_phi, PHI_RESULT (inner_phi),
4565 loop_latch_edge (outer_loop), UNKNOWN_LOCATION);
4566 if (dump_enabled_p ())
4568 dump_printf_loc (MSG_NOTE, vect_location,
4569 "created double reduction phi node: ");
4570 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, vect_phi, 0);
4571 dump_printf (MSG_NOTE, "\n");
4574 vect_phi_res = PHI_RESULT (vect_phi);
4576 /* Replace the use, i.e., set the correct vs1 in the regular
4577 reduction phi node. FORNOW, NCOPIES is always 1, so the
4578 loop is redundant. */
4579 use = reduction_phi;
4580 for (j = 0; j < ncopies; j++)
4582 edge pr_edge = loop_preheader_edge (loop);
4583 SET_PHI_ARG_DEF (use, pr_edge->dest_idx, vect_phi_res);
4584 use = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (use));
4590 phis.release ();
4591 if (nested_in_vect_loop)
4593 if (double_reduc)
4594 loop = outer_loop;
4595 else
4596 continue;
4599 phis.create (3);
4600 /* Find the loop-closed-use at the loop exit of the original scalar
4601 result. (The reduction result is expected to have two immediate uses,
4602 one at the latch block, and one at the loop exit). For double
4603 reductions we are looking for exit phis of the outer loop. */
4604 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
4606 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
4608 if (!is_gimple_debug (USE_STMT (use_p)))
4609 phis.safe_push (USE_STMT (use_p));
4611 else
4613 if (double_reduc && gimple_code (USE_STMT (use_p)) == GIMPLE_PHI)
4615 tree phi_res = PHI_RESULT (USE_STMT (use_p));
4617 FOR_EACH_IMM_USE_FAST (phi_use_p, phi_imm_iter, phi_res)
4619 if (!flow_bb_inside_loop_p (loop,
4620 gimple_bb (USE_STMT (phi_use_p)))
4621 && !is_gimple_debug (USE_STMT (phi_use_p)))
4622 phis.safe_push (USE_STMT (phi_use_p));
4628 FOR_EACH_VEC_ELT (phis, i, exit_phi)
4630 /* Replace the uses: */
4631 orig_name = PHI_RESULT (exit_phi);
4632 scalar_result = scalar_results[k];
4633 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
4634 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
4635 SET_USE (use_p, scalar_result);
4638 phis.release ();
4643 /* Function vectorizable_reduction.
4645 Check if STMT performs a reduction operation that can be vectorized.
4646 If VEC_STMT is also passed, vectorize the STMT: create a vectorized
4647 stmt to replace it, put it in VEC_STMT, and insert it at GSI.
4648 Return FALSE if not a vectorizable STMT, TRUE otherwise.
4650 This function also handles reduction idioms (patterns) that have been
4651 recognized in advance during vect_pattern_recog. In this case, STMT may be
4652 of this form:
4653 X = pattern_expr (arg0, arg1, ..., X)
4654 and it's STMT_VINFO_RELATED_STMT points to the last stmt in the original
4655 sequence that had been detected and replaced by the pattern-stmt (STMT).
4657 In some cases of reduction patterns, the type of the reduction variable X is
4658 different than the type of the other arguments of STMT.
4659 In such cases, the vectype that is used when transforming STMT into a vector
4660 stmt is different than the vectype that is used to determine the
4661 vectorization factor, because it consists of a different number of elements
4662 than the actual number of elements that are being operated upon in parallel.
4664 For example, consider an accumulation of shorts into an int accumulator.
4665 On some targets it's possible to vectorize this pattern operating on 8
4666 shorts at a time (hence, the vectype for purposes of determining the
4667 vectorization factor should be V8HI); on the other hand, the vectype that
4668 is used to create the vector form is actually V4SI (the type of the result).
4670 Upon entry to this function, STMT_VINFO_VECTYPE records the vectype that
4671 indicates what is the actual level of parallelism (V8HI in the example), so
4672 that the right vectorization factor would be derived. This vectype
4673 corresponds to the type of arguments to the reduction stmt, and should *NOT*
4674 be used to create the vectorized stmt. The right vectype for the vectorized
4675 stmt is obtained from the type of the result X:
4676 get_vectype_for_scalar_type (TREE_TYPE (X))
4678 This means that, contrary to "regular" reductions (or "regular" stmts in
4679 general), the following equation:
4680 STMT_VINFO_VECTYPE == get_vectype_for_scalar_type (TREE_TYPE (X))
4681 does *NOT* necessarily hold for reduction patterns. */
4683 bool
4684 vectorizable_reduction (gimple stmt, gimple_stmt_iterator *gsi,
4685 gimple *vec_stmt, slp_tree slp_node)
4687 tree vec_dest;
4688 tree scalar_dest;
4689 tree loop_vec_def0 = NULL_TREE, loop_vec_def1 = NULL_TREE;
4690 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
4691 tree vectype_out = STMT_VINFO_VECTYPE (stmt_info);
4692 tree vectype_in = NULL_TREE;
4693 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
4694 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
4695 enum tree_code code, orig_code, epilog_reduc_code;
4696 enum machine_mode vec_mode;
4697 int op_type;
4698 optab optab, reduc_optab;
4699 tree new_temp = NULL_TREE;
4700 tree def;
4701 gimple def_stmt;
4702 enum vect_def_type dt;
4703 gimple new_phi = NULL;
4704 tree scalar_type;
4705 bool is_simple_use;
4706 gimple orig_stmt;
4707 stmt_vec_info orig_stmt_info;
4708 tree expr = NULL_TREE;
4709 int i;
4710 int ncopies;
4711 int epilog_copies;
4712 stmt_vec_info prev_stmt_info, prev_phi_info;
4713 bool single_defuse_cycle = false;
4714 tree reduc_def = NULL_TREE;
4715 gimple new_stmt = NULL;
4716 int j;
4717 tree ops[3];
4718 bool nested_cycle = false, found_nested_cycle_def = false;
4719 gimple reduc_def_stmt = NULL;
4720 /* The default is that the reduction variable is the last in statement. */
4721 int reduc_index = 2;
4722 bool double_reduc = false, dummy;
4723 basic_block def_bb;
4724 struct loop * def_stmt_loop, *outer_loop = NULL;
4725 tree def_arg;
4726 gimple def_arg_stmt;
4727 auto_vec<tree> vec_oprnds0;
4728 auto_vec<tree> vec_oprnds1;
4729 auto_vec<tree> vect_defs;
4730 auto_vec<gimple> phis;
4731 int vec_num;
4732 tree def0, def1, tem, op0, op1 = NULL_TREE;
4734 /* In case of reduction chain we switch to the first stmt in the chain, but
4735 we don't update STMT_INFO, since only the last stmt is marked as reduction
4736 and has reduction properties. */
4737 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
4738 stmt = GROUP_FIRST_ELEMENT (stmt_info);
4740 if (nested_in_vect_loop_p (loop, stmt))
4742 outer_loop = loop;
4743 loop = loop->inner;
4744 nested_cycle = true;
4747 /* 1. Is vectorizable reduction? */
4748 /* Not supportable if the reduction variable is used in the loop, unless
4749 it's a reduction chain. */
4750 if (STMT_VINFO_RELEVANT (stmt_info) > vect_used_in_outer
4751 && !GROUP_FIRST_ELEMENT (stmt_info))
4752 return false;
4754 /* Reductions that are not used even in an enclosing outer-loop,
4755 are expected to be "live" (used out of the loop). */
4756 if (STMT_VINFO_RELEVANT (stmt_info) == vect_unused_in_scope
4757 && !STMT_VINFO_LIVE_P (stmt_info))
4758 return false;
4760 /* Make sure it was already recognized as a reduction computation. */
4761 if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_reduction_def
4762 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_nested_cycle)
4763 return false;
4765 /* 2. Has this been recognized as a reduction pattern?
4767 Check if STMT represents a pattern that has been recognized
4768 in earlier analysis stages. For stmts that represent a pattern,
4769 the STMT_VINFO_RELATED_STMT field records the last stmt in
4770 the original sequence that constitutes the pattern. */
4772 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
4773 if (orig_stmt)
4775 orig_stmt_info = vinfo_for_stmt (orig_stmt);
4776 gcc_assert (STMT_VINFO_IN_PATTERN_P (orig_stmt_info));
4777 gcc_assert (!STMT_VINFO_IN_PATTERN_P (stmt_info));
4780 /* 3. Check the operands of the operation. The first operands are defined
4781 inside the loop body. The last operand is the reduction variable,
4782 which is defined by the loop-header-phi. */
4784 gcc_assert (is_gimple_assign (stmt));
4786 /* Flatten RHS. */
4787 switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
4789 case GIMPLE_SINGLE_RHS:
4790 op_type = TREE_OPERAND_LENGTH (gimple_assign_rhs1 (stmt));
4791 if (op_type == ternary_op)
4793 tree rhs = gimple_assign_rhs1 (stmt);
4794 ops[0] = TREE_OPERAND (rhs, 0);
4795 ops[1] = TREE_OPERAND (rhs, 1);
4796 ops[2] = TREE_OPERAND (rhs, 2);
4797 code = TREE_CODE (rhs);
4799 else
4800 return false;
4801 break;
4803 case GIMPLE_BINARY_RHS:
4804 code = gimple_assign_rhs_code (stmt);
4805 op_type = TREE_CODE_LENGTH (code);
4806 gcc_assert (op_type == binary_op);
4807 ops[0] = gimple_assign_rhs1 (stmt);
4808 ops[1] = gimple_assign_rhs2 (stmt);
4809 break;
4811 case GIMPLE_TERNARY_RHS:
4812 code = gimple_assign_rhs_code (stmt);
4813 op_type = TREE_CODE_LENGTH (code);
4814 gcc_assert (op_type == ternary_op);
4815 ops[0] = gimple_assign_rhs1 (stmt);
4816 ops[1] = gimple_assign_rhs2 (stmt);
4817 ops[2] = gimple_assign_rhs3 (stmt);
4818 break;
4820 case GIMPLE_UNARY_RHS:
4821 return false;
4823 default:
4824 gcc_unreachable ();
4827 if (code == COND_EXPR && slp_node)
4828 return false;
4830 scalar_dest = gimple_assign_lhs (stmt);
4831 scalar_type = TREE_TYPE (scalar_dest);
4832 if (!POINTER_TYPE_P (scalar_type) && !INTEGRAL_TYPE_P (scalar_type)
4833 && !SCALAR_FLOAT_TYPE_P (scalar_type))
4834 return false;
4836 /* Do not try to vectorize bit-precision reductions. */
4837 if ((TYPE_PRECISION (scalar_type)
4838 != GET_MODE_PRECISION (TYPE_MODE (scalar_type))))
4839 return false;
4841 /* All uses but the last are expected to be defined in the loop.
4842 The last use is the reduction variable. In case of nested cycle this
4843 assumption is not true: we use reduc_index to record the index of the
4844 reduction variable. */
4845 for (i = 0; i < op_type - 1; i++)
4847 /* The condition of COND_EXPR is checked in vectorizable_condition(). */
4848 if (i == 0 && code == COND_EXPR)
4849 continue;
4851 is_simple_use = vect_is_simple_use_1 (ops[i], stmt, loop_vinfo, NULL,
4852 &def_stmt, &def, &dt, &tem);
4853 if (!vectype_in)
4854 vectype_in = tem;
4855 gcc_assert (is_simple_use);
4857 if (dt != vect_internal_def
4858 && dt != vect_external_def
4859 && dt != vect_constant_def
4860 && dt != vect_induction_def
4861 && !(dt == vect_nested_cycle && nested_cycle))
4862 return false;
4864 if (dt == vect_nested_cycle)
4866 found_nested_cycle_def = true;
4867 reduc_def_stmt = def_stmt;
4868 reduc_index = i;
4872 is_simple_use = vect_is_simple_use_1 (ops[i], stmt, loop_vinfo, NULL,
4873 &def_stmt, &def, &dt, &tem);
4874 if (!vectype_in)
4875 vectype_in = tem;
4876 gcc_assert (is_simple_use);
4877 if (!(dt == vect_reduction_def
4878 || dt == vect_nested_cycle
4879 || ((dt == vect_internal_def || dt == vect_external_def
4880 || dt == vect_constant_def || dt == vect_induction_def)
4881 && nested_cycle && found_nested_cycle_def)))
4883 /* For pattern recognized stmts, orig_stmt might be a reduction,
4884 but some helper statements for the pattern might not, or
4885 might be COND_EXPRs with reduction uses in the condition. */
4886 gcc_assert (orig_stmt);
4887 return false;
4889 if (!found_nested_cycle_def)
4890 reduc_def_stmt = def_stmt;
4892 gcc_assert (gimple_code (reduc_def_stmt) == GIMPLE_PHI);
4893 if (orig_stmt)
4894 gcc_assert (orig_stmt == vect_is_simple_reduction (loop_vinfo,
4895 reduc_def_stmt,
4896 !nested_cycle,
4897 &dummy));
4898 else
4900 gimple tmp = vect_is_simple_reduction (loop_vinfo, reduc_def_stmt,
4901 !nested_cycle, &dummy);
4902 /* We changed STMT to be the first stmt in reduction chain, hence we
4903 check that in this case the first element in the chain is STMT. */
4904 gcc_assert (stmt == tmp
4905 || GROUP_FIRST_ELEMENT (vinfo_for_stmt (tmp)) == stmt);
4908 if (STMT_VINFO_LIVE_P (vinfo_for_stmt (reduc_def_stmt)))
4909 return false;
4911 if (slp_node || PURE_SLP_STMT (stmt_info))
4912 ncopies = 1;
4913 else
4914 ncopies = (LOOP_VINFO_VECT_FACTOR (loop_vinfo)
4915 / TYPE_VECTOR_SUBPARTS (vectype_in));
4917 gcc_assert (ncopies >= 1);
4919 vec_mode = TYPE_MODE (vectype_in);
4921 if (code == COND_EXPR)
4923 if (!vectorizable_condition (stmt, gsi, NULL, ops[reduc_index], 0, NULL))
4925 if (dump_enabled_p ())
4926 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4927 "unsupported condition in reduction\n");
4929 return false;
4932 else
4934 /* 4. Supportable by target? */
4936 if (code == LSHIFT_EXPR || code == RSHIFT_EXPR
4937 || code == LROTATE_EXPR || code == RROTATE_EXPR)
4939 /* Shifts and rotates are only supported by vectorizable_shifts,
4940 not vectorizable_reduction. */
4941 if (dump_enabled_p ())
4942 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4943 "unsupported shift or rotation.\n");
4944 return false;
4947 /* 4.1. check support for the operation in the loop */
4948 optab = optab_for_tree_code (code, vectype_in, optab_default);
4949 if (!optab)
4951 if (dump_enabled_p ())
4952 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4953 "no optab.\n");
4955 return false;
4958 if (optab_handler (optab, vec_mode) == CODE_FOR_nothing)
4960 if (dump_enabled_p ())
4961 dump_printf (MSG_NOTE, "op not supported by target.\n");
4963 if (GET_MODE_SIZE (vec_mode) != UNITS_PER_WORD
4964 || LOOP_VINFO_VECT_FACTOR (loop_vinfo)
4965 < vect_min_worthwhile_factor (code))
4966 return false;
4968 if (dump_enabled_p ())
4969 dump_printf (MSG_NOTE, "proceeding using word mode.\n");
4972 /* Worthwhile without SIMD support? */
4973 if (!VECTOR_MODE_P (TYPE_MODE (vectype_in))
4974 && LOOP_VINFO_VECT_FACTOR (loop_vinfo)
4975 < vect_min_worthwhile_factor (code))
4977 if (dump_enabled_p ())
4978 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4979 "not worthwhile without SIMD support.\n");
4981 return false;
4985 /* 4.2. Check support for the epilog operation.
4987 If STMT represents a reduction pattern, then the type of the
4988 reduction variable may be different than the type of the rest
4989 of the arguments. For example, consider the case of accumulation
4990 of shorts into an int accumulator; The original code:
4991 S1: int_a = (int) short_a;
4992 orig_stmt-> S2: int_acc = plus <int_a ,int_acc>;
4994 was replaced with:
4995 STMT: int_acc = widen_sum <short_a, int_acc>
4997 This means that:
4998 1. The tree-code that is used to create the vector operation in the
4999 epilog code (that reduces the partial results) is not the
5000 tree-code of STMT, but is rather the tree-code of the original
5001 stmt from the pattern that STMT is replacing. I.e, in the example
5002 above we want to use 'widen_sum' in the loop, but 'plus' in the
5003 epilog.
5004 2. The type (mode) we use to check available target support
5005 for the vector operation to be created in the *epilog*, is
5006 determined by the type of the reduction variable (in the example
5007 above we'd check this: optab_handler (plus_optab, vect_int_mode])).
5008 However the type (mode) we use to check available target support
5009 for the vector operation to be created *inside the loop*, is
5010 determined by the type of the other arguments to STMT (in the
5011 example we'd check this: optab_handler (widen_sum_optab,
5012 vect_short_mode)).
5014 This is contrary to "regular" reductions, in which the types of all
5015 the arguments are the same as the type of the reduction variable.
5016 For "regular" reductions we can therefore use the same vector type
5017 (and also the same tree-code) when generating the epilog code and
5018 when generating the code inside the loop. */
5020 if (orig_stmt)
5022 /* This is a reduction pattern: get the vectype from the type of the
5023 reduction variable, and get the tree-code from orig_stmt. */
5024 orig_code = gimple_assign_rhs_code (orig_stmt);
5025 gcc_assert (vectype_out);
5026 vec_mode = TYPE_MODE (vectype_out);
5028 else
5030 /* Regular reduction: use the same vectype and tree-code as used for
5031 the vector code inside the loop can be used for the epilog code. */
5032 orig_code = code;
5035 if (nested_cycle)
5037 def_bb = gimple_bb (reduc_def_stmt);
5038 def_stmt_loop = def_bb->loop_father;
5039 def_arg = PHI_ARG_DEF_FROM_EDGE (reduc_def_stmt,
5040 loop_preheader_edge (def_stmt_loop));
5041 if (TREE_CODE (def_arg) == SSA_NAME
5042 && (def_arg_stmt = SSA_NAME_DEF_STMT (def_arg))
5043 && gimple_code (def_arg_stmt) == GIMPLE_PHI
5044 && flow_bb_inside_loop_p (outer_loop, gimple_bb (def_arg_stmt))
5045 && vinfo_for_stmt (def_arg_stmt)
5046 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_arg_stmt))
5047 == vect_double_reduction_def)
5048 double_reduc = true;
5051 epilog_reduc_code = ERROR_MARK;
5052 if (reduction_code_for_scalar_code (orig_code, &epilog_reduc_code))
5054 reduc_optab = optab_for_tree_code (epilog_reduc_code, vectype_out,
5055 optab_default);
5056 if (!reduc_optab)
5058 if (dump_enabled_p ())
5059 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5060 "no optab for reduction.\n");
5062 epilog_reduc_code = ERROR_MARK;
5065 if (reduc_optab
5066 && optab_handler (reduc_optab, vec_mode) == CODE_FOR_nothing)
5068 if (dump_enabled_p ())
5069 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5070 "reduc op not supported by target.\n");
5072 epilog_reduc_code = ERROR_MARK;
5075 else
5077 if (!nested_cycle || double_reduc)
5079 if (dump_enabled_p ())
5080 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5081 "no reduc code for scalar code.\n");
5083 return false;
5087 if (double_reduc && ncopies > 1)
5089 if (dump_enabled_p ())
5090 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5091 "multiple types in double reduction\n");
5093 return false;
5096 /* In case of widenning multiplication by a constant, we update the type
5097 of the constant to be the type of the other operand. We check that the
5098 constant fits the type in the pattern recognition pass. */
5099 if (code == DOT_PROD_EXPR
5100 && !types_compatible_p (TREE_TYPE (ops[0]), TREE_TYPE (ops[1])))
5102 if (TREE_CODE (ops[0]) == INTEGER_CST)
5103 ops[0] = fold_convert (TREE_TYPE (ops[1]), ops[0]);
5104 else if (TREE_CODE (ops[1]) == INTEGER_CST)
5105 ops[1] = fold_convert (TREE_TYPE (ops[0]), ops[1]);
5106 else
5108 if (dump_enabled_p ())
5109 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5110 "invalid types in dot-prod\n");
5112 return false;
5116 if (!vec_stmt) /* transformation not required. */
5118 if (!vect_model_reduction_cost (stmt_info, epilog_reduc_code, ncopies))
5119 return false;
5120 STMT_VINFO_TYPE (stmt_info) = reduc_vec_info_type;
5121 return true;
5124 /** Transform. **/
5126 if (dump_enabled_p ())
5127 dump_printf_loc (MSG_NOTE, vect_location, "transform reduction.\n");
5129 /* FORNOW: Multiple types are not supported for condition. */
5130 if (code == COND_EXPR)
5131 gcc_assert (ncopies == 1);
5133 /* Create the destination vector */
5134 vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
5136 /* In case the vectorization factor (VF) is bigger than the number
5137 of elements that we can fit in a vectype (nunits), we have to generate
5138 more than one vector stmt - i.e - we need to "unroll" the
5139 vector stmt by a factor VF/nunits. For more details see documentation
5140 in vectorizable_operation. */
5142 /* If the reduction is used in an outer loop we need to generate
5143 VF intermediate results, like so (e.g. for ncopies=2):
5144 r0 = phi (init, r0)
5145 r1 = phi (init, r1)
5146 r0 = x0 + r0;
5147 r1 = x1 + r1;
5148 (i.e. we generate VF results in 2 registers).
5149 In this case we have a separate def-use cycle for each copy, and therefore
5150 for each copy we get the vector def for the reduction variable from the
5151 respective phi node created for this copy.
5153 Otherwise (the reduction is unused in the loop nest), we can combine
5154 together intermediate results, like so (e.g. for ncopies=2):
5155 r = phi (init, r)
5156 r = x0 + r;
5157 r = x1 + r;
5158 (i.e. we generate VF/2 results in a single register).
5159 In this case for each copy we get the vector def for the reduction variable
5160 from the vectorized reduction operation generated in the previous iteration.
5163 if (STMT_VINFO_RELEVANT (stmt_info) == vect_unused_in_scope)
5165 single_defuse_cycle = true;
5166 epilog_copies = 1;
5168 else
5169 epilog_copies = ncopies;
5171 prev_stmt_info = NULL;
5172 prev_phi_info = NULL;
5173 if (slp_node)
5175 vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
5176 gcc_assert (TYPE_VECTOR_SUBPARTS (vectype_out)
5177 == TYPE_VECTOR_SUBPARTS (vectype_in));
5179 else
5181 vec_num = 1;
5182 vec_oprnds0.create (1);
5183 if (op_type == ternary_op)
5184 vec_oprnds1.create (1);
5187 phis.create (vec_num);
5188 vect_defs.create (vec_num);
5189 if (!slp_node)
5190 vect_defs.quick_push (NULL_TREE);
5192 for (j = 0; j < ncopies; j++)
5194 if (j == 0 || !single_defuse_cycle)
5196 for (i = 0; i < vec_num; i++)
5198 /* Create the reduction-phi that defines the reduction
5199 operand. */
5200 new_phi = create_phi_node (vec_dest, loop->header);
5201 set_vinfo_for_stmt (new_phi,
5202 new_stmt_vec_info (new_phi, loop_vinfo,
5203 NULL));
5204 if (j == 0 || slp_node)
5205 phis.quick_push (new_phi);
5209 if (code == COND_EXPR)
5211 gcc_assert (!slp_node);
5212 vectorizable_condition (stmt, gsi, vec_stmt,
5213 PHI_RESULT (phis[0]),
5214 reduc_index, NULL);
5215 /* Multiple types are not supported for condition. */
5216 break;
5219 /* Handle uses. */
5220 if (j == 0)
5222 op0 = ops[!reduc_index];
5223 if (op_type == ternary_op)
5225 if (reduc_index == 0)
5226 op1 = ops[2];
5227 else
5228 op1 = ops[1];
5231 if (slp_node)
5232 vect_get_vec_defs (op0, op1, stmt, &vec_oprnds0, &vec_oprnds1,
5233 slp_node, -1);
5234 else
5236 loop_vec_def0 = vect_get_vec_def_for_operand (ops[!reduc_index],
5237 stmt, NULL);
5238 vec_oprnds0.quick_push (loop_vec_def0);
5239 if (op_type == ternary_op)
5241 loop_vec_def1 = vect_get_vec_def_for_operand (op1, stmt,
5242 NULL);
5243 vec_oprnds1.quick_push (loop_vec_def1);
5247 else
5249 if (!slp_node)
5251 enum vect_def_type dt;
5252 gimple dummy_stmt;
5253 tree dummy;
5255 vect_is_simple_use (ops[!reduc_index], stmt, loop_vinfo, NULL,
5256 &dummy_stmt, &dummy, &dt);
5257 loop_vec_def0 = vect_get_vec_def_for_stmt_copy (dt,
5258 loop_vec_def0);
5259 vec_oprnds0[0] = loop_vec_def0;
5260 if (op_type == ternary_op)
5262 vect_is_simple_use (op1, stmt, loop_vinfo, NULL, &dummy_stmt,
5263 &dummy, &dt);
5264 loop_vec_def1 = vect_get_vec_def_for_stmt_copy (dt,
5265 loop_vec_def1);
5266 vec_oprnds1[0] = loop_vec_def1;
5270 if (single_defuse_cycle)
5271 reduc_def = gimple_assign_lhs (new_stmt);
5273 STMT_VINFO_RELATED_STMT (prev_phi_info) = new_phi;
5276 FOR_EACH_VEC_ELT (vec_oprnds0, i, def0)
5278 if (slp_node)
5279 reduc_def = PHI_RESULT (phis[i]);
5280 else
5282 if (!single_defuse_cycle || j == 0)
5283 reduc_def = PHI_RESULT (new_phi);
5286 def1 = ((op_type == ternary_op)
5287 ? vec_oprnds1[i] : NULL);
5288 if (op_type == binary_op)
5290 if (reduc_index == 0)
5291 expr = build2 (code, vectype_out, reduc_def, def0);
5292 else
5293 expr = build2 (code, vectype_out, def0, reduc_def);
5295 else
5297 if (reduc_index == 0)
5298 expr = build3 (code, vectype_out, reduc_def, def0, def1);
5299 else
5301 if (reduc_index == 1)
5302 expr = build3 (code, vectype_out, def0, reduc_def, def1);
5303 else
5304 expr = build3 (code, vectype_out, def0, def1, reduc_def);
5308 new_stmt = gimple_build_assign (vec_dest, expr);
5309 new_temp = make_ssa_name (vec_dest, new_stmt);
5310 gimple_assign_set_lhs (new_stmt, new_temp);
5311 vect_finish_stmt_generation (stmt, new_stmt, gsi);
5313 if (slp_node)
5315 SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt);
5316 vect_defs.quick_push (new_temp);
5318 else
5319 vect_defs[0] = new_temp;
5322 if (slp_node)
5323 continue;
5325 if (j == 0)
5326 STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt;
5327 else
5328 STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt;
5330 prev_stmt_info = vinfo_for_stmt (new_stmt);
5331 prev_phi_info = vinfo_for_stmt (new_phi);
5334 /* Finalize the reduction-phi (set its arguments) and create the
5335 epilog reduction code. */
5336 if ((!single_defuse_cycle || code == COND_EXPR) && !slp_node)
5338 new_temp = gimple_assign_lhs (*vec_stmt);
5339 vect_defs[0] = new_temp;
5342 vect_create_epilog_for_reduction (vect_defs, stmt, epilog_copies,
5343 epilog_reduc_code, phis, reduc_index,
5344 double_reduc, slp_node);
5346 return true;
5349 /* Function vect_min_worthwhile_factor.
5351 For a loop where we could vectorize the operation indicated by CODE,
5352 return the minimum vectorization factor that makes it worthwhile
5353 to use generic vectors. */
5355 vect_min_worthwhile_factor (enum tree_code code)
5357 switch (code)
5359 case PLUS_EXPR:
5360 case MINUS_EXPR:
5361 case NEGATE_EXPR:
5362 return 4;
5364 case BIT_AND_EXPR:
5365 case BIT_IOR_EXPR:
5366 case BIT_XOR_EXPR:
5367 case BIT_NOT_EXPR:
5368 return 2;
5370 default:
5371 return INT_MAX;
5376 /* Function vectorizable_induction
5378 Check if PHI performs an induction computation that can be vectorized.
5379 If VEC_STMT is also passed, vectorize the induction PHI: create a vectorized
5380 phi to replace it, put it in VEC_STMT, and add it to the same basic block.
5381 Return FALSE if not a vectorizable STMT, TRUE otherwise. */
5383 bool
5384 vectorizable_induction (gimple phi, gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
5385 gimple *vec_stmt)
5387 stmt_vec_info stmt_info = vinfo_for_stmt (phi);
5388 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
5389 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
5390 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
5391 int nunits = TYPE_VECTOR_SUBPARTS (vectype);
5392 int ncopies = LOOP_VINFO_VECT_FACTOR (loop_vinfo) / nunits;
5393 tree vec_def;
5395 gcc_assert (ncopies >= 1);
5396 /* FORNOW. These restrictions should be relaxed. */
5397 if (nested_in_vect_loop_p (loop, phi))
5399 imm_use_iterator imm_iter;
5400 use_operand_p use_p;
5401 gimple exit_phi;
5402 edge latch_e;
5403 tree loop_arg;
5405 if (ncopies > 1)
5407 if (dump_enabled_p ())
5408 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5409 "multiple types in nested loop.\n");
5410 return false;
5413 exit_phi = NULL;
5414 latch_e = loop_latch_edge (loop->inner);
5415 loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
5416 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
5418 gimple use_stmt = USE_STMT (use_p);
5419 if (is_gimple_debug (use_stmt))
5420 continue;
5422 if (!flow_bb_inside_loop_p (loop->inner, gimple_bb (use_stmt)))
5424 exit_phi = use_stmt;
5425 break;
5428 if (exit_phi)
5430 stmt_vec_info exit_phi_vinfo = vinfo_for_stmt (exit_phi);
5431 if (!(STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
5432 && !STMT_VINFO_LIVE_P (exit_phi_vinfo)))
5434 if (dump_enabled_p ())
5435 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5436 "inner-loop induction only used outside "
5437 "of the outer vectorized loop.\n");
5438 return false;
5443 if (!STMT_VINFO_RELEVANT_P (stmt_info))
5444 return false;
5446 /* FORNOW: SLP not supported. */
5447 if (STMT_SLP_TYPE (stmt_info))
5448 return false;
5450 gcc_assert (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def);
5452 if (gimple_code (phi) != GIMPLE_PHI)
5453 return false;
5455 if (!vec_stmt) /* transformation not required. */
5457 STMT_VINFO_TYPE (stmt_info) = induc_vec_info_type;
5458 if (dump_enabled_p ())
5459 dump_printf_loc (MSG_NOTE, vect_location,
5460 "=== vectorizable_induction ===\n");
5461 vect_model_induction_cost (stmt_info, ncopies);
5462 return true;
5465 /** Transform. **/
5467 if (dump_enabled_p ())
5468 dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
5470 vec_def = get_initial_def_for_induction (phi);
5471 *vec_stmt = SSA_NAME_DEF_STMT (vec_def);
5472 return true;
5475 /* Function vectorizable_live_operation.
5477 STMT computes a value that is used outside the loop. Check if
5478 it can be supported. */
5480 bool
5481 vectorizable_live_operation (gimple stmt,
5482 gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
5483 gimple *vec_stmt)
5485 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
5486 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
5487 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
5488 int i;
5489 int op_type;
5490 tree op;
5491 tree def;
5492 gimple def_stmt;
5493 enum vect_def_type dt;
5494 enum tree_code code;
5495 enum gimple_rhs_class rhs_class;
5497 gcc_assert (STMT_VINFO_LIVE_P (stmt_info));
5499 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def)
5500 return false;
5502 if (!is_gimple_assign (stmt))
5504 if (gimple_call_internal_p (stmt)
5505 && gimple_call_internal_fn (stmt) == IFN_GOMP_SIMD_LANE
5506 && gimple_call_lhs (stmt)
5507 && loop->simduid
5508 && TREE_CODE (gimple_call_arg (stmt, 0)) == SSA_NAME
5509 && loop->simduid
5510 == SSA_NAME_VAR (gimple_call_arg (stmt, 0)))
5512 edge e = single_exit (loop);
5513 basic_block merge_bb = e->dest;
5514 imm_use_iterator imm_iter;
5515 use_operand_p use_p;
5516 tree lhs = gimple_call_lhs (stmt);
5518 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
5520 gimple use_stmt = USE_STMT (use_p);
5521 if (gimple_code (use_stmt) == GIMPLE_PHI
5522 && gimple_bb (use_stmt) == merge_bb)
5524 if (vec_stmt)
5526 tree vfm1
5527 = build_int_cst (unsigned_type_node,
5528 loop_vinfo->vectorization_factor - 1);
5529 SET_PHI_ARG_DEF (use_stmt, e->dest_idx, vfm1);
5531 return true;
5536 return false;
5539 if (TREE_CODE (gimple_assign_lhs (stmt)) != SSA_NAME)
5540 return false;
5542 /* FORNOW. CHECKME. */
5543 if (nested_in_vect_loop_p (loop, stmt))
5544 return false;
5546 code = gimple_assign_rhs_code (stmt);
5547 op_type = TREE_CODE_LENGTH (code);
5548 rhs_class = get_gimple_rhs_class (code);
5549 gcc_assert (rhs_class != GIMPLE_UNARY_RHS || op_type == unary_op);
5550 gcc_assert (rhs_class != GIMPLE_BINARY_RHS || op_type == binary_op);
5552 /* FORNOW: support only if all uses are invariant. This means
5553 that the scalar operations can remain in place, unvectorized.
5554 The original last scalar value that they compute will be used. */
5556 for (i = 0; i < op_type; i++)
5558 if (rhs_class == GIMPLE_SINGLE_RHS)
5559 op = TREE_OPERAND (gimple_op (stmt, 1), i);
5560 else
5561 op = gimple_op (stmt, i + 1);
5562 if (op
5563 && !vect_is_simple_use (op, stmt, loop_vinfo, NULL, &def_stmt, &def,
5564 &dt))
5566 if (dump_enabled_p ())
5567 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5568 "use not simple.\n");
5569 return false;
5572 if (dt != vect_external_def && dt != vect_constant_def)
5573 return false;
5576 /* No transformation is required for the cases we currently support. */
5577 return true;
5580 /* Kill any debug uses outside LOOP of SSA names defined in STMT. */
5582 static void
5583 vect_loop_kill_debug_uses (struct loop *loop, gimple stmt)
5585 ssa_op_iter op_iter;
5586 imm_use_iterator imm_iter;
5587 def_operand_p def_p;
5588 gimple ustmt;
5590 FOR_EACH_PHI_OR_STMT_DEF (def_p, stmt, op_iter, SSA_OP_DEF)
5592 FOR_EACH_IMM_USE_STMT (ustmt, imm_iter, DEF_FROM_PTR (def_p))
5594 basic_block bb;
5596 if (!is_gimple_debug (ustmt))
5597 continue;
5599 bb = gimple_bb (ustmt);
5601 if (!flow_bb_inside_loop_p (loop, bb))
5603 if (gimple_debug_bind_p (ustmt))
5605 if (dump_enabled_p ())
5606 dump_printf_loc (MSG_NOTE, vect_location,
5607 "killing debug use\n");
5609 gimple_debug_bind_reset_value (ustmt);
5610 update_stmt (ustmt);
5612 else
5613 gcc_unreachable ();
5620 /* This function builds ni_name = number of iterations. Statements
5621 are emitted on the loop preheader edge. */
5623 static tree
5624 vect_build_loop_niters (loop_vec_info loop_vinfo)
5626 tree ni = unshare_expr (LOOP_VINFO_NITERS (loop_vinfo));
5627 if (TREE_CODE (ni) == INTEGER_CST)
5628 return ni;
5629 else
5631 tree ni_name, var;
5632 gimple_seq stmts = NULL;
5633 edge pe = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
5635 var = create_tmp_var (TREE_TYPE (ni), "niters");
5636 ni_name = force_gimple_operand (ni, &stmts, false, var);
5637 if (stmts)
5638 gsi_insert_seq_on_edge_immediate (pe, stmts);
5640 return ni_name;
5645 /* This function generates the following statements:
5647 ni_name = number of iterations loop executes
5648 ratio = ni_name / vf
5649 ratio_mult_vf_name = ratio * vf
5651 and places them on the loop preheader edge. */
5653 static void
5654 vect_generate_tmps_on_preheader (loop_vec_info loop_vinfo,
5655 tree ni_name,
5656 tree *ratio_mult_vf_name_ptr,
5657 tree *ratio_name_ptr)
5659 tree ni_minus_gap_name;
5660 tree var;
5661 tree ratio_name;
5662 tree ratio_mult_vf_name;
5663 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
5664 edge pe = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
5665 tree log_vf;
5667 log_vf = build_int_cst (TREE_TYPE (ni_name), exact_log2 (vf));
5669 /* If epilogue loop is required because of data accesses with gaps, we
5670 subtract one iteration from the total number of iterations here for
5671 correct calculation of RATIO. */
5672 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
5674 ni_minus_gap_name = fold_build2 (MINUS_EXPR, TREE_TYPE (ni_name),
5675 ni_name,
5676 build_one_cst (TREE_TYPE (ni_name)));
5677 if (!is_gimple_val (ni_minus_gap_name))
5679 var = create_tmp_var (TREE_TYPE (ni_name), "ni_gap");
5680 gimple stmts = NULL;
5681 ni_minus_gap_name = force_gimple_operand (ni_minus_gap_name, &stmts,
5682 true, var);
5683 gsi_insert_seq_on_edge_immediate (pe, stmts);
5686 else
5687 ni_minus_gap_name = ni_name;
5689 /* Create: ratio = ni >> log2(vf) */
5690 /* ??? As we have ni == number of latch executions + 1, ni could
5691 have overflown to zero. So avoid computing ratio based on ni
5692 but compute it using the fact that we know ratio will be at least
5693 one, thus via (ni - vf) >> log2(vf) + 1. */
5694 ratio_name
5695 = fold_build2 (PLUS_EXPR, TREE_TYPE (ni_name),
5696 fold_build2 (RSHIFT_EXPR, TREE_TYPE (ni_name),
5697 fold_build2 (MINUS_EXPR, TREE_TYPE (ni_name),
5698 ni_minus_gap_name,
5699 build_int_cst
5700 (TREE_TYPE (ni_name), vf)),
5701 log_vf),
5702 build_int_cst (TREE_TYPE (ni_name), 1));
5703 if (!is_gimple_val (ratio_name))
5705 var = create_tmp_var (TREE_TYPE (ni_name), "bnd");
5706 gimple stmts = NULL;
5707 ratio_name = force_gimple_operand (ratio_name, &stmts, true, var);
5708 gsi_insert_seq_on_edge_immediate (pe, stmts);
5710 *ratio_name_ptr = ratio_name;
5712 /* Create: ratio_mult_vf = ratio << log2 (vf). */
5714 if (ratio_mult_vf_name_ptr)
5716 ratio_mult_vf_name = fold_build2 (LSHIFT_EXPR, TREE_TYPE (ratio_name),
5717 ratio_name, log_vf);
5718 if (!is_gimple_val (ratio_mult_vf_name))
5720 var = create_tmp_var (TREE_TYPE (ni_name), "ratio_mult_vf");
5721 gimple stmts = NULL;
5722 ratio_mult_vf_name = force_gimple_operand (ratio_mult_vf_name, &stmts,
5723 true, var);
5724 gsi_insert_seq_on_edge_immediate (pe, stmts);
5726 *ratio_mult_vf_name_ptr = ratio_mult_vf_name;
5729 return;
5733 /* Function vect_transform_loop.
5735 The analysis phase has determined that the loop is vectorizable.
5736 Vectorize the loop - created vectorized stmts to replace the scalar
5737 stmts in the loop, and update the loop exit condition. */
5739 void
5740 vect_transform_loop (loop_vec_info loop_vinfo)
5742 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
5743 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
5744 int nbbs = loop->num_nodes;
5745 gimple_stmt_iterator si;
5746 int i;
5747 tree ratio = NULL;
5748 int vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
5749 bool grouped_store;
5750 bool slp_scheduled = false;
5751 gimple stmt, pattern_stmt;
5752 gimple_seq pattern_def_seq = NULL;
5753 gimple_stmt_iterator pattern_def_si = gsi_none ();
5754 bool transform_pattern_stmt = false;
5755 bool check_profitability = false;
5756 int th;
5757 /* Record number of iterations before we started tampering with the profile. */
5758 gcov_type expected_iterations = expected_loop_iterations_unbounded (loop);
5760 if (dump_enabled_p ())
5761 dump_printf_loc (MSG_NOTE, vect_location, "=== vec_transform_loop ===\n");
5763 /* If profile is inprecise, we have chance to fix it up. */
5764 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
5765 expected_iterations = LOOP_VINFO_INT_NITERS (loop_vinfo);
5767 /* Use the more conservative vectorization threshold. If the number
5768 of iterations is constant assume the cost check has been performed
5769 by our caller. If the threshold makes all loops profitable that
5770 run at least the vectorization factor number of times checking
5771 is pointless, too. */
5772 th = ((PARAM_VALUE (PARAM_MIN_VECT_LOOP_BOUND)
5773 * LOOP_VINFO_VECT_FACTOR (loop_vinfo)) - 1);
5774 th = MAX (th, LOOP_VINFO_COST_MODEL_MIN_ITERS (loop_vinfo));
5775 if (th >= LOOP_VINFO_VECT_FACTOR (loop_vinfo) - 1
5776 && !LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
5778 if (dump_enabled_p ())
5779 dump_printf_loc (MSG_NOTE, vect_location,
5780 "Profitability threshold is %d loop iterations.\n",
5781 th);
5782 check_profitability = true;
5785 /* Version the loop first, if required, so the profitability check
5786 comes first. */
5788 if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo)
5789 || LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
5791 vect_loop_versioning (loop_vinfo, th, check_profitability);
5792 check_profitability = false;
5795 tree ni_name = vect_build_loop_niters (loop_vinfo);
5796 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = ni_name;
5798 /* Peel the loop if there are data refs with unknown alignment.
5799 Only one data ref with unknown store is allowed. */
5801 if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo))
5803 vect_do_peeling_for_alignment (loop_vinfo, ni_name,
5804 th, check_profitability);
5805 check_profitability = false;
5806 /* The above adjusts LOOP_VINFO_NITERS, so cause ni_name to
5807 be re-computed. */
5808 ni_name = NULL_TREE;
5811 /* If the loop has a symbolic number of iterations 'n' (i.e. it's not a
5812 compile time constant), or it is a constant that doesn't divide by the
5813 vectorization factor, then an epilog loop needs to be created.
5814 We therefore duplicate the loop: the original loop will be vectorized,
5815 and will compute the first (n/VF) iterations. The second copy of the loop
5816 will remain scalar and will compute the remaining (n%VF) iterations.
5817 (VF is the vectorization factor). */
5819 if (LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
5820 || LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
5822 tree ratio_mult_vf;
5823 if (!ni_name)
5824 ni_name = vect_build_loop_niters (loop_vinfo);
5825 vect_generate_tmps_on_preheader (loop_vinfo, ni_name, &ratio_mult_vf,
5826 &ratio);
5827 vect_do_peeling_for_loop_bound (loop_vinfo, ni_name, ratio_mult_vf,
5828 th, check_profitability);
5830 else if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
5831 ratio = build_int_cst (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)),
5832 LOOP_VINFO_INT_NITERS (loop_vinfo) / vectorization_factor);
5833 else
5835 if (!ni_name)
5836 ni_name = vect_build_loop_niters (loop_vinfo);
5837 vect_generate_tmps_on_preheader (loop_vinfo, ni_name, NULL, &ratio);
5840 /* 1) Make sure the loop header has exactly two entries
5841 2) Make sure we have a preheader basic block. */
5843 gcc_assert (EDGE_COUNT (loop->header->preds) == 2);
5845 split_edge (loop_preheader_edge (loop));
5847 /* FORNOW: the vectorizer supports only loops which body consist
5848 of one basic block (header + empty latch). When the vectorizer will
5849 support more involved loop forms, the order by which the BBs are
5850 traversed need to be reconsidered. */
5852 for (i = 0; i < nbbs; i++)
5854 basic_block bb = bbs[i];
5855 stmt_vec_info stmt_info;
5856 gimple phi;
5858 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
5860 phi = gsi_stmt (si);
5861 if (dump_enabled_p ())
5863 dump_printf_loc (MSG_NOTE, vect_location,
5864 "------>vectorizing phi: ");
5865 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
5866 dump_printf (MSG_NOTE, "\n");
5868 stmt_info = vinfo_for_stmt (phi);
5869 if (!stmt_info)
5870 continue;
5872 if (MAY_HAVE_DEBUG_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
5873 vect_loop_kill_debug_uses (loop, phi);
5875 if (!STMT_VINFO_RELEVANT_P (stmt_info)
5876 && !STMT_VINFO_LIVE_P (stmt_info))
5877 continue;
5879 if (STMT_VINFO_VECTYPE (stmt_info)
5880 && (TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info))
5881 != (unsigned HOST_WIDE_INT) vectorization_factor)
5882 && dump_enabled_p ())
5883 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
5885 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def)
5887 if (dump_enabled_p ())
5888 dump_printf_loc (MSG_NOTE, vect_location, "transform phi.\n");
5889 vect_transform_stmt (phi, NULL, NULL, NULL, NULL);
5893 pattern_stmt = NULL;
5894 for (si = gsi_start_bb (bb); !gsi_end_p (si) || transform_pattern_stmt;)
5896 bool is_store;
5898 if (transform_pattern_stmt)
5899 stmt = pattern_stmt;
5900 else
5902 stmt = gsi_stmt (si);
5903 /* During vectorization remove existing clobber stmts. */
5904 if (gimple_clobber_p (stmt))
5906 unlink_stmt_vdef (stmt);
5907 gsi_remove (&si, true);
5908 release_defs (stmt);
5909 continue;
5913 if (dump_enabled_p ())
5915 dump_printf_loc (MSG_NOTE, vect_location,
5916 "------>vectorizing statement: ");
5917 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
5918 dump_printf (MSG_NOTE, "\n");
5921 stmt_info = vinfo_for_stmt (stmt);
5923 /* vector stmts created in the outer-loop during vectorization of
5924 stmts in an inner-loop may not have a stmt_info, and do not
5925 need to be vectorized. */
5926 if (!stmt_info)
5928 gsi_next (&si);
5929 continue;
5932 if (MAY_HAVE_DEBUG_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
5933 vect_loop_kill_debug_uses (loop, stmt);
5935 if (!STMT_VINFO_RELEVANT_P (stmt_info)
5936 && !STMT_VINFO_LIVE_P (stmt_info))
5938 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
5939 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
5940 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
5941 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
5943 stmt = pattern_stmt;
5944 stmt_info = vinfo_for_stmt (stmt);
5946 else
5948 gsi_next (&si);
5949 continue;
5952 else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
5953 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
5954 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
5955 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
5956 transform_pattern_stmt = true;
5958 /* If pattern statement has def stmts, vectorize them too. */
5959 if (is_pattern_stmt_p (stmt_info))
5961 if (pattern_def_seq == NULL)
5963 pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
5964 pattern_def_si = gsi_start (pattern_def_seq);
5966 else if (!gsi_end_p (pattern_def_si))
5967 gsi_next (&pattern_def_si);
5968 if (pattern_def_seq != NULL)
5970 gimple pattern_def_stmt = NULL;
5971 stmt_vec_info pattern_def_stmt_info = NULL;
5973 while (!gsi_end_p (pattern_def_si))
5975 pattern_def_stmt = gsi_stmt (pattern_def_si);
5976 pattern_def_stmt_info
5977 = vinfo_for_stmt (pattern_def_stmt);
5978 if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
5979 || STMT_VINFO_LIVE_P (pattern_def_stmt_info))
5980 break;
5981 gsi_next (&pattern_def_si);
5984 if (!gsi_end_p (pattern_def_si))
5986 if (dump_enabled_p ())
5988 dump_printf_loc (MSG_NOTE, vect_location,
5989 "==> vectorizing pattern def "
5990 "stmt: ");
5991 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
5992 pattern_def_stmt, 0);
5993 dump_printf (MSG_NOTE, "\n");
5996 stmt = pattern_def_stmt;
5997 stmt_info = pattern_def_stmt_info;
5999 else
6001 pattern_def_si = gsi_none ();
6002 transform_pattern_stmt = false;
6005 else
6006 transform_pattern_stmt = false;
6009 if (STMT_VINFO_VECTYPE (stmt_info))
6011 unsigned int nunits
6012 = (unsigned int)
6013 TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info));
6014 if (!STMT_SLP_TYPE (stmt_info)
6015 && nunits != (unsigned int) vectorization_factor
6016 && dump_enabled_p ())
6017 /* For SLP VF is set according to unrolling factor, and not
6018 to vector size, hence for SLP this print is not valid. */
6019 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
6022 /* SLP. Schedule all the SLP instances when the first SLP stmt is
6023 reached. */
6024 if (STMT_SLP_TYPE (stmt_info))
6026 if (!slp_scheduled)
6028 slp_scheduled = true;
6030 if (dump_enabled_p ())
6031 dump_printf_loc (MSG_NOTE, vect_location,
6032 "=== scheduling SLP instances ===\n");
6034 vect_schedule_slp (loop_vinfo, NULL);
6037 /* Hybrid SLP stmts must be vectorized in addition to SLP. */
6038 if (!vinfo_for_stmt (stmt) || PURE_SLP_STMT (stmt_info))
6040 if (!transform_pattern_stmt && gsi_end_p (pattern_def_si))
6042 pattern_def_seq = NULL;
6043 gsi_next (&si);
6045 continue;
6049 /* -------- vectorize statement ------------ */
6050 if (dump_enabled_p ())
6051 dump_printf_loc (MSG_NOTE, vect_location, "transform statement.\n");
6053 grouped_store = false;
6054 is_store = vect_transform_stmt (stmt, &si, &grouped_store, NULL, NULL);
6055 if (is_store)
6057 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
6059 /* Interleaving. If IS_STORE is TRUE, the vectorization of the
6060 interleaving chain was completed - free all the stores in
6061 the chain. */
6062 gsi_next (&si);
6063 vect_remove_stores (GROUP_FIRST_ELEMENT (stmt_info));
6065 else
6067 /* Free the attached stmt_vec_info and remove the stmt. */
6068 gimple store = gsi_stmt (si);
6069 free_stmt_vec_info (store);
6070 unlink_stmt_vdef (store);
6071 gsi_remove (&si, true);
6072 release_defs (store);
6075 /* Stores can only appear at the end of pattern statements. */
6076 gcc_assert (!transform_pattern_stmt);
6077 pattern_def_seq = NULL;
6079 else if (!transform_pattern_stmt && gsi_end_p (pattern_def_si))
6081 pattern_def_seq = NULL;
6082 gsi_next (&si);
6084 } /* stmts in BB */
6085 } /* BBs in loop */
6087 slpeel_make_loop_iterate_ntimes (loop, ratio);
6089 /* Reduce loop iterations by the vectorization factor. */
6090 scale_loop_profile (loop, GCOV_COMPUTE_SCALE (1, vectorization_factor),
6091 expected_iterations / vectorization_factor);
6092 loop->nb_iterations_upper_bound
6093 = loop->nb_iterations_upper_bound.udiv (double_int::from_uhwi (vectorization_factor),
6094 FLOOR_DIV_EXPR);
6095 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
6096 && loop->nb_iterations_upper_bound != double_int_zero)
6097 loop->nb_iterations_upper_bound = loop->nb_iterations_upper_bound - double_int_one;
6098 if (loop->any_estimate)
6100 loop->nb_iterations_estimate
6101 = loop->nb_iterations_estimate.udiv (double_int::from_uhwi (vectorization_factor),
6102 FLOOR_DIV_EXPR);
6103 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
6104 && loop->nb_iterations_estimate != double_int_zero)
6105 loop->nb_iterations_estimate = loop->nb_iterations_estimate - double_int_one;
6108 if (dump_enabled_p ())
6110 dump_printf_loc (MSG_NOTE, vect_location,
6111 "LOOP VECTORIZED\n");
6112 if (loop->inner)
6113 dump_printf_loc (MSG_NOTE, vect_location,
6114 "OUTER LOOP VECTORIZED\n");
6115 dump_printf (MSG_NOTE, "\n");