Debian Codegraph @

gcc/tree-vect-data-refs.cc

raw
1 /* Data References Analysis and Manipulation Utilities for Vectorization.
2 Copyright (C) 2003-2025 Free Software Foundation, Inc.
3 Contributed by Dorit Naishlos <[email protected]>
4 and Ira Rosen <[email protected]>
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
21
22 #define INCLUDE_ALGORITHM
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "backend.h"
27 #include "target.h"
28 #include "rtl.h"
29 #include "tree.h"
30 #include "gimple.h"
31 #include "predict.h"
32 #include "memmodel.h"
33 #include "tm_p.h"
34 #include "ssa.h"
35 #include "optabs-tree.h"
36 #include "cgraph.h"
37 #include "dumpfile.h"
38 #include "pretty-print.h"
39 #include "alias.h"
40 #include "fold-const.h"
41 #include "stor-layout.h"
42 #include "tree-eh.h"
43 #include "gimplify.h"
44 #include "gimple-iterator.h"
45 #include "gimplify-me.h"
46 #include "tree-ssa-loop-ivopts.h"
47 #include "tree-ssa-loop-manip.h"
48 #include "tree-ssa-loop.h"
49 #include "cfgloop.h"
50 #include "tree-scalar-evolution.h"
51 #include "tree-vectorizer.h"
52 #include "expr.h"
53 #include "builtins.h"
54 #include "tree-cfg.h"
55 #include "tree-hash-traits.h"
56 #include "vec-perm-indices.h"
57 #include "internal-fn.h"
58 #include "gimple-fold.h"
59 #include "optabs-query.h"
60
61 /* Return true if load- or store-lanes optab OPTAB is implemented for
62 COUNT vectors of type VECTYPE. NAME is the name of OPTAB.
63
64 If it is implemented and ELSVALS is nonzero store the possible else
65 values in the vector it points to. */
66
67 static bool
68 vect_lanes_optab_supported_p (const char *name, convert_optab optab,
69 tree vectype, unsigned HOST_WIDE_INT count,
70 vec<int> *elsvals = nullptr)
71 {
72 machine_mode mode, array_mode;
73 bool limit_p;
74
75 mode = TYPE_MODE (vectype);
76 if (!targetm.array_mode (mode, count).exists (&array_mode))
77 {
78 poly_uint64 bits = count * GET_MODE_BITSIZE (mode);
79 limit_p = !targetm.array_mode_supported_p (mode, count);
80 if (!int_mode_for_size (bits, limit_p).exists (&array_mode))
81 {
82 if (dump_enabled_p ())
83 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
84 "no array mode for %s[%wu]\n",
85 GET_MODE_NAME (mode), count);
86 return false;
87 }
88 }
89
90 enum insn_code icode;
91 if ((icode = convert_optab_handler (optab, array_mode, mode))
92 == CODE_FOR_nothing)
93 {
94 if (dump_enabled_p ())
95 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
96 "cannot use %s<%s><%s>\n", name,
97 GET_MODE_NAME (array_mode), GET_MODE_NAME (mode));
98 return false;
99 }
100
101 if (dump_enabled_p ())
102 dump_printf_loc (MSG_NOTE, vect_location,
103 "can use %s<%s><%s>\n", name, GET_MODE_NAME (array_mode),
104 GET_MODE_NAME (mode));
105
106 if (elsvals)
107 get_supported_else_vals (icode,
108 internal_fn_else_index (IFN_MASK_LEN_LOAD_LANES),
109 *elsvals);
110
111 return true;
112 }
113
114 /* Helper function to identify a simd clone call. If this is a call to a
115 function with simd clones then return the corresponding cgraph_node,
116 otherwise return NULL. */
117
118 static cgraph_node*
119 simd_clone_call_p (gimple *stmt)
120 {
121 gcall *call = dyn_cast <gcall *> (stmt);
122 if (!call)
123 return NULL;
124
125 tree fndecl = NULL_TREE;
126 if (gimple_call_internal_p (call, IFN_MASK_CALL))
127 fndecl = TREE_OPERAND (gimple_call_arg (stmt, 0), 0);
128 else
129 fndecl = gimple_call_fndecl (stmt);
130
131 if (fndecl == NULL_TREE)
132 return NULL;
133
134 cgraph_node *node = cgraph_node::get (fndecl);
135 if (node && node->simd_clones != NULL)
136 return node;
137
138 return NULL;
139 }
140
141
142
143 /* Return the smallest scalar part of STMT_INFO.
144 This is used to determine the vectype of the stmt. We generally set the
145 vectype according to the type of the result (lhs). For stmts whose
146 result-type is different than the type of the arguments (e.g., demotion,
147 promotion), vectype will be reset appropriately (later). Note that we have
148 to visit the smallest datatype in this function, because that determines the
149 VF. If the smallest datatype in the loop is present only as the rhs of a
150 promotion operation - we'd miss it.
151 Such a case, where a variable of this datatype does not appear in the lhs
152 anywhere in the loop, can only occur if it's an invariant: e.g.:
153 'int_x = (int) short_inv', which we'd expect to have been optimized away by
154 invariant motion. However, we cannot rely on invariant motion to always
155 take invariants out of the loop, and so in the case of promotion we also
156 have to check the rhs.
157 LHS_SIZE_UNIT and RHS_SIZE_UNIT contain the sizes of the corresponding
158 types. */
159
160 tree
161 vect_get_smallest_scalar_type (stmt_vec_info stmt_info, tree scalar_type)
162 {
163 HOST_WIDE_INT lhs, rhs;
164
165 /* During the analysis phase, this function is called on arbitrary
166 statements that might not have scalar results. */
167 if (!tree_fits_uhwi_p (TYPE_SIZE_UNIT (scalar_type)))
168 return scalar_type;
169
170 lhs = rhs = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (scalar_type));
171
172 gassign *assign = dyn_cast <gassign *> (stmt_info->stmt);
173 if (assign)
174 {
175 scalar_type = TREE_TYPE (gimple_assign_lhs (assign));
176 if (gimple_assign_cast_p (assign)
177 || gimple_assign_rhs_code (assign) == DOT_PROD_EXPR
178 || gimple_assign_rhs_code (assign) == WIDEN_SUM_EXPR
179 || gimple_assign_rhs_code (assign) == SAD_EXPR
180 || gimple_assign_rhs_code (assign) == WIDEN_MULT_EXPR
181 || gimple_assign_rhs_code (assign) == WIDEN_MULT_PLUS_EXPR
182 || gimple_assign_rhs_code (assign) == WIDEN_MULT_MINUS_EXPR
183 || gimple_assign_rhs_code (assign) == WIDEN_LSHIFT_EXPR
184 || gimple_assign_rhs_code (assign) == FLOAT_EXPR)
185 {
186 tree rhs_type = TREE_TYPE (gimple_assign_rhs1 (assign));
187
188 rhs = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (rhs_type));
189 if (rhs < lhs)
190 scalar_type = rhs_type;
191 }
192 }
193 else if (cgraph_node *node = simd_clone_call_p (stmt_info->stmt))
194 {
195 auto clone = node->simd_clones->simdclone;
196 for (unsigned int i = 0; i < clone->nargs; ++i)
197 {
198 if (clone->args[i].arg_type == SIMD_CLONE_ARG_TYPE_VECTOR)
199 {
200 tree arg_scalar_type = TREE_TYPE (clone->args[i].vector_type);
201 rhs = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (arg_scalar_type));
202 if (rhs < lhs)
203 {
204 scalar_type = arg_scalar_type;
205 lhs = rhs;
206 }
207 }
208 }
209 }
210 else if (gcall *call = dyn_cast <gcall *> (stmt_info->stmt))
211 {
212 unsigned int i = 0;
213 if (gimple_call_internal_p (call))
214 {
215 internal_fn ifn = gimple_call_internal_fn (call);
216 if (internal_load_fn_p (ifn))
217 /* For loads the LHS type does the trick. */
218 i = ~0U;
219 else if (internal_store_fn_p (ifn))
220 {
221 /* For stores use the tyep of the stored value. */
222 i = internal_fn_stored_value_index (ifn);
223 scalar_type = TREE_TYPE (gimple_call_arg (call, i));
224 i = ~0U;
225 }
226 else if (internal_fn_mask_index (ifn) == 0)
227 i = 1;
228 }
229 if (i < gimple_call_num_args (call))
230 {
231 tree rhs_type = TREE_TYPE (gimple_call_arg (call, i));
232 if (tree_fits_uhwi_p (TYPE_SIZE_UNIT (rhs_type)))
233 {
234 rhs = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (rhs_type));
235 if (rhs < lhs)
236 scalar_type = rhs_type;
237 }
238 }
239 }
240
241 return scalar_type;
242 }
243
244
245 /* Insert DDR into LOOP_VINFO list of ddrs that may alias and need to be
246 tested at run-time. Return TRUE if DDR was successfully inserted.
247 Return false if versioning is not supported. */
248
249 static opt_result
250 vect_mark_for_runtime_alias_test (ddr_p ddr, loop_vec_info loop_vinfo)
251 {
252 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
253
254 if ((unsigned) param_vect_max_version_for_alias_checks == 0)
255 return opt_result::failure_at (vect_location,
256 "will not create alias checks, as"
257 " --param vect-max-version-for-alias-checks"
258 " == 0\n");
259
260 opt_result res
261 = runtime_alias_check_p (ddr, loop,
262 optimize_loop_nest_for_speed_p (loop));
263 if (!res)
264 return res;
265
266 LOOP_VINFO_MAY_ALIAS_DDRS (loop_vinfo).safe_push (ddr);
267 return opt_result::success ();
268 }
269
270 /* Record that loop LOOP_VINFO needs to check that VALUE is nonzero. */
271
272 static void
273 vect_check_nonzero_value (loop_vec_info loop_vinfo, tree value)
274 {
275 const vec<tree> &checks = LOOP_VINFO_CHECK_NONZERO (loop_vinfo);
276 for (unsigned int i = 0; i < checks.length(); ++i)
277 if (checks[i] == value)
278 return;
279
280 if (dump_enabled_p ())
281 dump_printf_loc (MSG_NOTE, vect_location,
282 "need run-time check that %T is nonzero\n",
283 value);
284 LOOP_VINFO_CHECK_NONZERO (loop_vinfo).safe_push (value);
285 }
286
287 /* Return true if we know that the order of vectorized DR_INFO_A and
288 vectorized DR_INFO_B will be the same as the order of DR_INFO_A and
289 DR_INFO_B. At least one of the accesses is a write. */
290
291 static bool
292 vect_preserves_scalar_order_p (dr_vec_info *dr_info_a, dr_vec_info *dr_info_b)
293 {
294 stmt_vec_info stmtinfo_a = dr_info_a->stmt;
295 stmt_vec_info stmtinfo_b = dr_info_b->stmt;
296
297 /* Single statements are always kept in their original order. */
298 if (!STMT_VINFO_GROUPED_ACCESS (stmtinfo_a)
299 && !STMT_VINFO_GROUPED_ACCESS (stmtinfo_b))
300 return true;
301
302 /* If there is a loop invariant read involved we might vectorize it in
303 the prologue, breaking scalar oder with respect to the in-loop store. */
304 if ((DR_IS_READ (dr_info_a->dr) && integer_zerop (DR_STEP (dr_info_a->dr)))
305 || (DR_IS_READ (dr_info_b->dr) && integer_zerop (DR_STEP (dr_info_b->dr))))
306 return false;
307
308 /* STMT_A and STMT_B belong to overlapping groups. All loads are
309 emitted at the position of the first scalar load.
310 Stores in a group are emitted at the position of the last scalar store.
311 Compute that position and check whether the resulting order matches
312 the current one. */
313 stmt_vec_info il_a = DR_GROUP_FIRST_ELEMENT (stmtinfo_a);
314 if (il_a)
315 {
316 if (DR_IS_WRITE (STMT_VINFO_DATA_REF (stmtinfo_a)))
317 for (stmt_vec_info s = DR_GROUP_NEXT_ELEMENT (il_a); s;
318 s = DR_GROUP_NEXT_ELEMENT (s))
319 il_a = get_later_stmt (il_a, s);
320 else /* DR_IS_READ */
321 for (stmt_vec_info s = DR_GROUP_NEXT_ELEMENT (il_a); s;
322 s = DR_GROUP_NEXT_ELEMENT (s))
323 if (get_later_stmt (il_a, s) == il_a)
324 il_a = s;
325 }
326 else
327 il_a = stmtinfo_a;
328 stmt_vec_info il_b = DR_GROUP_FIRST_ELEMENT (stmtinfo_b);
329 if (il_b)
330 {
331 if (DR_IS_WRITE (STMT_VINFO_DATA_REF (stmtinfo_b)))
332 for (stmt_vec_info s = DR_GROUP_NEXT_ELEMENT (il_b); s;
333 s = DR_GROUP_NEXT_ELEMENT (s))
334 il_b = get_later_stmt (il_b, s);
335 else /* DR_IS_READ */
336 for (stmt_vec_info s = DR_GROUP_NEXT_ELEMENT (il_b); s;
337 s = DR_GROUP_NEXT_ELEMENT (s))
338 if (get_later_stmt (il_b, s) == il_b)
339 il_b = s;
340 }
341 else
342 il_b = stmtinfo_b;
343 bool a_after_b = (get_later_stmt (stmtinfo_a, stmtinfo_b) == stmtinfo_a);
344 return (get_later_stmt (il_a, il_b) == il_a) == a_after_b;
345 }
346
347 /* A subroutine of vect_analyze_data_ref_dependence. Handle
348 DDR_COULD_BE_INDEPENDENT_P ddr DDR that has a known set of dependence
349 distances. These distances are conservatively correct but they don't
350 reflect a guaranteed dependence.
351
352 Return true if this function does all the work necessary to avoid
353 an alias or false if the caller should use the dependence distances
354 to limit the vectorization factor in the usual way. LOOP_DEPTH is
355 the depth of the loop described by LOOP_VINFO and the other arguments
356 are as for vect_analyze_data_ref_dependence. */
357
358 static bool
359 vect_analyze_possibly_independent_ddr (data_dependence_relation *ddr,
360 loop_vec_info loop_vinfo,
361 int loop_depth, unsigned int *max_vf)
362 {
363 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
364 for (lambda_vector &dist_v : DDR_DIST_VECTS (ddr))
365 {
366 int dist = dist_v[loop_depth];
367 if (dist != 0 && !(dist > 0 && DDR_REVERSED_P (ddr)))
368 {
369 /* If the user asserted safelen >= DIST consecutive iterations
370 can be executed concurrently, assume independence.
371
372 ??? An alternative would be to add the alias check even
373 in this case, and vectorize the fallback loop with the
374 maximum VF set to safelen. However, if the user has
375 explicitly given a length, it's less likely that that
376 would be a win. */
377 if (loop->safelen >= 2 && abs_hwi (dist) <= loop->safelen)
378 {
379 if ((unsigned int) loop->safelen < *max_vf)
380 *max_vf = loop->safelen;
381 LOOP_VINFO_NO_DATA_DEPENDENCIES (loop_vinfo) = false;
382 continue;
383 }
384
385 /* For dependence distances of 2 or more, we have the option
386 of limiting VF or checking for an alias at runtime.
387 Prefer to check at runtime if we can, to avoid limiting
388 the VF unnecessarily when the bases are in fact independent.
389
390 Note that the alias checks will be removed if the VF ends up
391 being small enough. */
392 dr_vec_info *dr_info_a = loop_vinfo->lookup_dr (DDR_A (ddr));
393 dr_vec_info *dr_info_b = loop_vinfo->lookup_dr (DDR_B (ddr));
394 return (!STMT_VINFO_GATHER_SCATTER_P (dr_info_a->stmt)
395 && !STMT_VINFO_GATHER_SCATTER_P (dr_info_b->stmt)
396 && vect_mark_for_runtime_alias_test (ddr, loop_vinfo));
397 }
398 }
399 return true;
400 }
401
402
403 /* Function vect_analyze_data_ref_dependence.
404
405 FIXME: I needed to change the sense of the returned flag.
406
407 Return FALSE if there (might) exist a dependence between a memory-reference
408 DRA and a memory-reference DRB. When versioning for alias may check a
409 dependence at run-time, return TRUE. Adjust *MAX_VF according to
410 the data dependence. */
411
412 static opt_result
413 vect_analyze_data_ref_dependence (struct data_dependence_relation *ddr,
414 loop_vec_info loop_vinfo,
415 unsigned int *max_vf)
416 {
417 unsigned int i;
418 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
419 struct data_reference *dra = DDR_A (ddr);
420 struct data_reference *drb = DDR_B (ddr);
421 dr_vec_info *dr_info_a = loop_vinfo->lookup_dr (dra);
422 dr_vec_info *dr_info_b = loop_vinfo->lookup_dr (drb);
423 stmt_vec_info stmtinfo_a = dr_info_a->stmt;
424 stmt_vec_info stmtinfo_b = dr_info_b->stmt;
425 lambda_vector dist_v;
426 unsigned int loop_depth;
427
428 /* If user asserted safelen consecutive iterations can be
429 executed concurrently, assume independence. */
430 auto apply_safelen = [&]()
431 {
432 if (loop->safelen >= 2)
433 {
434 if ((unsigned int) loop->safelen < *max_vf)
435 *max_vf = loop->safelen;
436 LOOP_VINFO_NO_DATA_DEPENDENCIES (loop_vinfo) = false;
437 return true;
438 }
439 return false;
440 };
441
442 /* In loop analysis all data references should be vectorizable. */
443 if (!STMT_VINFO_VECTORIZABLE (stmtinfo_a)
444 || !STMT_VINFO_VECTORIZABLE (stmtinfo_b))
445 gcc_unreachable ();
446
447 /* Independent data accesses. */
448 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
449 return opt_result::success ();
450
451 if (dra == drb
452 || (DR_IS_READ (dra) && DR_IS_READ (drb)))
453 return opt_result::success ();
454
455 /* We do not have to consider dependences between accesses that belong
456 to the same group, unless the stride could be smaller than the
457 group size. */
458 if (DR_GROUP_FIRST_ELEMENT (stmtinfo_a)
459 && (DR_GROUP_FIRST_ELEMENT (stmtinfo_a)
460 == DR_GROUP_FIRST_ELEMENT (stmtinfo_b))
461 && !STMT_VINFO_STRIDED_P (stmtinfo_a))
462 return opt_result::success ();
463
464 /* Even if we have an anti-dependence then, as the vectorized loop covers at
465 least two scalar iterations, there is always also a true dependence.
466 As the vectorizer does not re-order loads and stores we can ignore
467 the anti-dependence if TBAA can disambiguate both DRs similar to the
468 case with known negative distance anti-dependences (positive
469 distance anti-dependences would violate TBAA constraints). */
470 if (((DR_IS_READ (dra) && DR_IS_WRITE (drb))
471 || (DR_IS_WRITE (dra) && DR_IS_READ (drb)))
472 && !alias_sets_conflict_p (get_alias_set (DR_REF (dra)),
473 get_alias_set (DR_REF (drb))))
474 return opt_result::success ();
475
476 if (STMT_VINFO_GATHER_SCATTER_P (stmtinfo_a)
477 || STMT_VINFO_GATHER_SCATTER_P (stmtinfo_b))
478 {
479 if (apply_safelen ())
480 return opt_result::success ();
481
482 return opt_result::failure_at
483 (stmtinfo_a->stmt,
484 "possible alias involving gather/scatter between %T and %T\n",
485 DR_REF (dra), DR_REF (drb));
486 }
487
488 /* Unknown data dependence. */
489 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
490 {
491 if (apply_safelen ())
492 return opt_result::success ();
493
494 if (dump_enabled_p ())
495 dump_printf_loc (MSG_MISSED_OPTIMIZATION, stmtinfo_a->stmt,
496 "versioning for alias required: "
497 "can't determine dependence between %T and %T\n",
498 DR_REF (dra), DR_REF (drb));
499
500 /* Add to list of ddrs that need to be tested at run-time. */
501 return vect_mark_for_runtime_alias_test (ddr, loop_vinfo);
502 }
503
504 /* Known data dependence. */
505 if (DDR_NUM_DIST_VECTS (ddr) == 0)
506 {
507 if (apply_safelen ())
508 return opt_result::success ();
509
510 if (dump_enabled_p ())
511 dump_printf_loc (MSG_MISSED_OPTIMIZATION, stmtinfo_a->stmt,
512 "versioning for alias required: "
513 "bad dist vector for %T and %T\n",
514 DR_REF (dra), DR_REF (drb));
515 /* Add to list of ddrs that need to be tested at run-time. */
516 return vect_mark_for_runtime_alias_test (ddr, loop_vinfo);
517 }
518
519 loop_depth = index_in_loop_nest (loop->num, DDR_LOOP_NEST (ddr));
520
521 if (DDR_COULD_BE_INDEPENDENT_P (ddr)
522 && vect_analyze_possibly_independent_ddr (ddr, loop_vinfo,
523 loop_depth, max_vf))
524 return opt_result::success ();
525
526 FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr), i, dist_v)
527 {
528 int dist = dist_v[loop_depth];
529
530 if (dump_enabled_p ())
531 dump_printf_loc (MSG_NOTE, vect_location,
532 "dependence distance = %d.\n", dist);
533
534 if (dist == 0)
535 {
536 if (dump_enabled_p ())
537 dump_printf_loc (MSG_NOTE, vect_location,
538 "dependence distance == 0 between %T and %T\n",
539 DR_REF (dra), DR_REF (drb));
540
541 /* When we perform grouped accesses and perform implicit CSE
542 by detecting equal accesses and doing disambiguation with
543 runtime alias tests like for
544 .. = a[i];
545 .. = a[i+1];
546 a[i] = ..;
547 a[i+1] = ..;
548 *p = ..;
549 .. = a[i];
550 .. = a[i+1];
551 where we will end up loading { a[i], a[i+1] } once, make
552 sure that inserting group loads before the first load and
553 stores after the last store will do the right thing.
554 Similar for groups like
555 a[i] = ...;
556 ... = a[i];
557 a[i+1] = ...;
558 where loads from the group interleave with the store. */
559 if (!vect_preserves_scalar_order_p (dr_info_a, dr_info_b))
560 return opt_result::failure_at (stmtinfo_a->stmt,
561 "READ_WRITE dependence"
562 " in interleaving.\n");
563
564 if (loop->safelen < 2)
565 {
566 tree indicator = dr_zero_step_indicator (dra);
567 if (!indicator || integer_zerop (indicator))
568 return opt_result::failure_at (stmtinfo_a->stmt,
569 "access also has a zero step\n");
570 else if (TREE_CODE (indicator) != INTEGER_CST)
571 vect_check_nonzero_value (loop_vinfo, indicator);
572 }
573 continue;
574 }
575
576 if (dist > 0 && DDR_REVERSED_P (ddr))
577 {
578 /* If DDR_REVERSED_P the order of the data-refs in DDR was
579 reversed (to make distance vector positive), and the actual
580 distance is negative. */
581 if (dump_enabled_p ())
582 dump_printf_loc (MSG_NOTE, vect_location,
583 "dependence distance negative.\n");
584 /* When doing outer loop vectorization, we need to check if there is
585 a backward dependence at the inner loop level if the dependence
586 at the outer loop is reversed. See PR81740. */
587 if (nested_in_vect_loop_p (loop, stmtinfo_a)
588 || nested_in_vect_loop_p (loop, stmtinfo_b))
589 {
590 unsigned inner_depth = index_in_loop_nest (loop->inner->num,
591 DDR_LOOP_NEST (ddr));
592 if (dist_v[inner_depth] < 0)
593 return opt_result::failure_at (stmtinfo_a->stmt,
594 "not vectorized, dependence "
595 "between data-refs %T and %T\n",
596 DR_REF (dra), DR_REF (drb));
597 }
598 /* Record a negative dependence distance to later limit the
599 amount of stmt copying / unrolling we can perform.
600 Only need to handle read-after-write dependence. */
601 if (DR_IS_READ (drb)
602 && (STMT_VINFO_MIN_NEG_DIST (stmtinfo_b) == 0
603 || STMT_VINFO_MIN_NEG_DIST (stmtinfo_b) > (unsigned)dist))
604 STMT_VINFO_MIN_NEG_DIST (stmtinfo_b) = dist;
605 continue;
606 }
607
608 unsigned int abs_dist = abs (dist);
609 if (abs_dist >= 2 && abs_dist < *max_vf)
610 {
611 /* The dependence distance requires reduction of the maximal
612 vectorization factor. */
613 *max_vf = abs_dist;
614 if (dump_enabled_p ())
615 dump_printf_loc (MSG_NOTE, vect_location,
616 "adjusting maximal vectorization factor to %i\n",
617 *max_vf);
618 }
619
620 if (abs_dist >= *max_vf)
621 {
622 /* Dependence distance does not create dependence, as far as
623 vectorization is concerned, in this case. */
624 if (dump_enabled_p ())
625 dump_printf_loc (MSG_NOTE, vect_location,
626 "dependence distance >= VF.\n");
627 continue;
628 }
629
630 return opt_result::failure_at (stmtinfo_a->stmt,
631 "not vectorized, possible dependence "
632 "between data-refs %T and %T\n",
633 DR_REF (dra), DR_REF (drb));
634 }
635
636 return opt_result::success ();
637 }
638
639 /* Function vect_analyze_early_break_dependences.
640
641 Examine all the data references in the loop and make sure that if we have
642 multiple exits that we are able to safely move stores such that they become
643 safe for vectorization. The function also calculates the place where to move
644 the instructions to and computes what the new vUSE chain should be.
645
646 This works in tandem with the CFG that will be produced by
647 slpeel_tree_duplicate_loop_to_edge_cfg later on.
648
649 This function tries to validate whether an early break vectorization
650 is possible for the current instruction sequence. Returns True i
651 possible, otherwise False.
652
653 Requirements:
654 - Any memory access must be to a fixed size buffer.
655 - There must not be any loads and stores to the same object.
656 - Multiple loads are allowed as long as they don't alias.
657
658 NOTE:
659 This implementation is very conservative. Any overlapping loads/stores
660 that take place before the early break statement gets rejected aside from
661 WAR dependencies.
662
663 i.e.:
664
665 a[i] = 8
666 c = a[i]
667 if (b[i])
668 ...
669
670 is not allowed, but
671
672 c = a[i]
673 a[i] = 8
674 if (b[i])
675 ...
676
677 is which is the common case. */
678
679 static opt_result
680 vect_analyze_early_break_dependences (loop_vec_info loop_vinfo)
681 {
682 DUMP_VECT_SCOPE ("vect_analyze_early_break_dependences");
683
684 /* List of all load data references found during traversal. */
685 auto_vec<data_reference *> bases;
686 basic_block dest_bb = NULL;
687
688 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
689 class loop *loop_nest = loop_outer (loop);
690
691 if (dump_enabled_p ())
692 dump_printf_loc (MSG_NOTE, vect_location,
693 "loop contains multiple exits, analyzing"
694 " statement dependencies.\n");
695
696 if (LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
697 if (dump_enabled_p ())
698 dump_printf_loc (MSG_NOTE, vect_location,
699 "alternate exit has been chosen as main exit.\n");
700
701 /* Since we don't support general control flow, the location we'll move the
702 side-effects to is always the latch connected exit. When we support
703 general control flow we can do better but for now this is fine. Move
704 side-effects to the in-loop destination of the last early exit. For the
705 PEELED case we move the side-effects to the latch block as this is
706 guaranteed to be the last block to be executed when a vector iteration
707 finished. */
708 if (LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
709 dest_bb = loop->latch;
710 else
711 dest_bb = single_pred (loop->latch);
712
713 /* We start looking from dest_bb, for the non-PEELED case we don't want to
714 move any stores already present, but we do want to read and validate the
715 loads. */
716 basic_block bb = dest_bb;
717
718 /* We move stores across all loads to the beginning of dest_bb, so
719 the first block processed below doesn't need dependence checking. */
720 bool check_deps = false;
721
722 do
723 {
724 gimple_stmt_iterator gsi = gsi_last_bb (bb);
725
726 /* Now analyze all the remaining statements and try to determine which
727 instructions are allowed/needed to be moved. */
728 while (!gsi_end_p (gsi))
729 {
730 gimple *stmt = gsi_stmt (gsi);
731 gsi_prev (&gsi);
732 if (is_gimple_debug (stmt))
733 continue;
734
735 stmt_vec_info stmt_vinfo
736 = vect_stmt_to_vectorize (loop_vinfo->lookup_stmt (stmt));
737 auto dr_ref = STMT_VINFO_DATA_REF (stmt_vinfo);
738 if (!dr_ref)
739 continue;
740
741 /* We know everything below dest_bb is safe since we know we
742 had a full vector iteration when reaching it. Either by
743 the loop entry / IV exit test being last or because this
744 is the loop latch itself. */
745 if (!check_deps)
746 continue;
747
748 /* Check if vector accesses to the object will be within bounds.
749 must be a constant or assume loop will be versioned or niters
750 bounded by VF so accesses are within range. We only need to check
751 the reads since writes are moved to a safe place where if we get
752 there we know they are safe to perform. */
753 if (DR_IS_READ (dr_ref))
754 {
755 dr_set_safe_speculative_read_required (stmt_vinfo, true);
756 bool inbounds = ref_within_array_bound (stmt, DR_REF (dr_ref));
757 DR_SCALAR_KNOWN_BOUNDS (STMT_VINFO_DR_INFO (stmt_vinfo)) = inbounds;
758
759 if (dump_enabled_p ())
760 dump_printf_loc (MSG_NOTE, vect_location,
761 "marking DR (read) as possibly needing peeling "
762 "for alignment at %G", stmt);
763 }
764
765 if (DR_IS_READ (dr_ref))
766 bases.safe_push (dr_ref);
767 else if (DR_IS_WRITE (dr_ref))
768 {
769 /* We are moving writes down in the CFG. To be sure that this
770 is valid after vectorization we have to check all the loads
771 we are sinking the stores past to see if any of them may
772 alias or are the same object.
773
774 Same objects will not be an issue because unless the store
775 is marked volatile the value can be forwarded. If the
776 store is marked volatile we don't vectorize the loop
777 anyway.
778
779 That leaves the check for aliasing. We don't really need
780 to care about the stores aliasing with each other since the
781 stores are moved in order so the effects are still observed
782 correctly. This leaves the check for WAR dependencies
783 which we would be introducing here if the DR can alias.
784 The check is quadratic in loads/stores but I have not found
785 a better API to do this. I believe all loads and stores
786 must be checked. We also must check them when we
787 encountered the store, since we don't care about loads past
788 the store. */
789
790 for (auto dr_read : bases)
791 if (dr_may_alias_p (dr_ref, dr_read, loop_nest))
792 {
793 if (dump_enabled_p ())
794 dump_printf_loc (MSG_MISSED_OPTIMIZATION,
795 vect_location,
796 "early breaks not supported: "
797 "overlapping loads and stores "
798 "found before the break "
799 "statement.\n");
800
801 return opt_result::failure_at (stmt,
802 "can't safely apply code motion to dependencies"
803 " to vectorize the early exit. %G may alias with"
804 " %G\n", stmt, dr_read->stmt);
805 }
806 }
807
808 if (gimple_vdef (stmt))
809 {
810 if (dump_enabled_p ())
811 dump_printf_loc (MSG_NOTE, vect_location,
812 "==> recording stmt %G", stmt);
813
814 LOOP_VINFO_EARLY_BRK_STORES (loop_vinfo).safe_push (stmt);
815 }
816 else if (gimple_vuse (stmt))
817 {
818 LOOP_VINFO_EARLY_BRK_VUSES (loop_vinfo).safe_insert (0, stmt);
819 if (dump_enabled_p ())
820 dump_printf_loc (MSG_NOTE, vect_location,
821 "marked statement for vUSE update: %G", stmt);
822 }
823 }
824
825 if (!single_pred_p (bb))
826 {
827 gcc_assert (bb == loop->header);
828 break;
829 }
830
831 /* If we possibly sink through a virtual PHI make sure to elide that. */
832 if (gphi *vphi = get_virtual_phi (bb))
833 LOOP_VINFO_EARLY_BRK_STORES (loop_vinfo).safe_push (vphi);
834
835 /* All earlier blocks need dependence checking. */
836 check_deps = true;
837 bb = single_pred (bb);
838 }
839 while (1);
840
841 /* We don't allow outer -> inner loop transitions which should have been
842 trapped already during loop form analysis. */
843 gcc_assert (dest_bb->loop_father == loop);
844
845 /* Check that the destination block we picked has only one pred. To relax this we
846 have to take special care when moving the statements. We don't currently support
847 such control flow however this check is there to simplify how we handle
848 labels that may be present anywhere in the IL. This check is to ensure that the
849 labels aren't significant for the CFG. */
850 if (!single_pred (dest_bb))
851 return opt_result::failure_at (vect_location,
852 "chosen loop exit block (BB %d) does not have a "
853 "single predecessor which is currently not "
854 "supported for early break vectorization.\n",
855 dest_bb->index);
856
857 LOOP_VINFO_EARLY_BRK_DEST_BB (loop_vinfo) = dest_bb;
858
859 if (!LOOP_VINFO_EARLY_BRK_VUSES (loop_vinfo).is_empty ())
860 {
861 /* All uses shall be updated to that of the first load. Entries are
862 stored in reverse order. */
863 tree vuse = gimple_vuse (LOOP_VINFO_EARLY_BRK_VUSES (loop_vinfo).last ());
864 for (auto g : LOOP_VINFO_EARLY_BRK_VUSES (loop_vinfo))
865 {
866 if (dump_enabled_p ())
867 dump_printf_loc (MSG_NOTE, vect_location,
868 "will update use: %T, mem_ref: %G", vuse, g);
869 }
870 }
871
872 if (dump_enabled_p ())
873 dump_printf_loc (MSG_NOTE, vect_location,
874 "recorded statements to be moved to BB %d\n",
875 LOOP_VINFO_EARLY_BRK_DEST_BB (loop_vinfo)->index);
876
877 return opt_result::success ();
878 }
879
880 /* Function vect_analyze_data_ref_dependences.
881
882 Examine all the data references in the loop, and make sure there do not
883 exist any data dependences between them. Set *MAX_VF according to
884 the maximum vectorization factor the data dependences allow. */
885
886 opt_result
887 vect_analyze_data_ref_dependences (loop_vec_info loop_vinfo,
888 unsigned int *max_vf)
889 {
890 unsigned int i;
891 struct data_dependence_relation *ddr;
892
893 DUMP_VECT_SCOPE ("vect_analyze_data_ref_dependences");
894
895 if (!LOOP_VINFO_DDRS (loop_vinfo).exists ())
896 {
897 LOOP_VINFO_DDRS (loop_vinfo)
898 .create (LOOP_VINFO_DATAREFS (loop_vinfo).length ()
899 * LOOP_VINFO_DATAREFS (loop_vinfo).length ());
900 /* We do not need read-read dependences. */
901 bool res = compute_all_dependences (LOOP_VINFO_DATAREFS (loop_vinfo),
902 &LOOP_VINFO_DDRS (loop_vinfo),
903 LOOP_VINFO_LOOP_NEST (loop_vinfo),
904 false);
905 gcc_assert (res);
906 }
907
908 LOOP_VINFO_NO_DATA_DEPENDENCIES (loop_vinfo) = true;
909
910 /* For epilogues we either have no aliases or alias versioning
911 was applied to original loop. Therefore we may just get max_vf
912 using VF of original loop. */
913 if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
914 *max_vf = LOOP_VINFO_ORIG_MAX_VECT_FACTOR (loop_vinfo);
915 else
916 FOR_EACH_VEC_ELT (LOOP_VINFO_DDRS (loop_vinfo), i, ddr)
917 {
918 opt_result res
919 = vect_analyze_data_ref_dependence (ddr, loop_vinfo, max_vf);
920 if (!res)
921 return res;
922 }
923
924 /* If we have early break statements in the loop, check to see if they
925 are of a form we can vectorizer. */
926 if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
927 return vect_analyze_early_break_dependences (loop_vinfo);
928
929 return opt_result::success ();
930 }
931
932
933 /* Function vect_slp_analyze_data_ref_dependence.
934
935 Return TRUE if there (might) exist a dependence between a memory-reference
936 DRA and a memory-reference DRB for VINFO. When versioning for alias
937 may check a dependence at run-time, return FALSE. Adjust *MAX_VF
938 according to the data dependence. */
939
940 static bool
941 vect_slp_analyze_data_ref_dependence (vec_info *vinfo,
942 struct data_dependence_relation *ddr)
943 {
944 struct data_reference *dra = DDR_A (ddr);
945 struct data_reference *drb = DDR_B (ddr);
946 dr_vec_info *dr_info_a = vinfo->lookup_dr (dra);
947 dr_vec_info *dr_info_b = vinfo->lookup_dr (drb);
948
949 /* We need to check dependences of statements marked as unvectorizable
950 as well, they still can prohibit vectorization. */
951
952 /* Independent data accesses. */
953 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
954 return false;
955
956 if (dra == drb)
957 return false;
958
959 /* Read-read is OK. */
960 if (DR_IS_READ (dra) && DR_IS_READ (drb))
961 return false;
962
963 /* If dra and drb are part of the same interleaving chain consider
964 them independent. */
965 if (STMT_VINFO_GROUPED_ACCESS (dr_info_a->stmt)
966 && (DR_GROUP_FIRST_ELEMENT (dr_info_a->stmt)
967 == DR_GROUP_FIRST_ELEMENT (dr_info_b->stmt)))
968 return false;
969
970 /* Unknown data dependence. */
971 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
972 {
973 if (dump_enabled_p ())
974 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
975 "can't determine dependence between %T and %T\n",
976 DR_REF (dra), DR_REF (drb));
977 }
978 else if (dump_enabled_p ())
979 dump_printf_loc (MSG_NOTE, vect_location,
980 "determined dependence between %T and %T\n",
981 DR_REF (dra), DR_REF (drb));
982
983 return true;
984 }
985
986
987 /* Analyze dependences involved in the transform of a store SLP NODE. */
988
989 static bool
990 vect_slp_analyze_store_dependences (vec_info *vinfo, slp_tree node)
991 {
992 /* This walks over all stmts involved in the SLP store done
993 in NODE verifying we can sink them up to the last stmt in the
994 group. */
995 stmt_vec_info last_access_info = vect_find_last_scalar_stmt_in_slp (node);
996 gcc_assert (DR_IS_WRITE (STMT_VINFO_DATA_REF (last_access_info)));
997
998 for (unsigned k = 0; k < SLP_TREE_SCALAR_STMTS (node).length (); ++k)
999 {
1000 stmt_vec_info access_info
1001 = vect_orig_stmt (SLP_TREE_SCALAR_STMTS (node)[k]);
1002 if (access_info == last_access_info)
1003 continue;
1004 data_reference *dr_a = STMT_VINFO_DATA_REF (access_info);
1005 ao_ref ref;
1006 bool ref_initialized_p = false;
1007 for (gimple_stmt_iterator gsi = gsi_for_stmt (access_info->stmt);
1008 gsi_stmt (gsi) != last_access_info->stmt; gsi_next (&gsi))
1009 {
1010 gimple *stmt = gsi_stmt (gsi);
1011 if (! gimple_vuse (stmt))
1012 continue;
1013
1014 /* If we couldn't record a (single) data reference for this
1015 stmt we have to resort to the alias oracle. */
1016 stmt_vec_info stmt_info = vinfo->lookup_stmt (stmt);
1017 data_reference *dr_b = STMT_VINFO_DATA_REF (stmt_info);
1018 if (!dr_b)
1019 {
1020 /* We are moving a store - this means
1021 we cannot use TBAA for disambiguation. */
1022 if (!ref_initialized_p)
1023 ao_ref_init (&ref, DR_REF (dr_a));
1024 if (stmt_may_clobber_ref_p_1 (stmt, &ref, false)
1025 || ref_maybe_used_by_stmt_p (stmt, &ref, false))
1026 return false;
1027 continue;
1028 }
1029
1030 gcc_assert (!gimple_visited_p (stmt));
1031
1032 ddr_p ddr = initialize_data_dependence_relation (dr_a,
1033 dr_b, vNULL);
1034 bool dependent = vect_slp_analyze_data_ref_dependence (vinfo, ddr);
1035 free_dependence_relation (ddr);
1036 if (dependent)
1037 return false;
1038 }
1039 }
1040 return true;
1041 }
1042
1043 /* Analyze dependences involved in the transform of a load SLP NODE. STORES
1044 contain the vector of scalar stores of this instance if we are
1045 disambiguating the loads. */
1046
1047 static bool
1048 vect_slp_analyze_load_dependences (vec_info *vinfo, slp_tree node,
1049 vec<stmt_vec_info> stores,
1050 stmt_vec_info last_store_info)
1051 {
1052 /* This walks over all stmts involved in the SLP load done
1053 in NODE verifying we can hoist them up to the first stmt in the
1054 group. */
1055 stmt_vec_info first_access_info = vect_find_first_scalar_stmt_in_slp (node);
1056 gcc_assert (DR_IS_READ (STMT_VINFO_DATA_REF (first_access_info)));
1057
1058 for (unsigned k = 0; k < SLP_TREE_SCALAR_STMTS (node).length (); ++k)
1059 {
1060 if (! SLP_TREE_SCALAR_STMTS (node)[k])
1061 continue;
1062 stmt_vec_info access_info
1063 = vect_orig_stmt (SLP_TREE_SCALAR_STMTS (node)[k]);
1064 if (access_info == first_access_info)
1065 continue;
1066 data_reference *dr_a = STMT_VINFO_DATA_REF (access_info);
1067 ao_ref ref;
1068 bool ref_initialized_p = false;
1069 hash_set<stmt_vec_info> grp_visited;
1070 for (gimple_stmt_iterator gsi = gsi_for_stmt (access_info->stmt);
1071 gsi_stmt (gsi) != first_access_info->stmt; gsi_prev (&gsi))
1072 {
1073 gimple *stmt = gsi_stmt (gsi);
1074 if (! gimple_vdef (stmt))
1075 continue;
1076
1077 stmt_vec_info stmt_info = vinfo->lookup_stmt (stmt);
1078
1079 /* If we run into a store of this same instance (we've just
1080 marked those) then delay dependence checking until we run
1081 into the last store because this is where it will have
1082 been sunk to (and we verified that we can do that already). */
1083 if (gimple_visited_p (stmt))
1084 {
1085 if (stmt_info != last_store_info)
1086 continue;
1087
1088 for (stmt_vec_info &store_info : stores)
1089 {
1090 data_reference *store_dr = STMT_VINFO_DATA_REF (store_info);
1091 ddr_p ddr = initialize_data_dependence_relation
1092 (dr_a, store_dr, vNULL);
1093 bool dependent
1094 = vect_slp_analyze_data_ref_dependence (vinfo, ddr);
1095 free_dependence_relation (ddr);
1096 if (dependent)
1097 return false;
1098 }
1099 continue;
1100 }
1101
1102 auto check_hoist = [&] (stmt_vec_info stmt_info) -> bool
1103 {
1104 /* We are hoisting a load - this means we can use TBAA for
1105 disambiguation. */
1106 if (!ref_initialized_p)
1107 ao_ref_init (&ref, DR_REF (dr_a));
1108 if (stmt_may_clobber_ref_p_1 (stmt_info->stmt, &ref, true))
1109 {
1110 /* If we couldn't record a (single) data reference for this
1111 stmt we have to give up now. */
1112 data_reference *dr_b = STMT_VINFO_DATA_REF (stmt_info);
1113 if (!dr_b)
1114 return false;
1115 ddr_p ddr = initialize_data_dependence_relation (dr_a,
1116 dr_b, vNULL);
1117 bool dependent
1118 = vect_slp_analyze_data_ref_dependence (vinfo, ddr);
1119 free_dependence_relation (ddr);
1120 if (dependent)
1121 return false;
1122 }
1123 /* No dependence. */
1124 return true;
1125 };
1126 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
1127 {
1128 /* When we run into a store group we have to honor
1129 that earlier stores might be moved here. We don't
1130 know exactly which and where to since we lack a
1131 back-mapping from DR to SLP node, so assume all
1132 earlier stores are sunk here. It's enough to
1133 consider the last stmt of a group for this.
1134 ??? Both this and the fact that we disregard that
1135 the conflicting instance might be removed later
1136 is overly conservative. */
1137 if (!grp_visited.add (DR_GROUP_FIRST_ELEMENT (stmt_info)))
1138 for (auto store_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
1139 store_info != NULL;
1140 store_info = DR_GROUP_NEXT_ELEMENT (store_info))
1141 if ((store_info == stmt_info
1142 || get_later_stmt (store_info, stmt_info) == stmt_info)
1143 && !check_hoist (store_info))
1144 return false;
1145 }
1146 else
1147 {
1148 if (!check_hoist (stmt_info))
1149 return false;
1150 }
1151 }
1152 }
1153 return true;
1154 }
1155
1156
1157 /* Function vect_analyze_data_ref_dependences.
1158
1159 Examine all the data references in the basic-block, and make sure there
1160 do not exist any data dependences between them. Set *MAX_VF according to
1161 the maximum vectorization factor the data dependences allow. */
1162
1163 bool
1164 vect_slp_analyze_instance_dependence (vec_info *vinfo, slp_instance instance)
1165 {
1166 DUMP_VECT_SCOPE ("vect_slp_analyze_instance_dependence");
1167
1168 /* The stores of this instance are at the root of the SLP tree. */
1169 slp_tree store = NULL;
1170 if (SLP_INSTANCE_KIND (instance) == slp_inst_kind_store)
1171 store = SLP_INSTANCE_TREE (instance);
1172
1173 /* Verify we can sink stores to the vectorized stmt insert location. */
1174 stmt_vec_info last_store_info = NULL;
1175 if (store)
1176 {
1177 if (! vect_slp_analyze_store_dependences (vinfo, store))
1178 return false;
1179
1180 /* Mark stores in this instance and remember the last one. */
1181 last_store_info = vect_find_last_scalar_stmt_in_slp (store);
1182 for (unsigned k = 0; k < SLP_TREE_SCALAR_STMTS (store).length (); ++k)
1183 gimple_set_visited (SLP_TREE_SCALAR_STMTS (store)[k]->stmt, true);
1184 }
1185
1186 bool res = true;
1187
1188 /* Verify we can sink loads to the vectorized stmt insert location,
1189 special-casing stores of this instance. */
1190 for (slp_tree &load : SLP_INSTANCE_LOADS (instance))
1191 if (! vect_slp_analyze_load_dependences (vinfo, load,
1192 store
1193 ? SLP_TREE_SCALAR_STMTS (store)
1194 : vNULL, last_store_info))
1195 {
1196 res = false;
1197 break;
1198 }
1199
1200 /* Unset the visited flag. */
1201 if (store)
1202 for (unsigned k = 0; k < SLP_TREE_SCALAR_STMTS (store).length (); ++k)
1203 gimple_set_visited (SLP_TREE_SCALAR_STMTS (store)[k]->stmt, false);
1204
1205 return res;
1206 }
1207
1208 /* Return the misalignment of DR_INFO accessed in VECTYPE with OFFSET
1209 applied. */
1210
1211 int
1212 dr_misalignment (dr_vec_info *dr_info, tree vectype, poly_int64 offset)
1213 {
1214 HOST_WIDE_INT diff = 0;
1215 /* Alignment is only analyzed for the first element of a DR group,
1216 use that but adjust misalignment by the offset of the access. */
1217 if (STMT_VINFO_GROUPED_ACCESS (dr_info->stmt))
1218 {
1219 dr_vec_info *first_dr
1220 = STMT_VINFO_DR_INFO (DR_GROUP_FIRST_ELEMENT (dr_info->stmt));
1221 /* vect_analyze_data_ref_accesses guarantees that DR_INIT are
1222 INTEGER_CSTs and the first element in the group has the lowest
1223 address. */
1224 diff = (TREE_INT_CST_LOW (DR_INIT (dr_info->dr))
1225 - TREE_INT_CST_LOW (DR_INIT (first_dr->dr)));
1226 gcc_assert (diff >= 0);
1227 dr_info = first_dr;
1228 }
1229
1230 int misalign = dr_info->misalignment;
1231 gcc_assert (misalign != DR_MISALIGNMENT_UNINITIALIZED);
1232 if (misalign == DR_MISALIGNMENT_UNKNOWN)
1233 return misalign;
1234
1235 /* If the access is only aligned for a vector type with smaller alignment
1236 requirement the access has unknown misalignment. */
1237 if (maybe_lt (dr_info->target_alignment * BITS_PER_UNIT,
1238 targetm.vectorize.preferred_vector_alignment (vectype)))
1239 return DR_MISALIGNMENT_UNKNOWN;
1240
1241 /* Apply the offset from the DR group start and the externally supplied
1242 offset which can for example result from a negative stride access. */
1243 poly_int64 misalignment = misalign + diff + offset;
1244
1245 /* Below we reject compile-time non-constant target alignments, but if
1246 our misalignment is zero, then we are known to already be aligned
1247 w.r.t. any such possible target alignment. */
1248 if (known_eq (misalignment, 0))
1249 return 0;
1250
1251 unsigned HOST_WIDE_INT target_alignment_c;
1252 if (!dr_info->target_alignment.is_constant (&target_alignment_c)
1253 || !known_misalignment (misalignment, target_alignment_c, &misalign))
1254 return DR_MISALIGNMENT_UNKNOWN;
1255 return misalign;
1256 }
1257
1258 /* Record the base alignment guarantee given by DRB, which occurs
1259 in STMT_INFO. */
1260
1261 static void
1262 vect_record_base_alignment (vec_info *vinfo, stmt_vec_info stmt_info,
1263 innermost_loop_behavior *drb)
1264 {
1265 bool existed;
1266 std::pair<stmt_vec_info, innermost_loop_behavior *> &entry
1267 = vinfo->base_alignments.get_or_insert (drb->base_address, &existed);
1268 if (!existed || entry.second->base_alignment < drb->base_alignment)
1269 {
1270 entry = std::make_pair (stmt_info, drb);
1271 if (dump_enabled_p ())
1272 dump_printf_loc (MSG_NOTE, vect_location,
1273 "recording new base alignment for %T\n"
1274 " alignment: %d\n"
1275 " misalignment: %d\n"
1276 " based on: %G",
1277 drb->base_address,
1278 drb->base_alignment,
1279 drb->base_misalignment,
1280 stmt_info->stmt);
1281 }
1282 }
1283
1284 /* If the region we're going to vectorize is reached, all unconditional
1285 data references occur at least once. We can therefore pool the base
1286 alignment guarantees from each unconditional reference. Do this by
1287 going through all the data references in VINFO and checking whether
1288 the containing statement makes the reference unconditionally. If so,
1289 record the alignment of the base address in VINFO so that it can be
1290 used for all other references with the same base. */
1291
1292 void
1293 vect_record_base_alignments (vec_info *vinfo)
1294 {
1295 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
1296 class loop *loop = loop_vinfo ? LOOP_VINFO_LOOP (loop_vinfo) : NULL;
1297 for (data_reference *dr : vinfo->shared->datarefs)
1298 {
1299 dr_vec_info *dr_info = vinfo->lookup_dr (dr);
1300 stmt_vec_info stmt_info = dr_info->stmt;
1301 if (!DR_IS_CONDITIONAL_IN_STMT (dr)
1302 && STMT_VINFO_VECTORIZABLE (stmt_info)
1303 && !STMT_VINFO_GATHER_SCATTER_P (stmt_info))
1304 {
1305 vect_record_base_alignment (vinfo, stmt_info, &DR_INNERMOST (dr));
1306
1307 /* If DR is nested in the loop that is being vectorized, we can also
1308 record the alignment of the base wrt the outer loop. */
1309 if (loop && nested_in_vect_loop_p (loop, stmt_info))
1310 vect_record_base_alignment
1311 (vinfo, stmt_info, &STMT_VINFO_DR_WRT_VEC_LOOP (stmt_info));
1312 }
1313 }
1314 }
1315
1316 /* Function vect_compute_data_ref_alignment
1317
1318 Compute the misalignment of the data reference DR_INFO when vectorizing
1319 with VECTYPE.
1320
1321 Output:
1322 1. initialized misalignment info for DR_INFO
1323
1324 FOR NOW: No analysis is actually performed. Misalignment is calculated
1325 only for trivial cases. TODO. */
1326
1327 static void
1328 vect_compute_data_ref_alignment (vec_info *vinfo, dr_vec_info *dr_info,
1329 tree vectype)
1330 {
1331 stmt_vec_info stmt_info = dr_info->stmt;
1332 vec_base_alignments *base_alignments = &vinfo->base_alignments;
1333 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
1334 class loop *loop = NULL;
1335 tree ref = DR_REF (dr_info->dr);
1336
1337 if (dump_enabled_p ())
1338 dump_printf_loc (MSG_NOTE, vect_location,
1339 "vect_compute_data_ref_alignment:\n");
1340
1341 if (loop_vinfo)
1342 loop = LOOP_VINFO_LOOP (loop_vinfo);
1343
1344 /* Initialize misalignment to unknown. */
1345 SET_DR_MISALIGNMENT (dr_info, DR_MISALIGNMENT_UNKNOWN);
1346
1347 if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
1348 return;
1349
1350 innermost_loop_behavior *drb = vect_dr_behavior (vinfo, dr_info);
1351 bool step_preserves_misalignment_p;
1352
1353 poly_uint64 vector_alignment
1354 = exact_div (targetm.vectorize.preferred_vector_alignment (vectype),
1355 BITS_PER_UNIT);
1356
1357 if (loop_vinfo
1358 && dr_safe_speculative_read_required (stmt_info))
1359 {
1360 poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1361 auto vectype_size
1362 = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (TREE_TYPE (vectype)));
1363 poly_uint64 new_alignment = vf * vectype_size;
1364 /* If we have a grouped access we require that the alignment be N * elem. */
1365 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
1366 new_alignment *= DR_GROUP_SIZE (DR_GROUP_FIRST_ELEMENT (stmt_info));
1367
1368 unsigned HOST_WIDE_INT target_alignment;
1369 if (new_alignment.is_constant (&target_alignment)
1370 && pow2p_hwi (target_alignment))
1371 {
1372 if (dump_enabled_p ())
1373 {
1374 dump_printf_loc (MSG_NOTE, vect_location,
1375 "alignment increased due to early break to ");
1376 dump_dec (MSG_NOTE, new_alignment);
1377 dump_printf (MSG_NOTE, " bytes.\n");
1378 }
1379 vector_alignment = target_alignment;
1380 }
1381 }
1382
1383 SET_DR_TARGET_ALIGNMENT (dr_info, vector_alignment);
1384
1385 /* If the main loop has peeled for alignment we have no way of knowing
1386 whether the data accesses in the epilogues are aligned. We can't at
1387 compile time answer the question whether we have entered the main loop or
1388 not. Fixes PR 92351. */
1389 if (loop_vinfo)
1390 {
1391 loop_vec_info orig_loop_vinfo = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
1392 if (orig_loop_vinfo
1393 && LOOP_VINFO_PEELING_FOR_ALIGNMENT (orig_loop_vinfo) != 0)
1394 return;
1395 }
1396
1397 unsigned HOST_WIDE_INT vect_align_c;
1398 if (!vector_alignment.is_constant (&vect_align_c))
1399 return;
1400
1401 /* No step for BB vectorization. */
1402 if (!loop)
1403 {
1404 gcc_assert (integer_zerop (drb->step));
1405 step_preserves_misalignment_p = true;
1406 }
1407
1408 else
1409 {
1410 /* We can only use base and misalignment information relative to
1411 an innermost loop if the misalignment stays the same throughout the
1412 execution of the loop. As above, this is the case if the stride of
1413 the dataref evenly divides by the alignment. Make sure to check
1414 previous epilogues and the main loop. */
1415 step_preserves_misalignment_p = true;
1416 auto lvinfo = loop_vinfo;
1417 while (lvinfo)
1418 {
1419 poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (lvinfo);
1420 step_preserves_misalignment_p
1421 &= multiple_p (drb->step_alignment * vf, vect_align_c);
1422 lvinfo = LOOP_VINFO_ORIG_LOOP_INFO (lvinfo);
1423 }
1424
1425 if (!step_preserves_misalignment_p && dump_enabled_p ())
1426 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1427 "step doesn't divide the vector alignment.\n");
1428
1429 /* In case the dataref is in an inner-loop of the loop that is being
1430 vectorized (LOOP), we use the base and misalignment information
1431 relative to the outer-loop (LOOP). This is ok only if the
1432 misalignment stays the same throughout the execution of the
1433 inner-loop, which is why we have to check that the stride of the
1434 dataref in the inner-loop evenly divides by the vector alignment. */
1435 if (step_preserves_misalignment_p
1436 && nested_in_vect_loop_p (loop, stmt_info))
1437 {
1438 step_preserves_misalignment_p
1439 = (DR_STEP_ALIGNMENT (dr_info->dr) % vect_align_c) == 0;
1440
1441 if (dump_enabled_p ())
1442 {
1443 if (step_preserves_misalignment_p)
1444 dump_printf_loc (MSG_NOTE, vect_location,
1445 "inner step divides the vector alignment.\n");
1446 else
1447 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1448 "inner step doesn't divide the vector"
1449 " alignment.\n");
1450 }
1451 }
1452 }
1453
1454 unsigned int base_alignment = drb->base_alignment;
1455 unsigned int base_misalignment = drb->base_misalignment;
1456
1457 /* Calculate the maximum of the pooled base address alignment and the
1458 alignment that we can compute for DR itself. */
1459 std::pair<stmt_vec_info, innermost_loop_behavior *> *entry
1460 = base_alignments->get (drb->base_address);
1461 if (entry
1462 && base_alignment < (*entry).second->base_alignment
1463 && (loop_vinfo
1464 || (dominated_by_p (CDI_DOMINATORS, gimple_bb (stmt_info->stmt),
1465 gimple_bb (entry->first->stmt))
1466 && (gimple_bb (stmt_info->stmt) != gimple_bb (entry->first->stmt)
1467 || (entry->first->dr_aux.group <= dr_info->group)))))
1468 {
1469 base_alignment = entry->second->base_alignment;
1470 base_misalignment = entry->second->base_misalignment;
1471 }
1472
1473 if (drb->offset_alignment < vect_align_c
1474 || !step_preserves_misalignment_p
1475 /* We need to know whether the step wrt the vectorized loop is
1476 negative when computing the starting misalignment below. */
1477 || TREE_CODE (drb->step) != INTEGER_CST)
1478 {
1479 if (dump_enabled_p ())
1480 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1481 "Unknown alignment for access: %T\n", ref);
1482 return;
1483 }
1484
1485 if (base_alignment < vect_align_c)
1486 {
1487 unsigned int max_alignment;
1488 tree base = get_base_for_alignment (drb->base_address, &max_alignment);
1489 if (max_alignment < vect_align_c
1490 || (loop_vinfo && LOOP_VINFO_EPILOGUE_P (loop_vinfo))
1491 || !vect_can_force_dr_alignment_p (base,
1492 vect_align_c * BITS_PER_UNIT))
1493 {
1494 if (dump_enabled_p ())
1495 dump_printf_loc (MSG_NOTE, vect_location,
1496 "can't force alignment of ref: %T\n", ref);
1497 return;
1498 }
1499
1500 /* Force the alignment of the decl.
1501 NOTE: This is the only change to the code we make during
1502 the analysis phase, before deciding to vectorize the loop. */
1503 if (dump_enabled_p ())
1504 dump_printf_loc (MSG_NOTE, vect_location,
1505 "force alignment of %T\n", ref);
1506
1507 dr_info->base_decl = base;
1508 dr_info->base_misaligned = true;
1509 base_misalignment = 0;
1510 }
1511 poly_int64 misalignment
1512 = base_misalignment + wi::to_poly_offset (drb->init).force_shwi ();
1513
1514 unsigned int const_misalignment;
1515 if (!known_misalignment (misalignment, vect_align_c, &const_misalignment))
1516 {
1517 if (dump_enabled_p ())
1518 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1519 "Non-constant misalignment for access: %T\n", ref);
1520 return;
1521 }
1522
1523 SET_DR_MISALIGNMENT (dr_info, const_misalignment);
1524
1525 if (dump_enabled_p ())
1526 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1527 "misalign = %d bytes of ref %T\n",
1528 const_misalignment, ref);
1529
1530 return;
1531 }
1532
1533 /* Return whether DR_INFO, which is related to DR_PEEL_INFO in
1534 that it only differs in DR_INIT, is aligned if DR_PEEL_INFO
1535 is made aligned via peeling. */
1536
1537 static bool
1538 vect_dr_aligned_if_related_peeled_dr_is (dr_vec_info *dr_info,
1539 dr_vec_info *dr_peel_info)
1540 {
1541 if (multiple_p (DR_TARGET_ALIGNMENT (dr_peel_info),
1542 DR_TARGET_ALIGNMENT (dr_info)))
1543 {
1544 poly_offset_int diff
1545 = (wi::to_poly_offset (DR_INIT (dr_peel_info->dr))
1546 - wi::to_poly_offset (DR_INIT (dr_info->dr)));
1547 if (known_eq (diff, 0)
1548 || multiple_p (diff, DR_TARGET_ALIGNMENT (dr_info)))
1549 return true;
1550 }
1551 return false;
1552 }
1553
1554 /* Return whether DR_INFO is aligned if DR_PEEL_INFO is made
1555 aligned via peeling. */
1556
1557 static bool
1558 vect_dr_aligned_if_peeled_dr_is (dr_vec_info *dr_info,
1559 dr_vec_info *dr_peel_info)
1560 {
1561 if (!operand_equal_p (DR_BASE_ADDRESS (dr_info->dr),
1562 DR_BASE_ADDRESS (dr_peel_info->dr), 0)
1563 || !operand_equal_p (DR_OFFSET (dr_info->dr),
1564 DR_OFFSET (dr_peel_info->dr), 0)
1565 || !operand_equal_p (DR_STEP (dr_info->dr),
1566 DR_STEP (dr_peel_info->dr), 0))
1567 return false;
1568
1569 return vect_dr_aligned_if_related_peeled_dr_is (dr_info, dr_peel_info);
1570 }
1571
1572 /* Compute the value for dr_info->misalign so that the access appears
1573 aligned. This is used by peeling to compensate for dr_misalignment
1574 applying the offset for negative step. */
1575
1576 int
1577 vect_dr_misalign_for_aligned_access (dr_vec_info *dr_info)
1578 {
1579 if (tree_int_cst_sgn (DR_STEP (dr_info->dr)) >= 0)
1580 return 0;
1581
1582 tree vectype = STMT_VINFO_VECTYPE (dr_info->stmt);
1583 poly_int64 misalignment
1584 = ((TYPE_VECTOR_SUBPARTS (vectype) - 1)
1585 * TREE_INT_CST_LOW (TYPE_SIZE_UNIT (TREE_TYPE (vectype))));
1586
1587 unsigned HOST_WIDE_INT target_alignment_c;
1588 int misalign;
1589 if (!dr_info->target_alignment.is_constant (&target_alignment_c)
1590 || !known_misalignment (misalignment, target_alignment_c, &misalign))
1591 return DR_MISALIGNMENT_UNKNOWN;
1592 return misalign;
1593 }
1594
1595 /* Function vect_update_misalignment_for_peel.
1596 Sets DR_INFO's misalignment
1597 - to 0 if it has the same alignment as DR_PEEL_INFO,
1598 - to the misalignment computed using NPEEL if DR_INFO's salignment is known,
1599 - to -1 (unknown) otherwise.
1600
1601 DR_INFO - the data reference whose misalignment is to be adjusted.
1602 DR_PEEL_INFO - the data reference whose misalignment is being made
1603 zero in the vector loop by the peel.
1604 NPEEL - the number of iterations in the peel loop if the misalignment
1605 of DR_PEEL_INFO is known at compile time. */
1606
1607 static void
1608 vect_update_misalignment_for_peel (dr_vec_info *dr_info,
1609 dr_vec_info *dr_peel_info, int npeel)
1610 {
1611 /* If dr_info is aligned of dr_peel_info is, then mark it so. */
1612 if (vect_dr_aligned_if_peeled_dr_is (dr_info, dr_peel_info))
1613 {
1614 SET_DR_MISALIGNMENT (dr_info,
1615 vect_dr_misalign_for_aligned_access (dr_peel_info));
1616 return;
1617 }
1618
1619 unsigned HOST_WIDE_INT alignment;
1620 if (DR_TARGET_ALIGNMENT (dr_info).is_constant (&alignment)
1621 && known_alignment_for_access_p (dr_info,
1622 STMT_VINFO_VECTYPE (dr_info->stmt))
1623 && known_alignment_for_access_p (dr_peel_info,
1624 STMT_VINFO_VECTYPE (dr_peel_info->stmt)))
1625 {
1626 int misal = dr_info->misalignment;
1627 misal += npeel * TREE_INT_CST_LOW (DR_STEP (dr_info->dr));
1628 misal &= alignment - 1;
1629 set_dr_misalignment (dr_info, misal);
1630 return;
1631 }
1632
1633 if (dump_enabled_p ())
1634 dump_printf_loc (MSG_NOTE, vect_location, "Setting misalignment " \
1635 "to unknown (-1).\n");
1636 SET_DR_MISALIGNMENT (dr_info, DR_MISALIGNMENT_UNKNOWN);
1637 }
1638
1639 /* Return true if alignment is relevant for DR_INFO. */
1640
1641 static bool
1642 vect_relevant_for_alignment_p (dr_vec_info *dr_info)
1643 {
1644 stmt_vec_info stmt_info = dr_info->stmt;
1645
1646 if (!STMT_VINFO_RELEVANT_P (stmt_info))
1647 return false;
1648
1649 /* For interleaving, only the alignment of the first access matters. */
1650 if (STMT_VINFO_GROUPED_ACCESS (stmt_info)
1651 && DR_GROUP_FIRST_ELEMENT (stmt_info) != stmt_info)
1652 return false;
1653
1654 /* Scatter-gather and invariant accesses continue to address individual
1655 scalars, so vector-level alignment is irrelevant. */
1656 if (STMT_VINFO_GATHER_SCATTER_P (stmt_info)
1657 || integer_zerop (DR_STEP (dr_info->dr)))
1658 return false;
1659
1660 /* Strided accesses perform only component accesses, alignment is
1661 irrelevant for them. */
1662 if (STMT_VINFO_STRIDED_P (stmt_info)
1663 && !STMT_VINFO_GROUPED_ACCESS (stmt_info))
1664 return false;
1665
1666 return true;
1667 }
1668
1669 /* Given an memory reference EXP return whether its alignment is less
1670 than its size. */
1671
1672 static bool
1673 not_size_aligned (tree exp)
1674 {
1675 if (!tree_fits_uhwi_p (TYPE_SIZE (TREE_TYPE (exp))))
1676 return true;
1677
1678 return (tree_to_uhwi (TYPE_SIZE (TREE_TYPE (exp)))
1679 > get_object_alignment (exp));
1680 }
1681
1682 /* Function vector_alignment_reachable_p
1683
1684 Return true if vector alignment for DR_INFO is reachable by peeling
1685 a few loop iterations. Return false otherwise. */
1686
1687 static bool
1688 vector_alignment_reachable_p (dr_vec_info *dr_info, poly_uint64 vf)
1689 {
1690 stmt_vec_info stmt_info = dr_info->stmt;
1691 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
1692 poly_uint64 nelements = TYPE_VECTOR_SUBPARTS (vectype);
1693 poly_uint64 vector_size = GET_MODE_SIZE (TYPE_MODE (vectype));
1694 unsigned elem_size = vector_element_size (vector_size, nelements);
1695 unsigned group_size = 1;
1696
1697 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
1698 {
1699 /* For interleaved access we peel only if number of iterations in
1700 the prolog loop ({VF - misalignment}), is a multiple of the
1701 number of the interleaved accesses. */
1702
1703 /* FORNOW: handle only known alignment. */
1704 if (!known_alignment_for_access_p (dr_info, vectype))
1705 return false;
1706
1707 unsigned mis_in_elements = dr_misalignment (dr_info, vectype) / elem_size;
1708 if (!multiple_p (nelements - mis_in_elements, DR_GROUP_SIZE (stmt_info)))
1709 return false;
1710
1711 group_size = DR_GROUP_SIZE (DR_GROUP_FIRST_ELEMENT (stmt_info));
1712 }
1713
1714 /* If the vectorization factor does not guarantee DR advancement of
1715 a multiple of the target alignment no peeling will help. */
1716 if (!multiple_p (elem_size * group_size * vf, dr_target_alignment (dr_info)))
1717 return false;
1718
1719 /* If misalignment is known at the compile time then allow peeling
1720 only if natural alignment is reachable through peeling. */
1721 if (known_alignment_for_access_p (dr_info, vectype)
1722 && !aligned_access_p (dr_info, vectype))
1723 {
1724 HOST_WIDE_INT elmsize =
1725 int_cst_value (TYPE_SIZE_UNIT (TREE_TYPE (vectype)));
1726 if (dump_enabled_p ())
1727 {
1728 dump_printf_loc (MSG_NOTE, vect_location,
1729 "data size = %wd. misalignment = %d.\n", elmsize,
1730 dr_misalignment (dr_info, vectype));
1731 }
1732 if (dr_misalignment (dr_info, vectype) % elmsize)
1733 {
1734 if (dump_enabled_p ())
1735 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1736 "data size does not divide the misalignment.\n");
1737 return false;
1738 }
1739 }
1740
1741 if (!known_alignment_for_access_p (dr_info, vectype))
1742 {
1743 tree type = TREE_TYPE (DR_REF (dr_info->dr));
1744 bool is_packed = not_size_aligned (DR_REF (dr_info->dr));
1745 if (dump_enabled_p ())
1746 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1747 "Unknown misalignment, %snaturally aligned\n",
1748 is_packed ? "not " : "");
1749 return targetm.vectorize.vector_alignment_reachable (type, is_packed);
1750 }
1751
1752 return true;
1753 }
1754
1755
1756 /* Calculate the cost of the memory access represented by DR_INFO. */
1757
1758 static void
1759 vect_get_data_access_cost (vec_info *vinfo, dr_vec_info *dr_info,
1760 dr_alignment_support alignment_support_scheme,
1761 int misalignment,
1762 unsigned int *inside_cost,
1763 unsigned int *outside_cost,
1764 stmt_vector_for_cost *body_cost_vec,
1765 stmt_vector_for_cost *prologue_cost_vec)
1766 {
1767 stmt_vec_info stmt_info = dr_info->stmt;
1768 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
1769 int ncopies;
1770
1771 if (PURE_SLP_STMT (stmt_info))
1772 ncopies = 1;
1773 else
1774 ncopies = vect_get_num_copies (loop_vinfo, STMT_VINFO_VECTYPE (stmt_info));
1775
1776 if (DR_IS_READ (dr_info->dr))
1777 vect_get_load_cost (vinfo, stmt_info, NULL, ncopies,
1778 alignment_support_scheme, misalignment, true,
1779 inside_cost, outside_cost, prologue_cost_vec,
1780 body_cost_vec, false);
1781 else
1782 vect_get_store_cost (vinfo,stmt_info, NULL, ncopies,
1783 alignment_support_scheme, misalignment, inside_cost,
1784 body_cost_vec);
1785
1786 if (dump_enabled_p ())
1787 dump_printf_loc (MSG_NOTE, vect_location,
1788 "vect_get_data_access_cost: inside_cost = %d, "
1789 "outside_cost = %d.\n", *inside_cost, *outside_cost);
1790 }
1791
1792
1793 typedef struct _vect_peel_info
1794 {
1795 dr_vec_info *dr_info;
1796 int npeel;
1797 unsigned int count;
1798 } *vect_peel_info;
1799
1800 typedef struct _vect_peel_extended_info
1801 {
1802 vec_info *vinfo;
1803 struct _vect_peel_info peel_info;
1804 unsigned int inside_cost;
1805 unsigned int outside_cost;
1806 } *vect_peel_extended_info;
1807
1808
1809 /* Peeling hashtable helpers. */
1810
1811 struct peel_info_hasher : free_ptr_hash <_vect_peel_info>
1812 {
1813 static inline hashval_t hash (const _vect_peel_info *);
1814 static inline bool equal (const _vect_peel_info *, const _vect_peel_info *);
1815 };
1816
1817 inline hashval_t
1818 peel_info_hasher::hash (const _vect_peel_info *peel_info)
1819 {
1820 return (hashval_t) peel_info->npeel;
1821 }
1822
1823 inline bool
1824 peel_info_hasher::equal (const _vect_peel_info *a, const _vect_peel_info *b)
1825 {
1826 return (a->npeel == b->npeel);
1827 }
1828
1829
1830 /* Insert DR_INFO into peeling hash table with NPEEL as key. */
1831
1832 static void
1833 vect_peeling_hash_insert (hash_table<peel_info_hasher> *peeling_htab,
1834 loop_vec_info loop_vinfo, dr_vec_info *dr_info,
1835 int npeel, bool supportable_if_not_aligned)
1836 {
1837 struct _vect_peel_info elem, *slot;
1838 _vect_peel_info **new_slot;
1839
1840 elem.npeel = npeel;
1841 slot = peeling_htab->find (&elem);
1842 if (slot)
1843 slot->count++;
1844 else
1845 {
1846 slot = XNEW (struct _vect_peel_info);
1847 slot->npeel = npeel;
1848 slot->dr_info = dr_info;
1849 slot->count = 1;
1850 new_slot = peeling_htab->find_slot (slot, INSERT);
1851 *new_slot = slot;
1852 }
1853
1854 /* If this DR is not supported with unknown misalignment then bias
1855 this slot when the cost model is disabled. */
1856 if (!supportable_if_not_aligned
1857 && unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
1858 slot->count += VECT_MAX_COST;
1859 }
1860
1861
1862 /* Traverse peeling hash table to find peeling option that aligns maximum
1863 number of data accesses. */
1864
1865 int
1866 vect_peeling_hash_get_most_frequent (_vect_peel_info **slot,
1867 _vect_peel_extended_info *max)
1868 {
1869 vect_peel_info elem = *slot;
1870
1871 if (elem->count > max->peel_info.count
1872 || (elem->count == max->peel_info.count
1873 && max->peel_info.npeel > elem->npeel))
1874 {
1875 max->peel_info.npeel = elem->npeel;
1876 max->peel_info.count = elem->count;
1877 max->peel_info.dr_info = elem->dr_info;
1878 }
1879
1880 return 1;
1881 }
1882
1883 /* Get the costs of peeling NPEEL iterations for LOOP_VINFO, checking
1884 data access costs for all data refs. If UNKNOWN_MISALIGNMENT is true,
1885 npeel is computed at runtime but DR0_INFO's misalignment will be zero
1886 after peeling. */
1887
1888 static void
1889 vect_get_peeling_costs_all_drs (loop_vec_info loop_vinfo,
1890 dr_vec_info *dr0_info,
1891 unsigned int *inside_cost,
1892 unsigned int *outside_cost,
1893 stmt_vector_for_cost *body_cost_vec,
1894 stmt_vector_for_cost *prologue_cost_vec,
1895 unsigned int npeel)
1896 {
1897 vec<data_reference_p> datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
1898
1899 bool dr0_alignment_known_p
1900 = (dr0_info
1901 && known_alignment_for_access_p (dr0_info,
1902 STMT_VINFO_VECTYPE (dr0_info->stmt)));
1903
1904 for (data_reference *dr : datarefs)
1905 {
1906 dr_vec_info *dr_info = loop_vinfo->lookup_dr (dr);
1907 if (!vect_relevant_for_alignment_p (dr_info))
1908 continue;
1909
1910 tree vectype = STMT_VINFO_VECTYPE (dr_info->stmt);
1911 dr_alignment_support alignment_support_scheme;
1912 int misalignment;
1913 unsigned HOST_WIDE_INT alignment;
1914
1915 bool negative = tree_int_cst_compare (DR_STEP (dr_info->dr),
1916 size_zero_node) < 0;
1917 poly_int64 off = 0;
1918 if (negative)
1919 off = ((TYPE_VECTOR_SUBPARTS (vectype) - 1)
1920 * -TREE_INT_CST_LOW (TYPE_SIZE_UNIT (TREE_TYPE (vectype))));
1921
1922 if (npeel == 0)
1923 misalignment = dr_misalignment (dr_info, vectype, off);
1924 else if (dr_info == dr0_info
1925 || vect_dr_aligned_if_peeled_dr_is (dr_info, dr0_info))
1926 misalignment = 0;
1927 else if (!dr0_alignment_known_p
1928 || !known_alignment_for_access_p (dr_info, vectype)
1929 || !DR_TARGET_ALIGNMENT (dr_info).is_constant (&alignment))
1930 misalignment = DR_MISALIGNMENT_UNKNOWN;
1931 else
1932 {
1933 misalignment = dr_misalignment (dr_info, vectype, off);
1934 misalignment += npeel * TREE_INT_CST_LOW (DR_STEP (dr_info->dr));
1935 misalignment &= alignment - 1;
1936 }
1937 alignment_support_scheme
1938 = vect_supportable_dr_alignment (loop_vinfo, dr_info, vectype,
1939 misalignment);
1940
1941 vect_get_data_access_cost (loop_vinfo, dr_info,
1942 alignment_support_scheme, misalignment,
1943 inside_cost, outside_cost,
1944 body_cost_vec, prologue_cost_vec);
1945 }
1946 }
1947
1948 /* Traverse peeling hash table and calculate cost for each peeling option.
1949 Find the one with the lowest cost. */
1950
1951 int
1952 vect_peeling_hash_get_lowest_cost (_vect_peel_info **slot,
1953 _vect_peel_extended_info *min)
1954 {
1955 vect_peel_info elem = *slot;
1956 int dummy;
1957 unsigned int inside_cost = 0, outside_cost = 0;
1958 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (min->vinfo);
1959 stmt_vector_for_cost prologue_cost_vec, body_cost_vec,
1960 epilogue_cost_vec;
1961
1962 prologue_cost_vec.create (2);
1963 body_cost_vec.create (2);
1964 epilogue_cost_vec.create (2);
1965
1966 vect_get_peeling_costs_all_drs (loop_vinfo, elem->dr_info, &inside_cost,
1967 &outside_cost, &body_cost_vec,
1968 &prologue_cost_vec, elem->npeel);
1969
1970 body_cost_vec.release ();
1971
1972 outside_cost += vect_get_known_peeling_cost
1973 (loop_vinfo, elem->npeel, &dummy,
1974 &LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo),
1975 &prologue_cost_vec, &epilogue_cost_vec);
1976
1977 /* Prologue and epilogue costs are added to the target model later.
1978 These costs depend only on the scalar iteration cost, the
1979 number of peeling iterations finally chosen, and the number of
1980 misaligned statements. So discard the information found here. */
1981 prologue_cost_vec.release ();
1982 epilogue_cost_vec.release ();
1983
1984 if (inside_cost < min->inside_cost
1985 || (inside_cost == min->inside_cost
1986 && outside_cost < min->outside_cost))
1987 {
1988 min->inside_cost = inside_cost;
1989 min->outside_cost = outside_cost;
1990 min->peel_info.dr_info = elem->dr_info;
1991 min->peel_info.npeel = elem->npeel;
1992 min->peel_info.count = elem->count;
1993 }
1994
1995 return 1;
1996 }
1997
1998
1999 /* Choose best peeling option by traversing peeling hash table and either
2000 choosing an option with the lowest cost (if cost model is enabled) or the
2001 option that aligns as many accesses as possible. */
2002
2003 static struct _vect_peel_extended_info
2004 vect_peeling_hash_choose_best_peeling (hash_table<peel_info_hasher> *peeling_htab,
2005 loop_vec_info loop_vinfo)
2006 {
2007 struct _vect_peel_extended_info res;
2008
2009 res.peel_info.dr_info = NULL;
2010 res.vinfo = loop_vinfo;
2011
2012 if (!unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
2013 {
2014 res.inside_cost = INT_MAX;
2015 res.outside_cost = INT_MAX;
2016 peeling_htab->traverse <_vect_peel_extended_info *,
2017 vect_peeling_hash_get_lowest_cost> (&res);
2018 }
2019 else
2020 {
2021 res.peel_info.count = 0;
2022 peeling_htab->traverse <_vect_peel_extended_info *,
2023 vect_peeling_hash_get_most_frequent> (&res);
2024 res.inside_cost = 0;
2025 res.outside_cost = 0;
2026 }
2027
2028 return res;
2029 }
2030
2031 /* Return true if the new peeling NPEEL is supported. */
2032
2033 static bool
2034 vect_peeling_supportable (loop_vec_info loop_vinfo, dr_vec_info *dr0_info,
2035 unsigned npeel)
2036 {
2037 vec<data_reference_p> datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
2038 enum dr_alignment_support supportable_dr_alignment;
2039
2040 bool dr0_alignment_known_p
2041 = known_alignment_for_access_p (dr0_info,
2042 STMT_VINFO_VECTYPE (dr0_info->stmt));
2043
2044 /* Ensure that all data refs can be vectorized after the peel. */
2045 for (data_reference *dr : datarefs)
2046 {
2047 if (dr == dr0_info->dr)
2048 continue;
2049
2050 dr_vec_info *dr_info = loop_vinfo->lookup_dr (dr);
2051 if (!vect_relevant_for_alignment_p (dr_info)
2052 || vect_dr_aligned_if_peeled_dr_is (dr_info, dr0_info))
2053 continue;
2054
2055 tree vectype = STMT_VINFO_VECTYPE (dr_info->stmt);
2056 int misalignment;
2057 unsigned HOST_WIDE_INT alignment;
2058 if (!dr0_alignment_known_p
2059 || !known_alignment_for_access_p (dr_info, vectype)
2060 || !DR_TARGET_ALIGNMENT (dr_info).is_constant (&alignment))
2061 misalignment = DR_MISALIGNMENT_UNKNOWN;
2062 else
2063 {
2064 misalignment = dr_misalignment (dr_info, vectype);
2065 misalignment += npeel * TREE_INT_CST_LOW (DR_STEP (dr_info->dr));
2066 misalignment &= alignment - 1;
2067 }
2068 supportable_dr_alignment
2069 = vect_supportable_dr_alignment (loop_vinfo, dr_info, vectype,
2070 misalignment);
2071 if (supportable_dr_alignment == dr_unaligned_unsupported)
2072 return false;
2073 }
2074
2075 return true;
2076 }
2077
2078 /* Compare two data-references DRA and DRB to group them into chunks
2079 with related alignment. */
2080
2081 static int
2082 dr_align_group_sort_cmp (const void *dra_, const void *drb_)
2083 {
2084 data_reference_p dra = *(data_reference_p *)const_cast<void *>(dra_);
2085 data_reference_p drb = *(data_reference_p *)const_cast<void *>(drb_);
2086 int cmp;
2087
2088 /* Stabilize sort. */
2089 if (dra == drb)
2090 return 0;
2091
2092 /* Ordering of DRs according to base. */
2093 cmp = data_ref_compare_tree (DR_BASE_ADDRESS (dra),
2094 DR_BASE_ADDRESS (drb));
2095 if (cmp != 0)
2096 return cmp;
2097
2098 /* And according to DR_OFFSET. */
2099 cmp = data_ref_compare_tree (DR_OFFSET (dra), DR_OFFSET (drb));
2100 if (cmp != 0)
2101 return cmp;
2102
2103 /* And after step. */
2104 cmp = data_ref_compare_tree (DR_STEP (dra), DR_STEP (drb));
2105 if (cmp != 0)
2106 return cmp;
2107
2108 /* Then sort after DR_INIT. In case of identical DRs sort after stmt UID. */
2109 cmp = data_ref_compare_tree (DR_INIT (dra), DR_INIT (drb));
2110 if (cmp == 0)
2111 return gimple_uid (DR_STMT (dra)) < gimple_uid (DR_STMT (drb)) ? -1 : 1;
2112 return cmp;
2113 }
2114
2115 /* Function vect_enhance_data_refs_alignment
2116
2117 This pass will use loop versioning and loop peeling in order to enhance
2118 the alignment of data references in the loop.
2119
2120 FOR NOW: we assume that whatever versioning/peeling takes place, only the
2121 original loop is to be vectorized. Any other loops that are created by
2122 the transformations performed in this pass - are not supposed to be
2123 vectorized. This restriction will be relaxed.
2124
2125 This pass will require a cost model to guide it whether to apply peeling
2126 or versioning or a combination of the two. For example, the scheme that
2127 intel uses when given a loop with several memory accesses, is as follows:
2128 choose one memory access ('p') which alignment you want to force by doing
2129 peeling. Then, either (1) generate a loop in which 'p' is aligned and all
2130 other accesses are not necessarily aligned, or (2) use loop versioning to
2131 generate one loop in which all accesses are aligned, and another loop in
2132 which only 'p' is necessarily aligned.
2133
2134 ("Automatic Intra-Register Vectorization for the Intel Architecture",
2135 Aart J.C. Bik, Milind Girkar, Paul M. Grey and Ximmin Tian, International
2136 Journal of Parallel Programming, Vol. 30, No. 2, April 2002.)
2137
2138 Devising a cost model is the most critical aspect of this work. It will
2139 guide us on which access to peel for, whether to use loop versioning, how
2140 many versions to create, etc. The cost model will probably consist of
2141 generic considerations as well as target specific considerations (on
2142 powerpc for example, misaligned stores are more painful than misaligned
2143 loads).
2144
2145 Here are the general steps involved in alignment enhancements:
2146
2147 -- original loop, before alignment analysis:
2148 for (i=0; i<N; i++){
2149 x = q[i]; # DR_MISALIGNMENT(q) = unknown
2150 p[i] = y; # DR_MISALIGNMENT(p) = unknown
2151 }
2152
2153 -- After vect_compute_data_refs_alignment:
2154 for (i=0; i<N; i++){
2155 x = q[i]; # DR_MISALIGNMENT(q) = 3
2156 p[i] = y; # DR_MISALIGNMENT(p) = unknown
2157 }
2158
2159 -- Possibility 1: we do loop versioning:
2160 if (p is aligned) {
2161 for (i=0; i<N; i++){ # loop 1A
2162 x = q[i]; # DR_MISALIGNMENT(q) = 3
2163 p[i] = y; # DR_MISALIGNMENT(p) = 0
2164 }
2165 }
2166 else {
2167 for (i=0; i<N; i++){ # loop 1B
2168 x = q[i]; # DR_MISALIGNMENT(q) = 3
2169 p[i] = y; # DR_MISALIGNMENT(p) = unaligned
2170 }
2171 }
2172
2173 -- Possibility 2: we do loop peeling:
2174 for (i = 0; i < 3; i++){ # (scalar loop, not to be vectorized).
2175 x = q[i];
2176 p[i] = y;
2177 }
2178 for (i = 3; i < N; i++){ # loop 2A
2179 x = q[i]; # DR_MISALIGNMENT(q) = 0
2180 p[i] = y; # DR_MISALIGNMENT(p) = unknown
2181 }
2182
2183 -- Possibility 3: combination of loop peeling and versioning:
2184 for (i = 0; i < 3; i++){ # (scalar loop, not to be vectorized).
2185 x = q[i];
2186 p[i] = y;
2187 }
2188 if (p is aligned) {
2189 for (i = 3; i<N; i++){ # loop 3A
2190 x = q[i]; # DR_MISALIGNMENT(q) = 0
2191 p[i] = y; # DR_MISALIGNMENT(p) = 0
2192 }
2193 }
2194 else {
2195 for (i = 3; i<N; i++){ # loop 3B
2196 x = q[i]; # DR_MISALIGNMENT(q) = 0
2197 p[i] = y; # DR_MISALIGNMENT(p) = unaligned
2198 }
2199 }
2200
2201 These loops are later passed to loop_transform to be vectorized. The
2202 vectorizer will use the alignment information to guide the transformation
2203 (whether to generate regular loads/stores, or with special handling for
2204 misalignment). */
2205
2206 opt_result
2207 vect_enhance_data_refs_alignment (loop_vec_info loop_vinfo)
2208 {
2209 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
2210 dr_vec_info *first_store = NULL;
2211 dr_vec_info *dr0_info = NULL;
2212 struct data_reference *dr;
2213 unsigned int i;
2214 bool do_peeling = false;
2215 bool do_versioning = false;
2216 unsigned int npeel = 0;
2217 bool one_misalignment_known = false;
2218 bool one_misalignment_unknown = false;
2219 bool one_dr_unsupportable = false;
2220 dr_vec_info *unsupportable_dr_info = NULL;
2221 unsigned int dr0_same_align_drs = 0, first_store_same_align_drs = 0;
2222 hash_table<peel_info_hasher> peeling_htab (1);
2223
2224 DUMP_VECT_SCOPE ("vect_enhance_data_refs_alignment");
2225
2226 /* Reset data so we can safely be called multiple times. */
2227 LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).truncate (0);
2228 LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) = 0;
2229
2230 if (LOOP_VINFO_DATAREFS (loop_vinfo).is_empty ())
2231 return opt_result::success ();
2232
2233 /* Sort the vector of datarefs so DRs that have the same or dependent
2234 alignment are next to each other. */
2235 auto_vec<data_reference_p> datarefs
2236 = LOOP_VINFO_DATAREFS (loop_vinfo).copy ();
2237 datarefs.qsort (dr_align_group_sort_cmp);
2238
2239 /* Compute the number of DRs that become aligned when we peel
2240 a dataref so it becomes aligned. */
2241 auto_vec<unsigned> n_same_align_refs (datarefs.length ());
2242 n_same_align_refs.quick_grow_cleared (datarefs.length ());
2243 unsigned i0;
2244 for (i0 = 0; i0 < datarefs.length (); ++i0)
2245 if (DR_BASE_ADDRESS (datarefs[i0]))
2246 break;
2247 for (i = i0 + 1; i <= datarefs.length (); ++i)
2248 {
2249 if (i == datarefs.length ()
2250 || !operand_equal_p (DR_BASE_ADDRESS (datarefs[i0]),
2251 DR_BASE_ADDRESS (datarefs[i]), 0)
2252 || !operand_equal_p (DR_OFFSET (datarefs[i0]),
2253 DR_OFFSET (datarefs[i]), 0)
2254 || !operand_equal_p (DR_STEP (datarefs[i0]),
2255 DR_STEP (datarefs[i]), 0))
2256 {
2257 /* The subgroup [i0, i-1] now only differs in DR_INIT and
2258 possibly DR_TARGET_ALIGNMENT. Still the whole subgroup
2259 will get known misalignment if we align one of the refs
2260 with the largest DR_TARGET_ALIGNMENT. */
2261 for (unsigned j = i0; j < i; ++j)
2262 {
2263 dr_vec_info *dr_infoj = loop_vinfo->lookup_dr (datarefs[j]);
2264 for (unsigned k = i0; k < i; ++k)
2265 {
2266 if (k == j)
2267 continue;
2268 dr_vec_info *dr_infok = loop_vinfo->lookup_dr (datarefs[k]);
2269 if (vect_dr_aligned_if_related_peeled_dr_is (dr_infok,
2270 dr_infoj))
2271 n_same_align_refs[j]++;
2272 }
2273 }
2274 i0 = i;
2275 }
2276 }
2277
2278 /* While cost model enhancements are expected in the future, the high level
2279 view of the code at this time is as follows:
2280
2281 A) If there is a misaligned access then see if peeling to align
2282 this access can make all data references satisfy
2283 vect_supportable_dr_alignment. If so, update data structures
2284 as needed and return true.
2285
2286 B) If peeling wasn't possible and there is a data reference with an
2287 unknown misalignment that does not satisfy vect_supportable_dr_alignment
2288 then see if loop versioning checks can be used to make all data
2289 references satisfy vect_supportable_dr_alignment. If so, update
2290 data structures as needed and return true.
2291
2292 C) If neither peeling nor versioning were successful then return false if
2293 any data reference does not satisfy vect_supportable_dr_alignment.
2294
2295 D) Return true (all data references satisfy vect_supportable_dr_alignment).
2296
2297 Note, Possibility 3 above (which is peeling and versioning together) is not
2298 being done at this time. */
2299
2300 /* (1) Peeling to force alignment. */
2301
2302 /* (1.1) Decide whether to perform peeling, and how many iterations to peel:
2303 Considerations:
2304 + How many accesses will become aligned due to the peeling
2305 - How many accesses will become unaligned due to the peeling,
2306 and the cost of misaligned accesses.
2307 - The cost of peeling (the extra runtime checks, the increase
2308 in code size). */
2309
2310 FOR_EACH_VEC_ELT (datarefs, i, dr)
2311 {
2312 dr_vec_info *dr_info = loop_vinfo->lookup_dr (dr);
2313 if (!vect_relevant_for_alignment_p (dr_info))
2314 continue;
2315
2316 stmt_vec_info stmt_info = dr_info->stmt;
2317 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
2318 do_peeling
2319 = vector_alignment_reachable_p (dr_info,
2320 LOOP_VINFO_VECT_FACTOR (loop_vinfo));
2321 if (do_peeling)
2322 {
2323 if (known_alignment_for_access_p (dr_info, vectype))
2324 {
2325 unsigned int npeel_tmp = 0;
2326 bool negative = tree_int_cst_compare (DR_STEP (dr),
2327 size_zero_node) < 0;
2328
2329 /* If known_alignment_for_access_p then we have set
2330 DR_MISALIGNMENT which is only done if we know it at compiler
2331 time, so it is safe to assume target alignment is constant.
2332 */
2333 unsigned int target_align =
2334 DR_TARGET_ALIGNMENT (dr_info).to_constant ();
2335 unsigned HOST_WIDE_INT dr_size = vect_get_scalar_dr_size (dr_info);
2336 poly_int64 off = 0;
2337 if (negative)
2338 off = (TYPE_VECTOR_SUBPARTS (vectype) - 1) * -dr_size;
2339 unsigned int mis = dr_misalignment (dr_info, vectype, off);
2340 mis = negative ? mis : -mis;
2341 if (mis != 0)
2342 npeel_tmp = (mis & (target_align - 1)) / dr_size;
2343
2344 /* For multiple types, it is possible that the bigger type access
2345 will have more than one peeling option. E.g., a loop with two
2346 types: one of size (vector size / 4), and the other one of
2347 size (vector size / 8). Vectorization factor will 8. If both
2348 accesses are misaligned by 3, the first one needs one scalar
2349 iteration to be aligned, and the second one needs 5. But the
2350 first one will be aligned also by peeling 5 scalar
2351 iterations, and in that case both accesses will be aligned.
2352 Hence, except for the immediate peeling amount, we also want
2353 to try to add full vector size, while we don't exceed
2354 vectorization factor.
2355 We do this automatically for cost model, since we calculate
2356 cost for every peeling option. */
2357 poly_uint64 nscalars = npeel_tmp;
2358 if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
2359 {
2360 poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2361 unsigned group_size = 1;
2362 if (STMT_SLP_TYPE (stmt_info)
2363 && STMT_VINFO_GROUPED_ACCESS (stmt_info))
2364 group_size = DR_GROUP_SIZE (stmt_info);
2365 nscalars = vf * group_size;
2366 }
2367
2368 /* Save info about DR in the hash table. Also include peeling
2369 amounts according to the explanation above. Indicate
2370 the alignment status when the ref is not aligned.
2371 ??? Rather than using unknown alignment here we should
2372 prune all entries from the peeling hashtable which cause
2373 DRs to be not supported. */
2374 bool supportable_if_not_aligned
2375 = vect_supportable_dr_alignment
2376 (loop_vinfo, dr_info, vectype, DR_MISALIGNMENT_UNKNOWN);
2377 while (known_le (npeel_tmp, nscalars))
2378 {
2379 vect_peeling_hash_insert (&peeling_htab, loop_vinfo,
2380 dr_info, npeel_tmp,
2381 supportable_if_not_aligned);
2382 npeel_tmp += MAX (1, target_align / dr_size);
2383 }
2384
2385 one_misalignment_known = true;
2386 }
2387 else
2388 {
2389 /* If we don't know any misalignment values, we prefer
2390 peeling for data-ref that has the maximum number of data-refs
2391 with the same alignment, unless the target prefers to align
2392 stores over load. */
2393 unsigned same_align_drs = n_same_align_refs[i];
2394 if (!dr0_info
2395 || dr0_same_align_drs < same_align_drs)
2396 {
2397 dr0_same_align_drs = same_align_drs;
2398 dr0_info = dr_info;
2399 }
2400 /* For data-refs with the same number of related
2401 accesses prefer the one where the misalign
2402 computation will be invariant in the outermost loop. */
2403 else if (dr0_same_align_drs == same_align_drs)
2404 {
2405 class loop *ivloop0, *ivloop;
2406 ivloop0 = outermost_invariant_loop_for_expr
2407 (loop, DR_BASE_ADDRESS (dr0_info->dr));
2408 ivloop = outermost_invariant_loop_for_expr
2409 (loop, DR_BASE_ADDRESS (dr));
2410 if ((ivloop && !ivloop0)
2411 || (ivloop && ivloop0
2412 && flow_loop_nested_p (ivloop, ivloop0)))
2413 dr0_info = dr_info;
2414 }
2415
2416 one_misalignment_unknown = true;
2417
2418 /* Check for data refs with unsupportable alignment that
2419 can be peeled. */
2420 enum dr_alignment_support supportable_dr_alignment
2421 = vect_supportable_dr_alignment (loop_vinfo, dr_info, vectype,
2422 DR_MISALIGNMENT_UNKNOWN);
2423 if (supportable_dr_alignment == dr_unaligned_unsupported)
2424 {
2425 one_dr_unsupportable = true;
2426 unsupportable_dr_info = dr_info;
2427 }
2428
2429 if (!first_store && DR_IS_WRITE (dr))
2430 {
2431 first_store = dr_info;
2432 first_store_same_align_drs = same_align_drs;
2433 }
2434 }
2435 }
2436 else
2437 {
2438 if (!aligned_access_p (dr_info, vectype))
2439 {
2440 if (dump_enabled_p ())
2441 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2442 "vector alignment may not be reachable\n");
2443 break;
2444 }
2445 }
2446 }
2447
2448 /* Check if we can possibly peel the loop. */
2449 if (!vect_can_advance_ivs_p (loop_vinfo)
2450 || !slpeel_can_duplicate_loop_p (loop, LOOP_VINFO_IV_EXIT (loop_vinfo),
2451 loop_preheader_edge (loop))
2452 || loop->inner
2453 /* We don't currently maintaing the LCSSA for prologue peeled inversed
2454 loops. */
2455 || LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
2456 do_peeling = false;
2457
2458 struct _vect_peel_extended_info peel_for_known_alignment;
2459 struct _vect_peel_extended_info peel_for_unknown_alignment;
2460 struct _vect_peel_extended_info best_peel;
2461
2462 peel_for_unknown_alignment.inside_cost = INT_MAX;
2463 peel_for_unknown_alignment.outside_cost = INT_MAX;
2464 peel_for_unknown_alignment.peel_info.count = 0;
2465
2466 if (do_peeling
2467 && one_misalignment_unknown)
2468 {
2469 /* Check if the target requires to prefer stores over loads, i.e., if
2470 misaligned stores are more expensive than misaligned loads (taking
2471 drs with same alignment into account). */
2472 unsigned int load_inside_cost = 0;
2473 unsigned int load_outside_cost = 0;
2474 unsigned int store_inside_cost = 0;
2475 unsigned int store_outside_cost = 0;
2476 unsigned int estimated_npeels = vect_vf_for_cost (loop_vinfo) / 2;
2477
2478 stmt_vector_for_cost dummy;
2479 dummy.create (2);
2480 vect_get_peeling_costs_all_drs (loop_vinfo, dr0_info,
2481 &load_inside_cost,
2482 &load_outside_cost,
2483 &dummy, &dummy, estimated_npeels);
2484 dummy.release ();
2485
2486 if (first_store)
2487 {
2488 dummy.create (2);
2489 vect_get_peeling_costs_all_drs (loop_vinfo, first_store,
2490 &store_inside_cost,
2491 &store_outside_cost,
2492 &dummy, &dummy,
2493 estimated_npeels);
2494 dummy.release ();
2495 }
2496 else
2497 {
2498 store_inside_cost = INT_MAX;
2499 store_outside_cost = INT_MAX;
2500 }
2501
2502 if (load_inside_cost > store_inside_cost
2503 || (load_inside_cost == store_inside_cost
2504 && load_outside_cost > store_outside_cost))
2505 {
2506 dr0_info = first_store;
2507 dr0_same_align_drs = first_store_same_align_drs;
2508 peel_for_unknown_alignment.inside_cost = store_inside_cost;
2509 peel_for_unknown_alignment.outside_cost = store_outside_cost;
2510 }
2511 else
2512 {
2513 peel_for_unknown_alignment.inside_cost = load_inside_cost;
2514 peel_for_unknown_alignment.outside_cost = load_outside_cost;
2515 }
2516
2517 stmt_vector_for_cost prologue_cost_vec, epilogue_cost_vec;
2518 prologue_cost_vec.create (2);
2519 epilogue_cost_vec.create (2);
2520
2521 int dummy2;
2522 peel_for_unknown_alignment.outside_cost += vect_get_known_peeling_cost
2523 (loop_vinfo, estimated_npeels, &dummy2,
2524 &LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo),
2525 &prologue_cost_vec, &epilogue_cost_vec);
2526
2527 prologue_cost_vec.release ();
2528 epilogue_cost_vec.release ();
2529
2530 peel_for_unknown_alignment.peel_info.count = dr0_same_align_drs + 1;
2531 }
2532
2533 peel_for_unknown_alignment.peel_info.npeel = 0;
2534 peel_for_unknown_alignment.peel_info.dr_info = dr0_info;
2535
2536 best_peel = peel_for_unknown_alignment;
2537
2538 peel_for_known_alignment.inside_cost = INT_MAX;
2539 peel_for_known_alignment.outside_cost = INT_MAX;
2540 peel_for_known_alignment.peel_info.count = 0;
2541 peel_for_known_alignment.peel_info.dr_info = NULL;
2542
2543 if (do_peeling && one_misalignment_known)
2544 {
2545 /* Peeling is possible, but there is no data access that is not supported
2546 unless aligned. So we try to choose the best possible peeling from
2547 the hash table. */
2548 peel_for_known_alignment = vect_peeling_hash_choose_best_peeling
2549 (&peeling_htab, loop_vinfo);
2550 }
2551
2552 /* Compare costs of peeling for known and unknown alignment. */
2553 if (peel_for_known_alignment.peel_info.dr_info != NULL
2554 && peel_for_unknown_alignment.inside_cost
2555 >= peel_for_known_alignment.inside_cost)
2556 {
2557 best_peel = peel_for_known_alignment;
2558
2559 /* If the best peeling for known alignment has NPEEL == 0, perform no
2560 peeling at all except if there is an unsupportable dr that we can
2561 align. */
2562 if (best_peel.peel_info.npeel == 0 && !one_dr_unsupportable)
2563 do_peeling = false;
2564 }
2565
2566 /* If there is an unsupportable data ref, prefer this over all choices so far
2567 since we'd have to discard a chosen peeling except when it accidentally
2568 aligned the unsupportable data ref. */
2569 if (one_dr_unsupportable)
2570 dr0_info = unsupportable_dr_info;
2571 else if (do_peeling)
2572 {
2573 /* Calculate the penalty for no peeling, i.e. leaving everything as-is.
2574 TODO: Use nopeel_outside_cost or get rid of it? */
2575 unsigned nopeel_inside_cost = 0;
2576 unsigned nopeel_outside_cost = 0;
2577
2578 stmt_vector_for_cost dummy;
2579 dummy.create (2);
2580 vect_get_peeling_costs_all_drs (loop_vinfo, NULL, &nopeel_inside_cost,
2581 &nopeel_outside_cost, &dummy, &dummy, 0);
2582 dummy.release ();
2583
2584 /* Add epilogue costs. As we do not peel for alignment here, no prologue
2585 costs will be recorded. */
2586 stmt_vector_for_cost prologue_cost_vec, epilogue_cost_vec;
2587 prologue_cost_vec.create (2);
2588 epilogue_cost_vec.create (2);
2589
2590 int dummy2;
2591 nopeel_outside_cost += vect_get_known_peeling_cost
2592 (loop_vinfo, 0, &dummy2,
2593 &LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo),
2594 &prologue_cost_vec, &epilogue_cost_vec);
2595
2596 prologue_cost_vec.release ();
2597 epilogue_cost_vec.release ();
2598
2599 npeel = best_peel.peel_info.npeel;
2600 dr0_info = best_peel.peel_info.dr_info;
2601
2602 /* If no peeling is not more expensive than the best peeling we
2603 have so far, don't perform any peeling. */
2604 if (nopeel_inside_cost <= best_peel.inside_cost)
2605 do_peeling = false;
2606 }
2607
2608 if (do_peeling)
2609 {
2610 stmt_vec_info stmt_info = dr0_info->stmt;
2611 if (known_alignment_for_access_p (dr0_info,
2612 STMT_VINFO_VECTYPE (stmt_info)))
2613 {
2614 bool negative = tree_int_cst_compare (DR_STEP (dr0_info->dr),
2615 size_zero_node) < 0;
2616 if (!npeel)
2617 {
2618 /* Since it's known at compile time, compute the number of
2619 iterations in the peeled loop (the peeling factor) for use in
2620 updating DR_MISALIGNMENT values. The peeling factor is the
2621 vectorization factor minus the misalignment as an element
2622 count. */
2623 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
2624 poly_int64 off = 0;
2625 if (negative)
2626 off = ((TYPE_VECTOR_SUBPARTS (vectype) - 1)
2627 * -TREE_INT_CST_LOW (TYPE_SIZE_UNIT (TREE_TYPE (vectype))));
2628 unsigned int mis
2629 = dr_misalignment (dr0_info, vectype, off);
2630 mis = negative ? mis : -mis;
2631 /* If known_alignment_for_access_p then we have set
2632 DR_MISALIGNMENT which is only done if we know it at compiler
2633 time, so it is safe to assume target alignment is constant.
2634 */
2635 unsigned int target_align =
2636 DR_TARGET_ALIGNMENT (dr0_info).to_constant ();
2637 npeel = ((mis & (target_align - 1))
2638 / vect_get_scalar_dr_size (dr0_info));
2639 }
2640
2641 /* For interleaved data access every iteration accesses all the
2642 members of the group, therefore we divide the number of iterations
2643 by the group size. */
2644 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
2645 npeel /= DR_GROUP_SIZE (stmt_info);
2646
2647 if (dump_enabled_p ())
2648 dump_printf_loc (MSG_NOTE, vect_location,
2649 "Try peeling by %d\n", npeel);
2650 }
2651
2652 /* Ensure that all datarefs can be vectorized after the peel. */
2653 if (!vect_peeling_supportable (loop_vinfo, dr0_info, npeel))
2654 do_peeling = false;
2655
2656 /* Check if all datarefs are supportable and log. */
2657 if (do_peeling
2658 && npeel == 0
2659 && known_alignment_for_access_p (dr0_info,
2660 STMT_VINFO_VECTYPE (stmt_info)))
2661 return opt_result::success ();
2662
2663 /* Cost model #1 - honor --param vect-max-peeling-for-alignment. */
2664 if (do_peeling)
2665 {
2666 unsigned max_allowed_peel
2667 = param_vect_max_peeling_for_alignment;
2668 if (loop_cost_model (loop) <= VECT_COST_MODEL_CHEAP)
2669 max_allowed_peel = 0;
2670 if (max_allowed_peel != (unsigned)-1)
2671 {
2672 unsigned max_peel = npeel;
2673 if (max_peel == 0)
2674 {
2675 poly_uint64 target_align = DR_TARGET_ALIGNMENT (dr0_info);
2676 unsigned HOST_WIDE_INT target_align_c;
2677 if (target_align.is_constant (&target_align_c))
2678 max_peel =
2679 target_align_c / vect_get_scalar_dr_size (dr0_info) - 1;
2680 else
2681 {
2682 do_peeling = false;
2683 if (dump_enabled_p ())
2684 dump_printf_loc (MSG_NOTE, vect_location,
2685 "Disable peeling, max peels set and vector"
2686 " alignment unknown\n");
2687 }
2688 }
2689 if (max_peel > max_allowed_peel)
2690 {
2691 do_peeling = false;
2692 if (dump_enabled_p ())
2693 dump_printf_loc (MSG_NOTE, vect_location,
2694 "Disable peeling, max peels reached: %d\n", max_peel);
2695 }
2696 }
2697 }
2698
2699 /* Cost model #2 - if peeling may result in a remaining loop not
2700 iterating enough to be vectorized then do not peel. Since this
2701 is a cost heuristic rather than a correctness decision, use the
2702 most likely runtime value for variable vectorization factors. */
2703 if (do_peeling
2704 && LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
2705 {
2706 unsigned int assumed_vf = vect_vf_for_cost (loop_vinfo);
2707 unsigned int max_peel = npeel == 0 ? assumed_vf - 1 : npeel;
2708 if ((unsigned HOST_WIDE_INT) LOOP_VINFO_INT_NITERS (loop_vinfo)
2709 < assumed_vf + max_peel)
2710 do_peeling = false;
2711 }
2712
2713 if (do_peeling)
2714 {
2715 /* (1.2) Update the DR_MISALIGNMENT of each data reference DR_i.
2716 If the misalignment of DR_i is identical to that of dr0 then set
2717 DR_MISALIGNMENT (DR_i) to zero. If the misalignment of DR_i and
2718 dr0 are known at compile time then increment DR_MISALIGNMENT (DR_i)
2719 by the peeling factor times the element size of DR_i (MOD the
2720 vectorization factor times the size). Otherwise, the
2721 misalignment of DR_i must be set to unknown. */
2722 FOR_EACH_VEC_ELT (datarefs, i, dr)
2723 if (dr != dr0_info->dr)
2724 {
2725 dr_vec_info *dr_info = loop_vinfo->lookup_dr (dr);
2726 if (!vect_relevant_for_alignment_p (dr_info))
2727 continue;
2728
2729 vect_update_misalignment_for_peel (dr_info, dr0_info, npeel);
2730 }
2731
2732 LOOP_VINFO_UNALIGNED_DR (loop_vinfo) = dr0_info;
2733 if (npeel)
2734 LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) = npeel;
2735 else
2736 LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) = -1;
2737 SET_DR_MISALIGNMENT (dr0_info,
2738 vect_dr_misalign_for_aligned_access (dr0_info));
2739 if (dump_enabled_p ())
2740 {
2741 dump_printf_loc (MSG_NOTE, vect_location,
2742 "Alignment of access forced using peeling.\n");
2743 dump_printf_loc (MSG_NOTE, vect_location,
2744 "Peeling for alignment will be applied.\n");
2745 }
2746
2747 /* The inside-loop cost will be accounted for in vectorizable_load
2748 and vectorizable_store correctly with adjusted alignments.
2749 Drop the body_cst_vec on the floor here. */
2750 return opt_result::success ();
2751 }
2752 }
2753
2754 /* (2) Versioning to force alignment. */
2755
2756 /* Try versioning if:
2757 1) optimize loop for speed and the cost-model is not cheap
2758 2) there is at least one unsupported misaligned data ref with an unknown
2759 misalignment, and
2760 3) all misaligned data refs with a known misalignment are supported, and
2761 4) the number of runtime alignment checks is within reason.
2762 5) the vectorization factor is a constant. */
2763
2764 do_versioning
2765 = (optimize_loop_nest_for_speed_p (loop)
2766 && !loop->inner /* FORNOW */
2767 && loop_cost_model (loop) > VECT_COST_MODEL_CHEAP)
2768 && LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant ();
2769
2770 if (do_versioning)
2771 {
2772 FOR_EACH_VEC_ELT (datarefs, i, dr)
2773 {
2774 dr_vec_info *dr_info = loop_vinfo->lookup_dr (dr);
2775 if (!vect_relevant_for_alignment_p (dr_info))
2776 continue;
2777
2778 stmt_vec_info stmt_info = dr_info->stmt;
2779 if (STMT_VINFO_STRIDED_P (stmt_info))
2780 {
2781 do_versioning = false;
2782 break;
2783 }
2784
2785 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
2786 bool negative = tree_int_cst_compare (DR_STEP (dr),
2787 size_zero_node) < 0;
2788 poly_int64 off = 0;
2789 if (negative)
2790 off = ((TYPE_VECTOR_SUBPARTS (vectype) - 1)
2791 * -TREE_INT_CST_LOW (TYPE_SIZE_UNIT (TREE_TYPE (vectype))));
2792 int misalignment;
2793 if ((misalignment = dr_misalignment (dr_info, vectype, off)) == 0)
2794 continue;
2795
2796 enum dr_alignment_support supportable_dr_alignment
2797 = vect_supportable_dr_alignment (loop_vinfo, dr_info, vectype,
2798 misalignment);
2799 if (supportable_dr_alignment == dr_unaligned_unsupported)
2800 {
2801 if (misalignment != DR_MISALIGNMENT_UNKNOWN
2802 || (LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).length ()
2803 >= (unsigned) param_vect_max_version_for_alignment_checks))
2804 {
2805 do_versioning = false;
2806 break;
2807 }
2808
2809 /* Forcing alignment in the first iteration is no good if
2810 we don't keep it across iterations. For now, just disable
2811 versioning in this case.
2812 ?? We could actually unroll the loop to achieve the required
2813 overall step alignment, and forcing the alignment could be
2814 done by doing some iterations of the non-vectorized loop. */
2815 if (!multiple_p (LOOP_VINFO_VECT_FACTOR (loop_vinfo)
2816 * DR_STEP_ALIGNMENT (dr),
2817 DR_TARGET_ALIGNMENT (dr_info)))
2818 {
2819 do_versioning = false;
2820 break;
2821 }
2822
2823 /* The rightmost bits of an aligned address must be zeros.
2824 Construct the mask needed for this test. For example,
2825 GET_MODE_SIZE for the vector mode V4SI is 16 bytes so the
2826 mask must be 15 = 0xf. */
2827 gcc_assert (DR_TARGET_ALIGNMENT (dr_info).is_constant ());
2828 int mask = DR_TARGET_ALIGNMENT (dr_info).to_constant () - 1;
2829
2830 /* FORNOW: use the same mask to test all potentially unaligned
2831 references in the loop. */
2832 if (LOOP_VINFO_PTR_MASK (loop_vinfo)
2833 && LOOP_VINFO_PTR_MASK (loop_vinfo) != mask)
2834 {
2835 do_versioning = false;
2836 break;
2837 }
2838
2839 LOOP_VINFO_PTR_MASK (loop_vinfo) = mask;
2840 LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).safe_push (stmt_info);
2841 }
2842 }
2843
2844 /* Versioning requires at least one misaligned data reference. */
2845 if (!LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo))
2846 do_versioning = false;
2847 else if (!do_versioning)
2848 LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).truncate (0);
2849 }
2850
2851 if (do_versioning)
2852 {
2853 const vec<stmt_vec_info> &may_misalign_stmts
2854 = LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo);
2855 stmt_vec_info stmt_info;
2856
2857 /* It can now be assumed that the data references in the statements
2858 in LOOP_VINFO_MAY_MISALIGN_STMTS will be aligned in the version
2859 of the loop being vectorized. */
2860 FOR_EACH_VEC_ELT (may_misalign_stmts, i, stmt_info)
2861 {
2862 dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
2863 SET_DR_MISALIGNMENT (dr_info,
2864 vect_dr_misalign_for_aligned_access (dr_info));
2865 if (dump_enabled_p ())
2866 dump_printf_loc (MSG_NOTE, vect_location,
2867 "Alignment of access forced using versioning.\n");
2868 }
2869
2870 if (dump_enabled_p ())
2871 dump_printf_loc (MSG_NOTE, vect_location,
2872 "Versioning for alignment will be applied.\n");
2873
2874 /* Peeling and versioning can't be done together at this time. */
2875 gcc_assert (! (do_peeling && do_versioning));
2876
2877 return opt_result::success ();
2878 }
2879
2880 /* This point is reached if neither peeling nor versioning is being done. */
2881 gcc_assert (! (do_peeling || do_versioning));
2882
2883 return opt_result::success ();
2884 }
2885
2886
2887 /* Function vect_analyze_data_refs_alignment
2888
2889 Analyze the alignment of the data-references in the loop.
2890 Return FALSE if a data reference is found that cannot be vectorized. */
2891
2892 opt_result
2893 vect_analyze_data_refs_alignment (loop_vec_info loop_vinfo)
2894 {
2895 DUMP_VECT_SCOPE ("vect_analyze_data_refs_alignment");
2896
2897 vec<data_reference_p> datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
2898 struct data_reference *dr;
2899 unsigned int i;
2900
2901 vect_record_base_alignments (loop_vinfo);
2902 FOR_EACH_VEC_ELT (datarefs, i, dr)
2903 {
2904 dr_vec_info *dr_info = loop_vinfo->lookup_dr (dr);
2905 if (STMT_VINFO_VECTORIZABLE (dr_info->stmt))
2906 {
2907 if (STMT_VINFO_GROUPED_ACCESS (dr_info->stmt)
2908 && DR_GROUP_FIRST_ELEMENT (dr_info->stmt) != dr_info->stmt)
2909 continue;
2910
2911 vect_compute_data_ref_alignment (loop_vinfo, dr_info,
2912 STMT_VINFO_VECTYPE (dr_info->stmt));
2913 }
2914 }
2915
2916 return opt_result::success ();
2917 }
2918
2919
2920 /* Analyze alignment of DRs of stmts in NODE. */
2921
2922 static bool
2923 vect_slp_analyze_node_alignment (vec_info *vinfo, slp_tree node)
2924 {
2925 /* Alignment is maintained in the first element of the group. */
2926 stmt_vec_info first_stmt_info = SLP_TREE_SCALAR_STMTS (node)[0];
2927 first_stmt_info = DR_GROUP_FIRST_ELEMENT (first_stmt_info);
2928 dr_vec_info *dr_info = STMT_VINFO_DR_INFO (first_stmt_info);
2929 tree vectype = SLP_TREE_VECTYPE (node);
2930 poly_uint64 vector_alignment
2931 = exact_div (targetm.vectorize.preferred_vector_alignment (vectype),
2932 BITS_PER_UNIT);
2933 if (dr_info->misalignment == DR_MISALIGNMENT_UNINITIALIZED)
2934 vect_compute_data_ref_alignment (vinfo, dr_info, SLP_TREE_VECTYPE (node));
2935 /* Re-analyze alignment when we're facing a vectorization with a bigger
2936 alignment requirement. */
2937 else if (known_lt (dr_info->target_alignment, vector_alignment))
2938 {
2939 poly_uint64 old_target_alignment = dr_info->target_alignment;
2940 int old_misalignment = dr_info->misalignment;
2941 vect_compute_data_ref_alignment (vinfo, dr_info, SLP_TREE_VECTYPE (node));
2942 /* But keep knowledge about a smaller alignment. */
2943 if (old_misalignment != DR_MISALIGNMENT_UNKNOWN
2944 && dr_info->misalignment == DR_MISALIGNMENT_UNKNOWN)
2945 {
2946 dr_info->target_alignment = old_target_alignment;
2947 dr_info->misalignment = old_misalignment;
2948 }
2949 }
2950 /* When we ever face unordered target alignments the first one wins in terms
2951 of analyzing and the other will become unknown in dr_misalignment. */
2952 return true;
2953 }
2954
2955 /* Function vect_slp_analyze_instance_alignment
2956
2957 Analyze the alignment of the data-references in the SLP instance.
2958 Return FALSE if a data reference is found that cannot be vectorized. */
2959
2960 bool
2961 vect_slp_analyze_instance_alignment (vec_info *vinfo,
2962 slp_instance instance)
2963 {
2964 DUMP_VECT_SCOPE ("vect_slp_analyze_instance_alignment");
2965
2966 slp_tree node;
2967 unsigned i;
2968 FOR_EACH_VEC_ELT (SLP_INSTANCE_LOADS (instance), i, node)
2969 if (! vect_slp_analyze_node_alignment (vinfo, node))
2970 return false;
2971
2972 if (SLP_INSTANCE_KIND (instance) == slp_inst_kind_store
2973 && ! vect_slp_analyze_node_alignment
2974 (vinfo, SLP_INSTANCE_TREE (instance)))
2975 return false;
2976
2977 return true;
2978 }
2979
2980
2981 /* Analyze groups of accesses: check that DR_INFO belongs to a group of
2982 accesses of legal size, step, etc. Detect gaps, single element
2983 interleaving, and other special cases. Set grouped access info.
2984 Collect groups of strided stores for further use in SLP analysis.
2985 Worker for vect_analyze_group_access. */
2986
2987 static bool
2988 vect_analyze_group_access_1 (vec_info *vinfo, dr_vec_info *dr_info)
2989 {
2990 data_reference *dr = dr_info->dr;
2991 tree step = DR_STEP (dr);
2992 tree scalar_type = TREE_TYPE (DR_REF (dr));
2993 HOST_WIDE_INT type_size = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (scalar_type));
2994 stmt_vec_info stmt_info = dr_info->stmt;
2995 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
2996 bb_vec_info bb_vinfo = dyn_cast <bb_vec_info> (vinfo);
2997 HOST_WIDE_INT dr_step = -1;
2998 HOST_WIDE_INT groupsize, last_accessed_element = 1;
2999 bool slp_impossible = false;
3000
3001 /* For interleaving, GROUPSIZE is STEP counted in elements, i.e., the
3002 size of the interleaving group (including gaps). */
3003 if (tree_fits_shwi_p (step))
3004 {
3005 dr_step = tree_to_shwi (step);
3006 /* Check that STEP is a multiple of type size. Otherwise there is
3007 a non-element-sized gap at the end of the group which we
3008 cannot represent in DR_GROUP_GAP or DR_GROUP_SIZE.
3009 ??? As we can handle non-constant step fine here we should
3010 simply remove uses of DR_GROUP_GAP between the last and first
3011 element and instead rely on DR_STEP. DR_GROUP_SIZE then would
3012 simply not include that gap. */
3013 if ((dr_step % type_size) != 0)
3014 {
3015 if (dump_enabled_p ())
3016 dump_printf_loc (MSG_NOTE, vect_location,
3017 "Step %T is not a multiple of the element size"
3018 " for %T\n",
3019 step, DR_REF (dr));
3020 return false;
3021 }
3022 groupsize = absu_hwi (dr_step) / type_size;
3023 }
3024 else
3025 groupsize = 0;
3026
3027 /* Not consecutive access is possible only if it is a part of interleaving. */
3028 if (!DR_GROUP_FIRST_ELEMENT (stmt_info))
3029 {
3030 /* Check if it this DR is a part of interleaving, and is a single
3031 element of the group that is accessed in the loop. */
3032
3033 /* Gaps are supported only for loads. STEP must be a multiple of the type
3034 size. */
3035 if (DR_IS_READ (dr)
3036 && (dr_step % type_size) == 0
3037 && groupsize > 0
3038 /* This could be UINT_MAX but as we are generating code in a very
3039 inefficient way we have to cap earlier.
3040 See PR91403 for example. */
3041 && groupsize <= 4096)
3042 {
3043 DR_GROUP_FIRST_ELEMENT (stmt_info) = stmt_info;
3044 DR_GROUP_SIZE (stmt_info) = groupsize;
3045 DR_GROUP_GAP (stmt_info) = groupsize - 1;
3046 if (dump_enabled_p ())
3047 dump_printf_loc (MSG_NOTE, vect_location,
3048 "Detected single element interleaving %T"
3049 " step %T\n",
3050 DR_REF (dr), step);
3051
3052 return true;
3053 }
3054
3055 if (dump_enabled_p ())
3056 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3057 "not consecutive access %G", stmt_info->stmt);
3058
3059 if (bb_vinfo)
3060 {
3061 /* Mark the statement as unvectorizable. */
3062 STMT_VINFO_VECTORIZABLE (stmt_info) = false;
3063 return true;
3064 }
3065
3066 if (dump_enabled_p ())
3067 dump_printf_loc (MSG_NOTE, vect_location, "using strided accesses\n");
3068 STMT_VINFO_STRIDED_P (stmt_info) = true;
3069 return true;
3070 }
3071
3072 if (DR_GROUP_FIRST_ELEMENT (stmt_info) == stmt_info)
3073 {
3074 /* First stmt in the interleaving chain. Check the chain. */
3075 stmt_vec_info next = DR_GROUP_NEXT_ELEMENT (stmt_info);
3076 struct data_reference *data_ref = dr;
3077 unsigned int count = 1;
3078 tree prev_init = DR_INIT (data_ref);
3079 HOST_WIDE_INT diff, gaps = 0;
3080
3081 /* By construction, all group members have INTEGER_CST DR_INITs. */
3082 while (next)
3083 {
3084 /* We never have the same DR multiple times. */
3085 gcc_assert (tree_int_cst_compare (DR_INIT (data_ref),
3086 DR_INIT (STMT_VINFO_DATA_REF (next))) != 0);
3087
3088 data_ref = STMT_VINFO_DATA_REF (next);
3089
3090 /* All group members have the same STEP by construction. */
3091 gcc_checking_assert (operand_equal_p (DR_STEP (data_ref), step, 0));
3092
3093 /* Check that the distance between two accesses is equal to the type
3094 size. Otherwise, we have gaps. */
3095 diff = (TREE_INT_CST_LOW (DR_INIT (data_ref))
3096 - TREE_INT_CST_LOW (prev_init)) / type_size;
3097 if (diff < 1 || diff > UINT_MAX)
3098 {
3099 /* For artificial testcases with array accesses with large
3100 constant indices we can run into overflow issues which
3101 can end up fooling the groupsize constraint below so
3102 check the individual gaps (which are represented as
3103 unsigned int) as well. */
3104 if (dump_enabled_p ())
3105 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3106 "interleaved access with gap larger "
3107 "than representable\n");
3108 return false;
3109 }
3110 if (diff != 1)
3111 {
3112 /* FORNOW: SLP of accesses with gaps is not supported. */
3113 slp_impossible = true;
3114 if (DR_IS_WRITE (data_ref))
3115 {
3116 if (dump_enabled_p ())
3117 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3118 "interleaved store with gaps\n");
3119 return false;
3120 }
3121
3122 gaps += diff - 1;
3123 }
3124
3125 last_accessed_element += diff;
3126
3127 /* Store the gap from the previous member of the group. If there is no
3128 gap in the access, DR_GROUP_GAP is always 1. */
3129 DR_GROUP_GAP (next) = diff;
3130
3131 prev_init = DR_INIT (data_ref);
3132 next = DR_GROUP_NEXT_ELEMENT (next);
3133 /* Count the number of data-refs in the chain. */
3134 count++;
3135 }
3136
3137 if (groupsize == 0)
3138 groupsize = count + gaps;
3139
3140 /* This could be UINT_MAX but as we are generating code in a very
3141 inefficient way we have to cap earlier. See PR78699 for example. */
3142 if (groupsize > 4096)
3143 {
3144 if (dump_enabled_p ())
3145 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3146 "group is too large\n");
3147 return false;
3148 }
3149
3150 /* Check that the size of the interleaving is equal to count for stores,
3151 i.e., that there are no gaps. */
3152 if (groupsize != count
3153 && !DR_IS_READ (dr))
3154 {
3155 groupsize = count;
3156 STMT_VINFO_STRIDED_P (stmt_info) = true;
3157 }
3158
3159 /* If there is a gap after the last load in the group it is the
3160 difference between the groupsize and the last accessed
3161 element.
3162 When there is no gap, this difference should be 0. */
3163 DR_GROUP_GAP (stmt_info) = groupsize - last_accessed_element;
3164
3165 DR_GROUP_SIZE (stmt_info) = groupsize;
3166 if (dump_enabled_p ())
3167 {
3168 dump_printf_loc (MSG_NOTE, vect_location,
3169 "Detected interleaving ");
3170 if (DR_IS_READ (dr))
3171 dump_printf (MSG_NOTE, "load ");
3172 else if (STMT_VINFO_STRIDED_P (stmt_info))
3173 dump_printf (MSG_NOTE, "strided store ");
3174 else
3175 dump_printf (MSG_NOTE, "store ");
3176 dump_printf (MSG_NOTE, "of size %u\n",
3177 (unsigned)groupsize);
3178 dump_printf_loc (MSG_NOTE, vect_location, "\t%G", stmt_info->stmt);
3179 next = DR_GROUP_NEXT_ELEMENT (stmt_info);
3180 while (next)
3181 {
3182 if (DR_GROUP_GAP (next) != 1)
3183 dump_printf_loc (MSG_NOTE, vect_location,
3184 "\t<gap of %d elements>\n",
3185 DR_GROUP_GAP (next) - 1);
3186 dump_printf_loc (MSG_NOTE, vect_location, "\t%G", next->stmt);
3187 next = DR_GROUP_NEXT_ELEMENT (next);
3188 }
3189 if (DR_GROUP_GAP (stmt_info) != 0)
3190 dump_printf_loc (MSG_NOTE, vect_location,
3191 "\t<gap of %d elements>\n",
3192 DR_GROUP_GAP (stmt_info));
3193 }
3194
3195 /* SLP: create an SLP data structure for every interleaving group of
3196 stores for further analysis in vect_analyse_slp. */
3197 if (DR_IS_WRITE (dr) && !slp_impossible)
3198 {
3199 if (loop_vinfo)
3200 LOOP_VINFO_GROUPED_STORES (loop_vinfo).safe_push (stmt_info);
3201 if (bb_vinfo)
3202 BB_VINFO_GROUPED_STORES (bb_vinfo).safe_push (stmt_info);
3203 }
3204 }
3205
3206 return true;
3207 }
3208
3209 /* Analyze groups of accesses: check that DR_INFO belongs to a group of
3210 accesses of legal size, step, etc. Detect gaps, single element
3211 interleaving, and other special cases. Set grouped access info.
3212 Collect groups of strided stores for further use in SLP analysis. */
3213
3214 static bool
3215 vect_analyze_group_access (vec_info *vinfo, dr_vec_info *dr_info)
3216 {
3217 if (!vect_analyze_group_access_1 (vinfo, dr_info))
3218 {
3219 /* Dissolve the group if present. */
3220 stmt_vec_info stmt_info = DR_GROUP_FIRST_ELEMENT (dr_info->stmt);
3221 while (stmt_info)
3222 {
3223 stmt_vec_info next = DR_GROUP_NEXT_ELEMENT (stmt_info);
3224 DR_GROUP_FIRST_ELEMENT (stmt_info) = NULL;
3225 DR_GROUP_NEXT_ELEMENT (stmt_info) = NULL;
3226 stmt_info = next;
3227 }
3228 return false;
3229 }
3230 return true;
3231 }
3232
3233 /* Analyze the access pattern of the data-reference DR_INFO.
3234 In case of non-consecutive accesses call vect_analyze_group_access() to
3235 analyze groups of accesses. */
3236
3237 static bool
3238 vect_analyze_data_ref_access (vec_info *vinfo, dr_vec_info *dr_info)
3239 {
3240 data_reference *dr = dr_info->dr;
3241 tree step = DR_STEP (dr);
3242 tree scalar_type = TREE_TYPE (DR_REF (dr));
3243 stmt_vec_info stmt_info = dr_info->stmt;
3244 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
3245 class loop *loop = NULL;
3246
3247 if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
3248 return true;
3249
3250 if (loop_vinfo)
3251 loop = LOOP_VINFO_LOOP (loop_vinfo);
3252
3253 if (loop_vinfo && !step)
3254 {
3255 if (dump_enabled_p ())
3256 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3257 "bad data-ref access in loop\n");
3258 return false;
3259 }
3260
3261 /* Allow loads with zero step in inner-loop vectorization. */
3262 if (loop_vinfo && integer_zerop (step))
3263 {
3264 DR_GROUP_FIRST_ELEMENT (stmt_info) = NULL;
3265 DR_GROUP_NEXT_ELEMENT (stmt_info) = NULL;
3266 if (!nested_in_vect_loop_p (loop, stmt_info))
3267 return DR_IS_READ (dr);
3268 /* Allow references with zero step for outer loops marked
3269 with pragma omp simd only - it guarantees absence of
3270 loop-carried dependencies between inner loop iterations. */
3271 if (loop->safelen < 2)
3272 {
3273 if (dump_enabled_p ())
3274 dump_printf_loc (MSG_NOTE, vect_location,
3275 "zero step in inner loop of nest\n");
3276 return false;
3277 }
3278 }
3279
3280 if (loop && nested_in_vect_loop_p (loop, stmt_info))
3281 {
3282 /* Interleaved accesses are not yet supported within outer-loop
3283 vectorization for references in the inner-loop. */
3284 DR_GROUP_FIRST_ELEMENT (stmt_info) = NULL;
3285 DR_GROUP_NEXT_ELEMENT (stmt_info) = NULL;
3286
3287 /* For the rest of the analysis we use the outer-loop step. */
3288 step = STMT_VINFO_DR_STEP (stmt_info);
3289 if (integer_zerop (step))
3290 {
3291 if (dump_enabled_p ())
3292 dump_printf_loc (MSG_NOTE, vect_location,
3293 "zero step in outer loop.\n");
3294 return DR_IS_READ (dr);
3295 }
3296 }
3297
3298 /* Consecutive? */
3299 if (TREE_CODE (step) == INTEGER_CST)
3300 {
3301 HOST_WIDE_INT dr_step = TREE_INT_CST_LOW (step);
3302 if (!tree_int_cst_compare (step, TYPE_SIZE_UNIT (scalar_type))
3303 || (dr_step < 0
3304 && !compare_tree_int (TYPE_SIZE_UNIT (scalar_type), -dr_step)))
3305 {
3306 /* Mark that it is not interleaving. */
3307 DR_GROUP_FIRST_ELEMENT (stmt_info) = NULL;
3308 DR_GROUP_NEXT_ELEMENT (stmt_info) = NULL;
3309 return true;
3310 }
3311 }
3312
3313 if (loop && nested_in_vect_loop_p (loop, stmt_info))
3314 {
3315 if (dump_enabled_p ())
3316 dump_printf_loc (MSG_NOTE, vect_location,
3317 "grouped access in outer loop.\n");
3318 return false;
3319 }
3320
3321
3322 /* Assume this is a DR handled by non-constant strided load case. */
3323 if (TREE_CODE (step) != INTEGER_CST)
3324 return (STMT_VINFO_STRIDED_P (stmt_info)
3325 && (!STMT_VINFO_GROUPED_ACCESS (stmt_info)
3326 || vect_analyze_group_access (vinfo, dr_info)));
3327
3328 /* Not consecutive access - check if it's a part of interleaving group. */
3329 return vect_analyze_group_access (vinfo, dr_info);
3330 }
3331
3332 /* Compare two data-references DRA and DRB to group them into chunks
3333 suitable for grouping. */
3334
3335 static int
3336 dr_group_sort_cmp (const void *dra_, const void *drb_)
3337 {
3338 dr_vec_info *dra_info = *(dr_vec_info **)const_cast<void *>(dra_);
3339 dr_vec_info *drb_info = *(dr_vec_info **)const_cast<void *>(drb_);
3340 data_reference_p dra = dra_info->dr;
3341 data_reference_p drb = drb_info->dr;
3342 int cmp;
3343
3344 /* Stabilize sort. */
3345 if (dra == drb)
3346 return 0;
3347
3348 /* Different group IDs lead never belong to the same group. */
3349 if (dra_info->group != drb_info->group)
3350 return dra_info->group < drb_info->group ? -1 : 1;
3351
3352 /* Ordering of DRs according to base. */
3353 cmp = data_ref_compare_tree (DR_BASE_ADDRESS (dra),
3354 DR_BASE_ADDRESS (drb));
3355 if (cmp != 0)
3356 return cmp;
3357
3358 /* And according to DR_OFFSET. */
3359 cmp = data_ref_compare_tree (DR_OFFSET (dra), DR_OFFSET (drb));
3360 if (cmp != 0)
3361 return cmp;
3362
3363 /* Put reads before writes. */
3364 if (DR_IS_READ (dra) != DR_IS_READ (drb))
3365 return DR_IS_READ (dra) ? -1 : 1;
3366
3367 /* Then sort after access size. */
3368 cmp = data_ref_compare_tree (TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dra))),
3369 TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (drb))));
3370 if (cmp != 0)
3371 return cmp;
3372
3373 /* And after step. */
3374 cmp = data_ref_compare_tree (DR_STEP (dra), DR_STEP (drb));
3375 if (cmp != 0)
3376 return cmp;
3377
3378 /* Then sort after DR_INIT. In case of identical DRs sort after stmt UID. */
3379 cmp = data_ref_compare_tree (DR_INIT (dra), DR_INIT (drb));
3380 if (cmp == 0)
3381 return gimple_uid (DR_STMT (dra)) < gimple_uid (DR_STMT (drb)) ? -1 : 1;
3382 return cmp;
3383 }
3384
3385 /* If OP is the result of a conversion, return the unconverted value,
3386 otherwise return null. */
3387
3388 static tree
3389 strip_conversion (tree op)
3390 {
3391 if (TREE_CODE (op) != SSA_NAME)
3392 return NULL_TREE;
3393 gimple *stmt = SSA_NAME_DEF_STMT (op);
3394 if (!is_gimple_assign (stmt)
3395 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt)))
3396 return NULL_TREE;
3397 return gimple_assign_rhs1 (stmt);
3398 }
3399
3400 /* Return true if vectorizable_* routines can handle statements STMT1_INFO
3401 and STMT2_INFO being in a single group. When ALLOW_SLP_P, masked loads can
3402 be grouped in SLP mode. */
3403
3404 static bool
3405 can_group_stmts_p (stmt_vec_info stmt1_info, stmt_vec_info stmt2_info,
3406 bool allow_slp_p)
3407 {
3408 if (gimple_assign_single_p (stmt1_info->stmt))
3409 return gimple_assign_single_p (stmt2_info->stmt);
3410
3411 gcall *call1 = dyn_cast <gcall *> (stmt1_info->stmt);
3412 if (call1 && gimple_call_internal_p (call1))
3413 {
3414 /* Check for two masked loads or two masked stores. */
3415 gcall *call2 = dyn_cast <gcall *> (stmt2_info->stmt);
3416 if (!call2 || !gimple_call_internal_p (call2))
3417 return false;
3418 internal_fn ifn = gimple_call_internal_fn (call1);
3419 if (ifn != IFN_MASK_LOAD && ifn != IFN_MASK_STORE)
3420 return false;
3421 if (ifn != gimple_call_internal_fn (call2))
3422 return false;
3423
3424 /* Check that the masks are the same. Cope with casts of masks,
3425 like those created by build_mask_conversion. */
3426 tree mask1 = gimple_call_arg (call1, 2);
3427 tree mask2 = gimple_call_arg (call2, 2);
3428 if (!operand_equal_p (mask1, mask2, 0) && !allow_slp_p)
3429 {
3430 mask1 = strip_conversion (mask1);
3431 if (!mask1)
3432 return false;
3433 mask2 = strip_conversion (mask2);
3434 if (!mask2)
3435 return false;
3436 if (!operand_equal_p (mask1, mask2, 0))
3437 return false;
3438 }
3439 return true;
3440 }
3441
3442 return false;
3443 }
3444
3445 /* Function vect_analyze_data_ref_accesses.
3446
3447 Analyze the access pattern of all the data references in the loop.
3448
3449 FORNOW: the only access pattern that is considered vectorizable is a
3450 simple step 1 (consecutive) access.
3451
3452 FORNOW: handle only arrays and pointer accesses. */
3453
3454 opt_result
3455 vect_analyze_data_ref_accesses (vec_info *vinfo,
3456 vec<int> *dataref_groups)
3457 {
3458 unsigned int i;
3459 vec<data_reference_p> datarefs = vinfo->shared->datarefs;
3460
3461 DUMP_VECT_SCOPE ("vect_analyze_data_ref_accesses");
3462
3463 if (datarefs.is_empty ())
3464 return opt_result::success ();
3465
3466 /* Sort the array of datarefs to make building the interleaving chains
3467 linear. Don't modify the original vector's order, it is needed for
3468 determining what dependencies are reversed. */
3469 vec<dr_vec_info *> datarefs_copy;
3470 datarefs_copy.create (datarefs.length ());
3471 for (unsigned i = 0; i < datarefs.length (); i++)
3472 {
3473 dr_vec_info *dr_info = vinfo->lookup_dr (datarefs[i]);
3474 /* If the caller computed DR grouping use that, otherwise group by
3475 basic blocks. */
3476 if (dataref_groups)
3477 dr_info->group = (*dataref_groups)[i];
3478 else
3479 dr_info->group = gimple_bb (DR_STMT (datarefs[i]))->index;
3480 datarefs_copy.quick_push (dr_info);
3481 }
3482 datarefs_copy.qsort (dr_group_sort_cmp);
3483 hash_set<stmt_vec_info> to_fixup;
3484
3485 /* Build the interleaving chains. */
3486 for (i = 0; i < datarefs_copy.length () - 1;)
3487 {
3488 dr_vec_info *dr_info_a = datarefs_copy[i];
3489 data_reference_p dra = dr_info_a->dr;
3490 int dra_group_id = dr_info_a->group;
3491 stmt_vec_info stmtinfo_a = dr_info_a->stmt;
3492 stmt_vec_info lastinfo = NULL;
3493 if (!STMT_VINFO_VECTORIZABLE (stmtinfo_a)
3494 || STMT_VINFO_GATHER_SCATTER_P (stmtinfo_a))
3495 {
3496 ++i;
3497 continue;
3498 }
3499 for (i = i + 1; i < datarefs_copy.length (); ++i)
3500 {
3501 dr_vec_info *dr_info_b = datarefs_copy[i];
3502 data_reference_p drb = dr_info_b->dr;
3503 int drb_group_id = dr_info_b->group;
3504 stmt_vec_info stmtinfo_b = dr_info_b->stmt;
3505 if (!STMT_VINFO_VECTORIZABLE (stmtinfo_b)
3506 || STMT_VINFO_GATHER_SCATTER_P (stmtinfo_b))
3507 break;
3508
3509 /* ??? Imperfect sorting (non-compatible types, non-modulo
3510 accesses, same accesses) can lead to a group to be artificially
3511 split here as we don't just skip over those. If it really
3512 matters we can push those to a worklist and re-iterate
3513 over them. The we can just skip ahead to the next DR here. */
3514
3515 /* DRs in a different DR group should not be put into the same
3516 interleaving group. */
3517 if (dra_group_id != drb_group_id)
3518 break;
3519
3520 /* Check that the data-refs have same first location (except init)
3521 and they are both either store or load (not load and store,
3522 not masked loads or stores). */
3523 if (DR_IS_READ (dra) != DR_IS_READ (drb)
3524 || data_ref_compare_tree (DR_BASE_ADDRESS (dra),
3525 DR_BASE_ADDRESS (drb)) != 0
3526 || data_ref_compare_tree (DR_OFFSET (dra), DR_OFFSET (drb)) != 0
3527 || !can_group_stmts_p (stmtinfo_a, stmtinfo_b, true))
3528 break;
3529
3530 /* Check that the data-refs have the same constant size. */
3531 tree sza = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dra)));
3532 tree szb = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (drb)));
3533 if (!tree_fits_uhwi_p (sza)
3534 || !tree_fits_uhwi_p (szb)
3535 || !tree_int_cst_equal (sza, szb))
3536 break;
3537
3538 /* Check that the data-refs have the same step. */
3539 if (data_ref_compare_tree (DR_STEP (dra), DR_STEP (drb)) != 0)
3540 break;
3541
3542 /* Check the types are compatible.
3543 ??? We don't distinguish this during sorting. */
3544 if (!types_compatible_p (TREE_TYPE (DR_REF (dra)),
3545 TREE_TYPE (DR_REF (drb))))
3546 break;
3547
3548 /* Check that the DR_INITs are compile-time constants. */
3549 if (!tree_fits_shwi_p (DR_INIT (dra))
3550 || !tree_fits_shwi_p (DR_INIT (drb)))
3551 break;
3552
3553 /* Different .GOMP_SIMD_LANE calls still give the same lane,
3554 just hold extra information. */
3555 if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmtinfo_a)
3556 && STMT_VINFO_SIMD_LANE_ACCESS_P (stmtinfo_b)
3557 && data_ref_compare_tree (DR_INIT (dra), DR_INIT (drb)) == 0)
3558 break;
3559
3560 /* Sorting has ensured that DR_INIT (dra) <= DR_INIT (drb). */
3561 HOST_WIDE_INT init_a = TREE_INT_CST_LOW (DR_INIT (dra));
3562 HOST_WIDE_INT init_b = TREE_INT_CST_LOW (DR_INIT (drb));
3563 HOST_WIDE_INT init_prev
3564 = TREE_INT_CST_LOW (DR_INIT (datarefs_copy[i-1]->dr));
3565 gcc_assert (init_a <= init_b
3566 && init_a <= init_prev
3567 && init_prev <= init_b);
3568
3569 /* Do not place the same access in the interleaving chain twice. */
3570 if (init_b == init_prev)
3571 {
3572 gcc_assert (gimple_uid (DR_STMT (datarefs_copy[i-1]->dr))
3573 < gimple_uid (DR_STMT (drb)));
3574 /* Simply link in duplicates and fix up the chain below. */
3575 }
3576 else
3577 {
3578 /* If init_b == init_a + the size of the type * k, we have an
3579 interleaving, and DRA is accessed before DRB. */
3580 unsigned HOST_WIDE_INT type_size_a = tree_to_uhwi (sza);
3581 if (type_size_a == 0
3582 || (((unsigned HOST_WIDE_INT)init_b - init_a)
3583 % type_size_a != 0))
3584 break;
3585
3586 /* If we have a store, the accesses are adjacent. This splits
3587 groups into chunks we support (we don't support vectorization
3588 of stores with gaps). */
3589 if (!DR_IS_READ (dra)
3590 && (((unsigned HOST_WIDE_INT)init_b - init_prev)
3591 != type_size_a))
3592 break;
3593
3594 /* If the step (if not zero or non-constant) is smaller than the
3595 difference between data-refs' inits this splits groups into
3596 suitable sizes. */
3597 if (tree_fits_shwi_p (DR_STEP (dra)))
3598 {
3599 unsigned HOST_WIDE_INT step
3600 = absu_hwi (tree_to_shwi (DR_STEP (dra)));
3601 if (step != 0
3602 && step <= ((unsigned HOST_WIDE_INT)init_b - init_a))
3603 break;
3604 }
3605 }
3606
3607 if (dump_enabled_p ())
3608 dump_printf_loc (MSG_NOTE, vect_location,
3609 DR_IS_READ (dra)
3610 ? "Detected interleaving load %T and %T\n"
3611 : "Detected interleaving store %T and %T\n",
3612 DR_REF (dra), DR_REF (drb));
3613
3614 /* Link the found element into the group list. */
3615 if (!DR_GROUP_FIRST_ELEMENT (stmtinfo_a))
3616 {
3617 DR_GROUP_FIRST_ELEMENT (stmtinfo_a) = stmtinfo_a;
3618 lastinfo = stmtinfo_a;
3619 }
3620 DR_GROUP_FIRST_ELEMENT (stmtinfo_b) = stmtinfo_a;
3621 DR_GROUP_NEXT_ELEMENT (lastinfo) = stmtinfo_b;
3622 lastinfo = stmtinfo_b;
3623
3624 if (! STMT_VINFO_SLP_VECT_ONLY (stmtinfo_a))
3625 {
3626 STMT_VINFO_SLP_VECT_ONLY (stmtinfo_a)
3627 = !can_group_stmts_p (stmtinfo_a, stmtinfo_b, false);
3628
3629 if (dump_enabled_p () && STMT_VINFO_SLP_VECT_ONLY (stmtinfo_a))
3630 dump_printf_loc (MSG_NOTE, vect_location,
3631 "Load suitable for SLP vectorization only.\n");
3632 }
3633
3634 if (init_b == init_prev
3635 && !to_fixup.add (DR_GROUP_FIRST_ELEMENT (stmtinfo_a))
3636 && dump_enabled_p ())
3637 dump_printf_loc (MSG_NOTE, vect_location,
3638 "Queuing group with duplicate access for fixup\n");
3639 }
3640 }
3641
3642 /* Fixup groups with duplicate entries by splitting it. */
3643 while (1)
3644 {
3645 hash_set<stmt_vec_info>::iterator it = to_fixup.begin ();
3646 if (!(it != to_fixup.end ()))
3647 break;
3648 stmt_vec_info grp = *it;
3649 to_fixup.remove (grp);
3650
3651 /* Find the earliest duplicate group member. */
3652 unsigned first_duplicate = -1u;
3653 stmt_vec_info next, g = grp;
3654 while ((next = DR_GROUP_NEXT_ELEMENT (g)))
3655 {
3656 if (tree_int_cst_equal (DR_INIT (STMT_VINFO_DR_INFO (next)->dr),
3657 DR_INIT (STMT_VINFO_DR_INFO (g)->dr))
3658 && gimple_uid (STMT_VINFO_STMT (next)) < first_duplicate)
3659 first_duplicate = gimple_uid (STMT_VINFO_STMT (next));
3660 g = next;
3661 }
3662 if (first_duplicate == -1U)
3663 continue;
3664
3665 /* Then move all stmts after the first duplicate to a new group.
3666 Note this is a heuristic but one with the property that *it
3667 is fixed up completely. */
3668 g = grp;
3669 stmt_vec_info newgroup = NULL, ng = grp;
3670 while ((next = DR_GROUP_NEXT_ELEMENT (g)))
3671 {
3672 if (gimple_uid (STMT_VINFO_STMT (next)) >= first_duplicate)
3673 {
3674 DR_GROUP_NEXT_ELEMENT (g) = DR_GROUP_NEXT_ELEMENT (next);
3675 if (!newgroup)
3676 {
3677 newgroup = next;
3678 STMT_VINFO_SLP_VECT_ONLY (newgroup)
3679 = STMT_VINFO_SLP_VECT_ONLY (grp);
3680 }
3681 else
3682 DR_GROUP_NEXT_ELEMENT (ng) = next;
3683 ng = next;
3684 DR_GROUP_FIRST_ELEMENT (ng) = newgroup;
3685 }
3686 else
3687 g = DR_GROUP_NEXT_ELEMENT (g);
3688 }
3689 DR_GROUP_NEXT_ELEMENT (ng) = NULL;
3690
3691 /* Fixup the new group which still may contain duplicates. */
3692 to_fixup.add (newgroup);
3693 }
3694
3695 dr_vec_info *dr_info;
3696 FOR_EACH_VEC_ELT (datarefs_copy, i, dr_info)
3697 {
3698 if (STMT_VINFO_VECTORIZABLE (dr_info->stmt)
3699 && !vect_analyze_data_ref_access (vinfo, dr_info))
3700 {
3701 if (dump_enabled_p ())
3702 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3703 "not vectorized: complicated access pattern.\n");
3704
3705 if (is_a <bb_vec_info> (vinfo))
3706 {
3707 /* Mark the statement as not vectorizable. */
3708 STMT_VINFO_VECTORIZABLE (dr_info->stmt) = false;
3709 continue;
3710 }
3711 else
3712 {
3713 datarefs_copy.release ();
3714 return opt_result::failure_at (dr_info->stmt->stmt,
3715 "not vectorized:"
3716 " complicated access pattern.\n");
3717 }
3718 }
3719 }
3720
3721 datarefs_copy.release ();
3722 return opt_result::success ();
3723 }
3724
3725 /* Function vect_vfa_segment_size.
3726
3727 Input:
3728 DR_INFO: The data reference.
3729 LENGTH_FACTOR: segment length to consider.
3730
3731 Return a value suitable for the dr_with_seg_len::seg_len field.
3732 This is the "distance travelled" by the pointer from the first
3733 iteration in the segment to the last. Note that it does not include
3734 the size of the access; in effect it only describes the first byte. */
3735
3736 static tree
3737 vect_vfa_segment_size (dr_vec_info *dr_info, tree length_factor)
3738 {
3739 length_factor = size_binop (MINUS_EXPR,
3740 fold_convert (sizetype, length_factor),
3741 size_one_node);
3742 return size_binop (MULT_EXPR, fold_convert (sizetype, DR_STEP (dr_info->dr)),
3743 length_factor);
3744 }
3745
3746 /* Return a value that, when added to abs (vect_vfa_segment_size (DR_INFO)),
3747 gives the worst-case number of bytes covered by the segment. */
3748
3749 static unsigned HOST_WIDE_INT
3750 vect_vfa_access_size (vec_info *vinfo, dr_vec_info *dr_info)
3751 {
3752 stmt_vec_info stmt_vinfo = dr_info->stmt;
3753 tree ref_type = TREE_TYPE (DR_REF (dr_info->dr));
3754 unsigned HOST_WIDE_INT ref_size = tree_to_uhwi (TYPE_SIZE_UNIT (ref_type));
3755 unsigned HOST_WIDE_INT access_size = ref_size;
3756 if (DR_GROUP_FIRST_ELEMENT (stmt_vinfo))
3757 {
3758 gcc_assert (DR_GROUP_FIRST_ELEMENT (stmt_vinfo) == stmt_vinfo);
3759 access_size *= DR_GROUP_SIZE (stmt_vinfo) - DR_GROUP_GAP (stmt_vinfo);
3760 }
3761 tree vectype = STMT_VINFO_VECTYPE (stmt_vinfo);
3762 int misalignment;
3763 if (STMT_VINFO_VEC_STMTS (stmt_vinfo).exists ()
3764 && ((misalignment = dr_misalignment (dr_info, vectype)), true)
3765 && (vect_supportable_dr_alignment (vinfo, dr_info, vectype, misalignment)
3766 == dr_explicit_realign_optimized))
3767 {
3768 /* We might access a full vector's worth. */
3769 access_size += tree_to_uhwi (TYPE_SIZE_UNIT (vectype)) - ref_size;
3770 }
3771 return access_size;
3772 }
3773
3774 /* Get the minimum alignment for all the scalar accesses that DR_INFO
3775 describes. */
3776
3777 static unsigned int
3778 vect_vfa_align (dr_vec_info *dr_info)
3779 {
3780 return dr_alignment (dr_info->dr);
3781 }
3782
3783 /* Function vect_no_alias_p.
3784
3785 Given data references A and B with equal base and offset, see whether
3786 the alias relation can be decided at compilation time. Return 1 if
3787 it can and the references alias, 0 if it can and the references do
3788 not alias, and -1 if we cannot decide at compile time. SEGMENT_LENGTH_A,
3789 SEGMENT_LENGTH_B, ACCESS_SIZE_A and ACCESS_SIZE_B are the equivalent
3790 of dr_with_seg_len::{seg_len,access_size} for A and B. */
3791
3792 static int
3793 vect_compile_time_alias (dr_vec_info *a, dr_vec_info *b,
3794 tree segment_length_a, tree segment_length_b,
3795 unsigned HOST_WIDE_INT access_size_a,
3796 unsigned HOST_WIDE_INT access_size_b)
3797 {
3798 poly_offset_int offset_a = wi::to_poly_offset (DR_INIT (a->dr));
3799 poly_offset_int offset_b = wi::to_poly_offset (DR_INIT (b->dr));
3800 poly_uint64 const_length_a;
3801 poly_uint64 const_length_b;
3802
3803 /* For negative step, we need to adjust address range by TYPE_SIZE_UNIT
3804 bytes, e.g., int a[3] -> a[1] range is [a+4, a+16) instead of
3805 [a, a+12) */
3806 if (tree_int_cst_compare (DR_STEP (a->dr), size_zero_node) < 0)
3807 {
3808 const_length_a = (-wi::to_poly_wide (segment_length_a)).force_uhwi ();
3809 offset_a -= const_length_a;
3810 }
3811 else
3812 const_length_a = tree_to_poly_uint64 (segment_length_a);
3813 if (tree_int_cst_compare (DR_STEP (b->dr), size_zero_node) < 0)
3814 {
3815 const_length_b = (-wi::to_poly_wide (segment_length_b)).force_uhwi ();
3816 offset_b -= const_length_b;
3817 }
3818 else
3819 const_length_b = tree_to_poly_uint64 (segment_length_b);
3820
3821 const_length_a += access_size_a;
3822 const_length_b += access_size_b;
3823
3824 if (ranges_known_overlap_p (offset_a, const_length_a,
3825 offset_b, const_length_b))
3826 return 1;
3827
3828 if (!ranges_maybe_overlap_p (offset_a, const_length_a,
3829 offset_b, const_length_b))
3830 return 0;
3831
3832 return -1;
3833 }
3834
3835 /* Return true if the minimum nonzero dependence distance for loop LOOP_DEPTH
3836 in DDR is >= VF. */
3837
3838 static bool
3839 dependence_distance_ge_vf (data_dependence_relation *ddr,
3840 unsigned int loop_depth, poly_uint64 vf)
3841 {
3842 if (DDR_ARE_DEPENDENT (ddr) != NULL_TREE
3843 || DDR_NUM_DIST_VECTS (ddr) == 0)
3844 return false;
3845
3846 /* If the dependence is exact, we should have limited the VF instead. */
3847 gcc_checking_assert (DDR_COULD_BE_INDEPENDENT_P (ddr));
3848
3849 unsigned int i;
3850 lambda_vector dist_v;
3851 FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr), i, dist_v)
3852 {
3853 HOST_WIDE_INT dist = dist_v[loop_depth];
3854 if (dist != 0
3855 && !(dist > 0 && DDR_REVERSED_P (ddr))
3856 && maybe_lt ((unsigned HOST_WIDE_INT) abs_hwi (dist), vf))
3857 return false;
3858 }
3859
3860 if (dump_enabled_p ())
3861 dump_printf_loc (MSG_NOTE, vect_location,
3862 "dependence distance between %T and %T is >= VF\n",
3863 DR_REF (DDR_A (ddr)), DR_REF (DDR_B (ddr)));
3864
3865 return true;
3866 }
3867
3868 /* Dump LOWER_BOUND using flags DUMP_KIND. Dumps are known to be enabled. */
3869
3870 static void
3871 dump_lower_bound (dump_flags_t dump_kind, const vec_lower_bound &lower_bound)
3872 {
3873 dump_printf (dump_kind, "%s (%T) >= ",
3874 lower_bound.unsigned_p ? "unsigned" : "abs",
3875 lower_bound.expr);
3876 dump_dec (dump_kind, lower_bound.min_value);
3877 }
3878
3879 /* Record that the vectorized loop requires the vec_lower_bound described
3880 by EXPR, UNSIGNED_P and MIN_VALUE. */
3881
3882 static void
3883 vect_check_lower_bound (loop_vec_info loop_vinfo, tree expr, bool unsigned_p,
3884 poly_uint64 min_value)
3885 {
3886 vec<vec_lower_bound> &lower_bounds
3887 = LOOP_VINFO_LOWER_BOUNDS (loop_vinfo);
3888 for (unsigned int i = 0; i < lower_bounds.length (); ++i)
3889 if (operand_equal_p (lower_bounds[i].expr, expr, 0))
3890 {
3891 unsigned_p &= lower_bounds[i].unsigned_p;
3892 min_value = upper_bound (lower_bounds[i].min_value, min_value);
3893 if (lower_bounds[i].unsigned_p != unsigned_p
3894 || maybe_lt (lower_bounds[i].min_value, min_value))
3895 {
3896 lower_bounds[i].unsigned_p = unsigned_p;
3897 lower_bounds[i].min_value = min_value;
3898 if (dump_enabled_p ())
3899 {
3900 dump_printf_loc (MSG_NOTE, vect_location,
3901 "updating run-time check to ");
3902 dump_lower_bound (MSG_NOTE, lower_bounds[i]);
3903 dump_printf (MSG_NOTE, "\n");
3904 }
3905 }
3906 return;
3907 }
3908
3909 vec_lower_bound lower_bound (expr, unsigned_p, min_value);
3910 if (dump_enabled_p ())
3911 {
3912 dump_printf_loc (MSG_NOTE, vect_location, "need a run-time check that ");
3913 dump_lower_bound (MSG_NOTE, lower_bound);
3914 dump_printf (MSG_NOTE, "\n");
3915 }
3916 LOOP_VINFO_LOWER_BOUNDS (loop_vinfo).safe_push (lower_bound);
3917 }
3918
3919 /* Return true if it's unlikely that the step of the vectorized form of DR_INFO
3920 will span fewer than GAP bytes. */
3921
3922 static bool
3923 vect_small_gap_p (loop_vec_info loop_vinfo, dr_vec_info *dr_info,
3924 poly_int64 gap)
3925 {
3926 stmt_vec_info stmt_info = dr_info->stmt;
3927 HOST_WIDE_INT count
3928 = estimated_poly_value (LOOP_VINFO_VECT_FACTOR (loop_vinfo));
3929 if (DR_GROUP_FIRST_ELEMENT (stmt_info))
3930 count *= DR_GROUP_SIZE (DR_GROUP_FIRST_ELEMENT (stmt_info));
3931 return (estimated_poly_value (gap)
3932 <= count * vect_get_scalar_dr_size (dr_info));
3933 }
3934
3935 /* Return true if we know that there is no alias between DR_INFO_A and
3936 DR_INFO_B when abs (DR_STEP (DR_INFO_A->dr)) >= N for some N.
3937 When returning true, set *LOWER_BOUND_OUT to this N. */
3938
3939 static bool
3940 vectorizable_with_step_bound_p (dr_vec_info *dr_info_a, dr_vec_info *dr_info_b,
3941 poly_uint64 *lower_bound_out)
3942 {
3943 /* Check that there is a constant gap of known sign between DR_A
3944 and DR_B. */
3945 data_reference *dr_a = dr_info_a->dr;
3946 data_reference *dr_b = dr_info_b->dr;
3947 poly_int64 init_a, init_b;
3948 if (!operand_equal_p (DR_BASE_ADDRESS (dr_a), DR_BASE_ADDRESS (dr_b), 0)
3949 || !operand_equal_p (DR_OFFSET (dr_a), DR_OFFSET (dr_b), 0)
3950 || !operand_equal_p (DR_STEP (dr_a), DR_STEP (dr_b), 0)
3951 || !poly_int_tree_p (DR_INIT (dr_a), &init_a)
3952 || !poly_int_tree_p (DR_INIT (dr_b), &init_b)
3953 || !ordered_p (init_a, init_b))
3954 return false;
3955
3956 /* Sort DR_A and DR_B by the address they access. */
3957 if (maybe_lt (init_b, init_a))
3958 {
3959 std::swap (init_a, init_b);
3960 std::swap (dr_info_a, dr_info_b);
3961 std::swap (dr_a, dr_b);
3962 }
3963
3964 /* If the two accesses could be dependent within a scalar iteration,
3965 make sure that we'd retain their order. */
3966 if (maybe_gt (init_a + vect_get_scalar_dr_size (dr_info_a), init_b)
3967 && !vect_preserves_scalar_order_p (dr_info_a, dr_info_b))
3968 return false;
3969
3970 /* There is no alias if abs (DR_STEP) is greater than or equal to
3971 the bytes spanned by the combination of the two accesses. */
3972 *lower_bound_out = init_b + vect_get_scalar_dr_size (dr_info_b) - init_a;
3973 return true;
3974 }
3975
3976 /* Function vect_prune_runtime_alias_test_list.
3977
3978 Prune a list of ddrs to be tested at run-time by versioning for alias.
3979 Merge several alias checks into one if possible.
3980 Return FALSE if resulting list of ddrs is longer then allowed by
3981 PARAM_VECT_MAX_VERSION_FOR_ALIAS_CHECKS, otherwise return TRUE. */
3982
3983 opt_result
3984 vect_prune_runtime_alias_test_list (loop_vec_info loop_vinfo)
3985 {
3986 typedef pair_hash <tree_operand_hash, tree_operand_hash> tree_pair_hash;
3987 hash_set <tree_pair_hash> compared_objects;
3988
3989 const vec<ddr_p> &may_alias_ddrs = LOOP_VINFO_MAY_ALIAS_DDRS (loop_vinfo);
3990 vec<dr_with_seg_len_pair_t> &comp_alias_ddrs
3991 = LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo);
3992 const vec<vec_object_pair> &check_unequal_addrs
3993 = LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo);
3994 poly_uint64 vect_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3995 tree scalar_loop_iters = LOOP_VINFO_NITERS (loop_vinfo);
3996
3997 ddr_p ddr;
3998 unsigned int i;
3999 tree length_factor;
4000
4001 DUMP_VECT_SCOPE ("vect_prune_runtime_alias_test_list");
4002
4003 /* Step values are irrelevant for aliasing if the number of vector
4004 iterations is equal to the number of scalar iterations (which can
4005 happen for fully-SLP loops). */
4006 bool vf_one_p = known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), 1U);
4007
4008 if (!vf_one_p)
4009 {
4010 /* Convert the checks for nonzero steps into bound tests. */
4011 tree value;
4012 FOR_EACH_VEC_ELT (LOOP_VINFO_CHECK_NONZERO (loop_vinfo), i, value)
4013 vect_check_lower_bound (loop_vinfo, value, true, 1);
4014 }
4015
4016 if (may_alias_ddrs.is_empty ())
4017 return opt_result::success ();
4018
4019 comp_alias_ddrs.create (may_alias_ddrs.length ());
4020
4021 unsigned int loop_depth
4022 = index_in_loop_nest (LOOP_VINFO_LOOP (loop_vinfo)->num,
4023 LOOP_VINFO_LOOP_NEST (loop_vinfo));
4024
4025 /* First, we collect all data ref pairs for aliasing checks. */
4026 FOR_EACH_VEC_ELT (may_alias_ddrs, i, ddr)
4027 {
4028 poly_uint64 lower_bound;
4029 tree segment_length_a, segment_length_b;
4030 unsigned HOST_WIDE_INT access_size_a, access_size_b;
4031 unsigned HOST_WIDE_INT align_a, align_b;
4032
4033 /* Ignore the alias if the VF we chose ended up being no greater
4034 than the dependence distance. */
4035 if (dependence_distance_ge_vf (ddr, loop_depth, vect_factor))
4036 continue;
4037
4038 if (DDR_OBJECT_A (ddr))
4039 {
4040 vec_object_pair new_pair (DDR_OBJECT_A (ddr), DDR_OBJECT_B (ddr));
4041 if (!compared_objects.add (new_pair))
4042 {
4043 if (dump_enabled_p ())
4044 dump_printf_loc (MSG_NOTE, vect_location,
4045 "checking that %T and %T"
4046 " have different addresses\n",
4047 new_pair.first, new_pair.second);
4048 LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo).safe_push (new_pair);
4049 }
4050 continue;
4051 }
4052
4053 dr_vec_info *dr_info_a = loop_vinfo->lookup_dr (DDR_A (ddr));
4054 stmt_vec_info stmt_info_a = dr_info_a->stmt;
4055
4056 dr_vec_info *dr_info_b = loop_vinfo->lookup_dr (DDR_B (ddr));
4057 stmt_vec_info stmt_info_b = dr_info_b->stmt;
4058
4059 bool preserves_scalar_order_p
4060 = vect_preserves_scalar_order_p (dr_info_a, dr_info_b);
4061 bool ignore_step_p
4062 = (vf_one_p
4063 && (preserves_scalar_order_p
4064 || operand_equal_p (DR_STEP (dr_info_a->dr),
4065 DR_STEP (dr_info_b->dr))));
4066
4067 /* Skip the pair if inter-iteration dependencies are irrelevant
4068 and intra-iteration dependencies are guaranteed to be honored. */
4069 if (ignore_step_p
4070 && (preserves_scalar_order_p
4071 || vectorizable_with_step_bound_p (dr_info_a, dr_info_b,
4072 &lower_bound)))
4073 {
4074 if (dump_enabled_p ())
4075 dump_printf_loc (MSG_NOTE, vect_location,
4076 "no need for alias check between "
4077 "%T and %T when VF is 1\n",
4078 DR_REF (dr_info_a->dr), DR_REF (dr_info_b->dr));
4079 continue;
4080 }
4081
4082 /* See whether we can handle the alias using a bounds check on
4083 the step, and whether that's likely to be the best approach.
4084 (It might not be, for example, if the minimum step is much larger
4085 than the number of bytes handled by one vector iteration.) */
4086 if (!ignore_step_p
4087 && TREE_CODE (DR_STEP (dr_info_a->dr)) != INTEGER_CST
4088 && vectorizable_with_step_bound_p (dr_info_a, dr_info_b,
4089 &lower_bound)
4090 && (vect_small_gap_p (loop_vinfo, dr_info_a, lower_bound)
4091 || vect_small_gap_p (loop_vinfo, dr_info_b, lower_bound)))
4092 {
4093 bool unsigned_p = dr_known_forward_stride_p (dr_info_a->dr);
4094 if (dump_enabled_p ())
4095 {
4096 dump_printf_loc (MSG_NOTE, vect_location, "no alias between "
4097 "%T and %T when the step %T is outside ",
4098 DR_REF (dr_info_a->dr),
4099 DR_REF (dr_info_b->dr),
4100 DR_STEP (dr_info_a->dr));
4101 if (unsigned_p)
4102 dump_printf (MSG_NOTE, "[0");
4103 else
4104 {
4105 dump_printf (MSG_NOTE, "(");
4106 dump_dec (MSG_NOTE, poly_int64 (-lower_bound));
4107 }
4108 dump_printf (MSG_NOTE, ", ");
4109 dump_dec (MSG_NOTE, lower_bound);
4110 dump_printf (MSG_NOTE, ")\n");
4111 }
4112 vect_check_lower_bound (loop_vinfo, DR_STEP (dr_info_a->dr),
4113 unsigned_p, lower_bound);
4114 continue;
4115 }
4116
4117 stmt_vec_info dr_group_first_a = DR_GROUP_FIRST_ELEMENT (stmt_info_a);
4118 if (dr_group_first_a)
4119 {
4120 stmt_info_a = dr_group_first_a;
4121 dr_info_a = STMT_VINFO_DR_INFO (stmt_info_a);
4122 }
4123
4124 stmt_vec_info dr_group_first_b = DR_GROUP_FIRST_ELEMENT (stmt_info_b);
4125 if (dr_group_first_b)
4126 {
4127 stmt_info_b = dr_group_first_b;
4128 dr_info_b = STMT_VINFO_DR_INFO (stmt_info_b);
4129 }
4130
4131 if (ignore_step_p)
4132 {
4133 segment_length_a = size_zero_node;
4134 segment_length_b = size_zero_node;
4135 }
4136 else
4137 {
4138 if (!operand_equal_p (DR_STEP (dr_info_a->dr),
4139 DR_STEP (dr_info_b->dr), 0))
4140 length_factor = scalar_loop_iters;
4141 else
4142 length_factor = size_int (vect_factor);
4143 segment_length_a = vect_vfa_segment_size (dr_info_a, length_factor);
4144 segment_length_b = vect_vfa_segment_size (dr_info_b, length_factor);
4145 }
4146 access_size_a = vect_vfa_access_size (loop_vinfo, dr_info_a);
4147 access_size_b = vect_vfa_access_size (loop_vinfo, dr_info_b);
4148 align_a = vect_vfa_align (dr_info_a);
4149 align_b = vect_vfa_align (dr_info_b);
4150
4151 /* See whether the alias is known at compilation time. */
4152 if (operand_equal_p (DR_BASE_ADDRESS (dr_info_a->dr),
4153 DR_BASE_ADDRESS (dr_info_b->dr), 0)
4154 && operand_equal_p (DR_OFFSET (dr_info_a->dr),
4155 DR_OFFSET (dr_info_b->dr), 0)
4156 && TREE_CODE (DR_STEP (dr_info_a->dr)) == INTEGER_CST
4157 && TREE_CODE (DR_STEP (dr_info_b->dr)) == INTEGER_CST
4158 && poly_int_tree_p (segment_length_a)
4159 && poly_int_tree_p (segment_length_b))
4160 {
4161 int res = vect_compile_time_alias (dr_info_a, dr_info_b,
4162 segment_length_a,
4163 segment_length_b,
4164 access_size_a,
4165 access_size_b);
4166 if (res >= 0 && dump_enabled_p ())
4167 {
4168 dump_printf_loc (MSG_NOTE, vect_location,
4169 "can tell at compile time that %T and %T",
4170 DR_REF (dr_info_a->dr), DR_REF (dr_info_b->dr));
4171 if (res == 0)
4172 dump_printf (MSG_NOTE, " do not alias\n");
4173 else
4174 dump_printf (MSG_NOTE, " alias\n");
4175 }
4176
4177 if (res == 0)
4178 continue;
4179
4180 if (res == 1)
4181 return opt_result::failure_at (stmt_info_b->stmt,
4182 "not vectorized:"
4183 " compilation time alias: %G%G",
4184 stmt_info_a->stmt,
4185 stmt_info_b->stmt);
4186 }
4187
4188 /* dr_with_seg_len requires the alignment to apply to the segment length
4189 and access size, not just the start address. The access size can be
4190 smaller than the pointer alignment for grouped accesses and bitfield
4191 references; see PR115192 and PR116125 respectively. */
4192 align_a = std::min (align_a, least_bit_hwi (access_size_a));
4193 align_b = std::min (align_b, least_bit_hwi (access_size_b));
4194
4195 dr_with_seg_len dr_a (dr_info_a->dr, segment_length_a,
4196 access_size_a, align_a);
4197 dr_with_seg_len dr_b (dr_info_b->dr, segment_length_b,
4198 access_size_b, align_b);
4199 /* Canonicalize the order to be the one that's needed for accurate
4200 RAW, WAR and WAW flags, in cases where the data references are
4201 well-ordered. The order doesn't really matter otherwise,
4202 but we might as well be consistent. */
4203 if (get_later_stmt (stmt_info_a, stmt_info_b) == stmt_info_a)
4204 std::swap (dr_a, dr_b);
4205
4206 dr_with_seg_len_pair_t dr_with_seg_len_pair
4207 (dr_a, dr_b, (preserves_scalar_order_p
4208 ? dr_with_seg_len_pair_t::WELL_ORDERED
4209 : dr_with_seg_len_pair_t::REORDERED));
4210
4211 comp_alias_ddrs.safe_push (dr_with_seg_len_pair);
4212 }
4213
4214 prune_runtime_alias_test_list (&comp_alias_ddrs, vect_factor);
4215
4216 unsigned int count = (comp_alias_ddrs.length ()
4217 + check_unequal_addrs.length ());
4218
4219 if (count
4220 && (loop_cost_model (LOOP_VINFO_LOOP (loop_vinfo))
4221 == VECT_COST_MODEL_VERY_CHEAP))
4222 return opt_result::failure_at
4223 (vect_location, "would need a runtime alias check\n");
4224
4225 if (dump_enabled_p ())
4226 dump_printf_loc (MSG_NOTE, vect_location,
4227 "improved number of alias checks from %d to %d\n",
4228 may_alias_ddrs.length (), count);
4229 unsigned limit = param_vect_max_version_for_alias_checks;
4230 if (loop_cost_model (LOOP_VINFO_LOOP (loop_vinfo)) == VECT_COST_MODEL_CHEAP)
4231 limit = param_vect_max_version_for_alias_checks * 6 / 10;
4232 if (count > limit)
4233 return opt_result::failure_at
4234 (vect_location,
4235 "number of versioning for alias run-time tests exceeds %d "
4236 "(--param vect-max-version-for-alias-checks)\n", limit);
4237
4238 return opt_result::success ();
4239 }
4240
4241 /* Check whether we can use an internal function for a gather load
4242 or scatter store. READ_P is true for loads and false for stores.
4243 MASKED_P is true if the load or store is conditional. MEMORY_TYPE is
4244 the type of the memory elements being loaded or stored. OFFSET_TYPE
4245 is the type of the offset that is being applied to the invariant
4246 base address. SCALE is the amount by which the offset should
4247 be multiplied *after* it has been converted to address width.
4248
4249 Return true if the function is supported, storing the function id in
4250 *IFN_OUT and the vector type for the offset in *OFFSET_VECTYPE_OUT.
4251
4252 If we can use gather and store the possible else values in ELSVALS. */
4253
4254 bool
4255 vect_gather_scatter_fn_p (vec_info *vinfo, bool read_p, bool masked_p,
4256 tree vectype, tree memory_type, tree offset_type,
4257 int scale, internal_fn *ifn_out,
4258 tree *offset_vectype_out, vec<int> *elsvals)
4259 {
4260 unsigned int memory_bits = tree_to_uhwi (TYPE_SIZE (memory_type));
4261 unsigned int element_bits = vector_element_bits (vectype);
4262 if (element_bits != memory_bits)
4263 /* For now the vector elements must be the same width as the
4264 memory elements. */
4265 return false;
4266
4267 /* Work out which function we need. */
4268 internal_fn ifn, alt_ifn, alt_ifn2;
4269 if (read_p)
4270 {
4271 ifn = masked_p ? IFN_MASK_GATHER_LOAD : IFN_GATHER_LOAD;
4272 alt_ifn = IFN_MASK_GATHER_LOAD;
4273 /* When target supports MASK_LEN_GATHER_LOAD, we always
4274 use MASK_LEN_GATHER_LOAD regardless whether len and
4275 mask are valid or not. */
4276 alt_ifn2 = IFN_MASK_LEN_GATHER_LOAD;
4277 }
4278 else
4279 {
4280 ifn = masked_p ? IFN_MASK_SCATTER_STORE : IFN_SCATTER_STORE;
4281 alt_ifn = IFN_MASK_SCATTER_STORE;
4282 /* When target supports MASK_LEN_SCATTER_STORE, we always
4283 use MASK_LEN_SCATTER_STORE regardless whether len and
4284 mask are valid or not. */
4285 alt_ifn2 = IFN_MASK_LEN_SCATTER_STORE;
4286 }
4287
4288 for (;;)
4289 {
4290 tree offset_vectype = get_vectype_for_scalar_type (vinfo, offset_type);
4291 if (!offset_vectype)
4292 return false;
4293
4294 /* Test whether the target supports this combination. */
4295 if (internal_gather_scatter_fn_supported_p (ifn, vectype, memory_type,
4296 offset_vectype, scale,
4297 elsvals))
4298 {
4299 *ifn_out = ifn;
4300 *offset_vectype_out = offset_vectype;
4301 return true;
4302 }
4303 else if (!masked_p
4304 && internal_gather_scatter_fn_supported_p (alt_ifn, vectype,
4305 memory_type,
4306 offset_vectype,
4307 scale, elsvals))
4308 {
4309 *ifn_out = alt_ifn;
4310 *offset_vectype_out = offset_vectype;
4311 return true;
4312 }
4313 else if (internal_gather_scatter_fn_supported_p (alt_ifn2, vectype,
4314 memory_type,
4315 offset_vectype, scale,
4316 elsvals))
4317 {
4318 *ifn_out = alt_ifn2;
4319 *offset_vectype_out = offset_vectype;
4320 return true;
4321 }
4322
4323 if (TYPE_PRECISION (offset_type) >= POINTER_SIZE
4324 && TYPE_PRECISION (offset_type) >= element_bits)
4325 return false;
4326
4327 offset_type = build_nonstandard_integer_type
4328 (TYPE_PRECISION (offset_type) * 2, TYPE_UNSIGNED (offset_type));
4329 }
4330 }
4331
4332 /* STMT_INFO is a call to an internal gather load or scatter store function.
4333 Describe the operation in INFO. */
4334
4335 static void
4336 vect_describe_gather_scatter_call (stmt_vec_info stmt_info,
4337 gather_scatter_info *info)
4338 {
4339 gcall *call = as_a <gcall *> (stmt_info->stmt);
4340 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
4341 data_reference *dr = STMT_VINFO_DATA_REF (stmt_info);
4342
4343 info->ifn = gimple_call_internal_fn (call);
4344 info->decl = NULL_TREE;
4345 info->base = gimple_call_arg (call, 0);
4346 info->offset = gimple_call_arg (call, 1);
4347 info->offset_dt = vect_unknown_def_type;
4348 info->offset_vectype = NULL_TREE;
4349 info->scale = TREE_INT_CST_LOW (gimple_call_arg (call, 2));
4350 info->element_type = TREE_TYPE (vectype);
4351 info->memory_type = TREE_TYPE (DR_REF (dr));
4352 }
4353
4354 /* Return true if a non-affine read or write in STMT_INFO is suitable for a
4355 gather load or scatter store. Describe the operation in *INFO if so.
4356 If it is suitable and ELSVALS is nonzero store the supported else values
4357 in the vector it points to. */
4358
4359 bool
4360 vect_check_gather_scatter (stmt_vec_info stmt_info, loop_vec_info loop_vinfo,
4361 gather_scatter_info *info, vec<int> *elsvals)
4362 {
4363 HOST_WIDE_INT scale = 1;
4364 poly_int64 pbitpos, pbitsize;
4365 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
4366 struct data_reference *dr = STMT_VINFO_DATA_REF (stmt_info);
4367 tree offtype = NULL_TREE;
4368 tree decl = NULL_TREE, base, off;
4369 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
4370 tree memory_type = TREE_TYPE (DR_REF (dr));
4371 machine_mode pmode;
4372 int punsignedp, reversep, pvolatilep = 0;
4373 internal_fn ifn;
4374 tree offset_vectype;
4375 bool masked_p = false;
4376
4377 /* See whether this is already a call to a gather/scatter internal function.
4378 If not, see whether it's a masked load or store. */
4379 gcall *call = dyn_cast <gcall *> (stmt_info->stmt);
4380 if (call && gimple_call_internal_p (call))
4381 {
4382 ifn = gimple_call_internal_fn (call);
4383 if (internal_gather_scatter_fn_p (ifn))
4384 {
4385 vect_describe_gather_scatter_call (stmt_info, info);
4386
4387 /* In pattern recog we simply used a ZERO else value that
4388 we need to correct here. To that end just re-use the
4389 (already succesful) check if we support a gather IFN
4390 and have it populate the else values. */
4391 if (DR_IS_READ (dr) && internal_fn_mask_index (ifn) >= 0 && elsvals)
4392 supports_vec_gather_load_p (TYPE_MODE (vectype), elsvals);
4393 return true;
4394 }
4395 masked_p = (ifn == IFN_MASK_LOAD || ifn == IFN_MASK_STORE);
4396 }
4397
4398 /* ??? For epilogues we adjust DR_REF to make the following stmt-based
4399 analysis work, but this adjustment doesn't work for epilogues of
4400 epilogues during transform, so disable gather/scatter in that case. */
4401 if (LOOP_VINFO_EPILOGUE_P (loop_vinfo)
4402 && LOOP_VINFO_EPILOGUE_P (LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo)))
4403 return false;
4404
4405 /* True if we should aim to use internal functions rather than
4406 built-in functions. */
4407 bool use_ifn_p = (DR_IS_READ (dr)
4408 ? supports_vec_gather_load_p (TYPE_MODE (vectype),
4409 elsvals)
4410 : supports_vec_scatter_store_p (TYPE_MODE (vectype)));
4411
4412 base = DR_REF (dr);
4413 /* For masked loads/stores, DR_REF (dr) is an artificial MEM_REF,
4414 see if we can use the def stmt of the address. */
4415 if (masked_p
4416 && TREE_CODE (base) == MEM_REF
4417 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME
4418 && integer_zerop (TREE_OPERAND (base, 1))
4419 && !expr_invariant_in_loop_p (loop, TREE_OPERAND (base, 0)))
4420 {
4421 gimple *def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (base, 0));
4422 if (is_gimple_assign (def_stmt)
4423 && gimple_assign_rhs_code (def_stmt) == ADDR_EXPR)
4424 base = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), 0);
4425 }
4426
4427 /* The gather and scatter builtins need address of the form
4428 loop_invariant + vector * {1, 2, 4, 8}
4429 or
4430 loop_invariant + sign_extend (vector) * { 1, 2, 4, 8 }.
4431 Unfortunately DR_BASE_ADDRESS/DR_OFFSET can be a mixture
4432 of loop invariants/SSA_NAMEs defined in the loop, with casts,
4433 multiplications and additions in it. To get a vector, we need
4434 a single SSA_NAME that will be defined in the loop and will
4435 contain everything that is not loop invariant and that can be
4436 vectorized. The following code attempts to find such a preexistng
4437 SSA_NAME OFF and put the loop invariants into a tree BASE
4438 that can be gimplified before the loop. */
4439 base = get_inner_reference (base, &pbitsize, &pbitpos, &off, &pmode,
4440 &punsignedp, &reversep, &pvolatilep);
4441 if (reversep)
4442 return false;
4443
4444 /* PR 107346. Packed structs can have fields at offsets that are not
4445 multiples of BITS_PER_UNIT. Do not use gather/scatters in such cases. */
4446 if (!multiple_p (pbitpos, BITS_PER_UNIT))
4447 return false;
4448
4449 /* We need to be able to form an address to the base which for example
4450 isn't possible for hard registers. */
4451 if (may_be_nonaddressable_p (base))
4452 return false;
4453
4454 poly_int64 pbytepos = exact_div (pbitpos, BITS_PER_UNIT);
4455
4456 if (TREE_CODE (base) == MEM_REF)
4457 {
4458 if (!integer_zerop (TREE_OPERAND (base, 1)))
4459 {
4460 if (off == NULL_TREE)
4461 off = wide_int_to_tree (sizetype, mem_ref_offset (base));
4462 else
4463 off = size_binop (PLUS_EXPR, off,
4464 fold_convert (sizetype, TREE_OPERAND (base, 1)));
4465 }
4466 base = TREE_OPERAND (base, 0);
4467 }
4468 else
4469 base = build_fold_addr_expr (base);
4470
4471 if (off == NULL_TREE)
4472 off = size_zero_node;
4473
4474 /* If base is not loop invariant, either off is 0, then we start with just
4475 the constant offset in the loop invariant BASE and continue with base
4476 as OFF, otherwise give up.
4477 We could handle that case by gimplifying the addition of base + off
4478 into some SSA_NAME and use that as off, but for now punt. */
4479 if (!expr_invariant_in_loop_p (loop, base))
4480 {
4481 if (!integer_zerop (off))
4482 return false;
4483 off = base;
4484 base = size_int (pbytepos);
4485 }
4486 /* Otherwise put base + constant offset into the loop invariant BASE
4487 and continue with OFF. */
4488 else
4489 {
4490 base = fold_convert (sizetype, base);
4491 base = size_binop (PLUS_EXPR, base, size_int (pbytepos));
4492 }
4493
4494 /* OFF at this point may be either a SSA_NAME or some tree expression
4495 from get_inner_reference. Try to peel off loop invariants from it
4496 into BASE as long as possible. */
4497 STRIP_NOPS (off);
4498 while (offtype == NULL_TREE)
4499 {
4500 enum tree_code code;
4501 tree op0, op1, add = NULL_TREE;
4502
4503 if (TREE_CODE (off) == SSA_NAME)
4504 {
4505 gimple *def_stmt = SSA_NAME_DEF_STMT (off);
4506
4507 if (expr_invariant_in_loop_p (loop, off))
4508 return false;
4509
4510 if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
4511 break;
4512
4513 op0 = gimple_assign_rhs1 (def_stmt);
4514 code = gimple_assign_rhs_code (def_stmt);
4515 op1 = gimple_assign_rhs2 (def_stmt);
4516 }
4517 else
4518 {
4519 if (get_gimple_rhs_class (TREE_CODE (off)) == GIMPLE_TERNARY_RHS)
4520 return false;
4521 code = TREE_CODE (off);
4522 extract_ops_from_tree (off, &code, &op0, &op1);
4523 }
4524 switch (code)
4525 {
4526 case POINTER_PLUS_EXPR:
4527 case PLUS_EXPR:
4528 if (expr_invariant_in_loop_p (loop, op0))
4529 {
4530 add = op0;
4531 off = op1;
4532 do_add:
4533 add = fold_convert (sizetype, add);
4534 if (scale != 1)
4535 add = size_binop (MULT_EXPR, add, size_int (scale));
4536 base = size_binop (PLUS_EXPR, base, add);
4537 continue;
4538 }
4539 if (expr_invariant_in_loop_p (loop, op1))
4540 {
4541 add = op1;
4542 off = op0;
4543 goto do_add;
4544 }
4545 break;
4546 case MINUS_EXPR:
4547 if (expr_invariant_in_loop_p (loop, op1))
4548 {
4549 add = fold_convert (sizetype, op1);
4550 add = size_binop (MINUS_EXPR, size_zero_node, add);
4551 off = op0;
4552 goto do_add;
4553 }
4554 break;
4555 case MULT_EXPR:
4556 if (scale == 1 && tree_fits_shwi_p (op1))
4557 {
4558 int new_scale = tree_to_shwi (op1);
4559 /* Only treat this as a scaling operation if the target
4560 supports it for at least some offset type. */
4561 if (use_ifn_p
4562 && !vect_gather_scatter_fn_p (loop_vinfo, DR_IS_READ (dr),
4563 masked_p, vectype, memory_type,
4564 signed_char_type_node,
4565 new_scale, &ifn,
4566 &offset_vectype,
4567 elsvals)
4568 && !vect_gather_scatter_fn_p (loop_vinfo, DR_IS_READ (dr),
4569 masked_p, vectype, memory_type,
4570 unsigned_char_type_node,
4571 new_scale, &ifn,
4572 &offset_vectype,
4573 elsvals))
4574 break;
4575 scale = new_scale;
4576 off = op0;
4577 continue;
4578 }
4579 break;
4580 case SSA_NAME:
4581 off = op0;
4582 continue;
4583 CASE_CONVERT:
4584 if (!POINTER_TYPE_P (TREE_TYPE (op0))
4585 && !INTEGRAL_TYPE_P (TREE_TYPE (op0)))
4586 break;
4587
4588 /* Don't include the conversion if the target is happy with
4589 the current offset type. */
4590 if (use_ifn_p
4591 && TREE_CODE (off) == SSA_NAME
4592 && !POINTER_TYPE_P (TREE_TYPE (off))
4593 && vect_gather_scatter_fn_p (loop_vinfo, DR_IS_READ (dr),
4594 masked_p, vectype, memory_type,
4595 TREE_TYPE (off), scale, &ifn,
4596 &offset_vectype, elsvals))
4597 break;
4598
4599 if (TYPE_PRECISION (TREE_TYPE (op0))
4600 == TYPE_PRECISION (TREE_TYPE (off)))
4601 {
4602 off = op0;
4603 continue;
4604 }
4605
4606 /* Include the conversion if it is widening and we're using
4607 the IFN path or the target can handle the converted from
4608 offset or the current size is not already the same as the
4609 data vector element size. */
4610 if ((TYPE_PRECISION (TREE_TYPE (op0))
4611 < TYPE_PRECISION (TREE_TYPE (off)))
4612 && (use_ifn_p
4613 || (DR_IS_READ (dr)
4614 ? (targetm.vectorize.builtin_gather
4615 && targetm.vectorize.builtin_gather (vectype,
4616 TREE_TYPE (op0),
4617 scale))
4618 : (targetm.vectorize.builtin_scatter
4619 && targetm.vectorize.builtin_scatter (vectype,
4620 TREE_TYPE (op0),
4621 scale)))
4622 || !operand_equal_p (TYPE_SIZE (TREE_TYPE (off)),
4623 TYPE_SIZE (TREE_TYPE (vectype)), 0)))
4624 {
4625 off = op0;
4626 offtype = TREE_TYPE (off);
4627 STRIP_NOPS (off);
4628 continue;
4629 }
4630 break;
4631 default:
4632 break;
4633 }
4634 break;
4635 }
4636
4637 /* If at the end OFF still isn't a SSA_NAME or isn't
4638 defined in the loop, punt. */
4639 if (TREE_CODE (off) != SSA_NAME
4640 || expr_invariant_in_loop_p (loop, off))
4641 return false;
4642
4643 if (offtype == NULL_TREE)
4644 offtype = TREE_TYPE (off);
4645
4646 if (use_ifn_p)
4647 {
4648 if (!vect_gather_scatter_fn_p (loop_vinfo, DR_IS_READ (dr), masked_p,
4649 vectype, memory_type, offtype, scale,
4650 &ifn, &offset_vectype, elsvals))
4651 ifn = IFN_LAST;
4652 decl = NULL_TREE;
4653 }
4654 else
4655 {
4656 if (DR_IS_READ (dr))
4657 {
4658 if (targetm.vectorize.builtin_gather)
4659 decl = targetm.vectorize.builtin_gather (vectype, offtype, scale);
4660 }
4661 else
4662 {
4663 if (targetm.vectorize.builtin_scatter)
4664 decl = targetm.vectorize.builtin_scatter (vectype, offtype, scale);
4665 }
4666 ifn = IFN_LAST;
4667 /* The offset vector type will be read from DECL when needed. */
4668 offset_vectype = NULL_TREE;
4669 }
4670
4671 info->ifn = ifn;
4672 info->decl = decl;
4673 info->base = base;
4674 info->offset = off;
4675 info->offset_dt = vect_unknown_def_type;
4676 info->offset_vectype = offset_vectype;
4677 info->scale = scale;
4678 info->element_type = TREE_TYPE (vectype);
4679 info->memory_type = memory_type;
4680 return true;
4681 }
4682
4683 /* Find the data references in STMT, analyze them with respect to LOOP and
4684 append them to DATAREFS. Return false if datarefs in this stmt cannot
4685 be handled. */
4686
4687 opt_result
4688 vect_find_stmt_data_reference (loop_p loop, gimple *stmt,
4689 vec<data_reference_p> *datarefs,
4690 vec<int> *dataref_groups, int group_id)
4691 {
4692 /* We can ignore clobbers for dataref analysis - they are removed during
4693 loop vectorization and BB vectorization checks dependences with a
4694 stmt walk. */
4695 if (gimple_clobber_p (stmt))
4696 return opt_result::success ();
4697
4698 if (gimple_has_volatile_ops (stmt))
4699 return opt_result::failure_at (stmt, "not vectorized: volatile type: %G",
4700 stmt);
4701
4702 if (stmt_can_throw_internal (cfun, stmt))
4703 return opt_result::failure_at (stmt,
4704 "not vectorized:"
4705 " statement can throw an exception: %G",
4706 stmt);
4707
4708 auto_vec<data_reference_p, 2> refs;
4709 opt_result res = find_data_references_in_stmt (loop, stmt, &refs);
4710 if (!res)
4711 return res;
4712
4713 if (refs.is_empty ())
4714 return opt_result::success ();
4715
4716 if (refs.length () > 1)
4717 {
4718 while (!refs.is_empty ())
4719 free_data_ref (refs.pop ());
4720 return opt_result::failure_at (stmt,
4721 "not vectorized: more than one "
4722 "data ref in stmt: %G", stmt);
4723 }
4724
4725 data_reference_p dr = refs.pop ();
4726 if (gcall *call = dyn_cast <gcall *> (stmt))
4727 if (!gimple_call_internal_p (call)
4728 || (gimple_call_internal_fn (call) != IFN_MASK_LOAD
4729 && gimple_call_internal_fn (call) != IFN_MASK_STORE))
4730 {
4731 free_data_ref (dr);
4732 return opt_result::failure_at (stmt,
4733 "not vectorized: dr in a call %G", stmt);
4734 }
4735
4736 if (TREE_CODE (DR_REF (dr)) == COMPONENT_REF
4737 && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (dr), 1)))
4738 {
4739 free_data_ref (dr);
4740 return opt_result::failure_at (stmt,
4741 "not vectorized:"
4742 " statement is an unsupported"
4743 " bitfield access %G", stmt);
4744 }
4745
4746 if (DR_BASE_ADDRESS (dr)
4747 && TREE_CODE (DR_BASE_ADDRESS (dr)) == INTEGER_CST)
4748 {
4749 free_data_ref (dr);
4750 return opt_result::failure_at (stmt,
4751 "not vectorized:"
4752 " base addr of dr is a constant\n");
4753 }
4754
4755 /* Check whether this may be a SIMD lane access and adjust the
4756 DR to make it easier for us to handle it. */
4757 if (loop
4758 && loop->simduid
4759 && (!DR_BASE_ADDRESS (dr)
4760 || !DR_OFFSET (dr)
4761 || !DR_INIT (dr)
4762 || !DR_STEP (dr)))
4763 {
4764 struct data_reference *newdr
4765 = create_data_ref (NULL, loop_containing_stmt (stmt), DR_REF (dr), stmt,
4766 DR_IS_READ (dr), DR_IS_CONDITIONAL_IN_STMT (dr));
4767 if (DR_BASE_ADDRESS (newdr)
4768 && DR_OFFSET (newdr)
4769 && DR_INIT (newdr)
4770 && DR_STEP (newdr)
4771 && TREE_CODE (DR_INIT (newdr)) == INTEGER_CST
4772 && integer_zerop (DR_STEP (newdr)))
4773 {
4774 tree base_address = DR_BASE_ADDRESS (newdr);
4775 tree off = DR_OFFSET (newdr);
4776 tree step = ssize_int (1);
4777 if (integer_zerop (off)
4778 && TREE_CODE (base_address) == POINTER_PLUS_EXPR)
4779 {
4780 off = TREE_OPERAND (base_address, 1);
4781 base_address = TREE_OPERAND (base_address, 0);
4782 }
4783 STRIP_NOPS (off);
4784 if (TREE_CODE (off) == MULT_EXPR
4785 && tree_fits_uhwi_p (TREE_OPERAND (off, 1)))
4786 {
4787 step = TREE_OPERAND (off, 1);
4788 off = TREE_OPERAND (off, 0);
4789 STRIP_NOPS (off);
4790 }
4791 if (CONVERT_EXPR_P (off)
4792 && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (off, 0)))
4793 < TYPE_PRECISION (TREE_TYPE (off))))
4794 off = TREE_OPERAND (off, 0);
4795 if (TREE_CODE (off) == SSA_NAME)
4796 {
4797 gimple *def = SSA_NAME_DEF_STMT (off);
4798 /* Look through widening conversion. */
4799 if (is_gimple_assign (def)
4800 && CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def)))
4801 {
4802 tree rhs1 = gimple_assign_rhs1 (def);
4803 if (TREE_CODE (rhs1) == SSA_NAME
4804 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
4805 && (TYPE_PRECISION (TREE_TYPE (off))
4806 > TYPE_PRECISION (TREE_TYPE (rhs1))))
4807 def = SSA_NAME_DEF_STMT (rhs1);
4808 }
4809 if (is_gimple_call (def)
4810 && gimple_call_internal_p (def)
4811 && (gimple_call_internal_fn (def) == IFN_GOMP_SIMD_LANE))
4812 {
4813 tree arg = gimple_call_arg (def, 0);
4814 tree reft = TREE_TYPE (DR_REF (newdr));
4815 gcc_assert (TREE_CODE (arg) == SSA_NAME);
4816 arg = SSA_NAME_VAR (arg);
4817 if (arg == loop->simduid
4818 /* For now. */
4819 && tree_int_cst_equal (TYPE_SIZE_UNIT (reft), step))
4820 {
4821 DR_BASE_ADDRESS (newdr) = base_address;
4822 DR_OFFSET (newdr) = ssize_int (0);
4823 DR_STEP (newdr) = step;
4824 DR_OFFSET_ALIGNMENT (newdr) = BIGGEST_ALIGNMENT;
4825 DR_STEP_ALIGNMENT (newdr) = highest_pow2_factor (step);
4826 /* Mark as simd-lane access. */
4827 tree arg2 = gimple_call_arg (def, 1);
4828 newdr->aux = (void *) (-1 - tree_to_uhwi (arg2));
4829 free_data_ref (dr);
4830 datarefs->safe_push (newdr);
4831 if (dataref_groups)
4832 dataref_groups->safe_push (group_id);
4833 return opt_result::success ();
4834 }
4835 }
4836 }
4837 }
4838 free_data_ref (newdr);
4839 }
4840
4841 datarefs->safe_push (dr);
4842 if (dataref_groups)
4843 dataref_groups->safe_push (group_id);
4844 return opt_result::success ();
4845 }
4846
4847 /* Function vect_analyze_data_refs.
4848
4849 Find all the data references in the loop or basic block.
4850
4851 The general structure of the analysis of data refs in the vectorizer is as
4852 follows:
4853 1- vect_analyze_data_refs(loop/bb): call
4854 compute_data_dependences_for_loop/bb to find and analyze all data-refs
4855 in the loop/bb and their dependences.
4856 2- vect_analyze_dependences(): apply dependence testing using ddrs.
4857 3- vect_analyze_drs_alignment(): check that ref_stmt.alignment is ok.
4858 4- vect_analyze_drs_access(): check that ref_stmt.step is ok.
4859
4860 */
4861
4862 opt_result
4863 vect_analyze_data_refs (vec_info *vinfo, poly_uint64 *min_vf, bool *fatal)
4864 {
4865 class loop *loop = NULL;
4866 unsigned int i;
4867 struct data_reference *dr;
4868 tree scalar_type;
4869
4870 DUMP_VECT_SCOPE ("vect_analyze_data_refs");
4871
4872 if (loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo))
4873 loop = LOOP_VINFO_LOOP (loop_vinfo);
4874
4875 /* Go through the data-refs, check that the analysis succeeded. Update
4876 pointer from stmt_vec_info struct to DR and vectype. */
4877
4878 vec<data_reference_p> datarefs = vinfo->shared->datarefs;
4879 FOR_EACH_VEC_ELT (datarefs, i, dr)
4880 {
4881 enum { SG_NONE, GATHER, SCATTER } gatherscatter = SG_NONE;
4882 poly_uint64 vf;
4883
4884 gcc_assert (DR_REF (dr));
4885 stmt_vec_info stmt_info = vinfo->lookup_stmt (DR_STMT (dr));
4886 gcc_assert (!stmt_info->dr_aux.dr);
4887 stmt_info->dr_aux.dr = dr;
4888 stmt_info->dr_aux.stmt = stmt_info;
4889
4890 /* Check that analysis of the data-ref succeeded. */
4891 if (!DR_BASE_ADDRESS (dr) || !DR_OFFSET (dr) || !DR_INIT (dr)
4892 || !DR_STEP (dr))
4893 {
4894 bool maybe_gather
4895 = DR_IS_READ (dr)
4896 && !TREE_THIS_VOLATILE (DR_REF (dr));
4897 bool maybe_scatter
4898 = DR_IS_WRITE (dr)
4899 && !TREE_THIS_VOLATILE (DR_REF (dr));
4900
4901 /* If target supports vector gather loads or scatter stores,
4902 see if they can't be used. */
4903 if (is_a <loop_vec_info> (vinfo)
4904 && !nested_in_vect_loop_p (loop, stmt_info))
4905 {
4906 if (maybe_gather || maybe_scatter)
4907 {
4908 if (maybe_gather)
4909 gatherscatter = GATHER;
4910 else
4911 gatherscatter = SCATTER;
4912 }
4913 }
4914
4915 if (gatherscatter == SG_NONE)
4916 {
4917 if (dump_enabled_p ())
4918 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4919 "not vectorized: data ref analysis "
4920 "failed %G", stmt_info->stmt);
4921 if (is_a <bb_vec_info> (vinfo))
4922 {
4923 /* In BB vectorization the ref can still participate
4924 in dependence analysis, we just can't vectorize it. */
4925 STMT_VINFO_VECTORIZABLE (stmt_info) = false;
4926 continue;
4927 }
4928 return opt_result::failure_at (stmt_info->stmt,
4929 "not vectorized:"
4930 " data ref analysis failed: %G",
4931 stmt_info->stmt);
4932 }
4933 }
4934
4935 /* See if this was detected as SIMD lane access. */
4936 if (dr->aux == (void *)-1
4937 || dr->aux == (void *)-2
4938 || dr->aux == (void *)-3
4939 || dr->aux == (void *)-4)
4940 {
4941 if (nested_in_vect_loop_p (loop, stmt_info))
4942 return opt_result::failure_at (stmt_info->stmt,
4943 "not vectorized:"
4944 " data ref analysis failed: %G",
4945 stmt_info->stmt);
4946 STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info)
4947 = -(uintptr_t) dr->aux;
4948 }
4949
4950 tree base = get_base_address (DR_REF (dr));
4951 if (base && VAR_P (base) && DECL_NONALIASED (base))
4952 {
4953 if (dump_enabled_p ())
4954 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
4955 "not vectorized: base object not addressable "
4956 "for stmt: %G", stmt_info->stmt);
4957 if (is_a <bb_vec_info> (vinfo))
4958 {
4959 /* In BB vectorization the ref can still participate
4960 in dependence analysis, we just can't vectorize it. */
4961 STMT_VINFO_VECTORIZABLE (stmt_info) = false;
4962 continue;
4963 }
4964 return opt_result::failure_at (stmt_info->stmt,
4965 "not vectorized: base object not"
4966 " addressable for stmt: %G",
4967 stmt_info->stmt);
4968 }
4969
4970 if (is_a <loop_vec_info> (vinfo)
4971 && DR_STEP (dr)
4972 && TREE_CODE (DR_STEP (dr)) != INTEGER_CST)
4973 {
4974 if (nested_in_vect_loop_p (loop, stmt_info))
4975 return opt_result::failure_at (stmt_info->stmt,
4976 "not vectorized: "
4977 "not suitable for strided load %G",
4978 stmt_info->stmt);
4979 STMT_VINFO_STRIDED_P (stmt_info) = true;
4980 }
4981
4982 /* Update DR field in stmt_vec_info struct. */
4983
4984 /* If the dataref is in an inner-loop of the loop that is considered for
4985 for vectorization, we also want to analyze the access relative to
4986 the outer-loop (DR contains information only relative to the
4987 inner-most enclosing loop). We do that by building a reference to the
4988 first location accessed by the inner-loop, and analyze it relative to
4989 the outer-loop. */
4990 if (loop && nested_in_vect_loop_p (loop, stmt_info))
4991 {
4992 /* Build a reference to the first location accessed by the
4993 inner loop: *(BASE + INIT + OFFSET). By construction,
4994 this address must be invariant in the inner loop, so we
4995 can consider it as being used in the outer loop. */
4996 tree base = unshare_expr (DR_BASE_ADDRESS (dr));
4997 tree offset = unshare_expr (DR_OFFSET (dr));
4998 tree init = unshare_expr (DR_INIT (dr));
4999 tree init_offset = fold_build2 (PLUS_EXPR, TREE_TYPE (offset),
5000 init, offset);
5001 tree init_addr = fold_build_pointer_plus (base, init_offset);
5002 tree init_ref = build_fold_indirect_ref (init_addr);
5003
5004 if (dump_enabled_p ())
5005 dump_printf_loc (MSG_NOTE, vect_location,
5006 "analyze in outer loop: %T\n", init_ref);
5007
5008 opt_result res
5009 = dr_analyze_innermost (&STMT_VINFO_DR_WRT_VEC_LOOP (stmt_info),
5010 init_ref, loop, stmt_info->stmt);
5011 if (!res)
5012 /* dr_analyze_innermost already explained the failure. */
5013 return res;
5014
5015 if (dump_enabled_p ())
5016 dump_printf_loc (MSG_NOTE, vect_location,
5017 "\touter base_address: %T\n"
5018 "\touter offset from base address: %T\n"
5019 "\touter constant offset from base address: %T\n"
5020 "\touter step: %T\n"
5021 "\touter base alignment: %d\n\n"
5022 "\touter base misalignment: %d\n"
5023 "\touter offset alignment: %d\n"
5024 "\touter step alignment: %d\n",
5025 STMT_VINFO_DR_BASE_ADDRESS (stmt_info),
5026 STMT_VINFO_DR_OFFSET (stmt_info),
5027 STMT_VINFO_DR_INIT (stmt_info),
5028 STMT_VINFO_DR_STEP (stmt_info),
5029 STMT_VINFO_DR_BASE_ALIGNMENT (stmt_info),
5030 STMT_VINFO_DR_BASE_MISALIGNMENT (stmt_info),
5031 STMT_VINFO_DR_OFFSET_ALIGNMENT (stmt_info),
5032 STMT_VINFO_DR_STEP_ALIGNMENT (stmt_info));
5033 }
5034
5035 /* Set vectype for STMT. */
5036 scalar_type = TREE_TYPE (DR_REF (dr));
5037 tree vectype = get_vectype_for_scalar_type (vinfo, scalar_type);
5038 if (!vectype)
5039 {
5040 if (dump_enabled_p ())
5041 {
5042 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5043 "not vectorized: no vectype for stmt: %G",
5044 stmt_info->stmt);
5045 dump_printf (MSG_MISSED_OPTIMIZATION, " scalar_type: ");
5046 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_DETAILS,
5047 scalar_type);
5048 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
5049 }
5050
5051 if (is_a <bb_vec_info> (vinfo))
5052 {
5053 /* No vector type is fine, the ref can still participate
5054 in dependence analysis, we just can't vectorize it. */
5055 STMT_VINFO_VECTORIZABLE (stmt_info) = false;
5056 continue;
5057 }
5058 if (fatal)
5059 *fatal = false;
5060 return opt_result::failure_at (stmt_info->stmt,
5061 "not vectorized:"
5062 " no vectype for stmt: %G"
5063 " scalar_type: %T\n",
5064 stmt_info->stmt, scalar_type);
5065 }
5066 else
5067 {
5068 if (dump_enabled_p ())
5069 dump_printf_loc (MSG_NOTE, vect_location,
5070 "got vectype for stmt: %G%T\n",
5071 stmt_info->stmt, vectype);
5072 }
5073
5074 /* Adjust the minimal vectorization factor according to the
5075 vector type. */
5076 vf = TYPE_VECTOR_SUBPARTS (vectype);
5077 *min_vf = upper_bound (*min_vf, vf);
5078
5079 /* Leave the BB vectorizer to pick the vector type later, based on
5080 the final dataref group size and SLP node size. */
5081 if (is_a <loop_vec_info> (vinfo))
5082 STMT_VINFO_VECTYPE (stmt_info) = vectype;
5083
5084 if (gatherscatter != SG_NONE)
5085 {
5086 gather_scatter_info gs_info;
5087 if (!vect_check_gather_scatter (stmt_info,
5088 as_a <loop_vec_info> (vinfo),
5089 &gs_info)
5090 || !get_vectype_for_scalar_type (vinfo,
5091 TREE_TYPE (gs_info.offset)))
5092 {
5093 if (fatal)
5094 *fatal = false;
5095 return opt_result::failure_at
5096 (stmt_info->stmt,
5097 (gatherscatter == GATHER)
5098 ? "not vectorized: not suitable for gather load %G"
5099 : "not vectorized: not suitable for scatter store %G",
5100 stmt_info->stmt);
5101 }
5102 STMT_VINFO_GATHER_SCATTER_P (stmt_info) = gatherscatter;
5103 }
5104 }
5105
5106 /* We used to stop processing and prune the list here. Verify we no
5107 longer need to. */
5108 gcc_assert (i == datarefs.length ());
5109
5110 return opt_result::success ();
5111 }
5112
5113
5114 /* Function vect_get_new_vect_var.
5115
5116 Returns a name for a new variable. The current naming scheme appends the
5117 prefix "vect_" or "vect_p" (depending on the value of VAR_KIND) to
5118 the name of vectorizer generated variables, and appends that to NAME if
5119 provided. */
5120
5121 tree
5122 vect_get_new_vect_var (tree type, enum vect_var_kind var_kind, const char *name)
5123 {
5124 const char *prefix;
5125 tree new_vect_var;
5126
5127 switch (var_kind)
5128 {
5129 case vect_simple_var:
5130 prefix = "vect";
5131 break;
5132 case vect_scalar_var:
5133 prefix = "stmp";
5134 break;
5135 case vect_mask_var:
5136 prefix = "mask";
5137 break;
5138 case vect_pointer_var:
5139 prefix = "vectp";
5140 break;
5141 default:
5142 gcc_unreachable ();
5143 }
5144
5145 if (name)
5146 {
5147 char* tmp = concat (prefix, "_", name, NULL);
5148 new_vect_var = create_tmp_reg (type, tmp);
5149 free (tmp);
5150 }
5151 else
5152 new_vect_var = create_tmp_reg (type, prefix);
5153
5154 return new_vect_var;
5155 }
5156
5157 /* Like vect_get_new_vect_var but return an SSA name. */
5158
5159 tree
5160 vect_get_new_ssa_name (tree type, enum vect_var_kind var_kind, const char *name)
5161 {
5162 const char *prefix;
5163 tree new_vect_var;
5164
5165 switch (var_kind)
5166 {
5167 case vect_simple_var:
5168 prefix = "vect";
5169 break;
5170 case vect_scalar_var:
5171 prefix = "stmp";
5172 break;
5173 case vect_pointer_var:
5174 prefix = "vectp";
5175 break;
5176 default:
5177 gcc_unreachable ();
5178 }
5179
5180 if (name)
5181 {
5182 char* tmp = concat (prefix, "_", name, NULL);
5183 new_vect_var = make_temp_ssa_name (type, NULL, tmp);
5184 free (tmp);
5185 }
5186 else
5187 new_vect_var = make_temp_ssa_name (type, NULL, prefix);
5188
5189 return new_vect_var;
5190 }
5191
5192 /* Duplicate points-to info on NAME from DR_INFO. */
5193
5194 static void
5195 vect_duplicate_ssa_name_ptr_info (tree name, dr_vec_info *dr_info)
5196 {
5197 duplicate_ssa_name_ptr_info (name, DR_PTR_INFO (dr_info->dr));
5198 /* DR_PTR_INFO is for a base SSA name, not including constant or
5199 variable offsets in the ref so its alignment info does not apply. */
5200 mark_ptr_info_alignment_unknown (SSA_NAME_PTR_INFO (name));
5201 }
5202
5203 /* Function vect_create_addr_base_for_vector_ref.
5204
5205 Create an expression that computes the address of the first memory location
5206 that will be accessed for a data reference.
5207
5208 Input:
5209 STMT_INFO: The statement containing the data reference.
5210 NEW_STMT_LIST: Must be initialized to NULL_TREE or a statement list.
5211 OFFSET: Optional. If supplied, it is be added to the initial address.
5212 LOOP: Specify relative to which loop-nest should the address be computed.
5213 For example, when the dataref is in an inner-loop nested in an
5214 outer-loop that is now being vectorized, LOOP can be either the
5215 outer-loop, or the inner-loop. The first memory location accessed
5216 by the following dataref ('in' points to short):
5217
5218 for (i=0; i<N; i++)
5219 for (j=0; j<M; j++)
5220 s += in[i+j]
5221
5222 is as follows:
5223 if LOOP=i_loop: &in (relative to i_loop)
5224 if LOOP=j_loop: &in+i*2B (relative to j_loop)
5225
5226 Output:
5227 1. Return an SSA_NAME whose value is the address of the memory location of
5228 the first vector of the data reference.
5229 2. If new_stmt_list is not NULL_TREE after return then the caller must insert
5230 these statement(s) which define the returned SSA_NAME.
5231
5232 FORNOW: We are only handling array accesses with step 1. */
5233
5234 tree
5235 vect_create_addr_base_for_vector_ref (vec_info *vinfo, stmt_vec_info stmt_info,
5236 gimple_seq *new_stmt_list,
5237 tree offset)
5238 {
5239 dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
5240 struct data_reference *dr = dr_info->dr;
5241 const char *base_name;
5242 tree addr_base;
5243 tree dest;
5244 gimple_seq seq = NULL;
5245 tree vect_ptr_type;
5246 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
5247 innermost_loop_behavior *drb = vect_dr_behavior (vinfo, dr_info);
5248
5249 tree data_ref_base = unshare_expr (drb->base_address);
5250 tree base_offset = unshare_expr (get_dr_vinfo_offset (vinfo, dr_info, true));
5251 tree init = unshare_expr (drb->init);
5252
5253 if (loop_vinfo)
5254 base_name = get_name (data_ref_base);
5255 else
5256 {
5257 base_offset = ssize_int (0);
5258 init = ssize_int (0);
5259 base_name = get_name (DR_REF (dr));
5260 }
5261
5262 /* Create base_offset */
5263 base_offset = size_binop (PLUS_EXPR,
5264 fold_convert (sizetype, base_offset),
5265 fold_convert (sizetype, init));
5266
5267 if (offset)
5268 {
5269 offset = fold_convert (sizetype, offset);
5270 base_offset = fold_build2 (PLUS_EXPR, sizetype,
5271 base_offset, offset);
5272 }
5273
5274 /* base + base_offset */
5275 if (loop_vinfo)
5276 addr_base = fold_build_pointer_plus (data_ref_base, base_offset);
5277 else
5278 addr_base = build1 (ADDR_EXPR,
5279 build_pointer_type (TREE_TYPE (DR_REF (dr))),
5280 /* Strip zero offset components since we don't need
5281 them and they can confuse late diagnostics if
5282 we CSE them wrongly. See PR106904 for example. */
5283 unshare_expr (strip_zero_offset_components
5284 (DR_REF (dr))));
5285
5286 vect_ptr_type = build_pointer_type (TREE_TYPE (DR_REF (dr)));
5287 dest = vect_get_new_vect_var (vect_ptr_type, vect_pointer_var, base_name);
5288 addr_base = force_gimple_operand (addr_base, &seq, true, dest);
5289 gimple_seq_add_seq (new_stmt_list, seq);
5290
5291 if (DR_PTR_INFO (dr)
5292 && TREE_CODE (addr_base) == SSA_NAME
5293 /* We should only duplicate pointer info to newly created SSA names. */
5294 && SSA_NAME_VAR (addr_base) == dest)
5295 {
5296 gcc_assert (!SSA_NAME_PTR_INFO (addr_base));
5297 vect_duplicate_ssa_name_ptr_info (addr_base, dr_info);
5298 }
5299
5300 if (dump_enabled_p ())
5301 dump_printf_loc (MSG_NOTE, vect_location, "created %T\n", addr_base);
5302
5303 return addr_base;
5304 }
5305
5306
5307 /* Function vect_create_data_ref_ptr.
5308
5309 Create a new pointer-to-AGGR_TYPE variable (ap), that points to the first
5310 location accessed in the loop by STMT_INFO, along with the def-use update
5311 chain to appropriately advance the pointer through the loop iterations.
5312 Also set aliasing information for the pointer. This pointer is used by
5313 the callers to this function to create a memory reference expression for
5314 vector load/store access.
5315
5316 Input:
5317 1. STMT_INFO: a stmt that references memory. Expected to be of the form
5318 GIMPLE_ASSIGN <name, data-ref> or
5319 GIMPLE_ASSIGN <data-ref, name>.
5320 2. AGGR_TYPE: the type of the reference, which should be either a vector
5321 or an array.
5322 3. AT_LOOP: the loop where the vector memref is to be created.
5323 4. OFFSET (optional): a byte offset to be added to the initial address
5324 accessed by the data-ref in STMT_INFO.
5325 5. BSI: location where the new stmts are to be placed if there is no loop
5326 6. ONLY_INIT: indicate if ap is to be updated in the loop, or remain
5327 pointing to the initial address.
5328 8. IV_STEP (optional, defaults to NULL): the amount that should be added
5329 to the IV during each iteration of the loop. NULL says to move
5330 by one copy of AGGR_TYPE up or down, depending on the step of the
5331 data reference.
5332
5333 Output:
5334 1. Declare a new ptr to vector_type, and have it point to the base of the
5335 data reference (initial addressed accessed by the data reference).
5336 For example, for vector of type V8HI, the following code is generated:
5337
5338 v8hi *ap;
5339 ap = (v8hi *)initial_address;
5340
5341 if OFFSET is not supplied:
5342 initial_address = &a[init];
5343 if OFFSET is supplied:
5344 initial_address = &a[init] + OFFSET;
5345 if BYTE_OFFSET is supplied:
5346 initial_address = &a[init] + BYTE_OFFSET;
5347
5348 Return the initial_address in INITIAL_ADDRESS.
5349
5350 2. If ONLY_INIT is true, just return the initial pointer. Otherwise, also
5351 update the pointer in each iteration of the loop.
5352
5353 Return the increment stmt that updates the pointer in PTR_INCR.
5354
5355 3. Return the pointer. */
5356
5357 tree
5358 vect_create_data_ref_ptr (vec_info *vinfo, stmt_vec_info stmt_info,
5359 tree aggr_type, class loop *at_loop, tree offset,
5360 tree *initial_address, gimple_stmt_iterator *gsi,
5361 gimple **ptr_incr, bool only_init,
5362 tree iv_step)
5363 {
5364 const char *base_name;
5365 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
5366 class loop *loop = NULL;
5367 bool nested_in_vect_loop = false;
5368 class loop *containing_loop = NULL;
5369 tree aggr_ptr_type;
5370 tree aggr_ptr;
5371 tree new_temp;
5372 gimple_seq new_stmt_list = NULL;
5373 edge pe = NULL;
5374 basic_block new_bb;
5375 tree aggr_ptr_init;
5376 dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
5377 struct data_reference *dr = dr_info->dr;
5378 tree aptr;
5379 gimple_stmt_iterator incr_gsi;
5380 bool insert_after;
5381 tree indx_before_incr, indx_after_incr;
5382 gimple *incr;
5383 bb_vec_info bb_vinfo = dyn_cast <bb_vec_info> (vinfo);
5384
5385 gcc_assert (iv_step != NULL_TREE
5386 || TREE_CODE (aggr_type) == ARRAY_TYPE
5387 || TREE_CODE (aggr_type) == VECTOR_TYPE);
5388
5389 if (loop_vinfo)
5390 {
5391 loop = LOOP_VINFO_LOOP (loop_vinfo);
5392 nested_in_vect_loop = nested_in_vect_loop_p (loop, stmt_info);
5393 containing_loop = (gimple_bb (stmt_info->stmt))->loop_father;
5394 pe = loop_preheader_edge (loop);
5395 }
5396 else
5397 {
5398 gcc_assert (bb_vinfo);
5399 only_init = true;
5400 *ptr_incr = NULL;
5401 }
5402
5403 /* Create an expression for the first address accessed by this load
5404 in LOOP. */
5405 base_name = get_name (DR_BASE_ADDRESS (dr));
5406
5407 if (dump_enabled_p ())
5408 {
5409 tree dr_base_type = TREE_TYPE (DR_BASE_OBJECT (dr));
5410 dump_printf_loc (MSG_NOTE, vect_location,
5411 "create %s-pointer variable to type: %T",
5412 get_tree_code_name (TREE_CODE (aggr_type)),
5413 aggr_type);
5414 if (TREE_CODE (dr_base_type) == ARRAY_TYPE)
5415 dump_printf (MSG_NOTE, " vectorizing an array ref: ");
5416 else if (TREE_CODE (dr_base_type) == VECTOR_TYPE)
5417 dump_printf (MSG_NOTE, " vectorizing a vector ref: ");
5418 else if (TREE_CODE (dr_base_type) == RECORD_TYPE)
5419 dump_printf (MSG_NOTE, " vectorizing a record based array ref: ");
5420 else
5421 dump_printf (MSG_NOTE, " vectorizing a pointer ref: ");
5422 dump_printf (MSG_NOTE, "%T\n", DR_BASE_OBJECT (dr));
5423 }
5424
5425 /* (1) Create the new aggregate-pointer variable.
5426 Vector and array types inherit the alias set of their component
5427 type by default so we need to use a ref-all pointer if the data
5428 reference does not conflict with the created aggregated data
5429 reference because it is not addressable. */
5430 bool need_ref_all = false;
5431 if (!alias_sets_conflict_p (get_alias_set (aggr_type),
5432 get_alias_set (DR_REF (dr))))
5433 need_ref_all = true;
5434 /* Likewise for any of the data references in the stmt group. */
5435 else if (DR_GROUP_SIZE (stmt_info) > 1)
5436 {
5437 stmt_vec_info sinfo = DR_GROUP_FIRST_ELEMENT (stmt_info);
5438 do
5439 {
5440 struct data_reference *sdr = STMT_VINFO_DATA_REF (sinfo);
5441 if (!alias_sets_conflict_p (get_alias_set (aggr_type),
5442 get_alias_set (DR_REF (sdr))))
5443 {
5444 need_ref_all = true;
5445 break;
5446 }
5447 sinfo = DR_GROUP_NEXT_ELEMENT (sinfo);
5448 }
5449 while (sinfo);
5450 }
5451 aggr_ptr_type = build_pointer_type_for_mode (aggr_type, VOIDmode,
5452 need_ref_all);
5453 aggr_ptr = vect_get_new_vect_var (aggr_ptr_type, vect_pointer_var, base_name);
5454
5455
5456 /* Note: If the dataref is in an inner-loop nested in LOOP, and we are
5457 vectorizing LOOP (i.e., outer-loop vectorization), we need to create two
5458 def-use update cycles for the pointer: one relative to the outer-loop
5459 (LOOP), which is what steps (3) and (4) below do. The other is relative
5460 to the inner-loop (which is the inner-most loop containing the dataref),
5461 and this is done be step (5) below.
5462
5463 When vectorizing inner-most loops, the vectorized loop (LOOP) is also the
5464 inner-most loop, and so steps (3),(4) work the same, and step (5) is
5465 redundant. Steps (3),(4) create the following:
5466
5467 vp0 = &base_addr;
5468 LOOP: vp1 = phi(vp0,vp2)
5469 ...
5470 ...
5471 vp2 = vp1 + step
5472 goto LOOP
5473
5474 If there is an inner-loop nested in loop, then step (5) will also be
5475 applied, and an additional update in the inner-loop will be created:
5476
5477 vp0 = &base_addr;
5478 LOOP: vp1 = phi(vp0,vp2)
5479 ...
5480 inner: vp3 = phi(vp1,vp4)
5481 vp4 = vp3 + inner_step
5482 if () goto inner
5483 ...
5484 vp2 = vp1 + step
5485 if () goto LOOP */
5486
5487 /* (2) Calculate the initial address of the aggregate-pointer, and set
5488 the aggregate-pointer to point to it before the loop. */
5489
5490 /* Create: (&(base[init_val]+offset) in the loop preheader. */
5491
5492 new_temp = vect_create_addr_base_for_vector_ref (vinfo,
5493 stmt_info, &new_stmt_list,
5494 offset);
5495 if (new_stmt_list)
5496 {
5497 if (pe)
5498 {
5499 new_bb = gsi_insert_seq_on_edge_immediate (pe, new_stmt_list);
5500 gcc_assert (!new_bb);
5501 }
5502 else
5503 gsi_insert_seq_before (gsi, new_stmt_list, GSI_SAME_STMT);
5504 }
5505
5506 *initial_address = new_temp;
5507 aggr_ptr_init = new_temp;
5508
5509 /* (3) Handle the updating of the aggregate-pointer inside the loop.
5510 This is needed when ONLY_INIT is false, and also when AT_LOOP is the
5511 inner-loop nested in LOOP (during outer-loop vectorization). */
5512
5513 /* No update in loop is required. */
5514 if (only_init && (!loop_vinfo || at_loop == loop))
5515 aptr = aggr_ptr_init;
5516 else
5517 {
5518 /* Accesses to invariant addresses should be handled specially
5519 by the caller. */
5520 tree step = vect_dr_behavior (vinfo, dr_info)->step;
5521 gcc_assert (!integer_zerop (step));
5522
5523 if (iv_step == NULL_TREE)
5524 {
5525 /* The step of the aggregate pointer is the type size,
5526 negated for downward accesses. */
5527 iv_step = TYPE_SIZE_UNIT (aggr_type);
5528 if (tree_int_cst_sgn (step) == -1)
5529 iv_step = fold_build1 (NEGATE_EXPR, TREE_TYPE (iv_step), iv_step);
5530 }
5531
5532 standard_iv_increment_position (loop, &incr_gsi, &insert_after);
5533
5534 create_iv (aggr_ptr_init, PLUS_EXPR,
5535 fold_convert (aggr_ptr_type, iv_step),
5536 aggr_ptr, loop, &incr_gsi, insert_after,
5537 &indx_before_incr, &indx_after_incr);
5538 incr = gsi_stmt (incr_gsi);
5539
5540 /* Copy the points-to information if it exists. */
5541 if (DR_PTR_INFO (dr))
5542 {
5543 vect_duplicate_ssa_name_ptr_info (indx_before_incr, dr_info);
5544 vect_duplicate_ssa_name_ptr_info (indx_after_incr, dr_info);
5545 }
5546 if (ptr_incr)
5547 *ptr_incr = incr;
5548
5549 aptr = indx_before_incr;
5550 }
5551
5552 if (!nested_in_vect_loop || only_init)
5553 return aptr;
5554
5555
5556 /* (4) Handle the updating of the aggregate-pointer inside the inner-loop
5557 nested in LOOP, if exists. */
5558
5559 gcc_assert (nested_in_vect_loop);
5560 if (!only_init)
5561 {
5562 standard_iv_increment_position (containing_loop, &incr_gsi,
5563 &insert_after);
5564 create_iv (aptr, PLUS_EXPR, fold_convert (aggr_ptr_type, DR_STEP (dr)),
5565 aggr_ptr, containing_loop, &incr_gsi, insert_after,
5566 &indx_before_incr, &indx_after_incr);
5567 incr = gsi_stmt (incr_gsi);
5568
5569 /* Copy the points-to information if it exists. */
5570 if (DR_PTR_INFO (dr))
5571 {
5572 vect_duplicate_ssa_name_ptr_info (indx_before_incr, dr_info);
5573 vect_duplicate_ssa_name_ptr_info (indx_after_incr, dr_info);
5574 }
5575 if (ptr_incr)
5576 *ptr_incr = incr;
5577
5578 return indx_before_incr;
5579 }
5580 else
5581 gcc_unreachable ();
5582 }
5583
5584
5585 /* Function bump_vector_ptr
5586
5587 Increment a pointer (to a vector type) by vector-size. If requested,
5588 i.e. if PTR-INCR is given, then also connect the new increment stmt
5589 to the existing def-use update-chain of the pointer, by modifying
5590 the PTR_INCR as illustrated below:
5591
5592 The pointer def-use update-chain before this function:
5593 DATAREF_PTR = phi (p_0, p_2)
5594 ....
5595 PTR_INCR: p_2 = DATAREF_PTR + step
5596
5597 The pointer def-use update-chain after this function:
5598 DATAREF_PTR = phi (p_0, p_2)
5599 ....
5600 NEW_DATAREF_PTR = DATAREF_PTR + BUMP
5601 ....
5602 PTR_INCR: p_2 = NEW_DATAREF_PTR + step
5603
5604 Input:
5605 DATAREF_PTR - ssa_name of a pointer (to vector type) that is being updated
5606 in the loop.
5607 PTR_INCR - optional. The stmt that updates the pointer in each iteration of
5608 the loop. The increment amount across iterations is expected
5609 to be vector_size.
5610 BSI - location where the new update stmt is to be placed.
5611 STMT_INFO - the original scalar memory-access stmt that is being vectorized.
5612 BUMP - optional. The offset by which to bump the pointer. If not given,
5613 the offset is assumed to be vector_size.
5614
5615 Output: Return NEW_DATAREF_PTR as illustrated above.
5616
5617 */
5618
5619 tree
5620 bump_vector_ptr (vec_info *vinfo,
5621 tree dataref_ptr, gimple *ptr_incr, gimple_stmt_iterator *gsi,
5622 stmt_vec_info stmt_info, tree bump)
5623 {
5624 struct data_reference *dr = STMT_VINFO_DATA_REF (stmt_info);
5625 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
5626 tree update = TYPE_SIZE_UNIT (vectype);
5627 gimple *incr_stmt;
5628 ssa_op_iter iter;
5629 use_operand_p use_p;
5630 tree new_dataref_ptr;
5631
5632 if (bump)
5633 update = bump;
5634
5635 if (TREE_CODE (dataref_ptr) == SSA_NAME)
5636 new_dataref_ptr = copy_ssa_name (dataref_ptr);
5637 else if (is_gimple_min_invariant (dataref_ptr))
5638 /* When possible avoid emitting a separate increment stmt that will
5639 force the addressed object addressable. */
5640 return build1 (ADDR_EXPR, TREE_TYPE (dataref_ptr),
5641 fold_build2 (MEM_REF,
5642 TREE_TYPE (TREE_TYPE (dataref_ptr)),
5643 dataref_ptr,
5644 fold_convert (ptr_type_node, update)));
5645 else
5646 new_dataref_ptr = make_ssa_name (TREE_TYPE (dataref_ptr));
5647 incr_stmt = gimple_build_assign (new_dataref_ptr, POINTER_PLUS_EXPR,
5648 dataref_ptr, update);
5649 vect_finish_stmt_generation (vinfo, stmt_info, incr_stmt, gsi);
5650 /* Fold the increment, avoiding excessive chains use-def chains of
5651 those, leading to compile-time issues for passes until the next
5652 forwprop pass which would do this as well. */
5653 gimple_stmt_iterator fold_gsi = gsi_for_stmt (incr_stmt);
5654 if (fold_stmt (&fold_gsi, follow_all_ssa_edges))
5655 {
5656 incr_stmt = gsi_stmt (fold_gsi);
5657 update_stmt (incr_stmt);
5658 }
5659
5660 /* Copy the points-to information if it exists. */
5661 if (DR_PTR_INFO (dr))
5662 {
5663 duplicate_ssa_name_ptr_info (new_dataref_ptr, DR_PTR_INFO (dr));
5664 mark_ptr_info_alignment_unknown (SSA_NAME_PTR_INFO (new_dataref_ptr));
5665 }
5666
5667 if (!ptr_incr)
5668 return new_dataref_ptr;
5669
5670 /* Update the vector-pointer's cross-iteration increment. */
5671 FOR_EACH_SSA_USE_OPERAND (use_p, ptr_incr, iter, SSA_OP_USE)
5672 {
5673 tree use = USE_FROM_PTR (use_p);
5674
5675 if (use == dataref_ptr)
5676 SET_USE (use_p, new_dataref_ptr);
5677 else
5678 gcc_assert (operand_equal_p (use, update, 0));
5679 }
5680
5681 return new_dataref_ptr;
5682 }
5683
5684
5685 /* Copy memory reference info such as base/clique from the SRC reference
5686 to the DEST MEM_REF. */
5687
5688 void
5689 vect_copy_ref_info (tree dest, tree src)
5690 {
5691 if (TREE_CODE (dest) != MEM_REF)
5692 return;
5693
5694 tree src_base = src;
5695 while (handled_component_p (src_base))
5696 src_base = TREE_OPERAND (src_base, 0);
5697 if (TREE_CODE (src_base) != MEM_REF
5698 && TREE_CODE (src_base) != TARGET_MEM_REF)
5699 return;
5700
5701 MR_DEPENDENCE_CLIQUE (dest) = MR_DEPENDENCE_CLIQUE (src_base);
5702 MR_DEPENDENCE_BASE (dest) = MR_DEPENDENCE_BASE (src_base);
5703 }
5704
5705
5706 /* Function vect_create_destination_var.
5707
5708 Create a new temporary of type VECTYPE. */
5709
5710 tree
5711 vect_create_destination_var (tree scalar_dest, tree vectype)
5712 {
5713 tree vec_dest;
5714 const char *name;
5715 char *new_name;
5716 tree type;
5717 enum vect_var_kind kind;
5718
5719 kind = vectype
5720 ? VECTOR_BOOLEAN_TYPE_P (vectype)
5721 ? vect_mask_var
5722 : vect_simple_var
5723 : vect_scalar_var;
5724 type = vectype ? vectype : TREE_TYPE (scalar_dest);
5725
5726 gcc_assert (TREE_CODE (scalar_dest) == SSA_NAME);
5727
5728 name = get_name (scalar_dest);
5729 if (name)
5730 new_name = xasprintf ("%s_%u", name, SSA_NAME_VERSION (scalar_dest));
5731 else
5732 new_name = xasprintf ("_%u", SSA_NAME_VERSION (scalar_dest));
5733 vec_dest = vect_get_new_vect_var (type, kind, new_name);
5734 free (new_name);
5735
5736 return vec_dest;
5737 }
5738
5739 /* Function vect_grouped_store_supported.
5740
5741 Returns TRUE if interleave high and interleave low permutations
5742 are supported, and FALSE otherwise. */
5743
5744 bool
5745 vect_grouped_store_supported (tree vectype, unsigned HOST_WIDE_INT count)
5746 {
5747 machine_mode mode = TYPE_MODE (vectype);
5748
5749 /* vect_permute_store_chain requires the group size to be equal to 3 or
5750 be a power of two. */
5751 if (count != 3 && exact_log2 (count) == -1)
5752 {
5753 if (dump_enabled_p ())
5754 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5755 "the size of the group of accesses"
5756 " is not a power of 2 or not eqaul to 3\n");
5757 return false;
5758 }
5759
5760 /* Check that the permutation is supported. */
5761 if (VECTOR_MODE_P (mode))
5762 {
5763 unsigned int i;
5764 if (count == 3)
5765 {
5766 unsigned int j0 = 0, j1 = 0, j2 = 0;
5767 unsigned int i, j;
5768
5769 unsigned int nelt;
5770 if (!GET_MODE_NUNITS (mode).is_constant (&nelt))
5771 {
5772 if (dump_enabled_p ())
5773 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5774 "cannot handle groups of 3 stores for"
5775 " variable-length vectors\n");
5776 return false;
5777 }
5778
5779 vec_perm_builder sel (nelt, nelt, 1);
5780 sel.quick_grow (nelt);
5781 vec_perm_indices indices;
5782 for (j = 0; j < 3; j++)
5783 {
5784 int nelt0 = ((3 - j) * nelt) % 3;
5785 int nelt1 = ((3 - j) * nelt + 1) % 3;
5786 int nelt2 = ((3 - j) * nelt + 2) % 3;
5787 for (i = 0; i < nelt; i++)
5788 {
5789 if (3 * i + nelt0 < nelt)
5790 sel[3 * i + nelt0] = j0++;
5791 if (3 * i + nelt1 < nelt)
5792 sel[3 * i + nelt1] = nelt + j1++;
5793 if (3 * i + nelt2 < nelt)
5794 sel[3 * i + nelt2] = 0;
5795 }
5796 indices.new_vector (sel, 2, nelt);
5797 if (!can_vec_perm_const_p (mode, mode, indices))
5798 {
5799 if (dump_enabled_p ())
5800 dump_printf (MSG_MISSED_OPTIMIZATION,
5801 "permutation op not supported by target.\n");
5802 return false;
5803 }
5804
5805 for (i = 0; i < nelt; i++)
5806 {
5807 if (3 * i + nelt0 < nelt)
5808 sel[3 * i + nelt0] = 3 * i + nelt0;
5809 if (3 * i + nelt1 < nelt)
5810 sel[3 * i + nelt1] = 3 * i + nelt1;
5811 if (3 * i + nelt2 < nelt)
5812 sel[3 * i + nelt2] = nelt + j2++;
5813 }
5814 indices.new_vector (sel, 2, nelt);
5815 if (!can_vec_perm_const_p (mode, mode, indices))
5816 {
5817 if (dump_enabled_p ())
5818 dump_printf (MSG_MISSED_OPTIMIZATION,
5819 "permutation op not supported by target.\n");
5820 return false;
5821 }
5822 }
5823 return true;
5824 }
5825 else
5826 {
5827 /* If length is not equal to 3 then only power of 2 is supported. */
5828 gcc_assert (pow2p_hwi (count));
5829 poly_uint64 nelt = GET_MODE_NUNITS (mode);
5830
5831 /* The encoding has 2 interleaved stepped patterns. */
5832 if(!multiple_p (nelt, 2))
5833 return false;
5834 vec_perm_builder sel (nelt, 2, 3);
5835 sel.quick_grow (6);
5836 for (i = 0; i < 3; i++)
5837 {
5838 sel[i * 2] = i;
5839 sel[i * 2 + 1] = i + nelt;
5840 }
5841 vec_perm_indices indices (sel, 2, nelt);
5842 if (can_vec_perm_const_p (mode, mode, indices))
5843 {
5844 for (i = 0; i < 6; i++)
5845 sel[i] += exact_div (nelt, 2);
5846 indices.new_vector (sel, 2, nelt);
5847 if (can_vec_perm_const_p (mode, mode, indices))
5848 return true;
5849 }
5850 }
5851 }
5852
5853 if (dump_enabled_p ())
5854 dump_printf (MSG_MISSED_OPTIMIZATION,
5855 "permutation op not supported by target.\n");
5856 return false;
5857 }
5858
5859 /* Return FN if vec_{mask_,mask_len_}store_lanes is available for COUNT vectors
5860 of type VECTYPE. MASKED_P says whether the masked form is needed. */
5861
5862 internal_fn
5863 vect_store_lanes_supported (tree vectype, unsigned HOST_WIDE_INT count,
5864 bool masked_p)
5865 {
5866 if (vect_lanes_optab_supported_p ("vec_mask_len_store_lanes",
5867 vec_mask_len_store_lanes_optab, vectype,
5868 count))
5869 return IFN_MASK_LEN_STORE_LANES;
5870 else if (masked_p)
5871 {
5872 if (vect_lanes_optab_supported_p ("vec_mask_store_lanes",
5873 vec_mask_store_lanes_optab, vectype,
5874 count))
5875 return IFN_MASK_STORE_LANES;
5876 }
5877 else
5878 {
5879 if (vect_lanes_optab_supported_p ("vec_store_lanes",
5880 vec_store_lanes_optab, vectype, count))
5881 return IFN_STORE_LANES;
5882 }
5883 return IFN_LAST;
5884 }
5885
5886
5887 /* Function vect_permute_store_chain.
5888
5889 Given a chain of interleaved stores in DR_CHAIN of LENGTH that must be
5890 a power of 2 or equal to 3, generate interleave_high/low stmts to reorder
5891 the data correctly for the stores. Return the final references for stores
5892 in RESULT_CHAIN.
5893
5894 E.g., LENGTH is 4 and the scalar type is short, i.e., VF is 8.
5895 The input is 4 vectors each containing 8 elements. We assign a number to
5896 each element, the input sequence is:
5897
5898 1st vec: 0 1 2 3 4 5 6 7
5899 2nd vec: 8 9 10 11 12 13 14 15
5900 3rd vec: 16 17 18 19 20 21 22 23
5901 4th vec: 24 25 26 27 28 29 30 31
5902
5903 The output sequence should be:
5904
5905 1st vec: 0 8 16 24 1 9 17 25
5906 2nd vec: 2 10 18 26 3 11 19 27
5907 3rd vec: 4 12 20 28 5 13 21 30
5908 4th vec: 6 14 22 30 7 15 23 31
5909
5910 i.e., we interleave the contents of the four vectors in their order.
5911
5912 We use interleave_high/low instructions to create such output. The input of
5913 each interleave_high/low operation is two vectors:
5914 1st vec 2nd vec
5915 0 1 2 3 4 5 6 7
5916 the even elements of the result vector are obtained left-to-right from the
5917 high/low elements of the first vector. The odd elements of the result are
5918 obtained left-to-right from the high/low elements of the second vector.
5919 The output of interleave_high will be: 0 4 1 5
5920 and of interleave_low: 2 6 3 7
5921
5922
5923 The permutation is done in log LENGTH stages. In each stage interleave_high
5924 and interleave_low stmts are created for each pair of vectors in DR_CHAIN,
5925 where the first argument is taken from the first half of DR_CHAIN and the
5926 second argument from it's second half.
5927 In our example,
5928
5929 I1: interleave_high (1st vec, 3rd vec)
5930 I2: interleave_low (1st vec, 3rd vec)
5931 I3: interleave_high (2nd vec, 4th vec)
5932 I4: interleave_low (2nd vec, 4th vec)
5933
5934 The output for the first stage is:
5935
5936 I1: 0 16 1 17 2 18 3 19
5937 I2: 4 20 5 21 6 22 7 23
5938 I3: 8 24 9 25 10 26 11 27
5939 I4: 12 28 13 29 14 30 15 31
5940
5941 The output of the second stage, i.e. the final result is:
5942
5943 I1: 0 8 16 24 1 9 17 25
5944 I2: 2 10 18 26 3 11 19 27
5945 I3: 4 12 20 28 5 13 21 30
5946 I4: 6 14 22 30 7 15 23 31. */
5947
5948 void
5949 vect_permute_store_chain (vec_info *vinfo, vec<tree> &dr_chain,
5950 unsigned int length,
5951 stmt_vec_info stmt_info,
5952 gimple_stmt_iterator *gsi,
5953 vec<tree> *result_chain)
5954 {
5955 tree vect1, vect2, high, low;
5956 gimple *perm_stmt;
5957 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
5958 tree perm_mask_low, perm_mask_high;
5959 tree data_ref;
5960 tree perm3_mask_low, perm3_mask_high;
5961 unsigned int i, j, n, log_length = exact_log2 (length);
5962
5963 result_chain->quick_grow (length);
5964 memcpy (result_chain->address (), dr_chain.address (),
5965 length * sizeof (tree));
5966
5967 if (length == 3)
5968 {
5969 /* vect_grouped_store_supported ensures that this is constant. */
5970 unsigned int nelt = TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
5971 unsigned int j0 = 0, j1 = 0, j2 = 0;
5972
5973 vec_perm_builder sel (nelt, nelt, 1);
5974 sel.quick_grow (nelt);
5975 vec_perm_indices indices;
5976 for (j = 0; j < 3; j++)
5977 {
5978 int nelt0 = ((3 - j) * nelt) % 3;
5979 int nelt1 = ((3 - j) * nelt + 1) % 3;
5980 int nelt2 = ((3 - j) * nelt + 2) % 3;
5981
5982 for (i = 0; i < nelt; i++)
5983 {
5984 if (3 * i + nelt0 < nelt)
5985 sel[3 * i + nelt0] = j0++;
5986 if (3 * i + nelt1 < nelt)
5987 sel[3 * i + nelt1] = nelt + j1++;
5988 if (3 * i + nelt2 < nelt)
5989 sel[3 * i + nelt2] = 0;
5990 }
5991 indices.new_vector (sel, 2, nelt);
5992 perm3_mask_low = vect_gen_perm_mask_checked (vectype, indices);
5993
5994 for (i = 0; i < nelt; i++)
5995 {
5996 if (3 * i + nelt0 < nelt)
5997 sel[3 * i + nelt0] = 3 * i + nelt0;
5998 if (3 * i + nelt1 < nelt)
5999 sel[3 * i + nelt1] = 3 * i + nelt1;
6000 if (3 * i + nelt2 < nelt)
6001 sel[3 * i + nelt2] = nelt + j2++;
6002 }
6003 indices.new_vector (sel, 2, nelt);
6004 perm3_mask_high = vect_gen_perm_mask_checked (vectype, indices);
6005
6006 vect1 = dr_chain[0];
6007 vect2 = dr_chain[1];
6008
6009 /* Create interleaving stmt:
6010 low = VEC_PERM_EXPR <vect1, vect2,
6011 {j, nelt, *, j + 1, nelt + j + 1, *,
6012 j + 2, nelt + j + 2, *, ...}> */
6013 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle3_low");
6014 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, vect1,
6015 vect2, perm3_mask_low);
6016 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6017
6018 vect1 = data_ref;
6019 vect2 = dr_chain[2];
6020 /* Create interleaving stmt:
6021 low = VEC_PERM_EXPR <vect1, vect2,
6022 {0, 1, nelt + j, 3, 4, nelt + j + 1,
6023 6, 7, nelt + j + 2, ...}> */
6024 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle3_high");
6025 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, vect1,
6026 vect2, perm3_mask_high);
6027 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6028 (*result_chain)[j] = data_ref;
6029 }
6030 }
6031 else
6032 {
6033 /* If length is not equal to 3 then only power of 2 is supported. */
6034 gcc_assert (pow2p_hwi (length));
6035
6036 /* The encoding has 2 interleaved stepped patterns. */
6037 poly_uint64 nelt = TYPE_VECTOR_SUBPARTS (vectype);
6038 vec_perm_builder sel (nelt, 2, 3);
6039 sel.quick_grow (6);
6040 for (i = 0; i < 3; i++)
6041 {
6042 sel[i * 2] = i;
6043 sel[i * 2 + 1] = i + nelt;
6044 }
6045 vec_perm_indices indices (sel, 2, nelt);
6046 perm_mask_high = vect_gen_perm_mask_checked (vectype, indices);
6047
6048 for (i = 0; i < 6; i++)
6049 sel[i] += exact_div (nelt, 2);
6050 indices.new_vector (sel, 2, nelt);
6051 perm_mask_low = vect_gen_perm_mask_checked (vectype, indices);
6052
6053 for (i = 0, n = log_length; i < n; i++)
6054 {
6055 for (j = 0; j < length/2; j++)
6056 {
6057 vect1 = dr_chain[j];
6058 vect2 = dr_chain[j+length/2];
6059
6060 /* Create interleaving stmt:
6061 high = VEC_PERM_EXPR <vect1, vect2, {0, nelt, 1, nelt+1,
6062 ...}> */
6063 high = make_temp_ssa_name (vectype, NULL, "vect_inter_high");
6064 perm_stmt = gimple_build_assign (high, VEC_PERM_EXPR, vect1,
6065 vect2, perm_mask_high);
6066 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6067 (*result_chain)[2*j] = high;
6068
6069 /* Create interleaving stmt:
6070 low = VEC_PERM_EXPR <vect1, vect2,
6071 {nelt/2, nelt*3/2, nelt/2+1, nelt*3/2+1,
6072 ...}> */
6073 low = make_temp_ssa_name (vectype, NULL, "vect_inter_low");
6074 perm_stmt = gimple_build_assign (low, VEC_PERM_EXPR, vect1,
6075 vect2, perm_mask_low);
6076 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6077 (*result_chain)[2*j+1] = low;
6078 }
6079 memcpy (dr_chain.address (), result_chain->address (),
6080 length * sizeof (tree));
6081 }
6082 }
6083 }
6084
6085 /* Function vect_setup_realignment
6086
6087 This function is called when vectorizing an unaligned load using
6088 the dr_explicit_realign[_optimized] scheme.
6089 This function generates the following code at the loop prolog:
6090
6091 p = initial_addr;
6092 x msq_init = *(floor(p)); # prolog load
6093 realignment_token = call target_builtin;
6094 loop:
6095 x msq = phi (msq_init, ---)
6096
6097 The stmts marked with x are generated only for the case of
6098 dr_explicit_realign_optimized.
6099
6100 The code above sets up a new (vector) pointer, pointing to the first
6101 location accessed by STMT_INFO, and a "floor-aligned" load using that
6102 pointer. It also generates code to compute the "realignment-token"
6103 (if the relevant target hook was defined), and creates a phi-node at the
6104 loop-header bb whose arguments are the result of the prolog-load (created
6105 by this function) and the result of a load that takes place in the loop
6106 (to be created by the caller to this function).
6107
6108 For the case of dr_explicit_realign_optimized:
6109 The caller to this function uses the phi-result (msq) to create the
6110 realignment code inside the loop, and sets up the missing phi argument,
6111 as follows:
6112 loop:
6113 msq = phi (msq_init, lsq)
6114 lsq = *(floor(p')); # load in loop
6115 result = realign_load (msq, lsq, realignment_token);
6116
6117 For the case of dr_explicit_realign:
6118 loop:
6119 msq = *(floor(p)); # load in loop
6120 p' = p + (VS-1);
6121 lsq = *(floor(p')); # load in loop
6122 result = realign_load (msq, lsq, realignment_token);
6123
6124 Input:
6125 STMT_INFO - (scalar) load stmt to be vectorized. This load accesses
6126 a memory location that may be unaligned.
6127 BSI - place where new code is to be inserted.
6128 ALIGNMENT_SUPPORT_SCHEME - which of the two misalignment handling schemes
6129 is used.
6130
6131 Output:
6132 REALIGNMENT_TOKEN - the result of a call to the builtin_mask_for_load
6133 target hook, if defined.
6134 Return value - the result of the loop-header phi node. */
6135
6136 tree
6137 vect_setup_realignment (vec_info *vinfo, stmt_vec_info stmt_info,
6138 gimple_stmt_iterator *gsi, tree *realignment_token,
6139 enum dr_alignment_support alignment_support_scheme,
6140 tree init_addr,
6141 class loop **at_loop)
6142 {
6143 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
6144 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
6145 dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
6146 struct data_reference *dr = dr_info->dr;
6147 class loop *loop = NULL;
6148 edge pe = NULL;
6149 tree scalar_dest = gimple_assign_lhs (stmt_info->stmt);
6150 tree vec_dest;
6151 gimple *inc;
6152 tree ptr;
6153 tree data_ref;
6154 basic_block new_bb;
6155 tree msq_init = NULL_TREE;
6156 tree new_temp;
6157 gphi *phi_stmt;
6158 tree msq = NULL_TREE;
6159 gimple_seq stmts = NULL;
6160 bool compute_in_loop = false;
6161 bool nested_in_vect_loop = false;
6162 class loop *containing_loop = (gimple_bb (stmt_info->stmt))->loop_father;
6163 class loop *loop_for_initial_load = NULL;
6164
6165 if (loop_vinfo)
6166 {
6167 loop = LOOP_VINFO_LOOP (loop_vinfo);
6168 nested_in_vect_loop = nested_in_vect_loop_p (loop, stmt_info);
6169 }
6170
6171 gcc_assert (alignment_support_scheme == dr_explicit_realign
6172 || alignment_support_scheme == dr_explicit_realign_optimized);
6173
6174 /* We need to generate three things:
6175 1. the misalignment computation
6176 2. the extra vector load (for the optimized realignment scheme).
6177 3. the phi node for the two vectors from which the realignment is
6178 done (for the optimized realignment scheme). */
6179
6180 /* 1. Determine where to generate the misalignment computation.
6181
6182 If INIT_ADDR is NULL_TREE, this indicates that the misalignment
6183 calculation will be generated by this function, outside the loop (in the
6184 preheader). Otherwise, INIT_ADDR had already been computed for us by the
6185 caller, inside the loop.
6186
6187 Background: If the misalignment remains fixed throughout the iterations of
6188 the loop, then both realignment schemes are applicable, and also the
6189 misalignment computation can be done outside LOOP. This is because we are
6190 vectorizing LOOP, and so the memory accesses in LOOP advance in steps that
6191 are a multiple of VS (the Vector Size), and therefore the misalignment in
6192 different vectorized LOOP iterations is always the same.
6193 The problem arises only if the memory access is in an inner-loop nested
6194 inside LOOP, which is now being vectorized using outer-loop vectorization.
6195 This is the only case when the misalignment of the memory access may not
6196 remain fixed throughout the iterations of the inner-loop (as explained in
6197 detail in vect_supportable_dr_alignment). In this case, not only is the
6198 optimized realignment scheme not applicable, but also the misalignment
6199 computation (and generation of the realignment token that is passed to
6200 REALIGN_LOAD) have to be done inside the loop.
6201
6202 In short, INIT_ADDR indicates whether we are in a COMPUTE_IN_LOOP mode
6203 or not, which in turn determines if the misalignment is computed inside
6204 the inner-loop, or outside LOOP. */
6205
6206 if (init_addr != NULL_TREE || !loop_vinfo)
6207 {
6208 compute_in_loop = true;
6209 gcc_assert (alignment_support_scheme == dr_explicit_realign);
6210 }
6211
6212
6213 /* 2. Determine where to generate the extra vector load.
6214
6215 For the optimized realignment scheme, instead of generating two vector
6216 loads in each iteration, we generate a single extra vector load in the
6217 preheader of the loop, and in each iteration reuse the result of the
6218 vector load from the previous iteration. In case the memory access is in
6219 an inner-loop nested inside LOOP, which is now being vectorized using
6220 outer-loop vectorization, we need to determine whether this initial vector
6221 load should be generated at the preheader of the inner-loop, or can be
6222 generated at the preheader of LOOP. If the memory access has no evolution
6223 in LOOP, it can be generated in the preheader of LOOP. Otherwise, it has
6224 to be generated inside LOOP (in the preheader of the inner-loop). */
6225
6226 if (nested_in_vect_loop)
6227 {
6228 tree outerloop_step = STMT_VINFO_DR_STEP (stmt_info);
6229 bool invariant_in_outerloop =
6230 (tree_int_cst_compare (outerloop_step, size_zero_node) == 0);
6231 loop_for_initial_load = (invariant_in_outerloop ? loop : loop->inner);
6232 }
6233 else
6234 loop_for_initial_load = loop;
6235 if (at_loop)
6236 *at_loop = loop_for_initial_load;
6237
6238 tree vuse = NULL_TREE;
6239 if (loop_for_initial_load)
6240 {
6241 pe = loop_preheader_edge (loop_for_initial_load);
6242 if (gphi *vphi = get_virtual_phi (loop_for_initial_load->header))
6243 vuse = PHI_ARG_DEF_FROM_EDGE (vphi, pe);
6244 }
6245 if (!vuse)
6246 vuse = gimple_vuse (gsi_stmt (*gsi));
6247
6248 /* 3. For the case of the optimized realignment, create the first vector
6249 load at the loop preheader. */
6250
6251 if (alignment_support_scheme == dr_explicit_realign_optimized)
6252 {
6253 /* Create msq_init = *(floor(p1)) in the loop preheader */
6254 gassign *new_stmt;
6255
6256 gcc_assert (!compute_in_loop);
6257 vec_dest = vect_create_destination_var (scalar_dest, vectype);
6258 ptr = vect_create_data_ref_ptr (vinfo, stmt_info, vectype,
6259 loop_for_initial_load, NULL_TREE,
6260 &init_addr, NULL, &inc, true);
6261 if (TREE_CODE (ptr) == SSA_NAME)
6262 new_temp = copy_ssa_name (ptr);
6263 else
6264 new_temp = make_ssa_name (TREE_TYPE (ptr));
6265 poly_uint64 align = DR_TARGET_ALIGNMENT (dr_info);
6266 tree type = TREE_TYPE (ptr);
6267 new_stmt = gimple_build_assign
6268 (new_temp, BIT_AND_EXPR, ptr,
6269 fold_build2 (MINUS_EXPR, type,
6270 build_int_cst (type, 0),
6271 build_int_cst (type, align)));
6272 new_bb = gsi_insert_on_edge_immediate (pe, new_stmt);
6273 gcc_assert (!new_bb);
6274 data_ref
6275 = build2 (MEM_REF, TREE_TYPE (vec_dest), new_temp,
6276 build_int_cst (reference_alias_ptr_type (DR_REF (dr)), 0));
6277 vect_copy_ref_info (data_ref, DR_REF (dr));
6278 new_stmt = gimple_build_assign (vec_dest, data_ref);
6279 new_temp = make_ssa_name (vec_dest, new_stmt);
6280 gimple_assign_set_lhs (new_stmt, new_temp);
6281 gimple_set_vuse (new_stmt, vuse);
6282 if (pe)
6283 {
6284 new_bb = gsi_insert_on_edge_immediate (pe, new_stmt);
6285 gcc_assert (!new_bb);
6286 }
6287 else
6288 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
6289
6290 msq_init = gimple_assign_lhs (new_stmt);
6291 }
6292
6293 /* 4. Create realignment token using a target builtin, if available.
6294 It is done either inside the containing loop, or before LOOP (as
6295 determined above). */
6296
6297 if (targetm.vectorize.builtin_mask_for_load)
6298 {
6299 gcall *new_stmt;
6300 tree builtin_decl;
6301
6302 /* Compute INIT_ADDR - the initial addressed accessed by this memref. */
6303 if (!init_addr)
6304 {
6305 /* Generate the INIT_ADDR computation outside LOOP. */
6306 init_addr = vect_create_addr_base_for_vector_ref (vinfo,
6307 stmt_info, &stmts,
6308 NULL_TREE);
6309 if (loop)
6310 {
6311 pe = loop_preheader_edge (loop);
6312 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
6313 gcc_assert (!new_bb);
6314 }
6315 else
6316 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
6317 }
6318
6319 builtin_decl = targetm.vectorize.builtin_mask_for_load ();
6320 new_stmt = gimple_build_call (builtin_decl, 1, init_addr);
6321 vec_dest =
6322 vect_create_destination_var (scalar_dest,
6323 gimple_call_return_type (new_stmt));
6324 new_temp = make_ssa_name (vec_dest, new_stmt);
6325 gimple_call_set_lhs (new_stmt, new_temp);
6326
6327 if (compute_in_loop)
6328 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
6329 else
6330 {
6331 /* Generate the misalignment computation outside LOOP. */
6332 pe = loop_preheader_edge (loop);
6333 new_bb = gsi_insert_on_edge_immediate (pe, new_stmt);
6334 gcc_assert (!new_bb);
6335 }
6336
6337 *realignment_token = gimple_call_lhs (new_stmt);
6338
6339 /* The result of the CALL_EXPR to this builtin is determined from
6340 the value of the parameter and no global variables are touched
6341 which makes the builtin a "const" function. Requiring the
6342 builtin to have the "const" attribute makes it unnecessary
6343 to call mark_call_clobbered. */
6344 gcc_assert (TREE_READONLY (builtin_decl));
6345 }
6346
6347 if (alignment_support_scheme == dr_explicit_realign)
6348 return msq;
6349
6350 gcc_assert (!compute_in_loop);
6351 gcc_assert (alignment_support_scheme == dr_explicit_realign_optimized);
6352
6353
6354 /* 5. Create msq = phi <msq_init, lsq> in loop */
6355
6356 pe = loop_preheader_edge (containing_loop);
6357 vec_dest = vect_create_destination_var (scalar_dest, vectype);
6358 msq = make_ssa_name (vec_dest);
6359 phi_stmt = create_phi_node (msq, containing_loop->header);
6360 add_phi_arg (phi_stmt, msq_init, pe, UNKNOWN_LOCATION);
6361
6362 return msq;
6363 }
6364
6365
6366 /* Function vect_grouped_load_supported.
6367
6368 COUNT is the size of the load group (the number of statements plus the
6369 number of gaps). SINGLE_ELEMENT_P is true if there is actually
6370 only one statement, with a gap of COUNT - 1.
6371
6372 Returns true if a suitable permute exists. */
6373
6374 bool
6375 vect_grouped_load_supported (tree vectype, bool single_element_p,
6376 unsigned HOST_WIDE_INT count)
6377 {
6378 machine_mode mode = TYPE_MODE (vectype);
6379
6380 /* If this is single-element interleaving with an element distance
6381 that leaves unused vector loads around punt - we at least create
6382 very sub-optimal code in that case (and blow up memory,
6383 see PR65518). */
6384 if (single_element_p && maybe_gt (count, TYPE_VECTOR_SUBPARTS (vectype)))
6385 {
6386 if (dump_enabled_p ())
6387 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6388 "single-element interleaving not supported "
6389 "for not adjacent vector loads\n");
6390 return false;
6391 }
6392
6393 /* vect_permute_load_chain requires the group size to be equal to 3 or
6394 be a power of two. */
6395 if (count != 3 && exact_log2 (count) == -1)
6396 {
6397 if (dump_enabled_p ())
6398 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6399 "the size of the group of accesses"
6400 " is not a power of 2 or not equal to 3\n");
6401 return false;
6402 }
6403
6404 /* Check that the permutation is supported. */
6405 if (VECTOR_MODE_P (mode))
6406 {
6407 unsigned int i, j;
6408 if (count == 3)
6409 {
6410 unsigned int nelt;
6411 if (!GET_MODE_NUNITS (mode).is_constant (&nelt))
6412 {
6413 if (dump_enabled_p ())
6414 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6415 "cannot handle groups of 3 loads for"
6416 " variable-length vectors\n");
6417 return false;
6418 }
6419
6420 vec_perm_builder sel (nelt, nelt, 1);
6421 sel.quick_grow (nelt);
6422 vec_perm_indices indices;
6423 unsigned int k;
6424 for (k = 0; k < 3; k++)
6425 {
6426 for (i = 0; i < nelt; i++)
6427 if (3 * i + k < 2 * nelt)
6428 sel[i] = 3 * i + k;
6429 else
6430 sel[i] = 0;
6431 indices.new_vector (sel, 2, nelt);
6432 if (!can_vec_perm_const_p (mode, mode, indices))
6433 {
6434 if (dump_enabled_p ())
6435 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6436 "shuffle of 3 loads is not supported by"
6437 " target\n");
6438 return false;
6439 }
6440 for (i = 0, j = 0; i < nelt; i++)
6441 if (3 * i + k < 2 * nelt)
6442 sel[i] = i;
6443 else
6444 sel[i] = nelt + ((nelt + k) % 3) + 3 * (j++);
6445 indices.new_vector (sel, 2, nelt);
6446 if (!can_vec_perm_const_p (mode, mode, indices))
6447 {
6448 if (dump_enabled_p ())
6449 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6450 "shuffle of 3 loads is not supported by"
6451 " target\n");
6452 return false;
6453 }
6454 }
6455 return true;
6456 }
6457 else
6458 {
6459 /* If length is not equal to 3 then only power of 2 is supported. */
6460 gcc_assert (pow2p_hwi (count));
6461 poly_uint64 nelt = GET_MODE_NUNITS (mode);
6462
6463 /* The encoding has a single stepped pattern. */
6464 vec_perm_builder sel (nelt, 1, 3);
6465 sel.quick_grow (3);
6466 for (i = 0; i < 3; i++)
6467 sel[i] = i * 2;
6468 vec_perm_indices indices (sel, 2, nelt);
6469 if (can_vec_perm_const_p (mode, mode, indices))
6470 {
6471 for (i = 0; i < 3; i++)
6472 sel[i] = i * 2 + 1;
6473 indices.new_vector (sel, 2, nelt);
6474 if (can_vec_perm_const_p (mode, mode, indices))
6475 return true;
6476 }
6477 }
6478 }
6479
6480 if (dump_enabled_p ())
6481 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6482 "extract even/odd not supported by target\n");
6483 return false;
6484 }
6485
6486 /* Return FN if vec_{masked_,mask_len_}load_lanes is available for COUNT vectors
6487 of type VECTYPE. MASKED_P says whether the masked form is needed.
6488 If it is available and ELSVALS is nonzero store the possible else values
6489 in the vector it points to. */
6490
6491 internal_fn
6492 vect_load_lanes_supported (tree vectype, unsigned HOST_WIDE_INT count,
6493 bool masked_p, vec<int> *elsvals)
6494 {
6495 if (vect_lanes_optab_supported_p ("vec_mask_len_load_lanes",
6496 vec_mask_len_load_lanes_optab, vectype,
6497 count, elsvals))
6498 return IFN_MASK_LEN_LOAD_LANES;
6499 else if (masked_p)
6500 {
6501 if (vect_lanes_optab_supported_p ("vec_mask_load_lanes",
6502 vec_mask_load_lanes_optab, vectype,
6503 count, elsvals))
6504 return IFN_MASK_LOAD_LANES;
6505 }
6506 else
6507 {
6508 if (vect_lanes_optab_supported_p ("vec_load_lanes", vec_load_lanes_optab,
6509 vectype, count, elsvals))
6510 return IFN_LOAD_LANES;
6511 }
6512 return IFN_LAST;
6513 }
6514
6515 /* Function vect_permute_load_chain.
6516
6517 Given a chain of interleaved loads in DR_CHAIN of LENGTH that must be
6518 a power of 2 or equal to 3, generate extract_even/odd stmts to reorder
6519 the input data correctly. Return the final references for loads in
6520 RESULT_CHAIN.
6521
6522 E.g., LENGTH is 4 and the scalar type is short, i.e., VF is 8.
6523 The input is 4 vectors each containing 8 elements. We assign a number to each
6524 element, the input sequence is:
6525
6526 1st vec: 0 1 2 3 4 5 6 7
6527 2nd vec: 8 9 10 11 12 13 14 15
6528 3rd vec: 16 17 18 19 20 21 22 23
6529 4th vec: 24 25 26 27 28 29 30 31
6530
6531 The output sequence should be:
6532
6533 1st vec: 0 4 8 12 16 20 24 28
6534 2nd vec: 1 5 9 13 17 21 25 29
6535 3rd vec: 2 6 10 14 18 22 26 30
6536 4th vec: 3 7 11 15 19 23 27 31
6537
6538 i.e., the first output vector should contain the first elements of each
6539 interleaving group, etc.
6540
6541 We use extract_even/odd instructions to create such output. The input of
6542 each extract_even/odd operation is two vectors
6543 1st vec 2nd vec
6544 0 1 2 3 4 5 6 7
6545
6546 and the output is the vector of extracted even/odd elements. The output of
6547 extract_even will be: 0 2 4 6
6548 and of extract_odd: 1 3 5 7
6549
6550
6551 The permutation is done in log LENGTH stages. In each stage extract_even
6552 and extract_odd stmts are created for each pair of vectors in DR_CHAIN in
6553 their order. In our example,
6554
6555 E1: extract_even (1st vec, 2nd vec)
6556 E2: extract_odd (1st vec, 2nd vec)
6557 E3: extract_even (3rd vec, 4th vec)
6558 E4: extract_odd (3rd vec, 4th vec)
6559
6560 The output for the first stage will be:
6561
6562 E1: 0 2 4 6 8 10 12 14
6563 E2: 1 3 5 7 9 11 13 15
6564 E3: 16 18 20 22 24 26 28 30
6565 E4: 17 19 21 23 25 27 29 31
6566
6567 In order to proceed and create the correct sequence for the next stage (or
6568 for the correct output, if the second stage is the last one, as in our
6569 example), we first put the output of extract_even operation and then the
6570 output of extract_odd in RESULT_CHAIN (which is then copied to DR_CHAIN).
6571 The input for the second stage is:
6572
6573 1st vec (E1): 0 2 4 6 8 10 12 14
6574 2nd vec (E3): 16 18 20 22 24 26 28 30
6575 3rd vec (E2): 1 3 5 7 9 11 13 15
6576 4th vec (E4): 17 19 21 23 25 27 29 31
6577
6578 The output of the second stage:
6579
6580 E1: 0 4 8 12 16 20 24 28
6581 E2: 2 6 10 14 18 22 26 30
6582 E3: 1 5 9 13 17 21 25 29
6583 E4: 3 7 11 15 19 23 27 31
6584
6585 And RESULT_CHAIN after reordering:
6586
6587 1st vec (E1): 0 4 8 12 16 20 24 28
6588 2nd vec (E3): 1 5 9 13 17 21 25 29
6589 3rd vec (E2): 2 6 10 14 18 22 26 30
6590 4th vec (E4): 3 7 11 15 19 23 27 31. */
6591
6592 static void
6593 vect_permute_load_chain (vec_info *vinfo, vec<tree> dr_chain,
6594 unsigned int length,
6595 stmt_vec_info stmt_info,
6596 gimple_stmt_iterator *gsi,
6597 vec<tree> *result_chain)
6598 {
6599 tree data_ref, first_vect, second_vect;
6600 tree perm_mask_even, perm_mask_odd;
6601 tree perm3_mask_low, perm3_mask_high;
6602 gimple *perm_stmt;
6603 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
6604 unsigned int i, j, log_length = exact_log2 (length);
6605
6606 result_chain->quick_grow (length);
6607 memcpy (result_chain->address (), dr_chain.address (),
6608 length * sizeof (tree));
6609
6610 if (length == 3)
6611 {
6612 /* vect_grouped_load_supported ensures that this is constant. */
6613 unsigned nelt = TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
6614 unsigned int k;
6615
6616 vec_perm_builder sel (nelt, nelt, 1);
6617 sel.quick_grow (nelt);
6618 vec_perm_indices indices;
6619 for (k = 0; k < 3; k++)
6620 {
6621 for (i = 0; i < nelt; i++)
6622 if (3 * i + k < 2 * nelt)
6623 sel[i] = 3 * i + k;
6624 else
6625 sel[i] = 0;
6626 indices.new_vector (sel, 2, nelt);
6627 perm3_mask_low = vect_gen_perm_mask_checked (vectype, indices);
6628
6629 for (i = 0, j = 0; i < nelt; i++)
6630 if (3 * i + k < 2 * nelt)
6631 sel[i] = i;
6632 else
6633 sel[i] = nelt + ((nelt + k) % 3) + 3 * (j++);
6634 indices.new_vector (sel, 2, nelt);
6635 perm3_mask_high = vect_gen_perm_mask_checked (vectype, indices);
6636
6637 first_vect = dr_chain[0];
6638 second_vect = dr_chain[1];
6639
6640 /* Create interleaving stmt (low part of):
6641 low = VEC_PERM_EXPR <first_vect, second_vect2, {k, 3 + k, 6 + k,
6642 ...}> */
6643 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle3_low");
6644 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, first_vect,
6645 second_vect, perm3_mask_low);
6646 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6647
6648 /* Create interleaving stmt (high part of):
6649 high = VEC_PERM_EXPR <first_vect, second_vect2, {k, 3 + k, 6 + k,
6650 ...}> */
6651 first_vect = data_ref;
6652 second_vect = dr_chain[2];
6653 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle3_high");
6654 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, first_vect,
6655 second_vect, perm3_mask_high);
6656 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6657 (*result_chain)[k] = data_ref;
6658 }
6659 }
6660 else
6661 {
6662 /* If length is not equal to 3 then only power of 2 is supported. */
6663 gcc_assert (pow2p_hwi (length));
6664
6665 /* The encoding has a single stepped pattern. */
6666 poly_uint64 nelt = TYPE_VECTOR_SUBPARTS (vectype);
6667 vec_perm_builder sel (nelt, 1, 3);
6668 sel.quick_grow (3);
6669 for (i = 0; i < 3; ++i)
6670 sel[i] = i * 2;
6671 vec_perm_indices indices (sel, 2, nelt);
6672 perm_mask_even = vect_gen_perm_mask_checked (vectype, indices);
6673
6674 for (i = 0; i < 3; ++i)
6675 sel[i] = i * 2 + 1;
6676 indices.new_vector (sel, 2, nelt);
6677 perm_mask_odd = vect_gen_perm_mask_checked (vectype, indices);
6678
6679 for (i = 0; i < log_length; i++)
6680 {
6681 for (j = 0; j < length; j += 2)
6682 {
6683 first_vect = dr_chain[j];
6684 second_vect = dr_chain[j+1];
6685
6686 /* data_ref = permute_even (first_data_ref, second_data_ref); */
6687 data_ref = make_temp_ssa_name (vectype, NULL, "vect_perm_even");
6688 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
6689 first_vect, second_vect,
6690 perm_mask_even);
6691 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6692 (*result_chain)[j/2] = data_ref;
6693
6694 /* data_ref = permute_odd (first_data_ref, second_data_ref); */
6695 data_ref = make_temp_ssa_name (vectype, NULL, "vect_perm_odd");
6696 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
6697 first_vect, second_vect,
6698 perm_mask_odd);
6699 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6700 (*result_chain)[j/2+length/2] = data_ref;
6701 }
6702 memcpy (dr_chain.address (), result_chain->address (),
6703 length * sizeof (tree));
6704 }
6705 }
6706 }
6707
6708 /* Function vect_shift_permute_load_chain.
6709
6710 Given a chain of loads in DR_CHAIN of LENGTH 2 or 3, generate
6711 sequence of stmts to reorder the input data accordingly.
6712 Return the final references for loads in RESULT_CHAIN.
6713 Return true if successed, false otherwise.
6714
6715 E.g., LENGTH is 3 and the scalar type is short, i.e., VF is 8.
6716 The input is 3 vectors each containing 8 elements. We assign a
6717 number to each element, the input sequence is:
6718
6719 1st vec: 0 1 2 3 4 5 6 7
6720 2nd vec: 8 9 10 11 12 13 14 15
6721 3rd vec: 16 17 18 19 20 21 22 23
6722
6723 The output sequence should be:
6724
6725 1st vec: 0 3 6 9 12 15 18 21
6726 2nd vec: 1 4 7 10 13 16 19 22
6727 3rd vec: 2 5 8 11 14 17 20 23
6728
6729 We use 3 shuffle instructions and 3 * 3 - 1 shifts to create such output.
6730
6731 First we shuffle all 3 vectors to get correct elements order:
6732
6733 1st vec: ( 0 3 6) ( 1 4 7) ( 2 5)
6734 2nd vec: ( 8 11 14) ( 9 12 15) (10 13)
6735 3rd vec: (16 19 22) (17 20 23) (18 21)
6736
6737 Next we unite and shift vector 3 times:
6738
6739 1st step:
6740 shift right by 6 the concatenation of:
6741 "1st vec" and "2nd vec"
6742 ( 0 3 6) ( 1 4 7) |( 2 5) _ ( 8 11 14) ( 9 12 15)| (10 13)
6743 "2nd vec" and "3rd vec"
6744 ( 8 11 14) ( 9 12 15) |(10 13) _ (16 19 22) (17 20 23)| (18 21)
6745 "3rd vec" and "1st vec"
6746 (16 19 22) (17 20 23) |(18 21) _ ( 0 3 6) ( 1 4 7)| ( 2 5)
6747 | New vectors |
6748
6749 So that now new vectors are:
6750
6751 1st vec: ( 2 5) ( 8 11 14) ( 9 12 15)
6752 2nd vec: (10 13) (16 19 22) (17 20 23)
6753 3rd vec: (18 21) ( 0 3 6) ( 1 4 7)
6754
6755 2nd step:
6756 shift right by 5 the concatenation of:
6757 "1st vec" and "3rd vec"
6758 ( 2 5) ( 8 11 14) |( 9 12 15) _ (18 21) ( 0 3 6)| ( 1 4 7)
6759 "2nd vec" and "1st vec"
6760 (10 13) (16 19 22) |(17 20 23) _ ( 2 5) ( 8 11 14)| ( 9 12 15)
6761 "3rd vec" and "2nd vec"
6762 (18 21) ( 0 3 6) |( 1 4 7) _ (10 13) (16 19 22)| (17 20 23)
6763 | New vectors |
6764
6765 So that now new vectors are:
6766
6767 1st vec: ( 9 12 15) (18 21) ( 0 3 6)
6768 2nd vec: (17 20 23) ( 2 5) ( 8 11 14)
6769 3rd vec: ( 1 4 7) (10 13) (16 19 22) READY
6770
6771 3rd step:
6772 shift right by 5 the concatenation of:
6773 "1st vec" and "1st vec"
6774 ( 9 12 15) (18 21) |( 0 3 6) _ ( 9 12 15) (18 21)| ( 0 3 6)
6775 shift right by 3 the concatenation of:
6776 "2nd vec" and "2nd vec"
6777 (17 20 23) |( 2 5) ( 8 11 14) _ (17 20 23)| ( 2 5) ( 8 11 14)
6778 | New vectors |
6779
6780 So that now all vectors are READY:
6781 1st vec: ( 0 3 6) ( 9 12 15) (18 21)
6782 2nd vec: ( 2 5) ( 8 11 14) (17 20 23)
6783 3rd vec: ( 1 4 7) (10 13) (16 19 22)
6784
6785 This algorithm is faster than one in vect_permute_load_chain if:
6786 1. "shift of a concatination" is faster than general permutation.
6787 This is usually so.
6788 2. The TARGET machine can't execute vector instructions in parallel.
6789 This is because each step of the algorithm depends on previous.
6790 The algorithm in vect_permute_load_chain is much more parallel.
6791
6792 The algorithm is applicable only for LOAD CHAIN LENGTH less than VF.
6793 */
6794
6795 static bool
6796 vect_shift_permute_load_chain (vec_info *vinfo, vec<tree> dr_chain,
6797 unsigned int length,
6798 stmt_vec_info stmt_info,
6799 gimple_stmt_iterator *gsi,
6800 vec<tree> *result_chain)
6801 {
6802 tree vect[3], vect_shift[3], data_ref, first_vect, second_vect;
6803 tree perm2_mask1, perm2_mask2, perm3_mask;
6804 tree select_mask, shift1_mask, shift2_mask, shift3_mask, shift4_mask;
6805 gimple *perm_stmt;
6806
6807 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
6808 machine_mode vmode = TYPE_MODE (vectype);
6809 unsigned int i;
6810 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
6811
6812 unsigned HOST_WIDE_INT nelt, vf;
6813 if (!TYPE_VECTOR_SUBPARTS (vectype).is_constant (&nelt)
6814 || !LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant (&vf))
6815 /* Not supported for variable-length vectors. */
6816 return false;
6817
6818 vec_perm_builder sel (nelt, nelt, 1);
6819 sel.quick_grow (nelt);
6820
6821 result_chain->quick_grow (length);
6822 memcpy (result_chain->address (), dr_chain.address (),
6823 length * sizeof (tree));
6824
6825 if (pow2p_hwi (length) && vf > 4)
6826 {
6827 unsigned int j, log_length = exact_log2 (length);
6828 for (i = 0; i < nelt / 2; ++i)
6829 sel[i] = i * 2;
6830 for (i = 0; i < nelt / 2; ++i)
6831 sel[nelt / 2 + i] = i * 2 + 1;
6832 vec_perm_indices indices (sel, 2, nelt);
6833 if (!can_vec_perm_const_p (vmode, vmode, indices))
6834 {
6835 if (dump_enabled_p ())
6836 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6837 "shuffle of 2 fields structure is not \
6838 supported by target\n");
6839 return false;
6840 }
6841 perm2_mask1 = vect_gen_perm_mask_checked (vectype, indices);
6842
6843 for (i = 0; i < nelt / 2; ++i)
6844 sel[i] = i * 2 + 1;
6845 for (i = 0; i < nelt / 2; ++i)
6846 sel[nelt / 2 + i] = i * 2;
6847 indices.new_vector (sel, 2, nelt);
6848 if (!can_vec_perm_const_p (vmode, vmode, indices))
6849 {
6850 if (dump_enabled_p ())
6851 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6852 "shuffle of 2 fields structure is not \
6853 supported by target\n");
6854 return false;
6855 }
6856 perm2_mask2 = vect_gen_perm_mask_checked (vectype, indices);
6857
6858 /* Generating permutation constant to shift all elements.
6859 For vector length 8 it is {4 5 6 7 8 9 10 11}. */
6860 for (i = 0; i < nelt; i++)
6861 sel[i] = nelt / 2 + i;
6862 indices.new_vector (sel, 2, nelt);
6863 if (!can_vec_perm_const_p (vmode, vmode, indices))
6864 {
6865 if (dump_enabled_p ())
6866 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6867 "shift permutation is not supported by target\n");
6868 return false;
6869 }
6870 shift1_mask = vect_gen_perm_mask_checked (vectype, indices);
6871
6872 /* Generating permutation constant to select vector from 2.
6873 For vector length 8 it is {0 1 2 3 12 13 14 15}. */
6874 for (i = 0; i < nelt / 2; i++)
6875 sel[i] = i;
6876 for (i = nelt / 2; i < nelt; i++)
6877 sel[i] = nelt + i;
6878 indices.new_vector (sel, 2, nelt);
6879 if (!can_vec_perm_const_p (vmode, vmode, indices))
6880 {
6881 if (dump_enabled_p ())
6882 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6883 "select is not supported by target\n");
6884 return false;
6885 }
6886 select_mask = vect_gen_perm_mask_checked (vectype, indices);
6887
6888 for (i = 0; i < log_length; i++)
6889 {
6890 for (j = 0; j < length; j += 2)
6891 {
6892 first_vect = dr_chain[j];
6893 second_vect = dr_chain[j + 1];
6894
6895 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle2");
6896 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
6897 first_vect, first_vect,
6898 perm2_mask1);
6899 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6900 vect[0] = data_ref;
6901
6902 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle2");
6903 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
6904 second_vect, second_vect,
6905 perm2_mask2);
6906 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6907 vect[1] = data_ref;
6908
6909 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shift");
6910 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
6911 vect[0], vect[1], shift1_mask);
6912 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6913 (*result_chain)[j/2 + length/2] = data_ref;
6914
6915 data_ref = make_temp_ssa_name (vectype, NULL, "vect_select");
6916 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
6917 vect[0], vect[1], select_mask);
6918 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
6919 (*result_chain)[j/2] = data_ref;
6920 }
6921 memcpy (dr_chain.address (), result_chain->address (),
6922 length * sizeof (tree));
6923 }
6924 return true;
6925 }
6926 if (length == 3 && vf > 2)
6927 {
6928 unsigned int k = 0, l = 0;
6929
6930 /* Generating permutation constant to get all elements in rigth order.
6931 For vector length 8 it is {0 3 6 1 4 7 2 5}. */
6932 for (i = 0; i < nelt; i++)
6933 {
6934 if (3 * k + (l % 3) >= nelt)
6935 {
6936 k = 0;
6937 l += (3 - (nelt % 3));
6938 }
6939 sel[i] = 3 * k + (l % 3);
6940 k++;
6941 }
6942 vec_perm_indices indices (sel, 2, nelt);
6943 if (!can_vec_perm_const_p (vmode, vmode, indices))
6944 {
6945 if (dump_enabled_p ())
6946 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6947 "shuffle of 3 fields structure is not \
6948 supported by target\n");
6949 return false;
6950 }
6951 perm3_mask = vect_gen_perm_mask_checked (vectype, indices);
6952
6953 /* Generating permutation constant to shift all elements.
6954 For vector length 8 it is {6 7 8 9 10 11 12 13}. */
6955 for (i = 0; i < nelt; i++)
6956 sel[i] = 2 * (nelt / 3) + (nelt % 3) + i;
6957 indices.new_vector (sel, 2, nelt);
6958 if (!can_vec_perm_const_p (vmode, vmode, indices))
6959 {
6960 if (dump_enabled_p ())
6961 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6962 "shift permutation is not supported by target\n");
6963 return false;
6964 }
6965 shift1_mask = vect_gen_perm_mask_checked (vectype, indices);
6966
6967 /* Generating permutation constant to shift all elements.
6968 For vector length 8 it is {5 6 7 8 9 10 11 12}. */
6969 for (i = 0; i < nelt; i++)
6970 sel[i] = 2 * (nelt / 3) + 1 + i;
6971 indices.new_vector (sel, 2, nelt);
6972 if (!can_vec_perm_const_p (vmode, vmode, indices))
6973 {
6974 if (dump_enabled_p ())
6975 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6976 "shift permutation is not supported by target\n");
6977 return false;
6978 }
6979 shift2_mask = vect_gen_perm_mask_checked (vectype, indices);
6980
6981 /* Generating permutation constant to shift all elements.
6982 For vector length 8 it is {3 4 5 6 7 8 9 10}. */
6983 for (i = 0; i < nelt; i++)
6984 sel[i] = (nelt / 3) + (nelt % 3) / 2 + i;
6985 indices.new_vector (sel, 2, nelt);
6986 if (!can_vec_perm_const_p (vmode, vmode, indices))
6987 {
6988 if (dump_enabled_p ())
6989 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6990 "shift permutation is not supported by target\n");
6991 return false;
6992 }
6993 shift3_mask = vect_gen_perm_mask_checked (vectype, indices);
6994
6995 /* Generating permutation constant to shift all elements.
6996 For vector length 8 it is {5 6 7 8 9 10 11 12}. */
6997 for (i = 0; i < nelt; i++)
6998 sel[i] = 2 * (nelt / 3) + (nelt % 3) / 2 + i;
6999 indices.new_vector (sel, 2, nelt);
7000 if (!can_vec_perm_const_p (vmode, vmode, indices))
7001 {
7002 if (dump_enabled_p ())
7003 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
7004 "shift permutation is not supported by target\n");
7005 return false;
7006 }
7007 shift4_mask = vect_gen_perm_mask_checked (vectype, indices);
7008
7009 for (k = 0; k < 3; k++)
7010 {
7011 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle3");
7012 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
7013 dr_chain[k], dr_chain[k],
7014 perm3_mask);
7015 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
7016 vect[k] = data_ref;
7017 }
7018
7019 for (k = 0; k < 3; k++)
7020 {
7021 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shift1");
7022 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
7023 vect[k % 3], vect[(k + 1) % 3],
7024 shift1_mask);
7025 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
7026 vect_shift[k] = data_ref;
7027 }
7028
7029 for (k = 0; k < 3; k++)
7030 {
7031 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shift2");
7032 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
7033 vect_shift[(4 - k) % 3],
7034 vect_shift[(3 - k) % 3],
7035 shift2_mask);
7036 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
7037 vect[k] = data_ref;
7038 }
7039
7040 (*result_chain)[3 - (nelt % 3)] = vect[2];
7041
7042 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shift3");
7043 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, vect[0],
7044 vect[0], shift3_mask);
7045 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
7046 (*result_chain)[nelt % 3] = data_ref;
7047
7048 data_ref = make_temp_ssa_name (vectype, NULL, "vect_shift4");
7049 perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, vect[1],
7050 vect[1], shift4_mask);
7051 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt, gsi);
7052 (*result_chain)[0] = data_ref;
7053 return true;
7054 }
7055 return false;
7056 }
7057
7058 /* Function vect_transform_grouped_load.
7059
7060 Given a chain of input interleaved data-refs (in DR_CHAIN), build statements
7061 to perform their permutation and ascribe the result vectorized statements to
7062 the scalar statements.
7063 */
7064
7065 void
7066 vect_transform_grouped_load (vec_info *vinfo, stmt_vec_info stmt_info,
7067 vec<tree> dr_chain,
7068 int size, gimple_stmt_iterator *gsi)
7069 {
7070 machine_mode mode;
7071 vec<tree> result_chain = vNULL;
7072
7073 /* DR_CHAIN contains input data-refs that are a part of the interleaving.
7074 RESULT_CHAIN is the output of vect_permute_load_chain, it contains permuted
7075 vectors, that are ready for vector computation. */
7076 result_chain.create (size);
7077
7078 /* If reassociation width for vector type is 2 or greater target machine can
7079 execute 2 or more vector instructions in parallel. Otherwise try to
7080 get chain for loads group using vect_shift_permute_load_chain. */
7081 mode = TYPE_MODE (STMT_VINFO_VECTYPE (stmt_info));
7082 if (targetm.sched.reassociation_width (VEC_PERM_EXPR, mode) > 1
7083 || pow2p_hwi (size)
7084 || !vect_shift_permute_load_chain (vinfo, dr_chain, size, stmt_info,
7085 gsi, &result_chain))
7086 vect_permute_load_chain (vinfo, dr_chain,
7087 size, stmt_info, gsi, &result_chain);
7088 vect_record_grouped_load_vectors (vinfo, stmt_info, result_chain);
7089 result_chain.release ();
7090 }
7091
7092 /* RESULT_CHAIN contains the output of a group of grouped loads that were
7093 generated as part of the vectorization of STMT_INFO. Assign the statement
7094 for each vector to the associated scalar statement. */
7095
7096 void
7097 vect_record_grouped_load_vectors (vec_info *, stmt_vec_info stmt_info,
7098 vec<tree> result_chain)
7099 {
7100 stmt_vec_info first_stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
7101 unsigned int i, gap_count;
7102 tree tmp_data_ref;
7103
7104 /* Put a permuted data-ref in the VECTORIZED_STMT field.
7105 Since we scan the chain starting from it's first node, their order
7106 corresponds the order of data-refs in RESULT_CHAIN. */
7107 stmt_vec_info next_stmt_info = first_stmt_info;
7108 gap_count = 1;
7109 FOR_EACH_VEC_ELT (result_chain, i, tmp_data_ref)
7110 {
7111 if (!next_stmt_info)
7112 break;
7113
7114 /* Skip the gaps. Loads created for the gaps will be removed by dead
7115 code elimination pass later. No need to check for the first stmt in
7116 the group, since it always exists.
7117 DR_GROUP_GAP is the number of steps in elements from the previous
7118 access (if there is no gap DR_GROUP_GAP is 1). We skip loads that
7119 correspond to the gaps. */
7120 if (next_stmt_info != first_stmt_info
7121 && gap_count < DR_GROUP_GAP (next_stmt_info))
7122 {
7123 gap_count++;
7124 continue;
7125 }
7126
7127 /* ??? The following needs cleanup after the removal of
7128 DR_GROUP_SAME_DR_STMT. */
7129 if (next_stmt_info)
7130 {
7131 gimple *new_stmt = SSA_NAME_DEF_STMT (tmp_data_ref);
7132 /* We assume that if VEC_STMT is not NULL, this is a case of multiple
7133 copies, and we put the new vector statement last. */
7134 STMT_VINFO_VEC_STMTS (next_stmt_info).safe_push (new_stmt);
7135
7136 next_stmt_info = DR_GROUP_NEXT_ELEMENT (next_stmt_info);
7137 gap_count = 1;
7138 }
7139 }
7140 }
7141
7142 /* Function vect_force_dr_alignment_p.
7143
7144 Returns whether the alignment of a DECL can be forced to be aligned
7145 on ALIGNMENT bit boundary. */
7146
7147 bool
7148 vect_can_force_dr_alignment_p (const_tree decl, poly_uint64 alignment)
7149 {
7150 if (!VAR_P (decl))
7151 return false;
7152
7153 if (decl_in_symtab_p (decl)
7154 && (!symtab_node::get (decl)
7155 || !symtab_node::get (decl)->can_increase_alignment_p ()))
7156 return false;
7157
7158 if (TREE_STATIC (decl))
7159 return (known_le (alignment,
7160 (unsigned HOST_WIDE_INT) MAX_OFILE_ALIGNMENT));
7161 else
7162 return (known_le (alignment, (unsigned HOST_WIDE_INT) MAX_STACK_ALIGNMENT));
7163 }
7164
7165 /* Return whether the data reference DR_INFO is supported with respect to its
7166 alignment.
7167 If CHECK_ALIGNED_ACCESSES is TRUE, check if the access is supported even
7168 it is aligned, i.e., check if it is possible to vectorize it with different
7169 alignment. */
7170
7171 enum dr_alignment_support
7172 vect_supportable_dr_alignment (vec_info *vinfo, dr_vec_info *dr_info,
7173 tree vectype, int misalignment)
7174 {
7175 data_reference *dr = dr_info->dr;
7176 stmt_vec_info stmt_info = dr_info->stmt;
7177 machine_mode mode = TYPE_MODE (vectype);
7178 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
7179 class loop *vect_loop = NULL;
7180 bool nested_in_vect_loop = false;
7181
7182 if (misalignment == 0)
7183 return dr_aligned;
7184 else if (dr_safe_speculative_read_required (stmt_info))
7185 return dr_unaligned_unsupported;
7186
7187 /* For now assume all conditional loads/stores support unaligned
7188 access without any special code. */
7189 if (gcall *stmt = dyn_cast <gcall *> (stmt_info->stmt))
7190 if (gimple_call_internal_p (stmt)
7191 && (gimple_call_internal_fn (stmt) == IFN_MASK_LOAD
7192 || gimple_call_internal_fn (stmt) == IFN_MASK_STORE))
7193 return dr_unaligned_supported;
7194
7195 if (loop_vinfo)
7196 {
7197 vect_loop = LOOP_VINFO_LOOP (loop_vinfo);
7198 nested_in_vect_loop = nested_in_vect_loop_p (vect_loop, stmt_info);
7199 }
7200
7201 /* Possibly unaligned access. */
7202
7203 /* We can choose between using the implicit realignment scheme (generating
7204 a misaligned_move stmt) and the explicit realignment scheme (generating
7205 aligned loads with a REALIGN_LOAD). There are two variants to the
7206 explicit realignment scheme: optimized, and unoptimized.
7207 We can optimize the realignment only if the step between consecutive
7208 vector loads is equal to the vector size. Since the vector memory
7209 accesses advance in steps of VS (Vector Size) in the vectorized loop, it
7210 is guaranteed that the misalignment amount remains the same throughout the
7211 execution of the vectorized loop. Therefore, we can create the
7212 "realignment token" (the permutation mask that is passed to REALIGN_LOAD)
7213 at the loop preheader.
7214
7215 However, in the case of outer-loop vectorization, when vectorizing a
7216 memory access in the inner-loop nested within the LOOP that is now being
7217 vectorized, while it is guaranteed that the misalignment of the
7218 vectorized memory access will remain the same in different outer-loop
7219 iterations, it is *not* guaranteed that is will remain the same throughout
7220 the execution of the inner-loop. This is because the inner-loop advances
7221 with the original scalar step (and not in steps of VS). If the inner-loop
7222 step happens to be a multiple of VS, then the misalignment remains fixed
7223 and we can use the optimized realignment scheme. For example:
7224
7225 for (i=0; i<N; i++)
7226 for (j=0; j<M; j++)
7227 s += a[i+j];
7228
7229 When vectorizing the i-loop in the above example, the step between
7230 consecutive vector loads is 1, and so the misalignment does not remain
7231 fixed across the execution of the inner-loop, and the realignment cannot
7232 be optimized (as illustrated in the following pseudo vectorized loop):
7233
7234 for (i=0; i<N; i+=4)
7235 for (j=0; j<M; j++){
7236 vs += vp[i+j]; // misalignment of &vp[i+j] is {0,1,2,3,0,1,2,3,...}
7237 // when j is {0,1,2,3,4,5,6,7,...} respectively.
7238 // (assuming that we start from an aligned address).
7239 }
7240
7241 We therefore have to use the unoptimized realignment scheme:
7242
7243 for (i=0; i<N; i+=4)
7244 for (j=k; j<M; j+=4)
7245 vs += vp[i+j]; // misalignment of &vp[i+j] is always k (assuming
7246 // that the misalignment of the initial address is
7247 // 0).
7248
7249 The loop can then be vectorized as follows:
7250
7251 for (k=0; k<4; k++){
7252 rt = get_realignment_token (&vp[k]);
7253 for (i=0; i<N; i+=4){
7254 v1 = vp[i+k];
7255 for (j=k; j<M; j+=4){
7256 v2 = vp[i+j+VS-1];
7257 va = REALIGN_LOAD <v1,v2,rt>;
7258 vs += va;
7259 v1 = v2;
7260 }
7261 }
7262 } */
7263
7264 if (DR_IS_READ (dr))
7265 {
7266 if (can_implement_p (vec_realign_load_optab, mode)
7267 && (!targetm.vectorize.builtin_mask_for_load
7268 || targetm.vectorize.builtin_mask_for_load ()))
7269 {
7270 /* If we are doing SLP then the accesses need not have the
7271 same alignment, instead it depends on the SLP group size. */
7272 if (loop_vinfo
7273 && STMT_SLP_TYPE (stmt_info)
7274 && STMT_VINFO_GROUPED_ACCESS (stmt_info)
7275 && !multiple_p (LOOP_VINFO_VECT_FACTOR (loop_vinfo)
7276 * (DR_GROUP_SIZE
7277 (DR_GROUP_FIRST_ELEMENT (stmt_info))),
7278 TYPE_VECTOR_SUBPARTS (vectype)))
7279 ;
7280 else if (!loop_vinfo
7281 || (nested_in_vect_loop
7282 && maybe_ne (TREE_INT_CST_LOW (DR_STEP (dr)),
7283 GET_MODE_SIZE (TYPE_MODE (vectype)))))
7284 return dr_explicit_realign;
7285 else
7286 return dr_explicit_realign_optimized;
7287 }
7288 }
7289
7290 bool is_packed = false;
7291 tree type = TREE_TYPE (DR_REF (dr));
7292 if (misalignment == DR_MISALIGNMENT_UNKNOWN)
7293 is_packed = not_size_aligned (DR_REF (dr));
7294 if (targetm.vectorize.support_vector_misalignment (mode, type, misalignment,
7295 is_packed))
7296 return dr_unaligned_supported;
7297
7298 /* Unsupported. */
7299 return dr_unaligned_unsupported;
7300 }