Debian Codegraph @

gcc/tree-vect-slp.cc

raw
1 /* SLP - Basic Block Vectorization
2 Copyright (C) 2007-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 #include "config.h"
23 #define INCLUDE_ALGORITHM
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 "tree-pass.h"
32 #include "ssa.h"
33 #include "optabs-tree.h"
34 #include "insn-config.h"
35 #include "recog.h" /* FIXME: for insn_data */
36 #include "fold-const.h"
37 #include "stor-layout.h"
38 #include "gimple-iterator.h"
39 #include "cfgloop.h"
40 #include "tree-vectorizer.h"
41 #include "langhooks.h"
42 #include "gimple-walk.h"
43 #include "dbgcnt.h"
44 #include "tree-vector-builder.h"
45 #include "vec-perm-indices.h"
46 #include "gimple-fold.h"
47 #include "internal-fn.h"
48 #include "dump-context.h"
49 #include "cfganal.h"
50 #include "tree-eh.h"
51 #include "tree-cfg.h"
52 #include "alloc-pool.h"
53 #include "sreal.h"
54 #include "predict.h"
55
56 static bool vect_transform_slp_perm_load_1 (vec_info *, slp_tree,
57 load_permutation_t &,
58 const vec<tree> &,
59 gimple_stmt_iterator *,
60 poly_uint64, bool, bool,
61 unsigned *,
62 unsigned * = nullptr,
63 bool = false);
64 static int vectorizable_slp_permutation_1 (vec_info *, gimple_stmt_iterator *,
65 slp_tree, lane_permutation_t &,
66 vec<slp_tree> &, bool);
67 static bool vectorizable_slp_permutation (vec_info *, gimple_stmt_iterator *,
68 slp_tree, stmt_vector_for_cost *);
69 static void vect_print_slp_tree (dump_flags_t, dump_location_t, slp_tree);
70 static bool vect_slp_can_convert_to_external (const vec<stmt_vec_info> &);
71
72 static object_allocator<_slp_tree> *slp_tree_pool;
73 static slp_tree slp_first_node;
74
75 void
76 vect_slp_init (void)
77 {
78 slp_tree_pool = new object_allocator<_slp_tree> ("SLP nodes");
79 }
80
81 void
82 vect_slp_fini (void)
83 {
84 while (slp_first_node)
85 delete slp_first_node;
86 delete slp_tree_pool;
87 slp_tree_pool = NULL;
88 }
89
90 void *
91 _slp_tree::operator new (size_t n)
92 {
93 gcc_assert (n == sizeof (_slp_tree));
94 return slp_tree_pool->allocate_raw ();
95 }
96
97 void
98 _slp_tree::operator delete (void *node, size_t n)
99 {
100 gcc_assert (n == sizeof (_slp_tree));
101 slp_tree_pool->remove_raw (node);
102 }
103
104
105 /* Initialize a SLP node. */
106
107 _slp_tree::_slp_tree ()
108 {
109 this->prev_node = NULL;
110 if (slp_first_node)
111 slp_first_node->prev_node = this;
112 this->next_node = slp_first_node;
113 slp_first_node = this;
114 SLP_TREE_SCALAR_STMTS (this) = vNULL;
115 SLP_TREE_SCALAR_OPS (this) = vNULL;
116 SLP_TREE_VEC_DEFS (this) = vNULL;
117 SLP_TREE_NUMBER_OF_VEC_STMTS (this) = 0;
118 SLP_TREE_CHILDREN (this) = vNULL;
119 SLP_TREE_LOAD_PERMUTATION (this) = vNULL;
120 SLP_TREE_LANE_PERMUTATION (this) = vNULL;
121 SLP_TREE_SIMD_CLONE_INFO (this) = vNULL;
122 SLP_TREE_DEF_TYPE (this) = vect_uninitialized_def;
123 SLP_TREE_CODE (this) = ERROR_MARK;
124 this->ldst_lanes = false;
125 SLP_TREE_VECTYPE (this) = NULL_TREE;
126 SLP_TREE_REPRESENTATIVE (this) = NULL;
127 SLP_TREE_MEMORY_ACCESS_TYPE (this) = VMAT_INVARIANT;
128 SLP_TREE_REF_COUNT (this) = 1;
129 this->failed = NULL;
130 this->max_nunits = 1;
131 this->lanes = 0;
132 }
133
134 /* Tear down a SLP node. */
135
136 _slp_tree::~_slp_tree ()
137 {
138 if (this->prev_node)
139 this->prev_node->next_node = this->next_node;
140 else
141 slp_first_node = this->next_node;
142 if (this->next_node)
143 this->next_node->prev_node = this->prev_node;
144 SLP_TREE_CHILDREN (this).release ();
145 SLP_TREE_SCALAR_STMTS (this).release ();
146 SLP_TREE_SCALAR_OPS (this).release ();
147 SLP_TREE_VEC_DEFS (this).release ();
148 SLP_TREE_LOAD_PERMUTATION (this).release ();
149 SLP_TREE_LANE_PERMUTATION (this).release ();
150 SLP_TREE_SIMD_CLONE_INFO (this).release ();
151 if (this->failed)
152 free (failed);
153 }
154
155 /* Push the single SSA definition in DEF to the vector of vector defs. */
156
157 void
158 _slp_tree::push_vec_def (gimple *def)
159 {
160 if (gphi *phi = dyn_cast <gphi *> (def))
161 vec_defs.quick_push (gimple_phi_result (phi));
162 else
163 {
164 def_operand_p defop = single_ssa_def_operand (def, SSA_OP_ALL_DEFS);
165 vec_defs.quick_push (get_def_from_ptr (defop));
166 }
167 }
168
169 /* Recursively free the memory allocated for the SLP tree rooted at NODE. */
170
171 void
172 vect_free_slp_tree (slp_tree node)
173 {
174 int i;
175 slp_tree child;
176
177 if (--SLP_TREE_REF_COUNT (node) != 0)
178 return;
179
180 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
181 if (child)
182 vect_free_slp_tree (child);
183
184 /* If the node defines any SLP only patterns then those patterns are no
185 longer valid and should be removed. */
186 stmt_vec_info rep_stmt_info = SLP_TREE_REPRESENTATIVE (node);
187 if (rep_stmt_info && STMT_VINFO_SLP_VECT_ONLY_PATTERN (rep_stmt_info))
188 {
189 stmt_vec_info stmt_info = vect_orig_stmt (rep_stmt_info);
190 STMT_VINFO_IN_PATTERN_P (stmt_info) = false;
191 STMT_SLP_TYPE (stmt_info) = STMT_SLP_TYPE (rep_stmt_info);
192 }
193
194 delete node;
195 }
196
197 /* Return a location suitable for dumpings related to the SLP instance. */
198
199 dump_user_location_t
200 _slp_instance::location () const
201 {
202 if (!root_stmts.is_empty ())
203 return root_stmts[0]->stmt;
204 else
205 return SLP_TREE_SCALAR_STMTS (root)[0]->stmt;
206 }
207
208
209 /* Free the memory allocated for the SLP instance. */
210
211 void
212 vect_free_slp_instance (slp_instance instance)
213 {
214 vect_free_slp_tree (SLP_INSTANCE_TREE (instance));
215 SLP_INSTANCE_LOADS (instance).release ();
216 SLP_INSTANCE_ROOT_STMTS (instance).release ();
217 SLP_INSTANCE_REMAIN_DEFS (instance).release ();
218 instance->subgraph_entries.release ();
219 instance->cost_vec.release ();
220 free (instance);
221 }
222
223
224 /* Create an SLP node for SCALAR_STMTS. */
225
226 slp_tree
227 vect_create_new_slp_node (unsigned nops, tree_code code)
228 {
229 slp_tree node = new _slp_tree;
230 SLP_TREE_SCALAR_STMTS (node) = vNULL;
231 SLP_TREE_CHILDREN (node).create (nops);
232 SLP_TREE_DEF_TYPE (node) = vect_internal_def;
233 SLP_TREE_CODE (node) = code;
234 return node;
235 }
236 /* Create an SLP node for SCALAR_STMTS. */
237
238 static slp_tree
239 vect_create_new_slp_node (slp_tree node,
240 vec<stmt_vec_info> scalar_stmts, unsigned nops)
241 {
242 SLP_TREE_SCALAR_STMTS (node) = scalar_stmts;
243 SLP_TREE_CHILDREN (node).create (nops);
244 SLP_TREE_DEF_TYPE (node) = vect_internal_def;
245 SLP_TREE_REPRESENTATIVE (node) = scalar_stmts[0];
246 SLP_TREE_LANES (node) = scalar_stmts.length ();
247 return node;
248 }
249
250 /* Create an SLP node for SCALAR_STMTS. */
251
252 static slp_tree
253 vect_create_new_slp_node (vec<stmt_vec_info> scalar_stmts, unsigned nops)
254 {
255 return vect_create_new_slp_node (new _slp_tree, scalar_stmts, nops);
256 }
257
258 /* Create an SLP node for OPS. */
259
260 static slp_tree
261 vect_create_new_slp_node (slp_tree node, vec<tree> ops)
262 {
263 SLP_TREE_SCALAR_OPS (node) = ops;
264 SLP_TREE_DEF_TYPE (node) = vect_external_def;
265 SLP_TREE_LANES (node) = ops.length ();
266 return node;
267 }
268
269 /* Create an SLP node for OPS. */
270
271 static slp_tree
272 vect_create_new_slp_node (vec<tree> ops)
273 {
274 return vect_create_new_slp_node (new _slp_tree, ops);
275 }
276
277
278 /* This structure is used in creation of an SLP tree. Each instance
279 corresponds to the same operand in a group of scalar stmts in an SLP
280 node. */
281 typedef struct _slp_oprnd_info
282 {
283 /* Def-stmts for the operands. */
284 vec<stmt_vec_info> def_stmts;
285 /* Operands. */
286 vec<tree> ops;
287 /* Information about the first statement, its vector def-type, type, the
288 operand itself in case it's constant, and an indication if it's a pattern
289 stmt and gather/scatter info. */
290 tree first_op_type;
291 enum vect_def_type first_dt;
292 bool any_pattern;
293 bool first_gs_p;
294 gather_scatter_info first_gs_info;
295 } *slp_oprnd_info;
296
297
298 /* Allocate operands info for NOPS operands, and GROUP_SIZE def-stmts for each
299 operand. */
300 static vec<slp_oprnd_info>
301 vect_create_oprnd_info (int nops, int group_size)
302 {
303 int i;
304 slp_oprnd_info oprnd_info;
305 vec<slp_oprnd_info> oprnds_info;
306
307 oprnds_info.create (nops);
308 for (i = 0; i < nops; i++)
309 {
310 oprnd_info = XNEW (struct _slp_oprnd_info);
311 oprnd_info->def_stmts.create (group_size);
312 oprnd_info->ops.create (group_size);
313 oprnd_info->first_dt = vect_uninitialized_def;
314 oprnd_info->first_op_type = NULL_TREE;
315 oprnd_info->any_pattern = false;
316 oprnd_info->first_gs_p = false;
317 oprnds_info.quick_push (oprnd_info);
318 }
319
320 return oprnds_info;
321 }
322
323
324 /* Free operands info. */
325
326 static void
327 vect_free_oprnd_info (vec<slp_oprnd_info> &oprnds_info)
328 {
329 int i;
330 slp_oprnd_info oprnd_info;
331
332 FOR_EACH_VEC_ELT (oprnds_info, i, oprnd_info)
333 {
334 oprnd_info->def_stmts.release ();
335 oprnd_info->ops.release ();
336 XDELETE (oprnd_info);
337 }
338
339 oprnds_info.release ();
340 }
341
342 /* Return the execution frequency of NODE (so that a higher value indicates
343 a "more important" node when optimizing for speed). */
344
345 static sreal
346 vect_slp_node_weight (slp_tree node)
347 {
348 stmt_vec_info stmt_info = vect_orig_stmt (SLP_TREE_REPRESENTATIVE (node));
349 basic_block bb = gimple_bb (stmt_info->stmt);
350 return bb->count.to_sreal_scale (ENTRY_BLOCK_PTR_FOR_FN (cfun)->count);
351 }
352
353 /* Return true if STMTS contains a pattern statement. */
354
355 static bool
356 vect_contains_pattern_stmt_p (vec<stmt_vec_info> stmts)
357 {
358 stmt_vec_info stmt_info;
359 unsigned int i;
360 FOR_EACH_VEC_ELT (stmts, i, stmt_info)
361 if (stmt_info && is_pattern_stmt_p (stmt_info))
362 return true;
363 return false;
364 }
365
366 /* Return true when all lanes in the external or constant NODE have
367 the same value. */
368
369 static bool
370 vect_slp_tree_uniform_p (slp_tree node)
371 {
372 gcc_assert (SLP_TREE_DEF_TYPE (node) == vect_constant_def
373 || SLP_TREE_DEF_TYPE (node) == vect_external_def);
374
375 /* Pre-exsting vectors. */
376 if (SLP_TREE_SCALAR_OPS (node).is_empty ())
377 return false;
378
379 unsigned i;
380 tree op, first = NULL_TREE;
381 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_OPS (node), i, op)
382 if (!first)
383 first = op;
384 else if (!operand_equal_p (first, op, 0))
385 return false;
386
387 return true;
388 }
389
390 /* Find the place of the data-ref in STMT_INFO in the interleaving chain
391 that starts from FIRST_STMT_INFO. Return -1 if the data-ref is not a part
392 of the chain. */
393
394 int
395 vect_get_place_in_interleaving_chain (stmt_vec_info stmt_info,
396 stmt_vec_info first_stmt_info)
397 {
398 stmt_vec_info next_stmt_info = first_stmt_info;
399 int result = 0;
400
401 if (first_stmt_info != DR_GROUP_FIRST_ELEMENT (stmt_info))
402 return -1;
403
404 do
405 {
406 if (next_stmt_info == stmt_info)
407 return result;
408 next_stmt_info = DR_GROUP_NEXT_ELEMENT (next_stmt_info);
409 if (next_stmt_info)
410 result += DR_GROUP_GAP (next_stmt_info);
411 }
412 while (next_stmt_info);
413
414 return -1;
415 }
416
417 /* Check whether it is possible to load COUNT elements of type ELT_TYPE
418 using the method implemented by duplicate_and_interleave. Return true
419 if so, returning the number of intermediate vectors in *NVECTORS_OUT
420 (if nonnull) and the type of each intermediate vector in *VECTOR_TYPE_OUT
421 (if nonnull). */
422
423 bool
424 can_duplicate_and_interleave_p (vec_info *vinfo, unsigned int count,
425 tree elt_type, unsigned int *nvectors_out,
426 tree *vector_type_out,
427 tree *permutes)
428 {
429 tree base_vector_type = get_vectype_for_scalar_type (vinfo, elt_type, count);
430 if (!base_vector_type || !VECTOR_MODE_P (TYPE_MODE (base_vector_type)))
431 return false;
432
433 machine_mode base_vector_mode = TYPE_MODE (base_vector_type);
434 poly_int64 elt_bytes = count * GET_MODE_UNIT_SIZE (base_vector_mode);
435 unsigned int nvectors = 1;
436 for (;;)
437 {
438 scalar_int_mode int_mode;
439 poly_int64 elt_bits = elt_bytes * BITS_PER_UNIT;
440 if (int_mode_for_size (elt_bits, 1).exists (&int_mode))
441 {
442 /* Get the natural vector type for this SLP group size. */
443 tree int_type = build_nonstandard_integer_type
444 (GET_MODE_BITSIZE (int_mode), 1);
445 tree vector_type
446 = get_vectype_for_scalar_type (vinfo, int_type, count);
447 poly_int64 half_nelts;
448 if (vector_type
449 && VECTOR_MODE_P (TYPE_MODE (vector_type))
450 && known_eq (GET_MODE_SIZE (TYPE_MODE (vector_type)),
451 GET_MODE_SIZE (base_vector_mode))
452 && multiple_p (GET_MODE_NUNITS (TYPE_MODE (vector_type)),
453 2, &half_nelts))
454 {
455 /* Try fusing consecutive sequences of COUNT / NVECTORS elements
456 together into elements of type INT_TYPE and using the result
457 to build NVECTORS vectors. */
458 poly_uint64 nelts = GET_MODE_NUNITS (TYPE_MODE (vector_type));
459 vec_perm_builder sel1 (nelts, 2, 3);
460 vec_perm_builder sel2 (nelts, 2, 3);
461
462 for (unsigned int i = 0; i < 3; ++i)
463 {
464 sel1.quick_push (i);
465 sel1.quick_push (i + nelts);
466 sel2.quick_push (half_nelts + i);
467 sel2.quick_push (half_nelts + i + nelts);
468 }
469 vec_perm_indices indices1 (sel1, 2, nelts);
470 vec_perm_indices indices2 (sel2, 2, nelts);
471 machine_mode vmode = TYPE_MODE (vector_type);
472 if (can_vec_perm_const_p (vmode, vmode, indices1)
473 && can_vec_perm_const_p (vmode, vmode, indices2))
474 {
475 if (nvectors_out)
476 *nvectors_out = nvectors;
477 if (vector_type_out)
478 *vector_type_out = vector_type;
479 if (permutes)
480 {
481 permutes[0] = vect_gen_perm_mask_checked (vector_type,
482 indices1);
483 permutes[1] = vect_gen_perm_mask_checked (vector_type,
484 indices2);
485 }
486 return true;
487 }
488 }
489 }
490 if (!multiple_p (elt_bytes, 2, &elt_bytes))
491 return false;
492 nvectors *= 2;
493 /* We need to be able to fuse COUNT / NVECTORS elements together. */
494 if (!multiple_p (count, nvectors))
495 return false;
496 }
497 }
498
499 /* Return true if DTA and DTB match. */
500
501 static bool
502 vect_def_types_match (enum vect_def_type dta, enum vect_def_type dtb)
503 {
504 return (dta == dtb
505 || ((dta == vect_external_def || dta == vect_constant_def)
506 && (dtb == vect_external_def || dtb == vect_constant_def)));
507 }
508
509 static const int cond_expr_maps[3][5] = {
510 { 4, -1, -2, 1, 2 },
511 { 4, -2, -1, 1, 2 },
512 { 4, -1, -2, 2, 1 }
513 };
514 static const int no_arg_map[] = { 0 };
515 static const int arg0_map[] = { 1, 0 };
516 static const int arg1_map[] = { 1, 1 };
517 static const int arg2_arg3_map[] = { 2, 2, 3 };
518 static const int arg1_arg3_map[] = { 2, 1, 3 };
519 static const int arg1_arg4_arg5_map[] = { 3, 1, 4, 5 };
520 static const int arg1_arg3_arg4_map[] = { 3, 1, 3, 4 };
521 static const int arg3_arg2_map[] = { 2, 3, 2 };
522 static const int op1_op0_map[] = { 2, 1, 0 };
523 static const int off_map[] = { 1, -3 };
524 static const int off_op0_map[] = { 2, -3, 0 };
525 static const int off_arg2_arg3_map[] = { 3, -3, 2, 3 };
526 static const int off_arg3_arg2_map[] = { 3, -3, 3, 2 };
527 static const int mask_call_maps[6][7] = {
528 { 1, 1, },
529 { 2, 1, 2, },
530 { 3, 1, 2, 3, },
531 { 4, 1, 2, 3, 4, },
532 { 5, 1, 2, 3, 4, 5, },
533 { 6, 1, 2, 3, 4, 5, 6 },
534 };
535
536 /* For most SLP statements, there is a one-to-one mapping between
537 gimple arguments and child nodes. If that is not true for STMT,
538 return an array that contains:
539
540 - the number of child nodes, followed by
541 - for each child node, the index of the argument associated with that node.
542 The special index -1 is the first operand of an embedded comparison and
543 the special index -2 is the second operand of an embedded comparison.
544 The special indes -3 is the offset of a gather as analyzed by
545 vect_check_gather_scatter.
546
547 SWAP is as for vect_get_and_check_slp_defs. */
548
549 static const int *
550 vect_get_operand_map (const gimple *stmt, bool gather_scatter_p = false,
551 unsigned char swap = 0)
552 {
553 if (auto assign = dyn_cast<const gassign *> (stmt))
554 {
555 if (gimple_assign_rhs_code (assign) == COND_EXPR
556 && COMPARISON_CLASS_P (gimple_assign_rhs1 (assign)))
557 gcc_unreachable ();
558 if (TREE_CODE_CLASS (gimple_assign_rhs_code (assign)) == tcc_comparison
559 && swap)
560 return op1_op0_map;
561 if (gather_scatter_p)
562 return (TREE_CODE (gimple_assign_lhs (assign)) != SSA_NAME
563 ? off_op0_map : off_map);
564 }
565 gcc_assert (!swap);
566 if (auto call = dyn_cast<const gcall *> (stmt))
567 {
568 if (gimple_call_internal_p (call))
569 switch (gimple_call_internal_fn (call))
570 {
571 case IFN_MASK_LOAD:
572 return gather_scatter_p ? off_arg2_arg3_map : arg2_arg3_map;
573
574 case IFN_GATHER_LOAD:
575 return arg1_map;
576
577 case IFN_MASK_GATHER_LOAD:
578 case IFN_MASK_LEN_GATHER_LOAD:
579 return arg1_arg4_arg5_map;
580
581 case IFN_SCATTER_STORE:
582 return arg1_arg3_map;
583
584 case IFN_MASK_SCATTER_STORE:
585 case IFN_MASK_LEN_SCATTER_STORE:
586 return arg1_arg3_arg4_map;
587
588 case IFN_MASK_STORE:
589 return gather_scatter_p ? off_arg3_arg2_map : arg3_arg2_map;
590
591 case IFN_MASK_CALL:
592 {
593 unsigned nargs = gimple_call_num_args (call);
594 if (nargs >= 2 && nargs <= 7)
595 return mask_call_maps[nargs-2];
596 else
597 return nullptr;
598 }
599
600 case IFN_CLZ:
601 case IFN_CTZ:
602 return arg0_map;
603
604 case IFN_GOMP_SIMD_LANE:
605 return no_arg_map;
606
607 default:
608 break;
609 }
610 }
611 return nullptr;
612 }
613
614 /* Return the SLP node child index for operand OP of STMT. */
615
616 int
617 vect_slp_child_index_for_operand (const gimple *stmt, int op,
618 bool gather_scatter_p)
619 {
620 const int *opmap = vect_get_operand_map (stmt, gather_scatter_p);
621 if (!opmap)
622 return op;
623 for (int i = 1; i < 1 + opmap[0]; ++i)
624 if (opmap[i] == op)
625 return i - 1;
626 gcc_unreachable ();
627 }
628
629 /* Get the defs for the rhs of STMT (collect them in OPRNDS_INFO), check that
630 they are of a valid type and that they match the defs of the first stmt of
631 the SLP group (stored in OPRNDS_INFO). This function tries to match stmts
632 by swapping operands of STMTS[STMT_NUM] when possible. Non-zero SWAP
633 indicates swap is required for cond_expr stmts. Specifically, SWAP
634 is 1 if STMT is cond and operands of comparison need to be swapped;
635 SWAP is 2 if STMT is cond and code of comparison needs to be inverted.
636
637 If there was a fatal error return -1; if the error could be corrected by
638 swapping operands of father node of this one, return 1; if everything is
639 ok return 0. */
640 static int
641 vect_get_and_check_slp_defs (vec_info *vinfo, unsigned char swap,
642 bool *skip_args,
643 vec<stmt_vec_info> stmts, unsigned stmt_num,
644 vec<slp_oprnd_info> *oprnds_info)
645 {
646 stmt_vec_info stmt_info = stmts[stmt_num];
647 tree oprnd;
648 unsigned int i, number_of_oprnds;
649 enum vect_def_type dt = vect_uninitialized_def;
650 slp_oprnd_info oprnd_info;
651 gather_scatter_info gs_info;
652 unsigned int gs_op = -1u;
653 unsigned int commutative_op = -1U;
654 bool first = stmt_num == 0;
655
656 if (!stmt_info)
657 {
658 for (auto oi : *oprnds_info)
659 {
660 oi->def_stmts.quick_push (NULL);
661 oi->ops.quick_push (NULL_TREE);
662 }
663 return 0;
664 }
665
666 if (!is_a<gcall *> (stmt_info->stmt)
667 && !is_a<gassign *> (stmt_info->stmt)
668 && !is_a<gphi *> (stmt_info->stmt))
669 return -1;
670
671 number_of_oprnds = gimple_num_args (stmt_info->stmt);
672 const int *map
673 = vect_get_operand_map (stmt_info->stmt,
674 STMT_VINFO_GATHER_SCATTER_P (stmt_info), swap);
675 if (map)
676 number_of_oprnds = *map++;
677 if (gcall *stmt = dyn_cast <gcall *> (stmt_info->stmt))
678 {
679 if (gimple_call_internal_p (stmt))
680 {
681 internal_fn ifn = gimple_call_internal_fn (stmt);
682 commutative_op = first_commutative_argument (ifn);
683 }
684 }
685 else if (gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt))
686 {
687 if (commutative_tree_code (gimple_assign_rhs_code (stmt)))
688 commutative_op = 0;
689 }
690
691 bool swapped = (swap != 0);
692 bool backedge = false;
693 enum vect_def_type *dts = XALLOCAVEC (enum vect_def_type, number_of_oprnds);
694 for (i = 0; i < number_of_oprnds; i++)
695 {
696 oprnd_info = (*oprnds_info)[i];
697 int opno = map ? map[i] : int (i);
698 if (opno == -3)
699 {
700 gcc_assert (STMT_VINFO_GATHER_SCATTER_P (stmt_info));
701 if (!is_a <loop_vec_info> (vinfo)
702 || !vect_check_gather_scatter (stmt_info,
703 as_a <loop_vec_info> (vinfo),
704 first ? &oprnd_info->first_gs_info
705 : &gs_info))
706 return -1;
707
708 if (first)
709 {
710 oprnd_info->first_gs_p = true;
711 oprnd = oprnd_info->first_gs_info.offset;
712 }
713 else
714 {
715 gs_op = i;
716 oprnd = gs_info.offset;
717 }
718 }
719 else if (opno < 0)
720 oprnd = TREE_OPERAND (gimple_arg (stmt_info->stmt, 0), -1 - opno);
721 else
722 {
723 oprnd = gimple_arg (stmt_info->stmt, opno);
724 if (gphi *stmt = dyn_cast <gphi *> (stmt_info->stmt))
725 {
726 edge e = gimple_phi_arg_edge (stmt, opno);
727 backedge = (is_a <bb_vec_info> (vinfo)
728 ? e->flags & EDGE_DFS_BACK
729 : dominated_by_p (CDI_DOMINATORS, e->src,
730 gimple_bb (stmt_info->stmt)));
731 }
732 }
733 if (TREE_CODE (oprnd) == VIEW_CONVERT_EXPR)
734 oprnd = TREE_OPERAND (oprnd, 0);
735
736 stmt_vec_info def_stmt_info;
737 if (!vect_is_simple_use (oprnd, vinfo, &dts[i], &def_stmt_info))
738 {
739 if (dump_enabled_p ())
740 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
741 "Build SLP failed: can't analyze def for %T\n",
742 oprnd);
743
744 return -1;
745 }
746
747 if (skip_args[i])
748 {
749 oprnd_info->def_stmts.quick_push (NULL);
750 oprnd_info->ops.quick_push (NULL_TREE);
751 oprnd_info->first_dt = vect_uninitialized_def;
752 continue;
753 }
754
755 oprnd_info->def_stmts.quick_push (def_stmt_info);
756 oprnd_info->ops.quick_push (oprnd);
757
758 if (def_stmt_info
759 && is_pattern_stmt_p (def_stmt_info))
760 {
761 if (STMT_VINFO_RELATED_STMT (vect_orig_stmt (def_stmt_info))
762 != def_stmt_info)
763 oprnd_info->any_pattern = true;
764 else
765 /* If we promote this to external use the original stmt def. */
766 oprnd_info->ops.last ()
767 = gimple_get_lhs (vect_orig_stmt (def_stmt_info)->stmt);
768 }
769
770 /* If there's a extern def on a backedge make sure we can
771 code-generate at the region start.
772 ??? This is another case that could be fixed by adjusting
773 how we split the function but at the moment we'd have conflicting
774 goals there. */
775 if (backedge
776 && dts[i] == vect_external_def
777 && is_a <bb_vec_info> (vinfo)
778 && TREE_CODE (oprnd) == SSA_NAME
779 && !SSA_NAME_IS_DEFAULT_DEF (oprnd)
780 && !dominated_by_p (CDI_DOMINATORS, vinfo->bbs[0],
781 gimple_bb (SSA_NAME_DEF_STMT (oprnd))))
782 {
783 if (dump_enabled_p ())
784 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
785 "Build SLP failed: extern def %T only defined "
786 "on backedge\n", oprnd);
787 return -1;
788 }
789
790 if (first)
791 {
792 tree type = TREE_TYPE (oprnd);
793 dt = dts[i];
794
795 /* For the swapping logic below force vect_reduction_def
796 for the reduction op in a SLP reduction group. */
797 if (!STMT_VINFO_DATA_REF (stmt_info)
798 && REDUC_GROUP_FIRST_ELEMENT (stmt_info)
799 && (int)i == STMT_VINFO_REDUC_IDX (stmt_info)
800 && def_stmt_info)
801 dts[i] = dt = vect_reduction_def;
802
803 /* Check the types of the definition. */
804 switch (dt)
805 {
806 case vect_external_def:
807 case vect_constant_def:
808 case vect_internal_def:
809 case vect_reduction_def:
810 case vect_double_reduction_def:
811 case vect_induction_def:
812 case vect_nested_cycle:
813 case vect_first_order_recurrence:
814 break;
815
816 default:
817 /* FORNOW: Not supported. */
818 if (dump_enabled_p ())
819 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
820 "Build SLP failed: illegal type of def %T\n",
821 oprnd);
822 return -1;
823 }
824
825 oprnd_info->first_dt = dt;
826 oprnd_info->first_op_type = type;
827 }
828 }
829 if (first)
830 return 0;
831
832 /* Now match the operand definition types to that of the first stmt. */
833 for (i = 0; i < number_of_oprnds;)
834 {
835 if (skip_args[i])
836 {
837 ++i;
838 continue;
839 }
840
841 oprnd_info = (*oprnds_info)[i];
842 dt = dts[i];
843 stmt_vec_info def_stmt_info = oprnd_info->def_stmts[stmt_num];
844 oprnd = oprnd_info->ops[stmt_num];
845 tree type = TREE_TYPE (oprnd);
846
847 if (!types_compatible_p (oprnd_info->first_op_type, type))
848 {
849 if (dump_enabled_p ())
850 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
851 "Build SLP failed: different operand types\n");
852 return 1;
853 }
854
855 if ((gs_op == i) != oprnd_info->first_gs_p)
856 {
857 if (dump_enabled_p ())
858 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
859 "Build SLP failed: mixed gather and non-gather\n");
860 return 1;
861 }
862 else if (gs_op == i)
863 {
864 if (!operand_equal_p (oprnd_info->first_gs_info.base,
865 gs_info.base))
866 {
867 if (dump_enabled_p ())
868 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
869 "Build SLP failed: different gather base\n");
870 return 1;
871 }
872 if (oprnd_info->first_gs_info.scale != gs_info.scale)
873 {
874 if (dump_enabled_p ())
875 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
876 "Build SLP failed: different gather scale\n");
877 return 1;
878 }
879 }
880
881 /* Not first stmt of the group, check that the def-stmt/s match
882 the def-stmt/s of the first stmt. Allow different definition
883 types for reduction chains: the first stmt must be a
884 vect_reduction_def (a phi node), and the rest
885 end in the reduction chain. */
886 if ((!vect_def_types_match (oprnd_info->first_dt, dt)
887 && !(oprnd_info->first_dt == vect_reduction_def
888 && !STMT_VINFO_DATA_REF (stmt_info)
889 && REDUC_GROUP_FIRST_ELEMENT (stmt_info)
890 && def_stmt_info
891 && !STMT_VINFO_DATA_REF (def_stmt_info)
892 && (REDUC_GROUP_FIRST_ELEMENT (def_stmt_info)
893 == REDUC_GROUP_FIRST_ELEMENT (stmt_info))))
894 || (!STMT_VINFO_DATA_REF (stmt_info)
895 && REDUC_GROUP_FIRST_ELEMENT (stmt_info)
896 && ((!def_stmt_info
897 || STMT_VINFO_DATA_REF (def_stmt_info)
898 || (REDUC_GROUP_FIRST_ELEMENT (def_stmt_info)
899 != REDUC_GROUP_FIRST_ELEMENT (stmt_info)))
900 != (oprnd_info->first_dt != vect_reduction_def))))
901 {
902 /* Try swapping operands if we got a mismatch. For BB
903 vectorization only in case it will clearly improve things. */
904 if (i == commutative_op && !swapped
905 && (!is_a <bb_vec_info> (vinfo)
906 || (!vect_def_types_match ((*oprnds_info)[i+1]->first_dt,
907 dts[i+1])
908 && (vect_def_types_match (oprnd_info->first_dt, dts[i+1])
909 || vect_def_types_match
910 ((*oprnds_info)[i+1]->first_dt, dts[i])))))
911 {
912 if (dump_enabled_p ())
913 dump_printf_loc (MSG_NOTE, vect_location,
914 "trying swapped operands\n");
915 std::swap (dts[i], dts[i+1]);
916 std::swap ((*oprnds_info)[i]->def_stmts[stmt_num],
917 (*oprnds_info)[i+1]->def_stmts[stmt_num]);
918 std::swap ((*oprnds_info)[i]->ops[stmt_num],
919 (*oprnds_info)[i+1]->ops[stmt_num]);
920 /* After swapping some operands we lost track whether an
921 operand has any pattern defs so be conservative here. */
922 if ((*oprnds_info)[i]->any_pattern
923 || (*oprnds_info)[i+1]->any_pattern)
924 (*oprnds_info)[i]->any_pattern
925 = (*oprnds_info)[i+1]->any_pattern = true;
926 swapped = true;
927 continue;
928 }
929
930 if (is_a <bb_vec_info> (vinfo)
931 && !oprnd_info->any_pattern
932 && number_of_oprnds > 1)
933 {
934 /* Now for commutative ops we should see whether we can
935 make the other operand matching. */
936 if (dump_enabled_p ())
937 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
938 "treating operand as external\n");
939 oprnd_info->first_dt = dt = vect_external_def;
940 }
941 else
942 {
943 if (dump_enabled_p ())
944 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
945 "Build SLP failed: different types\n");
946 return 1;
947 }
948 }
949
950 /* Make sure to demote the overall operand to external. */
951 if (dt == vect_external_def)
952 oprnd_info->first_dt = vect_external_def;
953 /* For a SLP reduction chain we want to duplicate the reduction to
954 each of the chain members. That gets us a sane SLP graph (still
955 the stmts are not 100% correct wrt the initial values). */
956 else if ((dt == vect_internal_def
957 || dt == vect_reduction_def)
958 && oprnd_info->first_dt == vect_reduction_def
959 && !STMT_VINFO_DATA_REF (stmt_info)
960 && REDUC_GROUP_FIRST_ELEMENT (stmt_info)
961 && !STMT_VINFO_DATA_REF (def_stmt_info)
962 && (REDUC_GROUP_FIRST_ELEMENT (def_stmt_info)
963 == REDUC_GROUP_FIRST_ELEMENT (stmt_info)))
964 {
965 oprnd_info->def_stmts[stmt_num] = oprnd_info->def_stmts[0];
966 oprnd_info->ops[stmt_num] = oprnd_info->ops[0];
967 }
968
969 ++i;
970 }
971
972 /* Swap operands. */
973 if (swapped)
974 {
975 if (dump_enabled_p ())
976 dump_printf_loc (MSG_NOTE, vect_location,
977 "swapped operands to match def types in %G",
978 stmt_info->stmt);
979 }
980
981 return 0;
982 }
983
984 /* Return true if call statements CALL1 and CALL2 are similar enough
985 to be combined into the same SLP group. */
986
987 bool
988 compatible_calls_p (gcall *call1, gcall *call2)
989 {
990 unsigned int nargs = gimple_call_num_args (call1);
991 if (nargs != gimple_call_num_args (call2))
992 return false;
993
994 if (gimple_call_combined_fn (call1) != gimple_call_combined_fn (call2))
995 return false;
996
997 if (gimple_call_internal_p (call1))
998 {
999 if (!types_compatible_p (TREE_TYPE (gimple_call_lhs (call1)),
1000 TREE_TYPE (gimple_call_lhs (call2))))
1001 return false;
1002 for (unsigned int i = 0; i < nargs; ++i)
1003 if (!types_compatible_p (TREE_TYPE (gimple_call_arg (call1, i)),
1004 TREE_TYPE (gimple_call_arg (call2, i))))
1005 return false;
1006 }
1007 else
1008 {
1009 if (!operand_equal_p (gimple_call_fn (call1),
1010 gimple_call_fn (call2), 0))
1011 return false;
1012
1013 if (gimple_call_fntype (call1) != gimple_call_fntype (call2))
1014 return false;
1015 }
1016
1017 /* Check that any unvectorized arguments are equal. */
1018 if (const int *map = vect_get_operand_map (call1))
1019 {
1020 unsigned int nkept = *map++;
1021 unsigned int mapi = 0;
1022 for (unsigned int i = 0; i < nargs; ++i)
1023 if (mapi < nkept && map[mapi] == int (i))
1024 mapi += 1;
1025 else if (!operand_equal_p (gimple_call_arg (call1, i),
1026 gimple_call_arg (call2, i)))
1027 return false;
1028 }
1029
1030 return true;
1031 }
1032
1033 /* A subroutine of vect_build_slp_tree for checking VECTYPE, which is the
1034 caller's attempt to find the vector type in STMT_INFO with the narrowest
1035 element type. Return true if VECTYPE is nonnull and if it is valid
1036 for STMT_INFO. When returning true, update MAX_NUNITS to reflect the
1037 number of units in VECTYPE. GROUP_SIZE and MAX_NUNITS are as for
1038 vect_build_slp_tree. */
1039
1040 static bool
1041 vect_record_max_nunits (vec_info *vinfo, stmt_vec_info stmt_info,
1042 unsigned int group_size,
1043 tree vectype, poly_uint64 *max_nunits)
1044 {
1045 if (!vectype)
1046 {
1047 if (dump_enabled_p ())
1048 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1049 "Build SLP failed: unsupported data-type in %G\n",
1050 stmt_info->stmt);
1051 /* Fatal mismatch. */
1052 return false;
1053 }
1054
1055 /* If populating the vector type requires unrolling then fail
1056 before adjusting *max_nunits for basic-block vectorization. */
1057 if (is_a <bb_vec_info> (vinfo)
1058 && !multiple_p (group_size, TYPE_VECTOR_SUBPARTS (vectype)))
1059 {
1060 if (dump_enabled_p ())
1061 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1062 "Build SLP failed: unrolling required "
1063 "in basic block SLP\n");
1064 /* Fatal mismatch. */
1065 return false;
1066 }
1067
1068 /* In case of multiple types we need to detect the smallest type. */
1069 vect_update_max_nunits (max_nunits, vectype);
1070 return true;
1071 }
1072
1073 /* Verify if the scalar stmts STMTS are isomorphic, require data
1074 permutation or are of unsupported types of operation. Return
1075 true if they are, otherwise return false and indicate in *MATCHES
1076 which stmts are not isomorphic to the first one. If MATCHES[0]
1077 is false then this indicates the comparison could not be
1078 carried out or the stmts will never be vectorized by SLP.
1079
1080 Note COND_EXPR is possibly isomorphic to another one after swapping its
1081 operands. Set SWAP[i] to 1 if stmt I is COND_EXPR and isomorphic to
1082 the first stmt by swapping the two operands of comparison; set SWAP[i]
1083 to 2 if stmt I is isormorphic to the first stmt by inverting the code
1084 of comparison. Take A1 >= B1 ? X1 : Y1 as an exmple, it can be swapped
1085 to (B1 <= A1 ? X1 : Y1); or be inverted to (A1 < B1) ? Y1 : X1. */
1086
1087 static bool
1088 vect_build_slp_tree_1 (vec_info *vinfo, unsigned char *swap,
1089 vec<stmt_vec_info> stmts, unsigned int group_size,
1090 poly_uint64 *max_nunits, bool *matches,
1091 bool *two_operators, tree *node_vectype)
1092 {
1093 unsigned int i;
1094 stmt_vec_info first_stmt_info = stmts[0];
1095 code_helper first_stmt_code = ERROR_MARK;
1096 code_helper alt_stmt_code = ERROR_MARK;
1097 code_helper first_cond_code = ERROR_MARK;
1098 bool need_same_oprnds = false;
1099 tree first_lhs = NULL_TREE;
1100 tree first_op1 = NULL_TREE;
1101 stmt_vec_info first_load = NULL, prev_first_load = NULL;
1102 bool first_stmt_ldst_p = false, first_stmt_ldst_masklen_p = false;
1103 bool first_stmt_phi_p = false;
1104 int first_reduc_idx = -1;
1105 bool maybe_soft_fail = false;
1106 tree soft_fail_nunits_vectype = NULL_TREE;
1107
1108 tree vectype, nunits_vectype;
1109 if (!vect_get_vector_types_for_stmt (vinfo, first_stmt_info, &vectype,
1110 &nunits_vectype, group_size))
1111 {
1112 /* Fatal mismatch. */
1113 matches[0] = false;
1114 return false;
1115 }
1116 /* Record nunits required but continue analysis, producing matches[]
1117 as if nunits was not an issue. This allows splitting of groups
1118 to happen. */
1119 if (nunits_vectype
1120 && !vect_record_max_nunits (vinfo, first_stmt_info, group_size,
1121 nunits_vectype, max_nunits))
1122 {
1123 gcc_assert (is_a <bb_vec_info> (vinfo));
1124 maybe_soft_fail = true;
1125 soft_fail_nunits_vectype = nunits_vectype;
1126 }
1127
1128 gcc_assert (vectype);
1129 *node_vectype = vectype;
1130
1131 /* For every stmt in NODE find its def stmt/s. */
1132 stmt_vec_info stmt_info;
1133 FOR_EACH_VEC_ELT (stmts, i, stmt_info)
1134 {
1135 bool ldst_p = false;
1136 bool ldst_masklen_p = false;
1137 bool phi_p = false;
1138 code_helper rhs_code = ERROR_MARK;
1139
1140 swap[i] = 0;
1141 matches[i] = false;
1142 if (!stmt_info)
1143 {
1144 matches[i] = true;
1145 continue;
1146 }
1147
1148 gimple *stmt = stmt_info->stmt;
1149 if (dump_enabled_p ())
1150 dump_printf_loc (MSG_NOTE, vect_location, "Build SLP for %G", stmt);
1151
1152 /* Fail to vectorize statements marked as unvectorizable, throw
1153 or are volatile. */
1154 if (!STMT_VINFO_VECTORIZABLE (stmt_info)
1155 || stmt_can_throw_internal (cfun, stmt)
1156 || gimple_has_volatile_ops (stmt))
1157 {
1158 if (dump_enabled_p ())
1159 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1160 "Build SLP failed: unvectorizable statement %G",
1161 stmt);
1162 /* ??? For BB vectorization we want to commutate operands in a way
1163 to shuffle all unvectorizable defs into one operand and have
1164 the other still vectorized. The following doesn't reliably
1165 work for this though but it's the easiest we can do here. */
1166 if (is_a <bb_vec_info> (vinfo) && i != 0)
1167 continue;
1168 /* Fatal mismatch. */
1169 matches[0] = false;
1170 return false;
1171 }
1172
1173 gcall *call_stmt = dyn_cast <gcall *> (stmt);
1174 tree lhs = gimple_get_lhs (stmt);
1175 if (lhs == NULL_TREE
1176 && (!call_stmt
1177 || !gimple_call_internal_p (stmt)
1178 || !internal_store_fn_p (gimple_call_internal_fn (stmt))))
1179 {
1180 if (dump_enabled_p ())
1181 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1182 "Build SLP failed: not GIMPLE_ASSIGN nor "
1183 "GIMPLE_CALL %G", stmt);
1184 if (is_a <bb_vec_info> (vinfo) && i != 0)
1185 continue;
1186 /* Fatal mismatch. */
1187 matches[0] = false;
1188 return false;
1189 }
1190
1191 if (call_stmt)
1192 {
1193 combined_fn cfn = gimple_call_combined_fn (call_stmt);
1194 if (cfn != CFN_LAST && cfn != CFN_MASK_CALL)
1195 rhs_code = cfn;
1196 else
1197 rhs_code = CALL_EXPR;
1198
1199 if (cfn == CFN_GATHER_LOAD
1200 || cfn == CFN_SCATTER_STORE)
1201 ldst_p = true;
1202 else if (cfn == CFN_MASK_LOAD
1203 || cfn == CFN_MASK_GATHER_LOAD
1204 || cfn == CFN_MASK_LEN_GATHER_LOAD
1205 || cfn == CFN_MASK_SCATTER_STORE
1206 || cfn == CFN_MASK_LEN_SCATTER_STORE)
1207 {
1208 ldst_p = true;
1209 ldst_masklen_p = true;
1210 }
1211 else if (cfn == CFN_MASK_STORE)
1212 {
1213 ldst_p = true;
1214 ldst_masklen_p = true;
1215 rhs_code = CFN_MASK_STORE;
1216 }
1217 else if (cfn == CFN_GOMP_SIMD_LANE)
1218 ;
1219 else if ((cfn != CFN_LAST
1220 && cfn != CFN_MASK_CALL
1221 && internal_fn_p (cfn)
1222 && !vectorizable_internal_fn_p (as_internal_fn (cfn)))
1223 || gimple_call_tail_p (call_stmt)
1224 || gimple_call_noreturn_p (call_stmt)
1225 || gimple_call_chain (call_stmt))
1226 {
1227 if (dump_enabled_p ())
1228 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1229 "Build SLP failed: unsupported call type %G",
1230 (gimple *) call_stmt);
1231 if (is_a <bb_vec_info> (vinfo) && i != 0)
1232 continue;
1233 /* Fatal mismatch. */
1234 matches[0] = false;
1235 return false;
1236 }
1237 }
1238 else if (gimple_code (stmt) == GIMPLE_PHI)
1239 {
1240 rhs_code = ERROR_MARK;
1241 phi_p = true;
1242 }
1243 else
1244 {
1245 rhs_code = gimple_assign_rhs_code (stmt);
1246 ldst_p = STMT_VINFO_DATA_REF (stmt_info) != nullptr;
1247 }
1248
1249 /* Check the operation. */
1250 if (i == 0)
1251 {
1252 first_lhs = lhs;
1253 first_stmt_code = rhs_code;
1254 first_stmt_ldst_p = ldst_p;
1255 first_stmt_ldst_masklen_p = ldst_masklen_p;
1256 first_stmt_phi_p = phi_p;
1257 first_reduc_idx = STMT_VINFO_REDUC_IDX (stmt_info);
1258
1259 /* Shift arguments should be equal in all the packed stmts for a
1260 vector shift with scalar shift operand. */
1261 if (rhs_code == LSHIFT_EXPR || rhs_code == RSHIFT_EXPR
1262 || rhs_code == LROTATE_EXPR
1263 || rhs_code == RROTATE_EXPR)
1264 {
1265 /* First see if we have a vector/vector shift. */
1266 if (!directly_supported_p (rhs_code, vectype, optab_vector))
1267 {
1268 /* No vector/vector shift, try for a vector/scalar shift. */
1269 if (!directly_supported_p (rhs_code, vectype, optab_scalar))
1270 {
1271 if (dump_enabled_p ())
1272 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1273 "Build SLP failed: "
1274 "op not supported by target.\n");
1275 if (is_a <bb_vec_info> (vinfo) && i != 0)
1276 continue;
1277 /* Fatal mismatch. */
1278 matches[0] = false;
1279 return false;
1280 }
1281 need_same_oprnds = true;
1282 first_op1 = gimple_assign_rhs2 (stmt);
1283 }
1284 }
1285 else if (rhs_code == WIDEN_LSHIFT_EXPR)
1286 {
1287 need_same_oprnds = true;
1288 first_op1 = gimple_assign_rhs2 (stmt);
1289 }
1290 else if (!ldst_p
1291 && rhs_code == BIT_FIELD_REF)
1292 {
1293 tree vec = TREE_OPERAND (gimple_assign_rhs1 (stmt), 0);
1294 if (!is_a <bb_vec_info> (vinfo)
1295 || TREE_CODE (vec) != SSA_NAME
1296 /* When the element types are not compatible we pun the
1297 source to the target vectype which requires equal size. */
1298 || ((!VECTOR_TYPE_P (TREE_TYPE (vec))
1299 || !types_compatible_p (TREE_TYPE (vectype),
1300 TREE_TYPE (TREE_TYPE (vec))))
1301 && !operand_equal_p (TYPE_SIZE (vectype),
1302 TYPE_SIZE (TREE_TYPE (vec)))))
1303 {
1304 if (dump_enabled_p ())
1305 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1306 "Build SLP failed: "
1307 "BIT_FIELD_REF not supported\n");
1308 /* Fatal mismatch. */
1309 matches[0] = false;
1310 return false;
1311 }
1312 }
1313 else if (rhs_code == CFN_DIV_POW2)
1314 {
1315 need_same_oprnds = true;
1316 first_op1 = gimple_call_arg (call_stmt, 1);
1317 }
1318 else if (rhs_code == CFN_GOMP_SIMD_LANE)
1319 {
1320 need_same_oprnds = true;
1321 first_op1 = gimple_call_arg (call_stmt, 1);
1322 }
1323 }
1324 else
1325 {
1326 if (first_reduc_idx != STMT_VINFO_REDUC_IDX (stmt_info)
1327 /* For SLP reduction groups the index isn't necessarily
1328 uniform but only that of the first stmt matters. */
1329 && !(first_reduc_idx != -1
1330 && STMT_VINFO_REDUC_IDX (stmt_info) != -1
1331 && REDUC_GROUP_FIRST_ELEMENT (stmt_info)))
1332 {
1333 if (dump_enabled_p ())
1334 {
1335 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1336 "Build SLP failed: different reduc_idx "
1337 "%d instead of %d in %G",
1338 STMT_VINFO_REDUC_IDX (stmt_info),
1339 first_reduc_idx, stmt);
1340 }
1341 /* Mismatch. */
1342 continue;
1343 }
1344 if (!ldst_p
1345 && first_stmt_code != rhs_code
1346 && alt_stmt_code == ERROR_MARK)
1347 alt_stmt_code = rhs_code;
1348 if ((!ldst_p
1349 && first_stmt_code != rhs_code
1350 && (first_stmt_code != IMAGPART_EXPR
1351 || rhs_code != REALPART_EXPR)
1352 && (first_stmt_code != REALPART_EXPR
1353 || rhs_code != IMAGPART_EXPR)
1354 /* Handle mismatches in plus/minus by computing both
1355 and merging the results. */
1356 && !((first_stmt_code == PLUS_EXPR
1357 || first_stmt_code == MINUS_EXPR)
1358 && (alt_stmt_code == PLUS_EXPR
1359 || alt_stmt_code == MINUS_EXPR)
1360 && rhs_code == alt_stmt_code)
1361 && !(first_stmt_code.is_tree_code ()
1362 && rhs_code.is_tree_code ()
1363 && (TREE_CODE_CLASS (tree_code (first_stmt_code))
1364 == tcc_comparison)
1365 && (swap_tree_comparison (tree_code (first_stmt_code))
1366 == tree_code (rhs_code))
1367 && (first_reduc_idx == -1
1368 || REDUC_GROUP_FIRST_ELEMENT (stmt_info))))
1369 || (ldst_p
1370 && (STMT_VINFO_GROUPED_ACCESS (stmt_info)
1371 != STMT_VINFO_GROUPED_ACCESS (first_stmt_info)))
1372 || (ldst_p
1373 && (STMT_VINFO_GATHER_SCATTER_P (stmt_info)
1374 != STMT_VINFO_GATHER_SCATTER_P (first_stmt_info)))
1375 || first_stmt_ldst_p != ldst_p
1376 || (ldst_p && first_stmt_ldst_masklen_p != ldst_masklen_p)
1377 || first_stmt_phi_p != phi_p)
1378 {
1379 if (dump_enabled_p ())
1380 {
1381 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1382 "Build SLP failed: different operation "
1383 "in stmt %G", stmt);
1384 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1385 "original stmt %G", first_stmt_info->stmt);
1386 }
1387 /* Mismatch. */
1388 continue;
1389 }
1390
1391 if (!ldst_p
1392 && first_stmt_code == BIT_FIELD_REF
1393 && (TREE_OPERAND (gimple_assign_rhs1 (first_stmt_info->stmt), 0)
1394 != TREE_OPERAND (gimple_assign_rhs1 (stmt_info->stmt), 0)))
1395 {
1396 if (dump_enabled_p ())
1397 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1398 "Build SLP failed: different BIT_FIELD_REF "
1399 "arguments in %G", stmt);
1400 /* Mismatch. */
1401 continue;
1402 }
1403
1404 if (call_stmt
1405 && first_stmt_code != CFN_MASK_LOAD
1406 && first_stmt_code != CFN_MASK_STORE)
1407 {
1408 if (!is_a <gcall *> (stmts[0]->stmt)
1409 || !compatible_calls_p (as_a <gcall *> (stmts[0]->stmt),
1410 call_stmt))
1411 {
1412 if (dump_enabled_p ())
1413 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1414 "Build SLP failed: different calls in %G",
1415 stmt);
1416 /* Mismatch. */
1417 continue;
1418 }
1419 }
1420
1421 if ((phi_p || gimple_could_trap_p (stmt_info->stmt))
1422 && (gimple_bb (first_stmt_info->stmt)
1423 != gimple_bb (stmt_info->stmt)))
1424 {
1425 if (dump_enabled_p ())
1426 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1427 "Build SLP failed: different BB for PHI "
1428 "or possibly trapping operation in %G", stmt);
1429 /* Mismatch. */
1430 continue;
1431 }
1432
1433 if (need_same_oprnds)
1434 {
1435 tree other_op1 = gimple_arg (stmt, 1);
1436 if (!operand_equal_p (first_op1, other_op1, 0))
1437 {
1438 if (dump_enabled_p ())
1439 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1440 "Build SLP failed: different shift "
1441 "arguments in %G", stmt);
1442 /* Mismatch. */
1443 continue;
1444 }
1445 }
1446
1447 if (first_lhs
1448 && lhs
1449 && !types_compatible_p (TREE_TYPE (lhs), TREE_TYPE (first_lhs)))
1450 {
1451 if (dump_enabled_p ())
1452 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1453 "Build SLP failed: different vector type "
1454 "in %G", stmt);
1455 /* Mismatch. */
1456 continue;
1457 }
1458 }
1459
1460 /* Grouped store or load. */
1461 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
1462 {
1463 gcc_assert (ldst_p);
1464 if (DR_IS_WRITE (STMT_VINFO_DATA_REF (stmt_info)))
1465 {
1466 /* Store. */
1467 gcc_assert (rhs_code == CFN_MASK_STORE
1468 || REFERENCE_CLASS_P (lhs)
1469 || DECL_P (lhs));
1470 }
1471 else
1472 {
1473 /* Load. */
1474 first_load = DR_GROUP_FIRST_ELEMENT (stmt_info);
1475 if (prev_first_load)
1476 {
1477 /* Check that there are no loads from different interleaving
1478 chains in the same node. */
1479 if (prev_first_load != first_load)
1480 {
1481 if (dump_enabled_p ())
1482 dump_printf_loc (MSG_MISSED_OPTIMIZATION,
1483 vect_location,
1484 "Build SLP failed: different "
1485 "interleaving chains in one node %G",
1486 stmt);
1487 /* Mismatch. */
1488 continue;
1489 }
1490 }
1491 else
1492 prev_first_load = first_load;
1493 }
1494 }
1495 /* Non-grouped store or load. */
1496 else if (ldst_p)
1497 {
1498 if (DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info))
1499 && rhs_code != CFN_GATHER_LOAD
1500 && rhs_code != CFN_MASK_GATHER_LOAD
1501 && rhs_code != CFN_MASK_LEN_GATHER_LOAD
1502 && rhs_code != CFN_SCATTER_STORE
1503 && rhs_code != CFN_MASK_SCATTER_STORE
1504 && rhs_code != CFN_MASK_LEN_SCATTER_STORE
1505 && !STMT_VINFO_GATHER_SCATTER_P (stmt_info)
1506 /* Not grouped loads are handled as externals for BB
1507 vectorization. For loop vectorization we can handle
1508 splats the same we handle single element interleaving. */
1509 && (is_a <bb_vec_info> (vinfo)
1510 || stmt_info != first_stmt_info))
1511 {
1512 /* Not grouped load. */
1513 if (dump_enabled_p ())
1514 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1515 "Build SLP failed: not grouped load %G", stmt);
1516
1517 if (i != 0)
1518 continue;
1519 /* Fatal mismatch. */
1520 matches[0] = false;
1521 return false;
1522 }
1523 }
1524 /* Not memory operation. */
1525 else
1526 {
1527 if (!phi_p
1528 && rhs_code.is_tree_code ()
1529 && TREE_CODE_CLASS (tree_code (rhs_code)) != tcc_binary
1530 && TREE_CODE_CLASS (tree_code (rhs_code)) != tcc_unary
1531 && TREE_CODE_CLASS (tree_code (rhs_code)) != tcc_expression
1532 && TREE_CODE_CLASS (tree_code (rhs_code)) != tcc_comparison
1533 && rhs_code != VIEW_CONVERT_EXPR
1534 && rhs_code != CALL_EXPR
1535 && rhs_code != BIT_FIELD_REF
1536 && rhs_code != SSA_NAME)
1537 {
1538 if (dump_enabled_p ())
1539 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1540 "Build SLP failed: operation unsupported %G",
1541 stmt);
1542 if (is_a <bb_vec_info> (vinfo) && i != 0)
1543 continue;
1544 /* Fatal mismatch. */
1545 matches[0] = false;
1546 return false;
1547 }
1548
1549 if (rhs_code == COND_EXPR)
1550 {
1551 tree cond_expr = gimple_assign_rhs1 (stmt);
1552 enum tree_code cond_code = TREE_CODE (cond_expr);
1553 enum tree_code swap_code = ERROR_MARK;
1554 enum tree_code invert_code = ERROR_MARK;
1555
1556 if (i == 0)
1557 first_cond_code = TREE_CODE (cond_expr);
1558 else if (TREE_CODE_CLASS (cond_code) == tcc_comparison)
1559 {
1560 bool honor_nans = HONOR_NANS (TREE_OPERAND (cond_expr, 0));
1561 swap_code = swap_tree_comparison (cond_code);
1562 invert_code = invert_tree_comparison (cond_code, honor_nans);
1563 }
1564
1565 if (first_cond_code == cond_code)
1566 ;
1567 /* Isomorphic can be achieved by swapping. */
1568 else if (first_cond_code == swap_code)
1569 swap[i] = 1;
1570 /* Isomorphic can be achieved by inverting. */
1571 else if (first_cond_code == invert_code)
1572 swap[i] = 2;
1573 else
1574 {
1575 if (dump_enabled_p ())
1576 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1577 "Build SLP failed: different"
1578 " operation %G", stmt);
1579 /* Mismatch. */
1580 continue;
1581 }
1582 }
1583
1584 if (i != 0
1585 && first_stmt_code != rhs_code
1586 && first_stmt_code.is_tree_code ()
1587 && rhs_code.is_tree_code ()
1588 && TREE_CODE_CLASS ((tree_code)first_stmt_code) == tcc_comparison
1589 && (swap_tree_comparison ((tree_code)first_stmt_code)
1590 == (tree_code)rhs_code))
1591 swap[i] = 1;
1592 }
1593
1594 matches[i] = true;
1595 }
1596
1597 for (i = 0; i < group_size; ++i)
1598 if (!matches[i])
1599 return false;
1600
1601 /* If we allowed a two-operation SLP node verify the target can cope
1602 with the permute we are going to use. */
1603 if (alt_stmt_code != ERROR_MARK
1604 && (!alt_stmt_code.is_tree_code ()
1605 || (TREE_CODE_CLASS (tree_code (alt_stmt_code)) != tcc_reference
1606 && TREE_CODE_CLASS (tree_code (alt_stmt_code)) != tcc_comparison)))
1607 {
1608 *two_operators = true;
1609 }
1610
1611 if (maybe_soft_fail)
1612 {
1613 unsigned HOST_WIDE_INT const_nunits;
1614 if (!TYPE_VECTOR_SUBPARTS
1615 (soft_fail_nunits_vectype).is_constant (&const_nunits)
1616 || const_nunits > group_size)
1617 matches[0] = false;
1618 else
1619 {
1620 /* With constant vector elements simulate a mismatch at the
1621 point we need to split. */
1622 unsigned tail = group_size & (const_nunits - 1);
1623 memset (&matches[group_size - tail], 0, sizeof (bool) * tail);
1624 }
1625 return false;
1626 }
1627
1628 return true;
1629 }
1630
1631 /* Traits for the hash_set to record failed SLP builds for a stmt set.
1632 Note we never remove apart from at destruction time so we do not
1633 need a special value for deleted that differs from empty. */
1634 struct bst_traits
1635 {
1636 typedef vec <stmt_vec_info> value_type;
1637 typedef vec <stmt_vec_info> compare_type;
1638 static inline hashval_t hash (value_type);
1639 static inline bool equal (value_type existing, value_type candidate);
1640 static inline bool is_empty (value_type x) { return !x.exists (); }
1641 static inline bool is_deleted (value_type x) { return !x.exists (); }
1642 static const bool empty_zero_p = true;
1643 static inline void mark_empty (value_type &x) { x.release (); }
1644 static inline void mark_deleted (value_type &x) { x.release (); }
1645 static inline void remove (value_type &x) { x.release (); }
1646 };
1647 inline hashval_t
1648 bst_traits::hash (value_type x)
1649 {
1650 inchash::hash h;
1651 for (unsigned i = 0; i < x.length (); ++i)
1652 h.add_int (x[i] ? gimple_uid (x[i]->stmt) : -1);
1653 return h.end ();
1654 }
1655 inline bool
1656 bst_traits::equal (value_type existing, value_type candidate)
1657 {
1658 if (existing.length () != candidate.length ())
1659 return false;
1660 for (unsigned i = 0; i < existing.length (); ++i)
1661 if (existing[i] != candidate[i])
1662 return false;
1663 return true;
1664 }
1665
1666 typedef hash_map <vec <stmt_vec_info>, slp_tree,
1667 simple_hashmap_traits <bst_traits, slp_tree> >
1668 scalar_stmts_to_slp_tree_map_t;
1669
1670 /* Release BST_MAP. */
1671
1672 static void
1673 release_scalar_stmts_to_slp_tree_map (scalar_stmts_to_slp_tree_map_t *bst_map)
1674 {
1675 /* The map keeps a reference on SLP nodes built, release that. */
1676 for (scalar_stmts_to_slp_tree_map_t::iterator it = bst_map->begin ();
1677 it != bst_map->end (); ++it)
1678 if ((*it).second)
1679 vect_free_slp_tree ((*it).second);
1680 delete bst_map;
1681 }
1682
1683 /* ??? This was std::pair<std::pair<tree_code, vect_def_type>, tree>
1684 but then vec::insert does memmove and that's not compatible with
1685 std::pair. */
1686 struct chain_op_t
1687 {
1688 chain_op_t (tree_code code_, vect_def_type dt_, tree op_)
1689 : code (code_), dt (dt_), op (op_) {}
1690 tree_code code;
1691 vect_def_type dt;
1692 tree op;
1693 };
1694
1695 /* Comparator for sorting associatable chains. */
1696
1697 static int
1698 dt_sort_cmp (const void *op1_, const void *op2_, void *)
1699 {
1700 auto *op1 = (const chain_op_t *) op1_;
1701 auto *op2 = (const chain_op_t *) op2_;
1702 if (op1->dt != op2->dt)
1703 return (int)op1->dt - (int)op2->dt;
1704 return (int)op1->code - (int)op2->code;
1705 }
1706
1707 /* Linearize the associatable expression chain at START with the
1708 associatable operation CODE (where PLUS_EXPR also allows MINUS_EXPR),
1709 filling CHAIN with the result and using WORKLIST as intermediate storage.
1710 CODE_STMT and ALT_CODE_STMT are filled with the first stmt using CODE
1711 or MINUS_EXPR. *CHAIN_STMTS if not NULL is filled with all computation
1712 stmts, starting with START. */
1713
1714 static void
1715 vect_slp_linearize_chain (vec_info *vinfo,
1716 vec<std::pair<tree_code, gimple *> > &worklist,
1717 vec<chain_op_t> &chain,
1718 enum tree_code code, gimple *start,
1719 gimple *&code_stmt, gimple *&alt_code_stmt,
1720 vec<gimple *> *chain_stmts)
1721 {
1722 /* For each lane linearize the addition/subtraction (or other
1723 uniform associatable operation) expression tree. */
1724 worklist.safe_push (std::make_pair (code, start));
1725 while (!worklist.is_empty ())
1726 {
1727 auto entry = worklist.pop ();
1728 gassign *stmt = as_a <gassign *> (entry.second);
1729 enum tree_code in_code = entry.first;
1730 enum tree_code this_code = gimple_assign_rhs_code (stmt);
1731 /* Pick some stmts suitable for SLP_TREE_REPRESENTATIVE. */
1732 if (!code_stmt
1733 && gimple_assign_rhs_code (stmt) == code)
1734 code_stmt = stmt;
1735 else if (!alt_code_stmt
1736 && gimple_assign_rhs_code (stmt) == MINUS_EXPR)
1737 alt_code_stmt = stmt;
1738 if (chain_stmts)
1739 chain_stmts->safe_push (stmt);
1740 for (unsigned opnum = 1; opnum <= 2; ++opnum)
1741 {
1742 tree op = gimple_op (stmt, opnum);
1743 vect_def_type dt;
1744 stmt_vec_info def_stmt_info;
1745 bool res = vect_is_simple_use (op, vinfo, &dt, &def_stmt_info);
1746 gcc_assert (res);
1747 if (dt == vect_internal_def
1748 && is_pattern_stmt_p (def_stmt_info))
1749 op = gimple_get_lhs (def_stmt_info->stmt);
1750 gimple *use_stmt;
1751 use_operand_p use_p;
1752 if (dt == vect_internal_def
1753 && single_imm_use (op, &use_p, &use_stmt)
1754 && is_gimple_assign (def_stmt_info->stmt)
1755 && (gimple_assign_rhs_code (def_stmt_info->stmt) == code
1756 || (code == PLUS_EXPR
1757 && (gimple_assign_rhs_code (def_stmt_info->stmt)
1758 == MINUS_EXPR))))
1759 {
1760 tree_code op_def_code = this_code;
1761 if (op_def_code == MINUS_EXPR && opnum == 1)
1762 op_def_code = PLUS_EXPR;
1763 if (in_code == MINUS_EXPR)
1764 op_def_code = op_def_code == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR;
1765 worklist.safe_push (std::make_pair (op_def_code,
1766 def_stmt_info->stmt));
1767 }
1768 else
1769 {
1770 tree_code op_def_code = this_code;
1771 if (op_def_code == MINUS_EXPR && opnum == 1)
1772 op_def_code = PLUS_EXPR;
1773 if (in_code == MINUS_EXPR)
1774 op_def_code = op_def_code == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR;
1775 chain.safe_push (chain_op_t (op_def_code, dt, op));
1776 }
1777 }
1778 }
1779 }
1780
1781 static slp_tree
1782 vect_build_slp_tree_2 (vec_info *vinfo, slp_tree node,
1783 vec<stmt_vec_info> stmts, unsigned int group_size,
1784 poly_uint64 *max_nunits,
1785 bool *matches, unsigned *limit, unsigned *tree_size,
1786 scalar_stmts_to_slp_tree_map_t *bst_map);
1787
1788 static slp_tree
1789 vect_build_slp_tree (vec_info *vinfo,
1790 vec<stmt_vec_info> stmts, unsigned int group_size,
1791 poly_uint64 *max_nunits,
1792 bool *matches, unsigned *limit, unsigned *tree_size,
1793 scalar_stmts_to_slp_tree_map_t *bst_map)
1794 {
1795 if (slp_tree *leader = bst_map->get (stmts))
1796 {
1797 if (dump_enabled_p ())
1798 dump_printf_loc (MSG_NOTE, vect_location, "re-using %sSLP tree %p\n",
1799 !(*leader)->failed ? "" : "failed ",
1800 (void *) *leader);
1801 if (!(*leader)->failed)
1802 {
1803 SLP_TREE_REF_COUNT (*leader)++;
1804 vect_update_max_nunits (max_nunits, (*leader)->max_nunits);
1805 stmts.release ();
1806 return *leader;
1807 }
1808 memcpy (matches, (*leader)->failed, sizeof (bool) * group_size);
1809 return NULL;
1810 }
1811
1812 /* Single-lane SLP doesn't have the chance of run-away, do not account
1813 it to the limit. */
1814 if (stmts.length () > 1)
1815 {
1816 if (*limit == 0)
1817 {
1818 if (dump_enabled_p ())
1819 dump_printf_loc (MSG_NOTE, vect_location,
1820 "SLP discovery limit exceeded\n");
1821 memset (matches, 0, sizeof (bool) * group_size);
1822 return NULL;
1823 }
1824 --*limit;
1825 }
1826
1827 /* Seed the bst_map with a stub node to be filled by vect_build_slp_tree_2
1828 so we can pick up backedge destinations during discovery. */
1829 slp_tree res = new _slp_tree;
1830 SLP_TREE_DEF_TYPE (res) = vect_internal_def;
1831 SLP_TREE_SCALAR_STMTS (res) = stmts;
1832 bst_map->put (stmts.copy (), res);
1833
1834 if (dump_enabled_p ())
1835 dump_printf_loc (MSG_NOTE, vect_location,
1836 "starting SLP discovery for node %p\n", (void *) res);
1837
1838 poly_uint64 this_max_nunits = 1;
1839 slp_tree res_ = vect_build_slp_tree_2 (vinfo, res, stmts, group_size,
1840 &this_max_nunits,
1841 matches, limit, tree_size, bst_map);
1842 if (!res_)
1843 {
1844 if (dump_enabled_p ())
1845 dump_printf_loc (MSG_NOTE, vect_location,
1846 "SLP discovery for node %p failed\n", (void *) res);
1847 /* Mark the node invalid so we can detect those when still in use
1848 as backedge destinations. */
1849 SLP_TREE_SCALAR_STMTS (res) = vNULL;
1850 SLP_TREE_DEF_TYPE (res) = vect_uninitialized_def;
1851 res->failed = XNEWVEC (bool, group_size);
1852 if (flag_checking)
1853 {
1854 unsigned i;
1855 for (i = 0; i < group_size; ++i)
1856 if (!matches[i])
1857 break;
1858 gcc_assert (i < group_size);
1859 }
1860 memcpy (res->failed, matches, sizeof (bool) * group_size);
1861 }
1862 else
1863 {
1864 if (dump_enabled_p ())
1865 dump_printf_loc (MSG_NOTE, vect_location,
1866 "SLP discovery for node %p succeeded\n",
1867 (void *) res);
1868 gcc_assert (res_ == res);
1869 res->max_nunits = this_max_nunits;
1870 vect_update_max_nunits (max_nunits, this_max_nunits);
1871 /* Keep a reference for the bst_map use. */
1872 SLP_TREE_REF_COUNT (res)++;
1873 }
1874 return res_;
1875 }
1876
1877 /* Helper for building an associated SLP node chain. */
1878
1879 static void
1880 vect_slp_build_two_operator_nodes (slp_tree perm, tree vectype,
1881 slp_tree op0, slp_tree op1,
1882 stmt_vec_info oper1, stmt_vec_info oper2,
1883 vec<std::pair<unsigned, unsigned> > lperm)
1884 {
1885 unsigned group_size = SLP_TREE_LANES (op1);
1886
1887 slp_tree child1 = new _slp_tree;
1888 SLP_TREE_DEF_TYPE (child1) = vect_internal_def;
1889 SLP_TREE_VECTYPE (child1) = vectype;
1890 SLP_TREE_LANES (child1) = group_size;
1891 SLP_TREE_CHILDREN (child1).create (2);
1892 SLP_TREE_CHILDREN (child1).quick_push (op0);
1893 SLP_TREE_CHILDREN (child1).quick_push (op1);
1894 SLP_TREE_REPRESENTATIVE (child1) = oper1;
1895
1896 slp_tree child2 = new _slp_tree;
1897 SLP_TREE_DEF_TYPE (child2) = vect_internal_def;
1898 SLP_TREE_VECTYPE (child2) = vectype;
1899 SLP_TREE_LANES (child2) = group_size;
1900 SLP_TREE_CHILDREN (child2).create (2);
1901 SLP_TREE_CHILDREN (child2).quick_push (op0);
1902 SLP_TREE_REF_COUNT (op0)++;
1903 SLP_TREE_CHILDREN (child2).quick_push (op1);
1904 SLP_TREE_REF_COUNT (op1)++;
1905 SLP_TREE_REPRESENTATIVE (child2) = oper2;
1906
1907 SLP_TREE_DEF_TYPE (perm) = vect_internal_def;
1908 SLP_TREE_CODE (perm) = VEC_PERM_EXPR;
1909 SLP_TREE_VECTYPE (perm) = vectype;
1910 SLP_TREE_LANES (perm) = group_size;
1911 /* ??? We should set this NULL but that's not expected. */
1912 SLP_TREE_REPRESENTATIVE (perm) = oper1;
1913 SLP_TREE_LANE_PERMUTATION (perm) = lperm;
1914 SLP_TREE_CHILDREN (perm).quick_push (child1);
1915 SLP_TREE_CHILDREN (perm).quick_push (child2);
1916 }
1917
1918 /* Recursively build an SLP tree starting from NODE.
1919 Fail (and return a value not equal to zero) if def-stmts are not
1920 isomorphic, require data permutation or are of unsupported types of
1921 operation. Otherwise, return 0.
1922 The value returned is the depth in the SLP tree where a mismatch
1923 was found. */
1924
1925 static slp_tree
1926 vect_build_slp_tree_2 (vec_info *vinfo, slp_tree node,
1927 vec<stmt_vec_info> stmts, unsigned int group_size,
1928 poly_uint64 *max_nunits,
1929 bool *matches, unsigned *limit, unsigned *tree_size,
1930 scalar_stmts_to_slp_tree_map_t *bst_map)
1931 {
1932 unsigned nops, i, this_tree_size = 0;
1933 poly_uint64 this_max_nunits = *max_nunits;
1934
1935 matches[0] = false;
1936
1937 stmt_vec_info stmt_info = stmts[0];
1938 if (!is_a<gcall *> (stmt_info->stmt)
1939 && !is_a<gassign *> (stmt_info->stmt)
1940 && !is_a<gphi *> (stmt_info->stmt))
1941 return NULL;
1942
1943 nops = gimple_num_args (stmt_info->stmt);
1944 if (const int *map = vect_get_operand_map (stmt_info->stmt,
1945 STMT_VINFO_GATHER_SCATTER_P
1946 (stmt_info)))
1947 nops = map[0];
1948
1949 /* If the SLP node is a PHI (induction or reduction), terminate
1950 the recursion. */
1951 bool *skip_args = XALLOCAVEC (bool, nops);
1952 memset (skip_args, 0, sizeof (bool) * nops);
1953 if (loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo))
1954 if (gphi *stmt = dyn_cast <gphi *> (stmt_info->stmt))
1955 {
1956 tree scalar_type = TREE_TYPE (PHI_RESULT (stmt));
1957 tree vectype = get_vectype_for_scalar_type (vinfo, scalar_type,
1958 group_size);
1959 if (!vect_record_max_nunits (vinfo, stmt_info, group_size, vectype,
1960 max_nunits))
1961 return NULL;
1962
1963 vect_def_type def_type = STMT_VINFO_DEF_TYPE (stmt_info);
1964 if (def_type == vect_induction_def)
1965 {
1966 /* Induction PHIs are not cycles but walk the initial
1967 value. Only for inner loops through, for outer loops
1968 we need to pick up the value from the actual PHIs
1969 to more easily support peeling and epilogue vectorization. */
1970 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1971 if (!nested_in_vect_loop_p (loop, stmt_info))
1972 skip_args[loop_preheader_edge (loop)->dest_idx] = true;
1973 else
1974 loop = loop->inner;
1975 skip_args[loop_latch_edge (loop)->dest_idx] = true;
1976 }
1977 else if (def_type == vect_reduction_def
1978 || def_type == vect_double_reduction_def
1979 || def_type == vect_nested_cycle
1980 || def_type == vect_first_order_recurrence)
1981 {
1982 /* Else def types have to match. */
1983 stmt_vec_info other_info;
1984 bool all_same = true;
1985 FOR_EACH_VEC_ELT (stmts, i, other_info)
1986 {
1987 if (STMT_VINFO_DEF_TYPE (other_info) != def_type)
1988 return NULL;
1989 if (other_info != stmt_info)
1990 all_same = false;
1991 }
1992 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1993 /* Reduction initial values are not explicitely represented. */
1994 if (def_type != vect_first_order_recurrence
1995 && gimple_bb (stmt_info->stmt) == loop->header)
1996 skip_args[loop_preheader_edge (loop)->dest_idx] = true;
1997 /* Reduction chain backedge defs are filled manually.
1998 ??? Need a better way to identify a SLP reduction chain PHI.
1999 Or a better overall way to SLP match those. */
2000 if (stmts.length () > 1
2001 && all_same && def_type == vect_reduction_def)
2002 skip_args[loop_latch_edge (loop)->dest_idx] = true;
2003 }
2004 else if (def_type != vect_internal_def)
2005 return NULL;
2006 }
2007
2008
2009 bool two_operators = false;
2010 unsigned char *swap = XALLOCAVEC (unsigned char, group_size);
2011 tree vectype = NULL_TREE;
2012 if (!vect_build_slp_tree_1 (vinfo, swap, stmts, group_size,
2013 &this_max_nunits, matches, &two_operators,
2014 &vectype))
2015 return NULL;
2016
2017 /* If the SLP node is a load, terminate the recursion unless masked. */
2018 if (STMT_VINFO_DATA_REF (stmt_info)
2019 && DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)))
2020 {
2021 if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
2022 gcc_assert (DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)));
2023 else
2024 {
2025 *max_nunits = this_max_nunits;
2026 (*tree_size)++;
2027 node = vect_create_new_slp_node (node, stmts, 0);
2028 SLP_TREE_VECTYPE (node) = vectype;
2029 /* And compute the load permutation. Whether it is actually
2030 a permutation depends on the unrolling factor which is
2031 decided later. */
2032 vec<unsigned> load_permutation;
2033 int j;
2034 stmt_vec_info load_info;
2035 load_permutation.create (group_size);
2036 stmt_vec_info first_stmt_info
2037 = STMT_VINFO_GROUPED_ACCESS (stmt_info)
2038 ? DR_GROUP_FIRST_ELEMENT (stmt_info) : stmt_info;
2039 bool any_permute = false;
2040 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), j, load_info)
2041 {
2042 int load_place;
2043 if (! load_info)
2044 {
2045 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
2046 load_place = j;
2047 else
2048 load_place = 0;
2049 }
2050 else if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
2051 load_place = vect_get_place_in_interleaving_chain
2052 (load_info, first_stmt_info);
2053 else
2054 load_place = 0;
2055 gcc_assert (load_place != -1);
2056 any_permute |= load_place != j;
2057 load_permutation.quick_push (load_place);
2058 }
2059
2060 if (gcall *stmt = dyn_cast <gcall *> (stmt_info->stmt))
2061 {
2062 gcc_assert (gimple_call_internal_p (stmt, IFN_MASK_LOAD));
2063 bool has_gaps = false;
2064 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
2065 for (stmt_vec_info si = DR_GROUP_NEXT_ELEMENT (first_stmt_info);
2066 si; si = DR_GROUP_NEXT_ELEMENT (si))
2067 if (DR_GROUP_GAP (si) != 1)
2068 has_gaps = true;
2069 /* We cannot handle permuted masked loads directly, see
2070 PR114375. We cannot handle strided masked loads or masked
2071 loads with gaps unless the mask is uniform. */
2072 if ((STMT_VINFO_GROUPED_ACCESS (stmt_info)
2073 && (DR_GROUP_GAP (first_stmt_info) != 0
2074 || (has_gaps
2075 && STMT_VINFO_SLP_VECT_ONLY (first_stmt_info))))
2076 || STMT_VINFO_STRIDED_P (stmt_info))
2077 {
2078 load_permutation.release ();
2079 matches[0] = false;
2080 return NULL;
2081 }
2082
2083 /* For permuted masked loads do an unpermuted masked load of
2084 the whole group followed by a SLP permute node. */
2085 if (any_permute
2086 || (STMT_VINFO_GROUPED_ACCESS (stmt_info)
2087 && DR_GROUP_SIZE (first_stmt_info) != group_size))
2088 {
2089 /* Discover the whole unpermuted load. */
2090 vec<stmt_vec_info> stmts2;
2091 unsigned dr_group_size = STMT_VINFO_GROUPED_ACCESS (stmt_info)
2092 ? DR_GROUP_SIZE (first_stmt_info) : 1;
2093 stmts2.create (dr_group_size);
2094 stmts2.quick_grow_cleared (dr_group_size);
2095 unsigned i = 0;
2096 for (stmt_vec_info si = first_stmt_info;
2097 si; si = DR_GROUP_NEXT_ELEMENT (si))
2098 {
2099 if (si != first_stmt_info)
2100 for (unsigned k = 1; k < DR_GROUP_GAP (si); ++k)
2101 stmts2[i++] = NULL;
2102 stmts2[i++] = si;
2103 }
2104 bool *matches2 = XALLOCAVEC (bool, dr_group_size);
2105 slp_tree unperm_load
2106 = vect_build_slp_tree (vinfo, stmts2, dr_group_size,
2107 &this_max_nunits, matches2, limit,
2108 &this_tree_size, bst_map);
2109 /* When we are able to do the full masked load emit that
2110 followed by 'node' being the desired final permutation. */
2111 if (unperm_load)
2112 {
2113 gcc_assert
2114 (!SLP_TREE_LOAD_PERMUTATION (unperm_load).exists ());
2115 lane_permutation_t lperm;
2116 lperm.create (group_size);
2117 for (unsigned j = 0; j < load_permutation.length (); ++j)
2118 lperm.quick_push
2119 (std::make_pair (0, load_permutation[j]));
2120 SLP_TREE_CODE (node) = VEC_PERM_EXPR;
2121 SLP_TREE_CHILDREN (node).safe_push (unperm_load);
2122 SLP_TREE_LANE_PERMUTATION (node) = lperm;
2123 load_permutation.release ();
2124 return node;
2125 }
2126 stmts2.release ();
2127 load_permutation.release ();
2128 matches[0] = false;
2129 return NULL;
2130 }
2131 load_permutation.release ();
2132 }
2133 else
2134 {
2135 if (!any_permute
2136 && STMT_VINFO_GROUPED_ACCESS (stmt_info)
2137 && group_size == DR_GROUP_SIZE (first_stmt_info))
2138 load_permutation.release ();
2139 SLP_TREE_LOAD_PERMUTATION (node) = load_permutation;
2140 return node;
2141 }
2142 }
2143 }
2144 else if (gimple_assign_single_p (stmt_info->stmt)
2145 && !gimple_vuse (stmt_info->stmt)
2146 && gimple_assign_rhs_code (stmt_info->stmt) == BIT_FIELD_REF)
2147 {
2148 /* vect_build_slp_tree_2 determined all BIT_FIELD_REFs reference
2149 the same SSA name vector of a compatible type to vectype. */
2150 vec<std::pair<unsigned, unsigned> > lperm = vNULL;
2151 tree vec = TREE_OPERAND (gimple_assign_rhs1 (stmt_info->stmt), 0);
2152 stmt_vec_info estmt_info;
2153 FOR_EACH_VEC_ELT (stmts, i, estmt_info)
2154 {
2155 gassign *estmt = as_a <gassign *> (estmt_info->stmt);
2156 tree bfref = gimple_assign_rhs1 (estmt);
2157 HOST_WIDE_INT lane;
2158 if (!known_eq (bit_field_size (bfref),
2159 tree_to_poly_uint64 (TYPE_SIZE (TREE_TYPE (vectype))))
2160 || !constant_multiple_p (bit_field_offset (bfref),
2161 bit_field_size (bfref), &lane))
2162 {
2163 lperm.release ();
2164 matches[0] = false;
2165 return NULL;
2166 }
2167 lperm.safe_push (std::make_pair (0, (unsigned)lane));
2168 }
2169 slp_tree vnode = vect_create_new_slp_node (vNULL);
2170 if (operand_equal_p (TYPE_SIZE (vectype), TYPE_SIZE (TREE_TYPE (vec))))
2171 /* ??? We record vectype here but we hide eventually necessary
2172 punning and instead rely on code generation to materialize
2173 VIEW_CONVERT_EXPRs as necessary. We instead should make
2174 this explicit somehow. */
2175 SLP_TREE_VECTYPE (vnode) = vectype;
2176 else
2177 {
2178 /* For different size but compatible elements we can still
2179 use VEC_PERM_EXPR without punning. */
2180 gcc_assert (VECTOR_TYPE_P (TREE_TYPE (vec))
2181 && types_compatible_p (TREE_TYPE (vectype),
2182 TREE_TYPE (TREE_TYPE (vec))));
2183 SLP_TREE_VECTYPE (vnode) = TREE_TYPE (vec);
2184 }
2185 auto nunits = TYPE_VECTOR_SUBPARTS (SLP_TREE_VECTYPE (vnode));
2186 unsigned HOST_WIDE_INT const_nunits;
2187 if (nunits.is_constant (&const_nunits))
2188 SLP_TREE_LANES (vnode) = const_nunits;
2189 SLP_TREE_VEC_DEFS (vnode).safe_push (vec);
2190 /* We are always building a permutation node even if it is an identity
2191 permute to shield the rest of the vectorizer from the odd node
2192 representing an actual vector without any scalar ops.
2193 ??? We could hide it completely with making the permute node
2194 external? */
2195 node = vect_create_new_slp_node (node, stmts, 1);
2196 SLP_TREE_CODE (node) = VEC_PERM_EXPR;
2197 SLP_TREE_LANE_PERMUTATION (node) = lperm;
2198 SLP_TREE_VECTYPE (node) = vectype;
2199 SLP_TREE_CHILDREN (node).quick_push (vnode);
2200 return node;
2201 }
2202 /* When discovery reaches an associatable operation see whether we can
2203 improve that to match up lanes in a way superior to the operand
2204 swapping code which at most looks at two defs.
2205 ??? For BB vectorization we cannot do the brute-force search
2206 for matching as we can succeed by means of builds from scalars
2207 and have no good way to "cost" one build against another. */
2208 else if (is_a <loop_vec_info> (vinfo)
2209 /* Do not bother for single-lane SLP. */
2210 && group_size > 1
2211 /* ??? We don't handle !vect_internal_def defs below. */
2212 && STMT_VINFO_DEF_TYPE (stmt_info) == vect_internal_def
2213 /* ??? Do not associate a reduction, this will wreck REDUC_IDX
2214 mapping as long as that exists on the stmt_info level. */
2215 && STMT_VINFO_REDUC_IDX (stmt_info) == -1
2216 && is_gimple_assign (stmt_info->stmt)
2217 && (associative_tree_code (gimple_assign_rhs_code (stmt_info->stmt))
2218 || gimple_assign_rhs_code (stmt_info->stmt) == MINUS_EXPR)
2219 && ((FLOAT_TYPE_P (vectype) && flag_associative_math)
2220 || (INTEGRAL_TYPE_P (TREE_TYPE (vectype))
2221 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (vectype)))))
2222 {
2223 /* See if we have a chain of (mixed) adds or subtracts or other
2224 associatable ops. */
2225 enum tree_code code = gimple_assign_rhs_code (stmt_info->stmt);
2226 if (code == MINUS_EXPR)
2227 code = PLUS_EXPR;
2228 stmt_vec_info other_op_stmt_info = NULL;
2229 stmt_vec_info op_stmt_info = NULL;
2230 unsigned chain_len = 0;
2231 auto_vec<chain_op_t> chain;
2232 auto_vec<std::pair<tree_code, gimple *> > worklist;
2233 auto_vec<vec<chain_op_t> > chains (group_size);
2234 auto_vec<slp_tree, 4> children;
2235 bool hard_fail = true;
2236 for (unsigned lane = 0; lane < group_size; ++lane)
2237 {
2238 if (!stmts[lane])
2239 {
2240 /* ??? Below we require lane zero is present. */
2241 if (lane == 0)
2242 {
2243 hard_fail = false;
2244 break;
2245 }
2246 chains.quick_push (vNULL);
2247 continue;
2248 }
2249 /* For each lane linearize the addition/subtraction (or other
2250 uniform associatable operation) expression tree. */
2251 gimple *op_stmt = NULL, *other_op_stmt = NULL;
2252 vect_slp_linearize_chain (vinfo, worklist, chain, code,
2253 stmts[lane]->stmt, op_stmt, other_op_stmt,
2254 NULL);
2255 if (!op_stmt_info && op_stmt)
2256 op_stmt_info = vinfo->lookup_stmt (op_stmt);
2257 if (!other_op_stmt_info && other_op_stmt)
2258 other_op_stmt_info = vinfo->lookup_stmt (other_op_stmt);
2259 if (chain.length () == 2)
2260 {
2261 /* In a chain of just two elements resort to the regular
2262 operand swapping scheme. Likewise if we run into a
2263 length mismatch process regularly as well as we did not
2264 process the other lanes we cannot report a good hint what
2265 lanes to try swapping in the parent. */
2266 hard_fail = false;
2267 break;
2268 }
2269 else if (chain_len == 0)
2270 chain_len = chain.length ();
2271 else if (chain.length () != chain_len)
2272 {
2273 /* ??? Here we could slip in magic to compensate with
2274 neutral operands. */
2275 matches[lane] = false;
2276 if (lane != group_size - 1)
2277 matches[0] = false;
2278 break;
2279 }
2280 chains.quick_push (chain.copy ());
2281 chain.truncate (0);
2282 }
2283 if (chains.length () == group_size)
2284 {
2285 /* We cannot yet use SLP_TREE_CODE to communicate the operation. */
2286 if (!op_stmt_info)
2287 {
2288 hard_fail = false;
2289 goto out;
2290 }
2291 /* Now we have a set of chains with the same length. */
2292 /* 1. pre-sort according to def_type and operation. */
2293 for (unsigned lane = 0; lane < group_size; ++lane)
2294 chains[lane].stablesort (dt_sort_cmp, vinfo);
2295 if (dump_enabled_p ())
2296 {
2297 dump_printf_loc (MSG_NOTE, vect_location,
2298 "pre-sorted chains of %s\n",
2299 get_tree_code_name (code));
2300 for (unsigned lane = 0; lane < group_size; ++lane)
2301 {
2302 if (!stmts[lane])
2303 dump_printf (MSG_NOTE, "--");
2304 else
2305 for (unsigned opnum = 0; opnum < chain_len; ++opnum)
2306 dump_printf (MSG_NOTE, "%s %T ",
2307 get_tree_code_name (chains[lane][opnum].code),
2308 chains[lane][opnum].op);
2309 dump_printf (MSG_NOTE, "\n");
2310 }
2311 }
2312 /* 2. try to build children nodes, associating as necessary. */
2313 /* 2a. prepare and perform early checks to avoid eating into
2314 discovery limit unnecessarily. */
2315 vect_def_type *dts = XALLOCAVEC (vect_def_type, chain_len);
2316 for (unsigned n = 0; n < chain_len; ++n)
2317 {
2318 vect_def_type dt = chains[0][n].dt;
2319 unsigned lane;
2320 for (lane = 0; lane < group_size; ++lane)
2321 if (stmts[lane] && chains[lane][n].dt != dt)
2322 {
2323 if (dt == vect_constant_def
2324 && chains[lane][n].dt == vect_external_def)
2325 dt = vect_external_def;
2326 else if (dt == vect_external_def
2327 && chains[lane][n].dt == vect_constant_def)
2328 ;
2329 else
2330 break;
2331 }
2332 if (lane != group_size)
2333 {
2334 if (dump_enabled_p ())
2335 dump_printf_loc (MSG_NOTE, vect_location,
2336 "giving up on chain due to mismatched "
2337 "def types\n");
2338 matches[lane] = false;
2339 if (lane != group_size - 1)
2340 matches[0] = false;
2341 goto out;
2342 }
2343 dts[n] = dt;
2344 if (dt == vect_constant_def
2345 || dt == vect_external_def)
2346 {
2347 /* Check whether we can build the invariant. If we can't
2348 we never will be able to. */
2349 tree type = TREE_TYPE (chains[0][n].op);
2350 if (!GET_MODE_SIZE (vinfo->vector_mode).is_constant ()
2351 && (TREE_CODE (type) == BOOLEAN_TYPE
2352 || !can_duplicate_and_interleave_p (vinfo, group_size,
2353 type)))
2354 {
2355 matches[0] = false;
2356 goto out;
2357 }
2358 }
2359 else if (dt != vect_internal_def)
2360 {
2361 /* Not sure, we might need sth special.
2362 gcc.dg/vect/pr96854.c,
2363 gfortran.dg/vect/fast-math-pr37021.f90
2364 and gfortran.dg/vect/pr61171.f trigger. */
2365 /* Soft-fail for now. */
2366 hard_fail = false;
2367 goto out;
2368 }
2369 }
2370 /* 2b. do the actual build. */
2371 for (unsigned n = 0; n < chain_len; ++n)
2372 {
2373 vect_def_type dt = dts[n];
2374 unsigned lane;
2375 if (dt == vect_constant_def
2376 || dt == vect_external_def)
2377 {
2378 vec<tree> ops;
2379 ops.create (group_size);
2380 for (lane = 0; lane < group_size; ++lane)
2381 if (stmts[lane])
2382 ops.quick_push (chains[lane][n].op);
2383 else
2384 ops.quick_push (NULL_TREE);
2385 slp_tree child = vect_create_new_slp_node (ops);
2386 SLP_TREE_DEF_TYPE (child) = dt;
2387 children.safe_push (child);
2388 }
2389 else
2390 {
2391 vec<stmt_vec_info> op_stmts;
2392 op_stmts.create (group_size);
2393 slp_tree child = NULL;
2394 /* Brute-force our way. We have to consider a lane
2395 failing after fixing an earlier fail up in the
2396 SLP discovery recursion. So track the current
2397 permute per lane. */
2398 unsigned *perms = XALLOCAVEC (unsigned, group_size);
2399 memset (perms, 0, sizeof (unsigned) * group_size);
2400 do
2401 {
2402 op_stmts.truncate (0);
2403 for (lane = 0; lane < group_size; ++lane)
2404 if (stmts[lane])
2405 op_stmts.quick_push
2406 (vinfo->lookup_def (chains[lane][n].op));
2407 else
2408 op_stmts.quick_push (NULL);
2409 child = vect_build_slp_tree (vinfo, op_stmts,
2410 group_size, &this_max_nunits,
2411 matches, limit,
2412 &this_tree_size, bst_map);
2413 /* ??? We're likely getting too many fatal mismatches
2414 here so maybe we want to ignore them (but then we
2415 have no idea which lanes fatally mismatched). */
2416 if (child || !matches[0])
2417 break;
2418 /* Swap another lane we have not yet matched up into
2419 lanes that did not match. If we run out of
2420 permute possibilities for a lane terminate the
2421 search. */
2422 bool term = false;
2423 for (lane = 1; lane < group_size; ++lane)
2424 if (!matches[lane])
2425 {
2426 if (n + perms[lane] + 1 == chain_len)
2427 {
2428 term = true;
2429 break;
2430 }
2431 if (dump_enabled_p ())
2432 dump_printf_loc (MSG_NOTE, vect_location,
2433 "swapping operand %d and %d "
2434 "of lane %d\n",
2435 n, n + perms[lane] + 1, lane);
2436 std::swap (chains[lane][n],
2437 chains[lane][n + perms[lane] + 1]);
2438 perms[lane]++;
2439 }
2440 if (term)
2441 break;
2442 }
2443 while (1);
2444 if (!child)
2445 {
2446 if (dump_enabled_p ())
2447 dump_printf_loc (MSG_NOTE, vect_location,
2448 "failed to match up op %d\n", n);
2449 op_stmts.release ();
2450 if (lane != group_size - 1)
2451 matches[0] = false;
2452 else
2453 matches[lane] = false;
2454 goto out;
2455 }
2456 if (dump_enabled_p ())
2457 {
2458 dump_printf_loc (MSG_NOTE, vect_location,
2459 "matched up op %d to\n", n);
2460 vect_print_slp_tree (MSG_NOTE, vect_location, child);
2461 }
2462 children.safe_push (child);
2463 }
2464 }
2465 /* 3. build SLP nodes to combine the chain. */
2466 for (unsigned lane = 0; lane < group_size; ++lane)
2467 if (stmts[lane] && chains[lane][0].code != code)
2468 {
2469 /* See if there's any alternate all-PLUS entry. */
2470 unsigned n;
2471 for (n = 1; n < chain_len; ++n)
2472 {
2473 for (lane = 0; lane < group_size; ++lane)
2474 if (stmts[lane] && chains[lane][n].code != code)
2475 break;
2476 if (lane == group_size)
2477 break;
2478 }
2479 if (n != chain_len)
2480 {
2481 /* Swap that in at first position. */
2482 std::swap (children[0], children[n]);
2483 for (lane = 0; lane < group_size; ++lane)
2484 if (stmts[lane])
2485 std::swap (chains[lane][0], chains[lane][n]);
2486 }
2487 else
2488 {
2489 /* ??? When this triggers and we end up with two
2490 vect_constant/external_def up-front things break (ICE)
2491 spectacularly finding an insertion place for the
2492 all-constant op. We should have a fully
2493 vect_internal_def operand though(?) so we can swap
2494 that into first place and then prepend the all-zero
2495 constant. */
2496 if (dump_enabled_p ())
2497 dump_printf_loc (MSG_NOTE, vect_location,
2498 "inserting constant zero to compensate "
2499 "for (partially) negated first "
2500 "operand\n");
2501 chain_len++;
2502 for (lane = 0; lane < group_size; ++lane)
2503 if (stmts[lane])
2504 chains[lane].safe_insert
2505 (0, chain_op_t (code, vect_constant_def, NULL_TREE));
2506 vec<tree> zero_ops;
2507 zero_ops.create (group_size);
2508 zero_ops.quick_push (build_zero_cst (TREE_TYPE (vectype)));
2509 for (lane = 1; lane < group_size; ++lane)
2510 if (stmts[lane])
2511 zero_ops.quick_push (zero_ops[0]);
2512 else
2513 zero_ops.quick_push (NULL_TREE);
2514 slp_tree zero = vect_create_new_slp_node (zero_ops);
2515 SLP_TREE_DEF_TYPE (zero) = vect_constant_def;
2516 children.safe_insert (0, zero);
2517 }
2518 break;
2519 }
2520 for (unsigned i = 1; i < children.length (); ++i)
2521 {
2522 slp_tree op0 = children[i - 1];
2523 slp_tree op1 = children[i];
2524 bool this_two_op = false;
2525 for (unsigned lane = 0; lane < group_size; ++lane)
2526 if (stmts[lane] && chains[lane][i].code != chains[0][i].code)
2527 {
2528 this_two_op = true;
2529 break;
2530 }
2531 slp_tree child;
2532 if (i == children.length () - 1)
2533 child = vect_create_new_slp_node (node, stmts, 2);
2534 else
2535 child = vect_create_new_slp_node (2, ERROR_MARK);
2536 if (this_two_op)
2537 {
2538 vec<std::pair<unsigned, unsigned> > lperm;
2539 lperm.create (group_size);
2540 for (unsigned lane = 0; lane < group_size; ++lane)
2541 lperm.quick_push (std::make_pair
2542 (chains[lane][i].code != chains[0][i].code, lane));
2543 vect_slp_build_two_operator_nodes (child, vectype, op0, op1,
2544 (chains[0][i].code == code
2545 ? op_stmt_info
2546 : other_op_stmt_info),
2547 (chains[0][i].code == code
2548 ? other_op_stmt_info
2549 : op_stmt_info),
2550 lperm);
2551 }
2552 else
2553 {
2554 SLP_TREE_DEF_TYPE (child) = vect_internal_def;
2555 SLP_TREE_VECTYPE (child) = vectype;
2556 SLP_TREE_LANES (child) = group_size;
2557 SLP_TREE_CHILDREN (child).quick_push (op0);
2558 SLP_TREE_CHILDREN (child).quick_push (op1);
2559 SLP_TREE_REPRESENTATIVE (child)
2560 = (chains[0][i].code == code
2561 ? op_stmt_info : other_op_stmt_info);
2562 }
2563 children[i] = child;
2564 }
2565 *tree_size += this_tree_size + 1;
2566 *max_nunits = this_max_nunits;
2567 while (!chains.is_empty ())
2568 chains.pop ().release ();
2569 return node;
2570 }
2571 out:
2572 if (dump_enabled_p ())
2573 dump_printf_loc (MSG_NOTE, vect_location,
2574 "failed to line up SLP graph by re-associating "
2575 "operations in lanes%s\n",
2576 !hard_fail ? " trying regular discovery" : "");
2577 while (!children.is_empty ())
2578 vect_free_slp_tree (children.pop ());
2579 while (!chains.is_empty ())
2580 chains.pop ().release ();
2581 /* Hard-fail, otherwise we might run into quadratic processing of the
2582 chains starting one stmt into the chain again. */
2583 if (hard_fail)
2584 return NULL;
2585 /* Fall thru to normal processing. */
2586 }
2587
2588 /* Get at the operands, verifying they are compatible. */
2589 vec<slp_oprnd_info> oprnds_info = vect_create_oprnd_info (nops, group_size);
2590 slp_oprnd_info oprnd_info;
2591 FOR_EACH_VEC_ELT (stmts, i, stmt_info)
2592 {
2593 int res = vect_get_and_check_slp_defs (vinfo, swap[i], skip_args,
2594 stmts, i, &oprnds_info);
2595 if (res != 0)
2596 matches[(res == -1) ? 0 : i] = false;
2597 if (!matches[0])
2598 break;
2599 }
2600 for (i = 0; i < group_size; ++i)
2601 if (!matches[i])
2602 {
2603 vect_free_oprnd_info (oprnds_info);
2604 return NULL;
2605 }
2606 swap = NULL;
2607
2608 bool has_two_operators_perm = false;
2609 auto_vec<unsigned> two_op_perm_indices[2];
2610 vec<stmt_vec_info> two_op_scalar_stmts[2] = {vNULL, vNULL};
2611
2612 if (two_operators && oprnds_info.length () == 2 && group_size > 2)
2613 {
2614 unsigned idx = 0;
2615 hash_map<gimple *, unsigned> seen;
2616 vec<slp_oprnd_info> new_oprnds_info
2617 = vect_create_oprnd_info (1, group_size);
2618 bool success = true;
2619
2620 enum tree_code code = ERROR_MARK;
2621 if (oprnds_info[0]->def_stmts[0]
2622 && is_a<gassign *> (oprnds_info[0]->def_stmts[0]->stmt))
2623 code = gimple_assign_rhs_code (oprnds_info[0]->def_stmts[0]->stmt);
2624 basic_block bb = nullptr;
2625
2626 for (unsigned j = 0; j < group_size; ++j)
2627 {
2628 FOR_EACH_VEC_ELT (oprnds_info, i, oprnd_info)
2629 {
2630 stmt_vec_info stmt_info = oprnd_info->def_stmts[j];
2631 if (!stmt_info
2632 || !is_a<gassign *> (stmt_info->stmt)
2633 || gimple_assign_rhs_code (stmt_info->stmt) != code
2634 || skip_args[i])
2635 {
2636 success = false;
2637 break;
2638 }
2639 /* Avoid mixing lanes with defs in different basic-blocks. */
2640 if (!bb)
2641 bb = gimple_bb (vect_orig_stmt (stmt_info)->stmt);
2642 else if (gimple_bb (vect_orig_stmt (stmt_info)->stmt) != bb)
2643 {
2644 success = false;
2645 break;
2646 }
2647
2648 bool exists;
2649 unsigned &stmt_idx
2650 = seen.get_or_insert (stmt_info->stmt, &exists);
2651
2652 if (!exists)
2653 {
2654 new_oprnds_info[0]->def_stmts.safe_push (stmt_info);
2655 new_oprnds_info[0]->ops.safe_push (oprnd_info->ops[j]);
2656 stmt_idx = idx;
2657 idx++;
2658 }
2659
2660 two_op_perm_indices[i].safe_push (stmt_idx);
2661 }
2662
2663 if (!success)
2664 break;
2665 }
2666
2667 if (success && idx == group_size)
2668 {
2669 if (dump_enabled_p ())
2670 {
2671 dump_printf_loc (MSG_NOTE, vect_location,
2672 "Replace two_operators operands:\n");
2673
2674 FOR_EACH_VEC_ELT (oprnds_info, i, oprnd_info)
2675 {
2676 dump_printf_loc (MSG_NOTE, vect_location,
2677 "Operand %u:\n", i);
2678 for (unsigned j = 0; j < group_size; j++)
2679 dump_printf_loc (MSG_NOTE, vect_location, "\tstmt %u %G",
2680 j, oprnd_info->def_stmts[j]->stmt);
2681 }
2682
2683 dump_printf_loc (MSG_NOTE, vect_location,
2684 "With a single operand:\n");
2685 for (unsigned j = 0; j < group_size; j++)
2686 dump_printf_loc (MSG_NOTE, vect_location, "\tstmt %u %G",
2687 j, new_oprnds_info[0]->def_stmts[j]->stmt);
2688 }
2689
2690 two_op_scalar_stmts[0].safe_splice (oprnds_info[0]->def_stmts);
2691 two_op_scalar_stmts[1].safe_splice (oprnds_info[1]->def_stmts);
2692
2693 new_oprnds_info[0]->first_op_type = oprnds_info[0]->first_op_type;
2694 new_oprnds_info[0]->first_dt = oprnds_info[0]->first_dt;
2695 new_oprnds_info[0]->any_pattern = oprnds_info[0]->any_pattern;
2696 new_oprnds_info[0]->first_gs_p = oprnds_info[0]->first_gs_p;
2697 new_oprnds_info[0]->first_gs_info = oprnds_info[0]->first_gs_info;
2698
2699 vect_free_oprnd_info (oprnds_info);
2700 oprnds_info = new_oprnds_info;
2701 nops = 1;
2702 has_two_operators_perm = true;
2703 }
2704 else
2705 vect_free_oprnd_info (new_oprnds_info);
2706 }
2707
2708 auto_vec<slp_tree, 4> children;
2709
2710 stmt_info = stmts[0];
2711
2712 /* Create SLP_TREE nodes for the definition node/s. */
2713 FOR_EACH_VEC_ELT (oprnds_info, i, oprnd_info)
2714 {
2715 slp_tree child = nullptr;
2716 unsigned int j;
2717
2718 /* We're skipping certain operands from processing, for example
2719 outer loop reduction initial defs. */
2720 if (skip_args[i])
2721 {
2722 children.safe_push (NULL);
2723 continue;
2724 }
2725
2726 if (oprnd_info->first_dt == vect_uninitialized_def)
2727 {
2728 /* COND_EXPR have one too many eventually if the condition
2729 is a SSA name. */
2730 gcc_assert (i == 3 && nops == 4);
2731 continue;
2732 }
2733
2734 if (is_a <bb_vec_info> (vinfo)
2735 && oprnd_info->first_dt == vect_internal_def
2736 && !oprnd_info->any_pattern)
2737 {
2738 /* For BB vectorization, if all defs are the same do not
2739 bother to continue the build along the single-lane
2740 graph but use a splat of the scalar value. */
2741 stmt_vec_info first_def = oprnd_info->def_stmts[0];
2742 for (j = 1; j < group_size; ++j)
2743 if (oprnd_info->def_stmts[j] != first_def)
2744 break;
2745 if (j == group_size
2746 /* But avoid doing this for loads where we may be
2747 able to CSE things, unless the stmt is not
2748 vectorizable. */
2749 && (!STMT_VINFO_VECTORIZABLE (first_def)
2750 || !gimple_vuse (first_def->stmt)))
2751 {
2752 if (dump_enabled_p ())
2753 dump_printf_loc (MSG_NOTE, vect_location,
2754 "Using a splat of the uniform operand %G",
2755 first_def->stmt);
2756 oprnd_info->first_dt = vect_external_def;
2757 }
2758 }
2759
2760 if (oprnd_info->first_dt == vect_external_def
2761 || oprnd_info->first_dt == vect_constant_def)
2762 {
2763 if (!GET_MODE_SIZE (vinfo->vector_mode).is_constant ())
2764 {
2765 tree op0;
2766 tree uniform_val = op0 = oprnd_info->ops[0];
2767 for (j = 1; j < oprnd_info->ops.length (); ++j)
2768 if (oprnd_info->ops[j]
2769 && !operand_equal_p (uniform_val, oprnd_info->ops[j]))
2770 {
2771 uniform_val = NULL_TREE;
2772 break;
2773 }
2774 if (!uniform_val
2775 && !can_duplicate_and_interleave_p (vinfo,
2776 oprnd_info->ops.length (),
2777 TREE_TYPE (op0)))
2778 {
2779 matches[j] = false;
2780 if (dump_enabled_p ())
2781 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2782 "Build SLP failed: invalid type of def "
2783 "for variable-length SLP %T\n", op0);
2784 goto fail;
2785 }
2786 }
2787 slp_tree invnode = vect_create_new_slp_node (oprnd_info->ops);
2788 SLP_TREE_DEF_TYPE (invnode) = oprnd_info->first_dt;
2789 oprnd_info->ops = vNULL;
2790 children.safe_push (invnode);
2791 continue;
2792 }
2793
2794 /* When we have a masked load with uniform mask discover this
2795 as a single-lane mask with a splat permute. This way we can
2796 recognize this as a masked load-lane by stripping the splat. */
2797 if (is_a <gcall *> (STMT_VINFO_STMT (stmt_info))
2798 && gimple_call_internal_p (STMT_VINFO_STMT (stmt_info),
2799 IFN_MASK_LOAD)
2800 && STMT_VINFO_GROUPED_ACCESS (stmt_info)
2801 && ! STMT_VINFO_SLP_VECT_ONLY (DR_GROUP_FIRST_ELEMENT (stmt_info)))
2802 {
2803 vec<stmt_vec_info> def_stmts2;
2804 def_stmts2.create (1);
2805 def_stmts2.quick_push (oprnd_info->def_stmts[0]);
2806 child = vect_build_slp_tree (vinfo, def_stmts2, 1,
2807 &this_max_nunits,
2808 matches, limit,
2809 &this_tree_size, bst_map);
2810 if (child)
2811 {
2812 slp_tree pnode = vect_create_new_slp_node (1, VEC_PERM_EXPR);
2813 SLP_TREE_VECTYPE (pnode) = SLP_TREE_VECTYPE (child);
2814 SLP_TREE_LANES (pnode) = group_size;
2815 SLP_TREE_SCALAR_STMTS (pnode).create (group_size);
2816 SLP_TREE_LANE_PERMUTATION (pnode).create (group_size);
2817 for (unsigned k = 0; k < group_size; ++k)
2818 {
2819 SLP_TREE_SCALAR_STMTS (pnode)
2820 .quick_push (oprnd_info->def_stmts[0]);
2821 SLP_TREE_LANE_PERMUTATION (pnode)
2822 .quick_push (std::make_pair (0u, 0u));
2823 }
2824 SLP_TREE_CHILDREN (pnode).quick_push (child);
2825 pnode->max_nunits = child->max_nunits;
2826 children.safe_push (pnode);
2827 oprnd_info->def_stmts = vNULL;
2828 continue;
2829 }
2830 else
2831 def_stmts2.release ();
2832 }
2833
2834 if ((child = vect_build_slp_tree (vinfo, oprnd_info->def_stmts,
2835 group_size, &this_max_nunits,
2836 matches, limit,
2837 &this_tree_size, bst_map)) != NULL)
2838 {
2839 oprnd_info->def_stmts = vNULL;
2840 children.safe_push (child);
2841 continue;
2842 }
2843
2844 /* If the SLP build for operand zero failed and operand zero
2845 and one can be commutated try that for the scalar stmts
2846 that failed the match. */
2847 if (i == 0
2848 /* A first scalar stmt mismatch signals a fatal mismatch. */
2849 && matches[0]
2850 /* ??? For COND_EXPRs we can swap the comparison operands
2851 as well as the arms under some constraints. */
2852 && nops == 2
2853 && oprnds_info[1]->first_dt == vect_internal_def
2854 && is_gimple_assign (stmt_info->stmt)
2855 /* Swapping operands for reductions breaks assumptions later on. */
2856 && STMT_VINFO_REDUC_IDX (stmt_info) == -1)
2857 {
2858 /* See whether we can swap the matching or the non-matching
2859 stmt operands. */
2860 bool swap_not_matching = true;
2861 do
2862 {
2863 for (j = 0; j < group_size; ++j)
2864 {
2865 if (matches[j] != !swap_not_matching)
2866 continue;
2867 stmt_vec_info stmt_info = stmts[j];
2868 /* Verify if we can swap operands of this stmt. */
2869 gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt);
2870 if (!stmt
2871 || !commutative_tree_code (gimple_assign_rhs_code (stmt)))
2872 {
2873 if (!swap_not_matching)
2874 goto fail;
2875 swap_not_matching = false;
2876 break;
2877 }
2878 }
2879 }
2880 while (j != group_size);
2881
2882 /* Swap mismatched definition stmts. */
2883 if (dump_enabled_p ())
2884 dump_printf_loc (MSG_NOTE, vect_location,
2885 "Re-trying with swapped operands of stmts ");
2886 for (j = 0; j < group_size; ++j)
2887 if (matches[j] == !swap_not_matching)
2888 {
2889 std::swap (oprnds_info[0]->def_stmts[j],
2890 oprnds_info[1]->def_stmts[j]);
2891 std::swap (oprnds_info[0]->ops[j],
2892 oprnds_info[1]->ops[j]);
2893 if (dump_enabled_p ())
2894 dump_printf (MSG_NOTE, "%d ", j);
2895 }
2896 if (dump_enabled_p ())
2897 dump_printf (MSG_NOTE, "\n");
2898 /* After swapping some operands we lost track whether an
2899 operand has any pattern defs so be conservative here. */
2900 if (oprnds_info[0]->any_pattern || oprnds_info[1]->any_pattern)
2901 oprnds_info[0]->any_pattern = oprnds_info[1]->any_pattern = true;
2902 /* And try again with scratch 'matches' ... */
2903 bool *tem = XALLOCAVEC (bool, group_size);
2904 if ((child = vect_build_slp_tree (vinfo, oprnd_info->def_stmts,
2905 group_size, &this_max_nunits,
2906 tem, limit,
2907 &this_tree_size, bst_map)) != NULL)
2908 {
2909 oprnd_info->def_stmts = vNULL;
2910 children.safe_push (child);
2911 continue;
2912 }
2913 }
2914 fail:
2915
2916 /* If the SLP build failed and we analyze a basic-block
2917 simply treat nodes we fail to build as externally defined
2918 (and thus build vectors from the scalar defs).
2919 The cost model will reject outright expensive cases.
2920 ??? This doesn't treat cases where permutation ultimatively
2921 fails (or we don't try permutation below). Ideally we'd
2922 even compute a permutation that will end up with the maximum
2923 SLP tree size... */
2924 if (is_a <bb_vec_info> (vinfo)
2925 /* ??? Rejecting patterns this way doesn't work. We'd have to
2926 do extra work to cancel the pattern so the uses see the
2927 scalar version. */
2928 && !is_pattern_stmt_p (stmt_info)
2929 && !oprnd_info->any_pattern)
2930 {
2931 /* But if there's a leading vector sized set of matching stmts
2932 fail here so we can split the group. This matches the condition
2933 vect_analyze_slp_instance uses. */
2934 /* ??? We might want to split here and combine the results to support
2935 multiple vector sizes better. */
2936 for (j = 0; j < group_size; ++j)
2937 if (!matches[j])
2938 break;
2939 if (!known_ge (j, TYPE_VECTOR_SUBPARTS (vectype))
2940 && vect_slp_can_convert_to_external (oprnd_info->def_stmts))
2941 {
2942 if (dump_enabled_p ())
2943 dump_printf_loc (MSG_NOTE, vect_location,
2944 "Building vector operands from scalars\n");
2945 this_tree_size++;
2946 child = vect_create_new_slp_node (oprnd_info->ops);
2947 children.safe_push (child);
2948 oprnd_info->ops = vNULL;
2949 continue;
2950 }
2951 }
2952
2953 gcc_assert (child == NULL);
2954 FOR_EACH_VEC_ELT (children, j, child)
2955 if (child)
2956 vect_free_slp_tree (child);
2957 vect_free_oprnd_info (oprnds_info);
2958 return NULL;
2959 }
2960
2961 vect_free_oprnd_info (oprnds_info);
2962
2963 /* If we have all children of a child built up from uniform scalars
2964 or does more than one possibly expensive vector construction then
2965 just throw that away, causing it built up from scalars.
2966 The exception is the SLP node for the vector store. */
2967 if (is_a <bb_vec_info> (vinfo)
2968 && !STMT_VINFO_GROUPED_ACCESS (stmt_info)
2969 /* ??? Rejecting patterns this way doesn't work. We'd have to
2970 do extra work to cancel the pattern so the uses see the
2971 scalar version. */
2972 && !is_pattern_stmt_p (stmt_info))
2973 {
2974 slp_tree child;
2975 unsigned j;
2976 bool all_uniform_p = true;
2977 unsigned n_vector_builds = 0;
2978 FOR_EACH_VEC_ELT (children, j, child)
2979 {
2980 if (!child)
2981 ;
2982 else if (SLP_TREE_DEF_TYPE (child) == vect_internal_def)
2983 all_uniform_p = false;
2984 else if (!vect_slp_tree_uniform_p (child))
2985 {
2986 all_uniform_p = false;
2987 if (SLP_TREE_DEF_TYPE (child) == vect_external_def)
2988 n_vector_builds++;
2989 }
2990 }
2991 if (all_uniform_p
2992 || n_vector_builds > 1
2993 || (n_vector_builds == children.length ()
2994 && is_a <gphi *> (stmt_info->stmt)))
2995 {
2996 /* Roll back. */
2997 matches[0] = false;
2998 FOR_EACH_VEC_ELT (children, j, child)
2999 if (child)
3000 vect_free_slp_tree (child);
3001
3002 if (dump_enabled_p ())
3003 dump_printf_loc (MSG_NOTE, vect_location,
3004 "Building parent vector operands from "
3005 "scalars instead\n");
3006 return NULL;
3007 }
3008 }
3009
3010 *tree_size += this_tree_size + 1;
3011 *max_nunits = this_max_nunits;
3012
3013 if (two_operators)
3014 {
3015 /* ??? We'd likely want to either cache in bst_map sth like
3016 { a+b, NULL, a+b, NULL } and { NULL, a-b, NULL, a-b } or
3017 the true { a+b, a+b, a+b, a+b } ... but there we don't have
3018 explicit stmts to put in so the keying on 'stmts' doesn't
3019 work (but we have the same issue with nodes that use 'ops'). */
3020
3021 if (has_two_operators_perm)
3022 {
3023 slp_tree child = children[0];
3024 children.truncate (0);
3025 for (i = 0; i < 2; i++)
3026 {
3027 slp_tree pnode
3028 = vect_create_new_slp_node (two_op_scalar_stmts[i], 2);
3029 SLP_TREE_CODE (pnode) = VEC_PERM_EXPR;
3030 SLP_TREE_VECTYPE (pnode) = vectype;
3031 SLP_TREE_CHILDREN (pnode).quick_push (child);
3032 SLP_TREE_CHILDREN (pnode).quick_push (child);
3033 lane_permutation_t& perm = SLP_TREE_LANE_PERMUTATION (pnode);
3034 children.safe_push (pnode);
3035
3036 for (unsigned j = 0; j < stmts.length (); j++)
3037 perm.safe_push (std::make_pair (0, two_op_perm_indices[i][j]));
3038 }
3039
3040 SLP_TREE_REF_COUNT (child) += 4;
3041 }
3042
3043 slp_tree one = new _slp_tree;
3044 slp_tree two = new _slp_tree;
3045 SLP_TREE_DEF_TYPE (one) = vect_internal_def;
3046 SLP_TREE_DEF_TYPE (two) = vect_internal_def;
3047 SLP_TREE_VECTYPE (one) = vectype;
3048 SLP_TREE_VECTYPE (two) = vectype;
3049 SLP_TREE_CHILDREN (one).safe_splice (children);
3050 SLP_TREE_CHILDREN (two).safe_splice (children);
3051 slp_tree child;
3052 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (two), i, child)
3053 SLP_TREE_REF_COUNT (child)++;
3054
3055 /* Here we record the original defs since this
3056 node represents the final lane configuration. */
3057 node = vect_create_new_slp_node (node, stmts, 2);
3058 SLP_TREE_VECTYPE (node) = vectype;
3059 SLP_TREE_CODE (node) = VEC_PERM_EXPR;
3060 SLP_TREE_CHILDREN (node).quick_push (one);
3061 SLP_TREE_CHILDREN (node).quick_push (two);
3062 gassign *stmt = as_a <gassign *> (stmts[0]->stmt);
3063 enum tree_code code0 = gimple_assign_rhs_code (stmt);
3064 enum tree_code ocode = ERROR_MARK;
3065 stmt_vec_info ostmt_info;
3066 unsigned j = 0;
3067 FOR_EACH_VEC_ELT (stmts, i, ostmt_info)
3068 {
3069 gassign *ostmt = as_a <gassign *> (ostmt_info->stmt);
3070 if (gimple_assign_rhs_code (ostmt) != code0)
3071 {
3072 SLP_TREE_LANE_PERMUTATION (node).safe_push (std::make_pair (1, i));
3073 ocode = gimple_assign_rhs_code (ostmt);
3074 j = i;
3075 }
3076 else
3077 SLP_TREE_LANE_PERMUTATION (node).safe_push (std::make_pair (0, i));
3078 }
3079
3080 SLP_TREE_CODE (one) = code0;
3081 SLP_TREE_CODE (two) = ocode;
3082 SLP_TREE_LANES (one) = stmts.length ();
3083 SLP_TREE_LANES (two) = stmts.length ();
3084 SLP_TREE_REPRESENTATIVE (one) = stmts[0];
3085 SLP_TREE_REPRESENTATIVE (two) = stmts[j];
3086
3087 return node;
3088 }
3089
3090 node = vect_create_new_slp_node (node, stmts, nops);
3091 SLP_TREE_VECTYPE (node) = vectype;
3092 SLP_TREE_CHILDREN (node).splice (children);
3093 return node;
3094 }
3095
3096 /* Dump a single SLP tree NODE. */
3097
3098 static void
3099 vect_print_slp_tree (dump_flags_t dump_kind, dump_location_t loc,
3100 slp_tree node)
3101 {
3102 unsigned i, j;
3103 slp_tree child;
3104 stmt_vec_info stmt_info;
3105 tree op;
3106
3107 dump_metadata_t metadata (dump_kind, loc.get_impl_location ());
3108 dump_user_location_t user_loc = loc.get_user_location ();
3109 dump_printf_loc (metadata, user_loc,
3110 "node%s %p (max_nunits=" HOST_WIDE_INT_PRINT_UNSIGNED
3111 ", refcnt=%u)",
3112 SLP_TREE_DEF_TYPE (node) == vect_external_def
3113 ? " (external)"
3114 : (SLP_TREE_DEF_TYPE (node) == vect_constant_def
3115 ? " (constant)"
3116 : ""), (void *) node,
3117 estimated_poly_value (node->max_nunits),
3118 SLP_TREE_REF_COUNT (node));
3119 if (SLP_TREE_VECTYPE (node))
3120 dump_printf (metadata, " %T", SLP_TREE_VECTYPE (node));
3121 dump_printf (metadata, "\n");
3122 if (SLP_TREE_DEF_TYPE (node) == vect_internal_def)
3123 {
3124 if (SLP_TREE_CODE (node) == VEC_PERM_EXPR)
3125 dump_printf_loc (metadata, user_loc, "op: VEC_PERM_EXPR\n");
3126 else
3127 dump_printf_loc (metadata, user_loc, "op template: %G",
3128 SLP_TREE_REPRESENTATIVE (node)->stmt);
3129 }
3130 if (SLP_TREE_SCALAR_STMTS (node).exists ())
3131 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
3132 if (stmt_info)
3133 dump_printf_loc (metadata, user_loc, "\t%sstmt %u %G",
3134 STMT_VINFO_LIVE_P (stmt_info) ? "[l] " : "",
3135 i, stmt_info->stmt);
3136 else
3137 dump_printf_loc (metadata, user_loc, "\tstmt %u ---\n", i);
3138 else
3139 {
3140 dump_printf_loc (metadata, user_loc, "\t{ ");
3141 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_OPS (node), i, op)
3142 dump_printf (metadata, "%T%s ", op,
3143 i < SLP_TREE_SCALAR_OPS (node).length () - 1 ? "," : "");
3144 dump_printf (metadata, "}\n");
3145 }
3146 if (SLP_TREE_LOAD_PERMUTATION (node).exists ())
3147 {
3148 dump_printf_loc (metadata, user_loc, "\tload permutation {");
3149 FOR_EACH_VEC_ELT (SLP_TREE_LOAD_PERMUTATION (node), i, j)
3150 dump_printf (dump_kind, " %u", j);
3151 dump_printf (dump_kind, " }\n");
3152 }
3153 if (SLP_TREE_LANE_PERMUTATION (node).exists ())
3154 {
3155 dump_printf_loc (metadata, user_loc, "\tlane permutation {");
3156 for (i = 0; i < SLP_TREE_LANE_PERMUTATION (node).length (); ++i)
3157 dump_printf (dump_kind, " %u[%u]",
3158 SLP_TREE_LANE_PERMUTATION (node)[i].first,
3159 SLP_TREE_LANE_PERMUTATION (node)[i].second);
3160 dump_printf (dump_kind, " }%s\n",
3161 node->ldst_lanes ? " (load-lanes)" : "");
3162 }
3163 if (SLP_TREE_CHILDREN (node).is_empty ())
3164 return;
3165 dump_printf_loc (metadata, user_loc, "\tchildren");
3166 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
3167 dump_printf (dump_kind, " %p", (void *)child);
3168 dump_printf (dump_kind, "%s\n",
3169 node->ldst_lanes && !SLP_TREE_LANE_PERMUTATION (node).exists ()
3170 ? " (store-lanes)" : "");
3171 }
3172
3173 DEBUG_FUNCTION void
3174 debug (slp_tree node)
3175 {
3176 debug_dump_context ctx;
3177 vect_print_slp_tree (MSG_NOTE,
3178 dump_location_t::from_location_t (UNKNOWN_LOCATION),
3179 node);
3180 }
3181
3182 /* Recursive helper for the dot producer below. */
3183
3184 static void
3185 dot_slp_tree (FILE *f, slp_tree node, hash_set<slp_tree> &visited)
3186 {
3187 if (visited.add (node))
3188 return;
3189
3190 fprintf (f, "\"%p\" [label=\"", (void *)node);
3191 vect_print_slp_tree (MSG_NOTE,
3192 dump_location_t::from_location_t (UNKNOWN_LOCATION),
3193 node);
3194 fprintf (f, "\"];\n");
3195
3196
3197 for (slp_tree child : SLP_TREE_CHILDREN (node))
3198 fprintf (f, "\"%p\" -> \"%p\";", (void *)node, (void *)child);
3199
3200 for (slp_tree child : SLP_TREE_CHILDREN (node))
3201 if (child)
3202 dot_slp_tree (f, child, visited);
3203 }
3204
3205 DEBUG_FUNCTION void
3206 dot_slp_tree (const char *fname, slp_tree node)
3207 {
3208 FILE *f = fopen (fname, "w");
3209 fprintf (f, "digraph {\n");
3210 fflush (f);
3211 {
3212 debug_dump_context ctx (f);
3213 hash_set<slp_tree> visited;
3214 dot_slp_tree (f, node, visited);
3215 }
3216 fflush (f);
3217 fprintf (f, "}\n");
3218 fclose (f);
3219 }
3220
3221 DEBUG_FUNCTION void
3222 dot_slp_tree (const char *fname, const vec<slp_instance> &slp_instances)
3223 {
3224 FILE *f = fopen (fname, "w");
3225 fprintf (f, "digraph {\n");
3226 fflush (f);
3227 {
3228 debug_dump_context ctx (f);
3229 hash_set<slp_tree> visited;
3230 for (auto inst : slp_instances)
3231 dot_slp_tree (f, SLP_INSTANCE_TREE (inst), visited);
3232 }
3233 fflush (f);
3234 fprintf (f, "}\n");
3235 fclose (f);
3236 }
3237
3238 /* Dump a slp tree NODE using flags specified in DUMP_KIND. */
3239
3240 static void
3241 vect_print_slp_graph (dump_flags_t dump_kind, dump_location_t loc,
3242 slp_tree node, hash_set<slp_tree> &visited)
3243 {
3244 unsigned i;
3245 slp_tree child;
3246
3247 if (visited.add (node))
3248 return;
3249
3250 vect_print_slp_tree (dump_kind, loc, node);
3251
3252 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
3253 if (child)
3254 vect_print_slp_graph (dump_kind, loc, child, visited);
3255 }
3256
3257 static void
3258 vect_print_slp_graph (dump_flags_t dump_kind, dump_location_t loc,
3259 slp_tree entry)
3260 {
3261 hash_set<slp_tree> visited;
3262 vect_print_slp_graph (dump_kind, loc, entry, visited);
3263 }
3264
3265 DEBUG_FUNCTION void
3266 debug (slp_instance instance)
3267 {
3268 debug_dump_context ctx;
3269 vect_print_slp_graph (MSG_NOTE,
3270 dump_location_t::from_location_t (UNKNOWN_LOCATION),
3271 SLP_INSTANCE_TREE (instance));
3272 }
3273
3274 /* Mark the tree rooted at NODE with PURE_SLP. */
3275
3276 static void
3277 vect_mark_slp_stmts (vec_info *vinfo, slp_tree node,
3278 hash_set<slp_tree> &visited)
3279 {
3280 int i;
3281 stmt_vec_info stmt_info;
3282 slp_tree child;
3283
3284 if (SLP_TREE_DEF_TYPE (node) != vect_internal_def)
3285 return;
3286
3287 if (visited.add (node))
3288 return;
3289
3290 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
3291 if (stmt_info)
3292 {
3293 STMT_SLP_TYPE (stmt_info) = pure_slp;
3294 /* ??? For .MASK_LOAD and .MASK_STORE detected as load/store-lanes
3295 when there is the mask_conversion pattern applied we have lost the
3296 alternate lanes of the uniform mask which nevertheless
3297 have separate pattern defs. To not confuse hybrid
3298 analysis we mark those as covered as well here. */
3299 if (node->ldst_lanes)
3300 if (gcall *call = dyn_cast <gcall *> (stmt_info->stmt))
3301 if (gimple_call_internal_p (call, IFN_MASK_LOAD)
3302 || gimple_call_internal_p (call, IFN_MASK_STORE))
3303 {
3304 tree mask = gimple_call_arg (call,
3305 internal_fn_mask_index
3306 (gimple_call_internal_fn (call)));
3307 if (TREE_CODE (mask) == SSA_NAME)
3308 if (stmt_vec_info mask_info = vinfo->lookup_def (mask))
3309 {
3310 mask_info = vect_stmt_to_vectorize (mask_info);
3311 STMT_SLP_TYPE (mask_info) = pure_slp;
3312 }
3313 }
3314 }
3315
3316 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
3317 if (child)
3318 vect_mark_slp_stmts (vinfo, child, visited);
3319 }
3320
3321 static void
3322 vect_mark_slp_stmts (vec_info *vinfo, slp_tree node)
3323 {
3324 hash_set<slp_tree> visited;
3325 vect_mark_slp_stmts (vinfo, node, visited);
3326 }
3327
3328 /* Mark the statements of the tree rooted at NODE as relevant (vect_used). */
3329
3330 static void
3331 vect_mark_slp_stmts_relevant (slp_tree node, hash_set<slp_tree> &visited)
3332 {
3333 int i;
3334 stmt_vec_info stmt_info;
3335 slp_tree child;
3336
3337 if (SLP_TREE_DEF_TYPE (node) != vect_internal_def)
3338 return;
3339
3340 if (visited.add (node))
3341 return;
3342
3343 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
3344 if (stmt_info)
3345 {
3346 gcc_assert (!STMT_VINFO_RELEVANT (stmt_info)
3347 || STMT_VINFO_RELEVANT (stmt_info) == vect_used_in_scope);
3348 STMT_VINFO_RELEVANT (stmt_info) = vect_used_in_scope;
3349 }
3350
3351 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
3352 if (child)
3353 vect_mark_slp_stmts_relevant (child, visited);
3354 }
3355
3356 static void
3357 vect_mark_slp_stmts_relevant (slp_tree node)
3358 {
3359 hash_set<slp_tree> visited;
3360 vect_mark_slp_stmts_relevant (node, visited);
3361 }
3362
3363
3364 /* Gather loads in the SLP graph NODE and populate the INST loads array. */
3365
3366 static void
3367 vect_gather_slp_loads (vec<slp_tree> &loads, slp_tree node,
3368 hash_set<slp_tree> &visited)
3369 {
3370 if (!node || visited.add (node))
3371 return;
3372
3373 if (SLP_TREE_DEF_TYPE (node) != vect_internal_def)
3374 return;
3375
3376 if (SLP_TREE_CODE (node) != VEC_PERM_EXPR)
3377 {
3378 stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (node);
3379 if (STMT_VINFO_DATA_REF (stmt_info)
3380 && DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)))
3381 loads.safe_push (node);
3382 }
3383
3384 unsigned i;
3385 slp_tree child;
3386 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
3387 vect_gather_slp_loads (loads, child, visited);
3388 }
3389
3390
3391 /* Find the last store in SLP INSTANCE. */
3392
3393 stmt_vec_info
3394 vect_find_last_scalar_stmt_in_slp (slp_tree node)
3395 {
3396 stmt_vec_info last = NULL;
3397 stmt_vec_info stmt_vinfo;
3398
3399 for (int i = 0; SLP_TREE_SCALAR_STMTS (node).iterate (i, &stmt_vinfo); i++)
3400 if (stmt_vinfo)
3401 {
3402 stmt_vinfo = vect_orig_stmt (stmt_vinfo);
3403 last = last ? get_later_stmt (stmt_vinfo, last) : stmt_vinfo;
3404 }
3405
3406 return last;
3407 }
3408
3409 /* Find the first stmt in NODE. */
3410
3411 stmt_vec_info
3412 vect_find_first_scalar_stmt_in_slp (slp_tree node)
3413 {
3414 stmt_vec_info first = NULL;
3415 stmt_vec_info stmt_vinfo;
3416
3417 for (int i = 0; SLP_TREE_SCALAR_STMTS (node).iterate (i, &stmt_vinfo); i++)
3418 if (stmt_vinfo)
3419 {
3420 stmt_vinfo = vect_orig_stmt (stmt_vinfo);
3421 if (!first
3422 || get_later_stmt (stmt_vinfo, first) == first)
3423 first = stmt_vinfo;
3424 }
3425
3426 return first;
3427 }
3428
3429 /* Splits a group of stores, currently beginning at FIRST_VINFO, into
3430 two groups: one (still beginning at FIRST_VINFO) of size GROUP1_SIZE
3431 (also containing the first GROUP1_SIZE stmts, since stores are
3432 consecutive), the second containing the remainder.
3433 Return the first stmt in the second group. */
3434
3435 static stmt_vec_info
3436 vect_split_slp_store_group (stmt_vec_info first_vinfo, unsigned group1_size)
3437 {
3438 gcc_assert (DR_GROUP_FIRST_ELEMENT (first_vinfo) == first_vinfo);
3439 gcc_assert (group1_size > 0);
3440 int group2_size = DR_GROUP_SIZE (first_vinfo) - group1_size;
3441 gcc_assert (group2_size > 0);
3442 DR_GROUP_SIZE (first_vinfo) = group1_size;
3443
3444 stmt_vec_info stmt_info = first_vinfo;
3445 for (unsigned i = group1_size; i > 1; i--)
3446 {
3447 stmt_info = DR_GROUP_NEXT_ELEMENT (stmt_info);
3448 gcc_assert (DR_GROUP_GAP (stmt_info) == 1);
3449 }
3450 /* STMT is now the last element of the first group. */
3451 stmt_vec_info group2 = DR_GROUP_NEXT_ELEMENT (stmt_info);
3452 DR_GROUP_NEXT_ELEMENT (stmt_info) = 0;
3453
3454 DR_GROUP_SIZE (group2) = group2_size;
3455 for (stmt_info = group2; stmt_info;
3456 stmt_info = DR_GROUP_NEXT_ELEMENT (stmt_info))
3457 {
3458 DR_GROUP_FIRST_ELEMENT (stmt_info) = group2;
3459 gcc_assert (DR_GROUP_GAP (stmt_info) == 1);
3460 }
3461
3462 /* For the second group, the DR_GROUP_GAP is that before the original group,
3463 plus skipping over the first vector. */
3464 DR_GROUP_GAP (group2) = DR_GROUP_GAP (first_vinfo) + group1_size;
3465
3466 /* DR_GROUP_GAP of the first group now has to skip over the second group too. */
3467 DR_GROUP_GAP (first_vinfo) += group2_size;
3468
3469 if (dump_enabled_p ())
3470 dump_printf_loc (MSG_NOTE, vect_location, "Split group into %d and %d\n",
3471 group1_size, group2_size);
3472
3473 return group2;
3474 }
3475
3476 /* Calculate the unrolling factor for an SLP instance with GROUP_SIZE
3477 statements and a vector of NUNITS elements. */
3478
3479 static poly_uint64
3480 calculate_unrolling_factor (poly_uint64 nunits, unsigned int group_size)
3481 {
3482 return exact_div (common_multiple (nunits, group_size), group_size);
3483 }
3484
3485 /* Helper that checks to see if a node is a load node. */
3486
3487 static inline bool
3488 vect_is_slp_load_node (slp_tree root)
3489 {
3490 return (SLP_TREE_CODE (root) != VEC_PERM_EXPR
3491 && SLP_TREE_DEF_TYPE (root) == vect_internal_def
3492 && STMT_VINFO_GROUPED_ACCESS (SLP_TREE_REPRESENTATIVE (root))
3493 && DR_IS_READ (STMT_VINFO_DATA_REF (SLP_TREE_REPRESENTATIVE (root))));
3494 }
3495
3496
3497 /* Helper function of optimize_load_redistribution that performs the operation
3498 recursively. */
3499
3500 static slp_tree
3501 optimize_load_redistribution_1 (scalar_stmts_to_slp_tree_map_t *bst_map,
3502 vec_info *vinfo, unsigned int group_size,
3503 hash_map<slp_tree, slp_tree> *load_map,
3504 slp_tree root)
3505 {
3506 if (slp_tree *leader = load_map->get (root))
3507 return *leader;
3508
3509 slp_tree node;
3510 unsigned i;
3511
3512 /* For now, we don't know anything about externals so do not do anything. */
3513 if (!root || SLP_TREE_DEF_TYPE (root) != vect_internal_def)
3514 return NULL;
3515 else if (SLP_TREE_CODE (root) == VEC_PERM_EXPR)
3516 {
3517 /* First convert this node into a load node and add it to the leaves
3518 list and flatten the permute from a lane to a load one. If it's
3519 unneeded it will be elided later. */
3520 vec<stmt_vec_info> stmts;
3521 stmts.create (SLP_TREE_LANES (root));
3522 lane_permutation_t lane_perm = SLP_TREE_LANE_PERMUTATION (root);
3523 for (unsigned j = 0; j < lane_perm.length (); j++)
3524 {
3525 std::pair<unsigned, unsigned> perm = lane_perm[j];
3526 node = SLP_TREE_CHILDREN (root)[perm.first];
3527
3528 if (!vect_is_slp_load_node (node)
3529 || SLP_TREE_CHILDREN (node).exists ())
3530 {
3531 stmts.release ();
3532 goto next;
3533 }
3534
3535 stmts.quick_push (SLP_TREE_SCALAR_STMTS (node)[perm.second]);
3536 }
3537
3538 if (dump_enabled_p ())
3539 dump_printf_loc (MSG_NOTE, vect_location,
3540 "converting stmts on permute node %p\n",
3541 (void *) root);
3542
3543 bool *matches = XALLOCAVEC (bool, group_size);
3544 poly_uint64 max_nunits = 1;
3545 unsigned tree_size = 0, limit = 1;
3546 node = vect_build_slp_tree (vinfo, stmts, group_size, &max_nunits,
3547 matches, &limit, &tree_size, bst_map);
3548 if (!node)
3549 stmts.release ();
3550
3551 load_map->put (root, node);
3552 return node;
3553 }
3554
3555 next:
3556 load_map->put (root, NULL);
3557
3558 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (root), i , node)
3559 {
3560 slp_tree value
3561 = optimize_load_redistribution_1 (bst_map, vinfo, group_size, load_map,
3562 node);
3563 if (value)
3564 {
3565 SLP_TREE_REF_COUNT (value)++;
3566 SLP_TREE_CHILDREN (root)[i] = value;
3567 /* ??? We know the original leafs of the replaced nodes will
3568 be referenced by bst_map, only the permutes created by
3569 pattern matching are not. */
3570 if (SLP_TREE_REF_COUNT (node) == 1)
3571 load_map->remove (node);
3572 vect_free_slp_tree (node);
3573 }
3574 }
3575
3576 return NULL;
3577 }
3578
3579 /* Temporary workaround for loads not being CSEd during SLP build. This
3580 function will traverse the SLP tree rooted in ROOT for INSTANCE and find
3581 VEC_PERM nodes that blend vectors from multiple nodes that all read from the
3582 same DR such that the final operation is equal to a permuted load. Such
3583 NODES are then directly converted into LOADS themselves. The nodes are
3584 CSEd using BST_MAP. */
3585
3586 static void
3587 optimize_load_redistribution (scalar_stmts_to_slp_tree_map_t *bst_map,
3588 vec_info *vinfo, unsigned int group_size,
3589 hash_map<slp_tree, slp_tree> *load_map,
3590 slp_tree root)
3591 {
3592 slp_tree node;
3593 unsigned i;
3594
3595 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (root), i , node)
3596 {
3597 slp_tree value
3598 = optimize_load_redistribution_1 (bst_map, vinfo, group_size, load_map,
3599 node);
3600 if (value)
3601 {
3602 SLP_TREE_REF_COUNT (value)++;
3603 SLP_TREE_CHILDREN (root)[i] = value;
3604 /* ??? We know the original leafs of the replaced nodes will
3605 be referenced by bst_map, only the permutes created by
3606 pattern matching are not. */
3607 if (SLP_TREE_REF_COUNT (node) == 1)
3608 load_map->remove (node);
3609 vect_free_slp_tree (node);
3610 }
3611 }
3612 }
3613
3614 /* Helper function of vect_match_slp_patterns.
3615
3616 Attempts to match patterns against the slp tree rooted in REF_NODE using
3617 VINFO. Patterns are matched in post-order traversal.
3618
3619 If matching is successful the value in REF_NODE is updated and returned, if
3620 not then it is returned unchanged. */
3621
3622 static bool
3623 vect_match_slp_patterns_2 (slp_tree *ref_node, vec_info *vinfo,
3624 slp_tree_to_load_perm_map_t *perm_cache,
3625 slp_compat_nodes_map_t *compat_cache,
3626 hash_set<slp_tree> *visited)
3627 {
3628 unsigned i;
3629 slp_tree node = *ref_node;
3630 bool found_p = false;
3631 if (!node || visited->add (node))
3632 return false;
3633
3634 slp_tree child;
3635 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
3636 found_p |= vect_match_slp_patterns_2 (&SLP_TREE_CHILDREN (node)[i],
3637 vinfo, perm_cache, compat_cache,
3638 visited);
3639
3640 for (unsigned x = 0; x < num__slp_patterns; x++)
3641 {
3642 vect_pattern *pattern
3643 = slp_patterns[x] (perm_cache, compat_cache, ref_node);
3644 if (pattern)
3645 {
3646 pattern->build (vinfo);
3647 delete pattern;
3648 found_p = true;
3649 }
3650 }
3651
3652 return found_p;
3653 }
3654
3655 /* Applies pattern matching to the given SLP tree rooted in REF_NODE using
3656 vec_info VINFO.
3657
3658 The modified tree is returned. Patterns are tried in order and multiple
3659 patterns may match. */
3660
3661 static bool
3662 vect_match_slp_patterns (slp_instance instance, vec_info *vinfo,
3663 hash_set<slp_tree> *visited,
3664 slp_tree_to_load_perm_map_t *perm_cache,
3665 slp_compat_nodes_map_t *compat_cache)
3666 {
3667 DUMP_VECT_SCOPE ("vect_match_slp_patterns");
3668 slp_tree *ref_node = &SLP_INSTANCE_TREE (instance);
3669
3670 if (dump_enabled_p ())
3671 dump_printf_loc (MSG_NOTE, vect_location,
3672 "Analyzing SLP tree %p for patterns\n",
3673 (void *) SLP_INSTANCE_TREE (instance));
3674
3675 return vect_match_slp_patterns_2 (ref_node, vinfo, perm_cache, compat_cache,
3676 visited);
3677 }
3678
3679 /* STMT_INFO is a store group of size GROUP_SIZE that we are considering
3680 vectorizing with VECTYPE that might be NULL. MASKED_P indicates whether
3681 the stores are masked.
3682 Return true if we could use IFN_STORE_LANES instead and if that appears
3683 to be the better approach. */
3684
3685 static bool
3686 vect_slp_prefer_store_lanes_p (vec_info *vinfo, stmt_vec_info stmt_info,
3687 tree vectype, bool masked_p,
3688 unsigned int group_size,
3689 unsigned int new_group_size)
3690 {
3691 if (!vectype)
3692 {
3693 tree scalar_type = TREE_TYPE (DR_REF (STMT_VINFO_DATA_REF (stmt_info)));
3694 vectype = get_vectype_for_scalar_type (vinfo, scalar_type);
3695 }
3696 if (!vectype)
3697 return false;
3698 /* Allow the split if one of the two new groups would operate on full
3699 vectors *within* rather than across one scalar loop iteration.
3700 This is purely a heuristic, but it should work well for group
3701 sizes of 3 and 4, where the possible splits are:
3702
3703 3->2+1: OK if the vector has exactly two elements
3704 4->2+2: Likewise
3705 4->3+1: Less clear-cut. */
3706 if (multiple_p (group_size - new_group_size, TYPE_VECTOR_SUBPARTS (vectype))
3707 || multiple_p (new_group_size, TYPE_VECTOR_SUBPARTS (vectype)))
3708 return false;
3709 return vect_store_lanes_supported (vectype, group_size, masked_p) != IFN_LAST;
3710 }
3711
3712 /* Analyze an SLP instance starting from a group of grouped stores. Call
3713 vect_build_slp_tree to build a tree of packed stmts if possible.
3714 Return FALSE if it's impossible to SLP any stmt in the loop. */
3715
3716 static bool
3717 vect_analyze_slp_instance (vec_info *vinfo,
3718 scalar_stmts_to_slp_tree_map_t *bst_map,
3719 stmt_vec_info stmt_info, slp_instance_kind kind,
3720 unsigned max_tree_size, unsigned *limit,
3721 bool force_single_lane);
3722
3723 /* Build an interleaving scheme for the store sources RHS_NODES from
3724 SCALAR_STMTS. */
3725
3726 static slp_tree
3727 vect_build_slp_store_interleaving (vec<slp_tree> &rhs_nodes,
3728 vec<stmt_vec_info> &scalar_stmts,
3729 poly_uint64 max_nunits)
3730 {
3731 unsigned int group_size = scalar_stmts.length ();
3732 slp_tree node = vect_create_new_slp_node (scalar_stmts,
3733 SLP_TREE_CHILDREN
3734 (rhs_nodes[0]).length ());
3735 SLP_TREE_VECTYPE (node) = SLP_TREE_VECTYPE (rhs_nodes[0]);
3736 node->max_nunits = max_nunits;
3737 for (unsigned l = 0;
3738 l < SLP_TREE_CHILDREN (rhs_nodes[0]).length (); ++l)
3739 {
3740 /* And a permute merging all RHS SLP trees. */
3741 slp_tree perm = vect_create_new_slp_node (rhs_nodes.length (),
3742 VEC_PERM_EXPR);
3743 SLP_TREE_CHILDREN (node).quick_push (perm);
3744 SLP_TREE_LANE_PERMUTATION (perm).create (group_size);
3745 SLP_TREE_VECTYPE (perm) = SLP_TREE_VECTYPE (node);
3746 perm->max_nunits = max_nunits;
3747 SLP_TREE_LANES (perm) = group_size;
3748 /* ??? We should set this NULL but that's not expected. */
3749 SLP_TREE_REPRESENTATIVE (perm)
3750 = SLP_TREE_REPRESENTATIVE (SLP_TREE_CHILDREN (rhs_nodes[0])[l]);
3751 for (unsigned j = 0; j < rhs_nodes.length (); ++j)
3752 {
3753 SLP_TREE_CHILDREN (perm)
3754 .quick_push (SLP_TREE_CHILDREN (rhs_nodes[j])[l]);
3755 SLP_TREE_CHILDREN (rhs_nodes[j])[l]->refcnt++;
3756 for (unsigned k = 0;
3757 k < SLP_TREE_SCALAR_STMTS (rhs_nodes[j]).length (); ++k)
3758 {
3759 /* ??? We should populate SLP_TREE_SCALAR_STMTS
3760 or SLP_TREE_SCALAR_OPS but then we might have
3761 a mix of both in our children. */
3762 SLP_TREE_LANE_PERMUTATION (perm)
3763 .quick_push (std::make_pair (j, k));
3764 }
3765 }
3766
3767 /* Now we have a single permute node but we cannot code-generate
3768 the case with more than two inputs.
3769 Perform pairwise reduction, reducing the two inputs
3770 with the least number of lanes to one and then repeat until
3771 we end up with two inputs. That scheme makes sure we end
3772 up with permutes satisfying the restriction of requiring at
3773 most two vector inputs to produce a single vector output
3774 when the number of lanes is even. */
3775 while (SLP_TREE_CHILDREN (perm).length () > 2)
3776 {
3777 /* When we have three equal sized groups left the pairwise
3778 reduction does not result in a scheme that avoids using
3779 three vectors. Instead merge the first two groups
3780 to the final size with do-not-care elements (chosen
3781 from the first group) and then merge with the third.
3782 { A0, B0, x, A1, B1, x, ... }
3783 -> { A0, B0, C0, A1, B1, C1, ... }
3784 This handles group size of three (and at least
3785 power-of-two multiples of that). */
3786 if (SLP_TREE_CHILDREN (perm).length () == 3
3787 && (SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[0])
3788 == SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[1]))
3789 && (SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[0])
3790 == SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[2])))
3791 {
3792 int ai = 0;
3793 int bi = 1;
3794 slp_tree a = SLP_TREE_CHILDREN (perm)[ai];
3795 slp_tree b = SLP_TREE_CHILDREN (perm)[bi];
3796 unsigned n = SLP_TREE_LANES (perm);
3797
3798 slp_tree permab = vect_create_new_slp_node (2, VEC_PERM_EXPR);
3799 SLP_TREE_LANES (permab) = n;
3800 SLP_TREE_LANE_PERMUTATION (permab).create (n);
3801 SLP_TREE_VECTYPE (permab) = SLP_TREE_VECTYPE (perm);
3802 permab->max_nunits = max_nunits;
3803 /* ??? Should be NULL but that's not expected. */
3804 SLP_TREE_REPRESENTATIVE (permab) = SLP_TREE_REPRESENTATIVE (perm);
3805 SLP_TREE_CHILDREN (permab).quick_push (a);
3806 for (unsigned k = 0; k < SLP_TREE_LANES (a); ++k)
3807 SLP_TREE_LANE_PERMUTATION (permab)
3808 .quick_push (std::make_pair (0, k));
3809 SLP_TREE_CHILDREN (permab).quick_push (b);
3810 for (unsigned k = 0; k < SLP_TREE_LANES (b); ++k)
3811 SLP_TREE_LANE_PERMUTATION (permab)
3812 .quick_push (std::make_pair (1, k));
3813 /* Push the do-not-care lanes. */
3814 for (unsigned k = 0; k < SLP_TREE_LANES (a); ++k)
3815 SLP_TREE_LANE_PERMUTATION (permab)
3816 .quick_push (std::make_pair (0, k));
3817
3818 /* Put the merged node into 'perm', in place of a. */
3819 SLP_TREE_CHILDREN (perm)[ai] = permab;
3820 /* Adjust the references to b in the permutation
3821 of perm and to the later children which we'll
3822 remove. */
3823 for (unsigned k = 0; k < SLP_TREE_LANES (perm); ++k)
3824 {
3825 std::pair<unsigned, unsigned> &p
3826 = SLP_TREE_LANE_PERMUTATION (perm)[k];
3827 if (p.first == (unsigned) bi)
3828 {
3829 p.first = ai;
3830 p.second += SLP_TREE_LANES (a);
3831 }
3832 else if (p.first > (unsigned) bi)
3833 p.first--;
3834 }
3835 SLP_TREE_CHILDREN (perm).ordered_remove (bi);
3836 break;
3837 }
3838
3839 /* Pick the two nodes with the least number of lanes,
3840 prefer the earliest candidate and maintain ai < bi. */
3841 int ai = -1;
3842 int bi = -1;
3843 for (unsigned ci = 0; ci < SLP_TREE_CHILDREN (perm).length (); ++ci)
3844 {
3845 if (ai == -1)
3846 ai = ci;
3847 else if (bi == -1)
3848 bi = ci;
3849 else if ((SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[ci])
3850 < SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[ai]))
3851 || (SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[ci])
3852 < SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[bi])))
3853 {
3854 if (SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[ai])
3855 <= SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[bi]))
3856 bi = ci;
3857 else
3858 {
3859 ai = bi;
3860 bi = ci;
3861 }
3862 }
3863 }
3864
3865 /* Produce a merge of nodes ai and bi. */
3866 slp_tree a = SLP_TREE_CHILDREN (perm)[ai];
3867 slp_tree b = SLP_TREE_CHILDREN (perm)[bi];
3868 unsigned n = SLP_TREE_LANES (a) + SLP_TREE_LANES (b);
3869 slp_tree permab = vect_create_new_slp_node (2, VEC_PERM_EXPR);
3870 SLP_TREE_LANES (permab) = n;
3871 SLP_TREE_LANE_PERMUTATION (permab).create (n);
3872 SLP_TREE_VECTYPE (permab) = SLP_TREE_VECTYPE (perm);
3873 permab->max_nunits = max_nunits;
3874 /* ??? Should be NULL but that's not expected. */
3875 SLP_TREE_REPRESENTATIVE (permab) = SLP_TREE_REPRESENTATIVE (perm);
3876 SLP_TREE_CHILDREN (permab).quick_push (a);
3877 for (unsigned k = 0; k < SLP_TREE_LANES (a); ++k)
3878 SLP_TREE_LANE_PERMUTATION (permab)
3879 .quick_push (std::make_pair (0, k));
3880 SLP_TREE_CHILDREN (permab).quick_push (b);
3881 for (unsigned k = 0; k < SLP_TREE_LANES (b); ++k)
3882 SLP_TREE_LANE_PERMUTATION (permab)
3883 .quick_push (std::make_pair (1, k));
3884
3885 /* Put the merged node into 'perm', in place of a. */
3886 SLP_TREE_CHILDREN (perm)[ai] = permab;
3887 /* Adjust the references to b in the permutation
3888 of perm and to the later children which we'll
3889 remove. */
3890 for (unsigned k = 0; k < SLP_TREE_LANES (perm); ++k)
3891 {
3892 std::pair<unsigned, unsigned> &p
3893 = SLP_TREE_LANE_PERMUTATION (perm)[k];
3894 if (p.first == (unsigned) bi)
3895 {
3896 p.first = ai;
3897 p.second += SLP_TREE_LANES (a);
3898 }
3899 else if (p.first > (unsigned) bi)
3900 p.first--;
3901 }
3902 SLP_TREE_CHILDREN (perm).ordered_remove (bi);
3903 }
3904 }
3905
3906 return node;
3907 }
3908
3909 /* Analyze an SLP instance starting from SCALAR_STMTS which are a group
3910 of KIND. Return true if successful. */
3911
3912 static bool
3913 vect_build_slp_instance (vec_info *vinfo,
3914 slp_instance_kind kind,
3915 vec<stmt_vec_info> &scalar_stmts,
3916 vec<stmt_vec_info> &root_stmt_infos,
3917 vec<tree> &remain,
3918 unsigned max_tree_size, unsigned *limit,
3919 scalar_stmts_to_slp_tree_map_t *bst_map,
3920 /* ??? We need stmt_info for group splitting. */
3921 stmt_vec_info stmt_info_,
3922 bool force_single_lane)
3923 {
3924 /* If there's no budget left bail out early. */
3925 if (*limit == 0)
3926 return false;
3927
3928 if (kind == slp_inst_kind_ctor)
3929 {
3930 if (dump_enabled_p ())
3931 dump_printf_loc (MSG_NOTE, vect_location,
3932 "Analyzing vectorizable constructor: %G\n",
3933 root_stmt_infos[0]->stmt);
3934 }
3935 else if (kind == slp_inst_kind_gcond)
3936 {
3937 if (dump_enabled_p ())
3938 dump_printf_loc (MSG_NOTE, vect_location,
3939 "Analyzing vectorizable control flow: %G",
3940 root_stmt_infos[0]->stmt);
3941 }
3942
3943 if (dump_enabled_p ())
3944 {
3945 dump_printf_loc (MSG_NOTE, vect_location,
3946 "Starting SLP discovery for\n");
3947 for (unsigned i = 0; i < scalar_stmts.length (); ++i)
3948 dump_printf_loc (MSG_NOTE, vect_location,
3949 " %G", scalar_stmts[i]->stmt);
3950 }
3951
3952 /* Build the tree for the SLP instance. */
3953 unsigned int group_size = scalar_stmts.length ();
3954 bool *matches = XALLOCAVEC (bool, group_size);
3955 poly_uint64 max_nunits = 1;
3956 unsigned tree_size = 0;
3957 unsigned i;
3958
3959 slp_tree node = NULL;
3960 if (group_size > 1 && force_single_lane)
3961 {
3962 matches[0] = true;
3963 matches[1] = false;
3964 }
3965 else
3966 node = vect_build_slp_tree (vinfo, scalar_stmts, group_size,
3967 &max_nunits, matches, limit,
3968 &tree_size, bst_map);
3969 if (node != NULL)
3970 {
3971 /* Calculate the unrolling factor based on the smallest type. */
3972 poly_uint64 unrolling_factor
3973 = calculate_unrolling_factor (max_nunits, group_size);
3974
3975 if (maybe_ne (unrolling_factor, 1U)
3976 && is_a <bb_vec_info> (vinfo))
3977 {
3978 unsigned HOST_WIDE_INT const_max_nunits;
3979 if (!max_nunits.is_constant (&const_max_nunits)
3980 || const_max_nunits > group_size)
3981 {
3982 if (dump_enabled_p ())
3983 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3984 "Build SLP failed: store group "
3985 "size not a multiple of the vector size "
3986 "in basic block SLP\n");
3987 vect_free_slp_tree (node);
3988 return false;
3989 }
3990 /* Fatal mismatch. */
3991 if (dump_enabled_p ())
3992 dump_printf_loc (MSG_NOTE, vect_location,
3993 "SLP discovery succeeded but node needs "
3994 "splitting\n");
3995 memset (matches, true, group_size);
3996 matches[group_size / const_max_nunits * const_max_nunits] = false;
3997 vect_free_slp_tree (node);
3998 }
3999 else
4000 {
4001 /* Create a new SLP instance. */
4002 slp_instance new_instance = XNEW (class _slp_instance);
4003 SLP_INSTANCE_TREE (new_instance) = node;
4004 SLP_INSTANCE_LOADS (new_instance) = vNULL;
4005 SLP_INSTANCE_ROOT_STMTS (new_instance) = root_stmt_infos;
4006 SLP_INSTANCE_REMAIN_DEFS (new_instance) = remain;
4007 SLP_INSTANCE_KIND (new_instance) = kind;
4008 new_instance->reduc_phis = NULL;
4009 new_instance->cost_vec = vNULL;
4010 new_instance->subgraph_entries = vNULL;
4011
4012 if (dump_enabled_p ())
4013 dump_printf_loc (MSG_NOTE, vect_location,
4014 "SLP size %u vs. limit %u.\n",
4015 tree_size, max_tree_size);
4016
4017 /* Fixup SLP reduction chains. */
4018 if (kind == slp_inst_kind_reduc_chain)
4019 {
4020 /* If this is a reduction chain with a conversion in front
4021 amend the SLP tree with a node for that. */
4022 gimple *scalar_def
4023 = vect_orig_stmt (scalar_stmts[group_size - 1])->stmt;
4024 if (STMT_VINFO_DEF_TYPE (scalar_stmts[0]) != vect_reduction_def)
4025 {
4026 /* Get at the conversion stmt - we know it's the single use
4027 of the last stmt of the reduction chain. */
4028 use_operand_p use_p;
4029 bool r = single_imm_use (gimple_assign_lhs (scalar_def),
4030 &use_p, &scalar_def);
4031 gcc_assert (r);
4032 stmt_vec_info next_info = vinfo->lookup_stmt (scalar_def);
4033 next_info = vect_stmt_to_vectorize (next_info);
4034 scalar_stmts = vNULL;
4035 scalar_stmts.create (group_size);
4036 for (unsigned i = 0; i < group_size; ++i)
4037 scalar_stmts.quick_push (next_info);
4038 slp_tree conv = vect_create_new_slp_node (scalar_stmts, 1);
4039 SLP_TREE_VECTYPE (conv) = STMT_VINFO_VECTYPE (next_info);
4040 SLP_TREE_CHILDREN (conv).quick_push (node);
4041 SLP_INSTANCE_TREE (new_instance) = conv;
4042 /* We also have to fake this conversion stmt as SLP reduction
4043 group so we don't have to mess with too much code
4044 elsewhere. */
4045 REDUC_GROUP_FIRST_ELEMENT (next_info) = next_info;
4046 REDUC_GROUP_NEXT_ELEMENT (next_info) = NULL;
4047 }
4048 /* Fill the backedge child of the PHI SLP node. The
4049 general matching code cannot find it because the
4050 scalar code does not reflect how we vectorize the
4051 reduction. */
4052 use_operand_p use_p;
4053 imm_use_iterator imm_iter;
4054 class loop *loop = LOOP_VINFO_LOOP (as_a <loop_vec_info> (vinfo));
4055 FOR_EACH_IMM_USE_FAST (use_p, imm_iter,
4056 gimple_get_lhs (scalar_def))
4057 /* There are exactly two non-debug uses, the reduction
4058 PHI and the loop-closed PHI node. */
4059 if (!is_gimple_debug (USE_STMT (use_p))
4060 && gimple_bb (USE_STMT (use_p)) == loop->header)
4061 {
4062 auto_vec<stmt_vec_info, 64> phis (group_size);
4063 stmt_vec_info phi_info
4064 = vinfo->lookup_stmt (USE_STMT (use_p));
4065 for (unsigned i = 0; i < group_size; ++i)
4066 phis.quick_push (phi_info);
4067 slp_tree *phi_node = bst_map->get (phis);
4068 unsigned dest_idx = loop_latch_edge (loop)->dest_idx;
4069 SLP_TREE_CHILDREN (*phi_node)[dest_idx]
4070 = SLP_INSTANCE_TREE (new_instance);
4071 SLP_INSTANCE_TREE (new_instance)->refcnt++;
4072 }
4073 }
4074
4075 vinfo->slp_instances.safe_push (new_instance);
4076
4077 /* ??? We've replaced the old SLP_INSTANCE_GROUP_SIZE with
4078 the number of scalar stmts in the root in a few places.
4079 Verify that assumption holds. */
4080 gcc_assert (SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (new_instance))
4081 .length () == group_size);
4082
4083 if (dump_enabled_p ())
4084 {
4085 dump_printf_loc (MSG_NOTE, vect_location,
4086 "Final SLP tree for instance %p:\n",
4087 (void *) new_instance);
4088 vect_print_slp_graph (MSG_NOTE, vect_location,
4089 SLP_INSTANCE_TREE (new_instance));
4090 }
4091
4092 return true;
4093 }
4094 }
4095 /* Failed to SLP. */
4096
4097 stmt_vec_info stmt_info = stmt_info_;
4098 /* Try to break the group up into pieces. */
4099 if (*limit > 0 && kind == slp_inst_kind_store)
4100 {
4101 /* ??? We could delay all the actual splitting of store-groups
4102 until after SLP discovery of the original group completed.
4103 Then we can recurse to vect_build_slp_instance directly. */
4104 for (i = 0; i < group_size; i++)
4105 if (!matches[i])
4106 break;
4107
4108 /* For basic block SLP, try to break the group up into multiples of
4109 a vector size. */
4110 if (is_a <bb_vec_info> (vinfo)
4111 && (i > 1 && i < group_size))
4112 {
4113 /* Free the allocated memory. */
4114 scalar_stmts.release ();
4115
4116 tree scalar_type
4117 = TREE_TYPE (DR_REF (STMT_VINFO_DATA_REF (stmt_info)));
4118 tree vectype = get_vectype_for_scalar_type (vinfo, scalar_type,
4119 1 << floor_log2 (i));
4120 unsigned HOST_WIDE_INT const_nunits;
4121 if (vectype
4122 && TYPE_VECTOR_SUBPARTS (vectype).is_constant (&const_nunits))
4123 {
4124 /* Split into two groups at the first vector boundary. */
4125 gcc_assert ((const_nunits & (const_nunits - 1)) == 0);
4126 unsigned group1_size = i & ~(const_nunits - 1);
4127
4128 if (dump_enabled_p ())
4129 dump_printf_loc (MSG_NOTE, vect_location,
4130 "Splitting SLP group at stmt %u\n", i);
4131 stmt_vec_info rest = vect_split_slp_store_group (stmt_info,
4132 group1_size);
4133 bool res = vect_analyze_slp_instance (vinfo, bst_map, stmt_info,
4134 kind, max_tree_size,
4135 limit, false);
4136 /* Split the rest at the failure point and possibly
4137 re-analyze the remaining matching part if it has
4138 at least two lanes. */
4139 if (group1_size < i
4140 && (i + 1 < group_size
4141 || i - group1_size > 1))
4142 {
4143 stmt_vec_info rest2 = rest;
4144 rest = vect_split_slp_store_group (rest, i - group1_size);
4145 if (i - group1_size > 1)
4146 res |= vect_analyze_slp_instance (vinfo, bst_map, rest2,
4147 kind, max_tree_size,
4148 limit, false);
4149 }
4150 /* Re-analyze the non-matching tail if it has at least
4151 two lanes. */
4152 if (i + 1 < group_size)
4153 res |= vect_analyze_slp_instance (vinfo, bst_map,
4154 rest, kind, max_tree_size,
4155 limit, false);
4156 return res;
4157 }
4158 }
4159
4160 /* For loop vectorization split the RHS into arbitrary pieces of
4161 size >= 1. */
4162 else if (is_a <loop_vec_info> (vinfo)
4163 && (group_size != 1 && i < group_size))
4164 {
4165 gcall *call = dyn_cast <gcall *> (stmt_info->stmt);
4166 bool masked_p = call
4167 && gimple_call_internal_p (call)
4168 && internal_fn_mask_index (gimple_call_internal_fn (call)) != -1;
4169 /* There are targets that cannot do even/odd interleaving schemes
4170 so they absolutely need to use load/store-lanes. For now
4171 force single-lane SLP for them - they would be happy with
4172 uniform power-of-two lanes (but depending on element size),
4173 but even if we can use 'i' as indicator we would need to
4174 backtrack when later lanes fail to discover with the same
4175 granularity. We cannot turn any of strided or scatter store
4176 into store-lanes. */
4177 /* ??? If this is not in sync with what get_load_store_type
4178 later decides the SLP representation is not good for other
4179 store vectorization methods. */
4180 bool want_store_lanes
4181 = (! STMT_VINFO_GATHER_SCATTER_P (stmt_info)
4182 && ! STMT_VINFO_STRIDED_P (stmt_info)
4183 && ! STMT_VINFO_SLP_VECT_ONLY (stmt_info)
4184 && compare_step_with_zero (vinfo, stmt_info) > 0
4185 && vect_slp_prefer_store_lanes_p (vinfo, stmt_info, NULL_TREE,
4186 masked_p, group_size, i));
4187 if (want_store_lanes || force_single_lane)
4188 i = 1;
4189
4190 /* A fatal discovery fail doesn't always mean single-lane SLP
4191 isn't a possibility, so try. */
4192 if (i == 0)
4193 i = 1;
4194
4195 if (dump_enabled_p ())
4196 dump_printf_loc (MSG_NOTE, vect_location,
4197 "Splitting SLP group at stmt %u\n", i);
4198
4199 /* Analyze the stored values and pinch them together with
4200 a permute node so we can preserve the whole store group. */
4201 auto_vec<slp_tree> rhs_nodes;
4202 poly_uint64 max_nunits = 1;
4203
4204 unsigned int rhs_common_nlanes = 0;
4205 unsigned int start = 0, end = i;
4206 while (start < group_size)
4207 {
4208 gcc_assert (end - start >= 1);
4209 vec<stmt_vec_info> substmts;
4210 substmts.create (end - start);
4211 for (unsigned j = start; j < end; ++j)
4212 substmts.quick_push (scalar_stmts[j]);
4213 max_nunits = 1;
4214 node = vect_build_slp_tree (vinfo, substmts, end - start,
4215 &max_nunits,
4216 matches, limit, &tree_size, bst_map);
4217 if (node)
4218 {
4219 rhs_nodes.safe_push (node);
4220 vect_update_max_nunits (&max_nunits, node->max_nunits);
4221 if (start == 0)
4222 rhs_common_nlanes = SLP_TREE_LANES (node);
4223 else if (rhs_common_nlanes != SLP_TREE_LANES (node))
4224 rhs_common_nlanes = 0;
4225 start = end;
4226 if (want_store_lanes || force_single_lane)
4227 end = start + 1;
4228 else
4229 end = group_size;
4230 }
4231 else
4232 {
4233 substmts.release ();
4234 if (end - start == 1)
4235 {
4236 /* Single-lane discovery failed. Free ressources. */
4237 for (auto node : rhs_nodes)
4238 vect_free_slp_tree (node);
4239 scalar_stmts.release ();
4240 if (dump_enabled_p ())
4241 dump_printf_loc (MSG_NOTE, vect_location,
4242 "SLP discovery failed\n");
4243 return false;
4244 }
4245
4246 /* ??? It really happens that we soft-fail SLP
4247 build at a mismatch but the matching part hard-fails
4248 later. As we know we arrived here with a group
4249 larger than one try a group of size one! */
4250 if (!matches[0])
4251 end = start + 1;
4252 else
4253 for (unsigned j = start; j < end; j++)
4254 if (!matches[j - start])
4255 {
4256 end = j;
4257 break;
4258 }
4259 }
4260 }
4261
4262 /* Now re-assess whether we want store lanes in case the
4263 discovery ended up producing all single-lane RHSs. */
4264 if (! want_store_lanes
4265 && rhs_common_nlanes == 1
4266 && ! STMT_VINFO_GATHER_SCATTER_P (stmt_info)
4267 && ! STMT_VINFO_STRIDED_P (stmt_info)
4268 && ! STMT_VINFO_SLP_VECT_ONLY (stmt_info)
4269 && compare_step_with_zero (vinfo, stmt_info) > 0
4270 && (vect_store_lanes_supported (SLP_TREE_VECTYPE (rhs_nodes[0]),
4271 group_size, masked_p)
4272 != IFN_LAST))
4273 want_store_lanes = true;
4274
4275 /* Now we assume we can build the root SLP node from all stores. */
4276 if (want_store_lanes)
4277 {
4278 /* For store-lanes feed the store node with all RHS nodes
4279 in order. */
4280 node = vect_create_new_slp_node (scalar_stmts,
4281 SLP_TREE_CHILDREN
4282 (rhs_nodes[0]).length ());
4283 SLP_TREE_VECTYPE (node) = SLP_TREE_VECTYPE (rhs_nodes[0]);
4284 node->max_nunits = max_nunits;
4285 node->ldst_lanes = true;
4286 SLP_TREE_CHILDREN (node)
4287 .reserve_exact (SLP_TREE_CHILDREN (rhs_nodes[0]).length ()
4288 + rhs_nodes.length () - 1);
4289 /* First store value and possibly mask. */
4290 SLP_TREE_CHILDREN (node)
4291 .splice (SLP_TREE_CHILDREN (rhs_nodes[0]));
4292 /* Rest of the store values. All mask nodes are the same,
4293 this should be guaranteed by dataref group discovery. */
4294 for (unsigned j = 1; j < rhs_nodes.length (); ++j)
4295 SLP_TREE_CHILDREN (node)
4296 .quick_push (SLP_TREE_CHILDREN (rhs_nodes[j])[0]);
4297 for (slp_tree child : SLP_TREE_CHILDREN (node))
4298 child->refcnt++;
4299 }
4300 else
4301 node = vect_build_slp_store_interleaving (rhs_nodes, scalar_stmts,
4302 max_nunits);
4303
4304 while (!rhs_nodes.is_empty ())
4305 vect_free_slp_tree (rhs_nodes.pop ());
4306
4307 /* Create a new SLP instance. */
4308 slp_instance new_instance = XNEW (class _slp_instance);
4309 SLP_INSTANCE_TREE (new_instance) = node;
4310 SLP_INSTANCE_LOADS (new_instance) = vNULL;
4311 SLP_INSTANCE_ROOT_STMTS (new_instance) = root_stmt_infos;
4312 SLP_INSTANCE_REMAIN_DEFS (new_instance) = remain;
4313 SLP_INSTANCE_KIND (new_instance) = kind;
4314 new_instance->reduc_phis = NULL;
4315 new_instance->cost_vec = vNULL;
4316 new_instance->subgraph_entries = vNULL;
4317
4318 if (dump_enabled_p ())
4319 dump_printf_loc (MSG_NOTE, vect_location,
4320 "SLP size %u vs. limit %u.\n",
4321 tree_size, max_tree_size);
4322
4323 vinfo->slp_instances.safe_push (new_instance);
4324
4325 /* ??? We've replaced the old SLP_INSTANCE_GROUP_SIZE with
4326 the number of scalar stmts in the root in a few places.
4327 Verify that assumption holds. */
4328 gcc_assert (SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (new_instance))
4329 .length () == group_size);
4330
4331 if (dump_enabled_p ())
4332 {
4333 dump_printf_loc (MSG_NOTE, vect_location,
4334 "Final SLP tree for instance %p:\n",
4335 (void *) new_instance);
4336 vect_print_slp_graph (MSG_NOTE, vect_location,
4337 SLP_INSTANCE_TREE (new_instance));
4338 }
4339 return true;
4340 }
4341 else
4342 /* Free the allocated memory. */
4343 scalar_stmts.release ();
4344
4345 /* Even though the first vector did not all match, we might be able to SLP
4346 (some) of the remainder. FORNOW ignore this possibility. */
4347 }
4348 else
4349 /* Free the allocated memory. */
4350 scalar_stmts.release ();
4351
4352 /* Failed to SLP. */
4353 if (dump_enabled_p ())
4354 dump_printf_loc (MSG_NOTE, vect_location, "SLP discovery failed\n");
4355 return false;
4356 }
4357
4358
4359 /* Analyze an SLP instance starting from a group of grouped stores. Call
4360 vect_build_slp_tree to build a tree of packed stmts if possible.
4361 Return FALSE if it's impossible to SLP any stmt in the loop. */
4362
4363 static bool
4364 vect_analyze_slp_instance (vec_info *vinfo,
4365 scalar_stmts_to_slp_tree_map_t *bst_map,
4366 stmt_vec_info stmt_info,
4367 slp_instance_kind kind,
4368 unsigned max_tree_size, unsigned *limit,
4369 bool force_single_lane)
4370 {
4371 vec<stmt_vec_info> scalar_stmts;
4372
4373 if (is_a <bb_vec_info> (vinfo))
4374 vect_location = stmt_info->stmt;
4375
4376 stmt_vec_info next_info = stmt_info;
4377 if (kind == slp_inst_kind_store)
4378 {
4379 /* Collect the stores and store them in scalar_stmts. */
4380 scalar_stmts.create (DR_GROUP_SIZE (stmt_info));
4381 while (next_info)
4382 {
4383 scalar_stmts.quick_push (vect_stmt_to_vectorize (next_info));
4384 next_info = DR_GROUP_NEXT_ELEMENT (next_info);
4385 }
4386 }
4387 else if (kind == slp_inst_kind_reduc_chain)
4388 {
4389 /* Collect the reduction stmts and store them in scalar_stmts. */
4390 scalar_stmts.create (REDUC_GROUP_SIZE (stmt_info));
4391 while (next_info)
4392 {
4393 scalar_stmts.quick_push (vect_stmt_to_vectorize (next_info));
4394 next_info = REDUC_GROUP_NEXT_ELEMENT (next_info);
4395 }
4396 /* Mark the first element of the reduction chain as reduction to properly
4397 transform the node. In the reduction analysis phase only the last
4398 element of the chain is marked as reduction. */
4399 STMT_VINFO_DEF_TYPE (stmt_info)
4400 = STMT_VINFO_DEF_TYPE (scalar_stmts.last ());
4401 STMT_VINFO_REDUC_DEF (vect_orig_stmt (stmt_info))
4402 = STMT_VINFO_REDUC_DEF (vect_orig_stmt (scalar_stmts.last ()));
4403 }
4404 else
4405 gcc_unreachable ();
4406
4407 vec<stmt_vec_info> roots = vNULL;
4408 vec<tree> remain = vNULL;
4409 /* Build the tree for the SLP instance. */
4410 bool res = vect_build_slp_instance (vinfo, kind, scalar_stmts,
4411 roots, remain,
4412 max_tree_size, limit, bst_map,
4413 kind == slp_inst_kind_store
4414 ? stmt_info : NULL, force_single_lane);
4415
4416 /* ??? If this is slp_inst_kind_store and the above succeeded here's
4417 where we should do store group splitting. */
4418
4419 return res;
4420 }
4421
4422 /* qsort comparator ordering SLP load nodes. */
4423
4424 static int
4425 vllp_cmp (const void *a_, const void *b_)
4426 {
4427 const slp_tree a = *(const slp_tree *)a_;
4428 const slp_tree b = *(const slp_tree *)b_;
4429 stmt_vec_info a0 = SLP_TREE_SCALAR_STMTS (a)[0];
4430 stmt_vec_info b0 = SLP_TREE_SCALAR_STMTS (b)[0];
4431 if (STMT_VINFO_GROUPED_ACCESS (a0)
4432 && STMT_VINFO_GROUPED_ACCESS (b0)
4433 && DR_GROUP_FIRST_ELEMENT (a0) == DR_GROUP_FIRST_ELEMENT (b0))
4434 {
4435 /* Same group, order after lanes used. */
4436 if (SLP_TREE_LANES (a) < SLP_TREE_LANES (b))
4437 return 1;
4438 else if (SLP_TREE_LANES (a) > SLP_TREE_LANES (b))
4439 return -1;
4440 else
4441 {
4442 /* Try to order loads using the same lanes together, breaking
4443 the tie with the lane number that first differs. */
4444 if (!SLP_TREE_LOAD_PERMUTATION (a).exists ()
4445 && !SLP_TREE_LOAD_PERMUTATION (b).exists ())
4446 return 0;
4447 else if (SLP_TREE_LOAD_PERMUTATION (a).exists ()
4448 && !SLP_TREE_LOAD_PERMUTATION (b).exists ())
4449 return 1;
4450 else if (!SLP_TREE_LOAD_PERMUTATION (a).exists ()
4451 && SLP_TREE_LOAD_PERMUTATION (b).exists ())
4452 return -1;
4453 else
4454 {
4455 for (unsigned i = 0; i < SLP_TREE_LANES (a); ++i)
4456 if (SLP_TREE_LOAD_PERMUTATION (a)[i]
4457 != SLP_TREE_LOAD_PERMUTATION (b)[i])
4458 {
4459 /* In-order lane first, that's what the above case for
4460 no permutation does. */
4461 if (SLP_TREE_LOAD_PERMUTATION (a)[i] == i)
4462 return -1;
4463 else if (SLP_TREE_LOAD_PERMUTATION (b)[i] == i)
4464 return 1;
4465 else if (SLP_TREE_LOAD_PERMUTATION (a)[i]
4466 < SLP_TREE_LOAD_PERMUTATION (b)[i])
4467 return -1;
4468 else
4469 return 1;
4470 }
4471 return 0;
4472 }
4473 }
4474 }
4475 else /* Different groups or non-groups. */
4476 {
4477 /* Order groups as their first element to keep them together. */
4478 if (STMT_VINFO_GROUPED_ACCESS (a0))
4479 a0 = DR_GROUP_FIRST_ELEMENT (a0);
4480 if (STMT_VINFO_GROUPED_ACCESS (b0))
4481 b0 = DR_GROUP_FIRST_ELEMENT (b0);
4482 if (a0 == b0)
4483 return 0;
4484 /* Tie using UID. */
4485 else if (gimple_uid (STMT_VINFO_STMT (a0))
4486 < gimple_uid (STMT_VINFO_STMT (b0)))
4487 return -1;
4488 else
4489 {
4490 gcc_assert (gimple_uid (STMT_VINFO_STMT (a0))
4491 != gimple_uid (STMT_VINFO_STMT (b0)));
4492 return 1;
4493 }
4494 }
4495 }
4496
4497 /* Process the set of LOADS that are all from the same dataref group. */
4498
4499 static void
4500 vect_lower_load_permutations (loop_vec_info loop_vinfo,
4501 scalar_stmts_to_slp_tree_map_t *bst_map,
4502 const array_slice<slp_tree> &loads,
4503 bool force_single_lane)
4504 {
4505 /* We at this point want to lower without a fixed VF or vector
4506 size in mind which means we cannot actually compute whether we
4507 need three or more vectors for a load permutation yet. So always
4508 lower. */
4509 stmt_vec_info first
4510 = DR_GROUP_FIRST_ELEMENT (SLP_TREE_SCALAR_STMTS (loads[0])[0]);
4511 unsigned group_lanes = DR_GROUP_SIZE (first);
4512
4513 /* Verify if all load permutations can be implemented with a suitably
4514 large element load-lanes operation. */
4515 unsigned ld_lanes_lanes = SLP_TREE_LANES (loads[0]);
4516 if (STMT_VINFO_STRIDED_P (first)
4517 || compare_step_with_zero (loop_vinfo, first) <= 0
4518 || exact_log2 (ld_lanes_lanes) == -1
4519 /* ??? For now only support the single-lane case as there is
4520 missing support on the store-lane side and code generation
4521 isn't up to the task yet. */
4522 || ld_lanes_lanes != 1
4523 || vect_load_lanes_supported (SLP_TREE_VECTYPE (loads[0]),
4524 group_lanes / ld_lanes_lanes,
4525 false) == IFN_LAST)
4526 ld_lanes_lanes = 0;
4527 else
4528 /* Verify the loads access the same number of lanes aligned to
4529 ld_lanes_lanes. */
4530 for (slp_tree load : loads)
4531 {
4532 if (SLP_TREE_LANES (load) != ld_lanes_lanes)
4533 {
4534 ld_lanes_lanes = 0;
4535 break;
4536 }
4537 unsigned first = SLP_TREE_LOAD_PERMUTATION (load)[0];
4538 if (first % ld_lanes_lanes != 0)
4539 {
4540 ld_lanes_lanes = 0;
4541 break;
4542 }
4543 for (unsigned i = 1; i < SLP_TREE_LANES (load); ++i)
4544 if (SLP_TREE_LOAD_PERMUTATION (load)[i] != first + i)
4545 {
4546 ld_lanes_lanes = 0;
4547 break;
4548 }
4549 }
4550
4551 /* Only a power-of-two number of lanes matches interleaving with N levels.
4552 ??? An even number of lanes could be reduced to 1<<ceil_log2(N)-1 lanes
4553 at each step. */
4554 if (ld_lanes_lanes == 0 && exact_log2 (group_lanes) == -1 && group_lanes != 3)
4555 return;
4556
4557 for (slp_tree load : loads)
4558 {
4559 /* Leave masked or gather loads alone for now. */
4560 if (!SLP_TREE_CHILDREN (load).is_empty ())
4561 continue;
4562
4563 /* We want to pattern-match special cases here and keep those
4564 alone. Candidates are splats and load-lane. */
4565
4566 /* We need to lower only loads of less than half of the groups
4567 lanes, including duplicate lanes. Note this leaves nodes
4568 with a non-1:1 load permutation around instead of canonicalizing
4569 those into a load and a permute node. Removing this early
4570 check would do such canonicalization. */
4571 if (SLP_TREE_LANES (load) >= (group_lanes + 1) / 2
4572 && ld_lanes_lanes == 0)
4573 continue;
4574
4575 /* Build the permute to get the original load permutation order. */
4576 bool contiguous = true;
4577 lane_permutation_t final_perm;
4578 final_perm.create (SLP_TREE_LANES (load));
4579 for (unsigned i = 0; i < SLP_TREE_LANES (load); ++i)
4580 {
4581 final_perm.quick_push
4582 (std::make_pair (0, SLP_TREE_LOAD_PERMUTATION (load)[i]));
4583 if (i != 0
4584 && (SLP_TREE_LOAD_PERMUTATION (load)[i]
4585 != SLP_TREE_LOAD_PERMUTATION (load)[i-1] + 1))
4586 contiguous = false;
4587 }
4588
4589 /* When the load permutation accesses a contiguous unpermuted,
4590 power-of-two aligned and sized chunk leave the load alone.
4591 We can likely (re-)load it more efficiently rather than
4592 extracting it from the larger load.
4593 ??? Long-term some of the lowering should move to where
4594 the vector types involved are fixed. */
4595 if (!force_single_lane
4596 && ld_lanes_lanes == 0
4597 && contiguous
4598 && (SLP_TREE_LANES (load) > 1 || loads.size () == 1)
4599 && pow2p_hwi (SLP_TREE_LANES (load))
4600 && pow2p_hwi (group_lanes)
4601 && SLP_TREE_LOAD_PERMUTATION (load)[0] % SLP_TREE_LANES (load) == 0
4602 && group_lanes % SLP_TREE_LANES (load) == 0)
4603 {
4604 final_perm.release ();
4605 continue;
4606 }
4607
4608 /* First build (and possibly re-use) a load node for the
4609 unpermuted group. Gaps in the middle and on the end are
4610 represented with NULL stmts. */
4611 vec<stmt_vec_info> stmts;
4612 stmts.create (group_lanes);
4613 for (stmt_vec_info s = first; s; s = DR_GROUP_NEXT_ELEMENT (s))
4614 {
4615 if (s != first)
4616 for (unsigned i = 1; i < DR_GROUP_GAP (s); ++i)
4617 stmts.quick_push (NULL);
4618 stmts.quick_push (s);
4619 }
4620 for (unsigned i = 0; i < DR_GROUP_GAP (first); ++i)
4621 stmts.quick_push (NULL);
4622 poly_uint64 max_nunits = 1;
4623 bool *matches = XALLOCAVEC (bool, group_lanes);
4624 unsigned limit = 1;
4625 unsigned tree_size = 0;
4626 slp_tree l0 = vect_build_slp_tree (loop_vinfo, stmts,
4627 group_lanes,
4628 &max_nunits, matches, &limit,
4629 &tree_size, bst_map);
4630 gcc_assert (!SLP_TREE_LOAD_PERMUTATION (l0).exists ());
4631
4632 if (ld_lanes_lanes != 0)
4633 {
4634 /* ??? If this is not in sync with what get_load_store_type
4635 later decides the SLP representation is not good for other
4636 store vectorization methods. */
4637 l0->ldst_lanes = true;
4638 load->ldst_lanes = true;
4639 }
4640
4641 while (1)
4642 {
4643 unsigned group_lanes = SLP_TREE_LANES (l0);
4644 if (ld_lanes_lanes != 0
4645 || SLP_TREE_LANES (load) >= (group_lanes + 1) / 2)
4646 break;
4647
4648 /* Try to lower by reducing the group to half its size using an
4649 interleaving scheme. For this try to compute whether all
4650 elements needed for this load are in even or odd elements of
4651 an even/odd decomposition with N consecutive elements.
4652 Thus { e, e, o, o, e, e, o, o } woud be an even/odd decomposition
4653 with N == 2. */
4654 /* ??? Only an even number of lanes can be handed this way, but the
4655 fallback below could work for any number. We have to make sure
4656 to round up in that case. */
4657 gcc_assert ((group_lanes & 1) == 0 || group_lanes == 3);
4658 unsigned even = 0, odd = 0;
4659 if ((group_lanes & 1) == 0)
4660 {
4661 even = (1 << ceil_log2 (group_lanes)) - 1;
4662 odd = even;
4663 for (auto l : final_perm)
4664 {
4665 even &= ~l.second;
4666 odd &= l.second;
4667 }
4668 }
4669
4670 /* Now build an even or odd extraction from the unpermuted load. */
4671 lane_permutation_t perm;
4672 perm.create ((group_lanes + 1) / 2);
4673 unsigned even_level = even ? 1 << ctz_hwi (even) : 0;
4674 unsigned odd_level = odd ? 1 << ctz_hwi (odd) : 0;
4675 if (even_level
4676 && group_lanes % (2 * even_level) == 0
4677 /* ??? When code generating permutes we do not try to pun
4678 to larger component modes so level != 1 isn't a natural
4679 even/odd extract. Prefer one if possible. */
4680 && (even_level == 1 || !odd_level || odd_level != 1))
4681 {
4682 /* { 0, 1, ... 4, 5 ..., } */
4683 for (unsigned i = 0; i < group_lanes / 2 / even_level; ++i)
4684 for (unsigned j = 0; j < even_level; ++j)
4685 perm.quick_push (std::make_pair (0, 2 * i * even_level + j));
4686 }
4687 else if (odd_level)
4688 {
4689 /* { ..., 2, 3, ... 6, 7 } */
4690 gcc_assert (group_lanes % (2 * odd_level) == 0);
4691 for (unsigned i = 0; i < group_lanes / 2 / odd_level; ++i)
4692 for (unsigned j = 0; j < odd_level; ++j)
4693 perm.quick_push
4694 (std::make_pair (0, (2 * i + 1) * odd_level + j));
4695 }
4696 else
4697 {
4698 /* As fallback extract all used lanes and fill to half the
4699 group size by repeating the last element.
4700 ??? This is quite a bad strathegy for re-use - we could
4701 brute force our way to find more optimal filling lanes to
4702 maximize re-use when looking at all loads from the group. */
4703 auto_bitmap l;
4704 for (auto p : final_perm)
4705 bitmap_set_bit (l, p.second);
4706 unsigned i = 0;
4707 bitmap_iterator bi;
4708 EXECUTE_IF_SET_IN_BITMAP (l, 0, i, bi)
4709 perm.quick_push (std::make_pair (0, i));
4710 while (perm.length () < (group_lanes + 1) / 2)
4711 perm.quick_push (perm.last ());
4712 }
4713
4714 /* Update final_perm with the intermediate permute. */
4715 for (unsigned i = 0; i < final_perm.length (); ++i)
4716 {
4717 unsigned l = final_perm[i].second;
4718 unsigned j;
4719 for (j = 0; j < perm.length (); ++j)
4720 if (perm[j].second == l)
4721 {
4722 final_perm[i].second = j;
4723 break;
4724 }
4725 gcc_assert (j < perm.length ());
4726 }
4727
4728 /* And create scalar stmts. */
4729 vec<stmt_vec_info> perm_stmts;
4730 perm_stmts.create (perm.length ());
4731 for (unsigned i = 0; i < perm.length (); ++i)
4732 perm_stmts.quick_push (SLP_TREE_SCALAR_STMTS (l0)[perm[i].second]);
4733
4734 slp_tree p = vect_create_new_slp_node (1, VEC_PERM_EXPR);
4735 SLP_TREE_CHILDREN (p).quick_push (l0);
4736 SLP_TREE_LANE_PERMUTATION (p) = perm;
4737 SLP_TREE_VECTYPE (p) = SLP_TREE_VECTYPE (load);
4738 SLP_TREE_LANES (p) = perm.length ();
4739 SLP_TREE_REPRESENTATIVE (p) = SLP_TREE_REPRESENTATIVE (load);
4740 /* ??? As we have scalar stmts for this intermediate permute we
4741 could CSE it via bst_map but we do not want to pick up
4742 another SLP node with a load permutation. We instead should
4743 have a "local" CSE map here. */
4744 SLP_TREE_SCALAR_STMTS (p) = perm_stmts;
4745
4746 /* We now have a node for (group_lanes + 1) / 2 lanes. */
4747 l0 = p;
4748 }
4749
4750 /* And finally from the ordered reduction node create the
4751 permute to shuffle the lanes into the original load-permutation
4752 order. We replace the original load node with this. */
4753 SLP_TREE_CODE (load) = VEC_PERM_EXPR;
4754 SLP_TREE_LOAD_PERMUTATION (load).release ();
4755 SLP_TREE_LANE_PERMUTATION (load) = final_perm;
4756 SLP_TREE_CHILDREN (load).create (1);
4757 SLP_TREE_CHILDREN (load).quick_push (l0);
4758 }
4759 }
4760
4761 /* Transform SLP loads in the SLP graph created by SLP discovery to
4762 group loads from the same group and lower load permutations that
4763 are unlikely to be supported into a series of permutes.
4764 In the degenerate case of having only single-lane SLP instances
4765 this should result in a series of permute nodes emulating an
4766 interleaving scheme. */
4767
4768 static void
4769 vect_lower_load_permutations (loop_vec_info loop_vinfo,
4770 scalar_stmts_to_slp_tree_map_t *bst_map,
4771 bool force_single_lane)
4772 {
4773 /* Gather and sort loads across all instances. */
4774 hash_set<slp_tree> visited;
4775 auto_vec<slp_tree> loads;
4776 for (auto inst : loop_vinfo->slp_instances)
4777 vect_gather_slp_loads (loads, SLP_INSTANCE_TREE (inst), visited);
4778 if (loads.is_empty ())
4779 return;
4780 loads.qsort (vllp_cmp);
4781
4782 /* Now process each dataref group separately. */
4783 unsigned firsti = 0;
4784 for (unsigned i = 1; i < loads.length (); ++i)
4785 {
4786 slp_tree first = loads[firsti];
4787 slp_tree next = loads[i];
4788 stmt_vec_info a0 = SLP_TREE_SCALAR_STMTS (first)[0];
4789 stmt_vec_info b0 = SLP_TREE_SCALAR_STMTS (next)[0];
4790 if (STMT_VINFO_GROUPED_ACCESS (a0)
4791 && STMT_VINFO_GROUPED_ACCESS (b0)
4792 && DR_GROUP_FIRST_ELEMENT (a0) == DR_GROUP_FIRST_ELEMENT (b0))
4793 continue;
4794 /* Now we have one or multiple SLP loads of the same group from
4795 firsti to i - 1. */
4796 if (STMT_VINFO_GROUPED_ACCESS (a0))
4797 vect_lower_load_permutations (loop_vinfo, bst_map,
4798 make_array_slice (&loads[firsti],
4799 i - firsti),
4800 force_single_lane);
4801 firsti = i;
4802 }
4803 if (firsti < loads.length ()
4804 && STMT_VINFO_GROUPED_ACCESS (SLP_TREE_SCALAR_STMTS (loads[firsti])[0]))
4805 vect_lower_load_permutations (loop_vinfo, bst_map,
4806 make_array_slice (&loads[firsti],
4807 loads.length () - firsti),
4808 force_single_lane);
4809 }
4810
4811 /* Check if there are stmts in the loop can be vectorized using SLP. Build SLP
4812 trees of packed scalar stmts if SLP is possible. */
4813
4814 opt_result
4815 vect_analyze_slp (vec_info *vinfo, unsigned max_tree_size,
4816 bool force_single_lane)
4817 {
4818 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
4819 unsigned int i;
4820 stmt_vec_info first_element;
4821 slp_instance instance;
4822
4823 DUMP_VECT_SCOPE ("vect_analyze_slp");
4824
4825 unsigned limit = max_tree_size;
4826
4827 scalar_stmts_to_slp_tree_map_t *bst_map
4828 = new scalar_stmts_to_slp_tree_map_t ();
4829
4830 /* Find SLP sequences starting from groups of grouped stores. */
4831 FOR_EACH_VEC_ELT (vinfo->grouped_stores, i, first_element)
4832 vect_analyze_slp_instance (vinfo, bst_map, first_element,
4833 slp_inst_kind_store, max_tree_size, &limit,
4834 force_single_lane);
4835
4836 /* For loops also start SLP discovery from non-grouped stores. */
4837 if (loop_vinfo)
4838 {
4839 data_reference_p dr;
4840 FOR_EACH_VEC_ELT (vinfo->shared->datarefs, i, dr)
4841 if (DR_IS_WRITE (dr))
4842 {
4843 stmt_vec_info stmt_info = vinfo->lookup_dr (dr)->stmt;
4844 /* Grouped stores are already handled above. */
4845 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
4846 continue;
4847 vec<stmt_vec_info> stmts;
4848 vec<stmt_vec_info> roots = vNULL;
4849 vec<tree> remain = vNULL;
4850 stmts.create (1);
4851 stmts.quick_push (stmt_info);
4852 vect_build_slp_instance (vinfo, slp_inst_kind_store,
4853 stmts, roots, remain, max_tree_size,
4854 &limit, bst_map, NULL, force_single_lane);
4855 }
4856 }
4857
4858 if (bb_vec_info bb_vinfo = dyn_cast <bb_vec_info> (vinfo))
4859 {
4860 for (unsigned i = 0; i < bb_vinfo->roots.length (); ++i)
4861 {
4862 vect_location = bb_vinfo->roots[i].roots[0]->stmt;
4863 /* Apply patterns. */
4864 for (unsigned j = 0; j < bb_vinfo->roots[i].stmts.length (); ++j)
4865 bb_vinfo->roots[i].stmts[j]
4866 = vect_stmt_to_vectorize (bb_vinfo->roots[i].stmts[j]);
4867 if (vect_build_slp_instance (bb_vinfo, bb_vinfo->roots[i].kind,
4868 bb_vinfo->roots[i].stmts,
4869 bb_vinfo->roots[i].roots,
4870 bb_vinfo->roots[i].remain,
4871 max_tree_size, &limit, bst_map, NULL,
4872 false))
4873 {
4874 bb_vinfo->roots[i].stmts = vNULL;
4875 bb_vinfo->roots[i].roots = vNULL;
4876 bb_vinfo->roots[i].remain = vNULL;
4877 }
4878 }
4879 }
4880
4881 if (loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo))
4882 {
4883 /* Find SLP sequences starting from reduction chains. */
4884 FOR_EACH_VEC_ELT (loop_vinfo->reduction_chains, i, first_element)
4885 if (! STMT_VINFO_RELEVANT_P (first_element)
4886 && ! STMT_VINFO_LIVE_P (first_element))
4887 ;
4888 else if (force_single_lane
4889 || ! vect_analyze_slp_instance (vinfo, bst_map, first_element,
4890 slp_inst_kind_reduc_chain,
4891 max_tree_size, &limit,
4892 force_single_lane))
4893 {
4894 /* Dissolve reduction chain group. */
4895 stmt_vec_info vinfo = first_element;
4896 stmt_vec_info last = NULL;
4897 while (vinfo)
4898 {
4899 stmt_vec_info next = REDUC_GROUP_NEXT_ELEMENT (vinfo);
4900 REDUC_GROUP_FIRST_ELEMENT (vinfo) = NULL;
4901 REDUC_GROUP_NEXT_ELEMENT (vinfo) = NULL;
4902 last = vinfo;
4903 vinfo = next;
4904 }
4905 STMT_VINFO_DEF_TYPE (first_element) = vect_internal_def;
4906 /* It can be still vectorized as part of an SLP reduction. */
4907 loop_vinfo->reductions.safe_push (last);
4908 }
4909
4910 /* Find SLP sequences starting from groups of reductions. */
4911 if (loop_vinfo->reductions.length () > 0)
4912 {
4913 /* Collect reduction statements we can combine into
4914 a SLP reduction. */
4915 vec<stmt_vec_info> scalar_stmts;
4916 scalar_stmts.create (loop_vinfo->reductions.length ());
4917 for (auto next_info : loop_vinfo->reductions)
4918 {
4919 next_info = vect_stmt_to_vectorize (next_info);
4920 if ((STMT_VINFO_RELEVANT_P (next_info)
4921 || STMT_VINFO_LIVE_P (next_info))
4922 /* ??? Make sure we didn't skip a conversion around a
4923 reduction path. In that case we'd have to reverse
4924 engineer that conversion stmt following the chain using
4925 reduc_idx and from the PHI using reduc_def. */
4926 && (STMT_VINFO_DEF_TYPE (next_info) == vect_reduction_def
4927 || (STMT_VINFO_DEF_TYPE (next_info)
4928 == vect_double_reduction_def)))
4929 {
4930 /* Do not discover SLP reductions combining lane-reducing
4931 ops, that will fail later. */
4932 if (!force_single_lane
4933 && !lane_reducing_stmt_p (STMT_VINFO_STMT (next_info)))
4934 scalar_stmts.quick_push (next_info);
4935 else
4936 {
4937 /* Do SLP discovery for single-lane reductions. */
4938 vec<stmt_vec_info> stmts;
4939 vec<stmt_vec_info> roots = vNULL;
4940 vec<tree> remain = vNULL;
4941 stmts.create (1);
4942 stmts.quick_push (next_info);
4943 vect_build_slp_instance (vinfo,
4944 slp_inst_kind_reduc_group,
4945 stmts, roots, remain,
4946 max_tree_size, &limit,
4947 bst_map, NULL,
4948 force_single_lane);
4949 }
4950 }
4951 }
4952 /* Save for re-processing on failure. */
4953 vec<stmt_vec_info> saved_stmts = scalar_stmts.copy ();
4954 vec<stmt_vec_info> roots = vNULL;
4955 vec<tree> remain = vNULL;
4956 if (scalar_stmts.length () <= 1
4957 || !vect_build_slp_instance (loop_vinfo,
4958 slp_inst_kind_reduc_group,
4959 scalar_stmts, roots, remain,
4960 max_tree_size, &limit, bst_map,
4961 NULL, force_single_lane))
4962 {
4963 if (scalar_stmts.length () <= 1)
4964 scalar_stmts.release ();
4965 /* Do SLP discovery for single-lane reductions. */
4966 for (auto stmt_info : saved_stmts)
4967 {
4968 vec<stmt_vec_info> stmts;
4969 vec<stmt_vec_info> roots = vNULL;
4970 vec<tree> remain = vNULL;
4971 stmts.create (1);
4972 stmts.quick_push (vect_stmt_to_vectorize (stmt_info));
4973 vect_build_slp_instance (vinfo,
4974 slp_inst_kind_reduc_group,
4975 stmts, roots, remain,
4976 max_tree_size, &limit,
4977 bst_map, NULL, force_single_lane);
4978 }
4979 }
4980 saved_stmts.release ();
4981 }
4982
4983 /* Make sure to vectorize only-live stmts, usually inductions. */
4984 for (edge e : get_loop_exit_edges (LOOP_VINFO_LOOP (loop_vinfo)))
4985 for (auto gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi);
4986 gsi_next (&gsi))
4987 {
4988 gphi *lc_phi = *gsi;
4989 tree def = gimple_phi_arg_def_from_edge (lc_phi, e);
4990 stmt_vec_info stmt_info;
4991 if (TREE_CODE (def) == SSA_NAME
4992 && !virtual_operand_p (def)
4993 && (stmt_info = loop_vinfo->lookup_def (def))
4994 && ((stmt_info = vect_stmt_to_vectorize (stmt_info)), true)
4995 && STMT_VINFO_RELEVANT (stmt_info) == vect_used_only_live
4996 && STMT_VINFO_LIVE_P (stmt_info)
4997 && (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def
4998 || (STMT_VINFO_DEF_TYPE (stmt_info) == vect_internal_def
4999 && STMT_VINFO_REDUC_IDX (stmt_info) == -1)))
5000 {
5001 vec<stmt_vec_info> stmts;
5002 vec<stmt_vec_info> roots = vNULL;
5003 vec<tree> remain = vNULL;
5004 stmts.create (1);
5005 stmts.quick_push (vect_stmt_to_vectorize (stmt_info));
5006 vect_build_slp_instance (vinfo,
5007 slp_inst_kind_reduc_group,
5008 stmts, roots, remain,
5009 max_tree_size, &limit,
5010 bst_map, NULL, force_single_lane);
5011 }
5012 }
5013
5014 /* Find SLP sequences starting from gconds. */
5015 for (auto cond : LOOP_VINFO_LOOP_CONDS (loop_vinfo))
5016 {
5017 auto cond_info = loop_vinfo->lookup_stmt (cond);
5018
5019 cond_info = vect_stmt_to_vectorize (cond_info);
5020 vec<stmt_vec_info> roots = vNULL;
5021 roots.safe_push (cond_info);
5022 gimple *stmt = STMT_VINFO_STMT (cond_info);
5023 tree args0 = gimple_cond_lhs (stmt);
5024 tree args1 = gimple_cond_rhs (stmt);
5025
5026 /* These should be enforced by cond lowering. */
5027 gcc_assert (gimple_cond_code (stmt) == NE_EXPR);
5028 gcc_assert (zerop (args1));
5029
5030 /* An argument without a loop def will be codegened from vectorizing the
5031 root gcond itself. As such we don't need to try to build an SLP tree
5032 from them. It's highly likely that the resulting SLP tree here if both
5033 arguments have a def will be incompatible, but we rely on it being split
5034 later on. */
5035 auto varg = loop_vinfo->lookup_def (args0);
5036 vec<stmt_vec_info> stmts;
5037 vec<tree> remain = vNULL;
5038 stmts.create (1);
5039 stmts.quick_push (vect_stmt_to_vectorize (varg));
5040
5041 if (! vect_build_slp_instance (vinfo, slp_inst_kind_gcond,
5042 stmts, roots, remain,
5043 max_tree_size, &limit,
5044 bst_map, NULL, force_single_lane))
5045 roots.release ();
5046 }
5047
5048 /* Find and create slp instances for inductions that have been forced
5049 live due to early break. */
5050 edge latch_e = loop_latch_edge (LOOP_VINFO_LOOP (loop_vinfo));
5051 for (auto stmt_info : LOOP_VINFO_EARLY_BREAKS_LIVE_IVS (loop_vinfo))
5052 {
5053 vec<stmt_vec_info> stmts;
5054 vec<stmt_vec_info> roots = vNULL;
5055 vec<tree> remain = vNULL;
5056 gphi *phi = as_a<gphi *> (STMT_VINFO_STMT (stmt_info));
5057 tree def = gimple_phi_arg_def_from_edge (phi, latch_e);
5058 stmt_vec_info lc_info = loop_vinfo->lookup_def (def);
5059 if (lc_info)
5060 {
5061 stmts.create (1);
5062 stmts.quick_push (vect_stmt_to_vectorize (lc_info));
5063 vect_build_slp_instance (vinfo, slp_inst_kind_reduc_group,
5064 stmts, roots, remain,
5065 max_tree_size, &limit,
5066 bst_map, NULL, force_single_lane);
5067 }
5068 /* When the latch def is from a different cycle this can only
5069 be a induction. Build a simple instance for this.
5070 ??? We should be able to start discovery from the PHI
5071 for all inductions, but then there will be stray
5072 non-SLP stmts we choke on as needing non-SLP handling. */
5073 auto_vec<stmt_vec_info, 1> tem;
5074 tem.quick_push (stmt_info);
5075 if (!bst_map->get (tem))
5076 {
5077 stmts.create (1);
5078 stmts.quick_push (stmt_info);
5079 vect_build_slp_instance (vinfo, slp_inst_kind_reduc_group,
5080 stmts, roots, remain,
5081 max_tree_size, &limit,
5082 bst_map, NULL, force_single_lane);
5083 }
5084 }
5085 }
5086
5087 hash_set<slp_tree> visited_patterns;
5088 slp_tree_to_load_perm_map_t perm_cache;
5089 slp_compat_nodes_map_t compat_cache;
5090
5091 /* See if any patterns can be found in the SLP tree. */
5092 bool pattern_found = false;
5093 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (vinfo), i, instance)
5094 pattern_found |= vect_match_slp_patterns (instance, vinfo,
5095 &visited_patterns, &perm_cache,
5096 &compat_cache);
5097
5098 /* If any were found optimize permutations of loads. */
5099 if (pattern_found)
5100 {
5101 hash_map<slp_tree, slp_tree> load_map;
5102 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (vinfo), i, instance)
5103 {
5104 slp_tree root = SLP_INSTANCE_TREE (instance);
5105 optimize_load_redistribution (bst_map, vinfo, SLP_TREE_LANES (root),
5106 &load_map, root);
5107 }
5108 }
5109
5110 /* Check whether we should force some SLP instances to use load/store-lanes
5111 and do so by forcing SLP re-discovery with single lanes. We used
5112 to cancel SLP when this applied to all instances in a loop but now
5113 we decide this per SLP instance. It's important to do this only
5114 after SLP pattern recognition. */
5115 if (is_a <loop_vec_info> (vinfo))
5116 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (vinfo), i, instance)
5117 if (SLP_INSTANCE_KIND (instance) == slp_inst_kind_store
5118 && !SLP_INSTANCE_TREE (instance)->ldst_lanes)
5119 {
5120 slp_tree slp_root = SLP_INSTANCE_TREE (instance);
5121 unsigned int group_size = SLP_TREE_LANES (slp_root);
5122 tree vectype = SLP_TREE_VECTYPE (slp_root);
5123
5124 stmt_vec_info rep_info = SLP_TREE_REPRESENTATIVE (slp_root);
5125 gimple *rep = STMT_VINFO_STMT (rep_info);
5126 bool masked = (is_gimple_call (rep)
5127 && gimple_call_internal_p (rep)
5128 && internal_fn_mask_index
5129 (gimple_call_internal_fn (rep)) != -1);
5130 if (!STMT_VINFO_GROUPED_ACCESS (rep_info)
5131 || slp_root->ldst_lanes
5132 || (vect_store_lanes_supported (vectype, group_size, masked)
5133 == IFN_LAST))
5134 continue;
5135
5136 auto_vec<slp_tree> loads;
5137 hash_set<slp_tree> visited;
5138 vect_gather_slp_loads (loads, slp_root, visited);
5139
5140 /* Check whether any load in the SLP instance is possibly
5141 permuted. */
5142 bool loads_permuted = false;
5143 slp_tree load_node;
5144 unsigned j;
5145 FOR_EACH_VEC_ELT (loads, j, load_node)
5146 {
5147 if (!SLP_TREE_LOAD_PERMUTATION (load_node).exists ())
5148 continue;
5149 unsigned k;
5150 stmt_vec_info load_info;
5151 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (load_node), k, load_info)
5152 if (SLP_TREE_LOAD_PERMUTATION (load_node)[k] != k)
5153 {
5154 loads_permuted = true;
5155 break;
5156 }
5157 }
5158
5159 /* If the loads and stores can use load/store-lanes force re-discovery
5160 with single lanes. */
5161 if (loads_permuted)
5162 {
5163 bool can_use_lanes = true;
5164 bool prefer_load_lanes = false;
5165 FOR_EACH_VEC_ELT (loads, j, load_node)
5166 if (STMT_VINFO_GROUPED_ACCESS
5167 (SLP_TREE_REPRESENTATIVE (load_node)))
5168 {
5169 stmt_vec_info stmt_vinfo = DR_GROUP_FIRST_ELEMENT
5170 (SLP_TREE_REPRESENTATIVE (load_node));
5171 rep = STMT_VINFO_STMT (stmt_vinfo);
5172 masked = (is_gimple_call (rep)
5173 && gimple_call_internal_p (rep)
5174 && internal_fn_mask_index
5175 (gimple_call_internal_fn (rep)));
5176 /* Use SLP for strided accesses (or if we can't
5177 load-lanes). */
5178 if (STMT_VINFO_STRIDED_P (stmt_vinfo)
5179 || compare_step_with_zero (vinfo, stmt_vinfo) <= 0
5180 || vect_load_lanes_supported
5181 (STMT_VINFO_VECTYPE (stmt_vinfo),
5182 DR_GROUP_SIZE (stmt_vinfo), masked) == IFN_LAST
5183 /* ??? During SLP re-discovery with a single lane
5184 a masked grouped load will appear permuted and
5185 discovery will fail. We have to rework this
5186 on the discovery side - for now avoid ICEing. */
5187 || masked)
5188 {
5189 can_use_lanes = false;
5190 break;
5191 }
5192 /* Make sure that the target would prefer store-lanes
5193 for at least one of the loads.
5194
5195 ??? Perhaps we should instead require this for
5196 all loads? */
5197 prefer_load_lanes
5198 = (prefer_load_lanes
5199 || SLP_TREE_LANES (load_node) == group_size
5200 || (vect_slp_prefer_store_lanes_p
5201 (vinfo, stmt_vinfo,
5202 STMT_VINFO_VECTYPE (stmt_vinfo), masked,
5203 group_size, SLP_TREE_LANES (load_node))));
5204 }
5205
5206 if (can_use_lanes && prefer_load_lanes)
5207 {
5208 if (dump_enabled_p ())
5209 dump_printf_loc (MSG_NOTE, vect_location,
5210 "SLP instance %p can use load/store-lanes,"
5211 " re-discovering with single-lanes\n",
5212 (void *) instance);
5213
5214 stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (slp_root);
5215
5216 vect_free_slp_instance (instance);
5217 limit = max_tree_size;
5218 bool res = vect_analyze_slp_instance (vinfo, bst_map,
5219 stmt_info,
5220 slp_inst_kind_store,
5221 max_tree_size, &limit,
5222 true);
5223 gcc_assert (res);
5224 auto new_inst = LOOP_VINFO_SLP_INSTANCES (vinfo).pop ();
5225 LOOP_VINFO_SLP_INSTANCES (vinfo)[i] = new_inst;
5226 }
5227 }
5228 }
5229
5230 /* When we end up with load permutations that we cannot possibly handle,
5231 like those requiring three vector inputs, lower them using interleaving
5232 like schemes. */
5233 if (loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo))
5234 {
5235 vect_lower_load_permutations (loop_vinfo, bst_map, force_single_lane);
5236 if (dump_enabled_p ())
5237 {
5238 dump_printf_loc (MSG_NOTE, vect_location,
5239 "SLP graph after lowering permutations:\n");
5240 hash_set<slp_tree> visited;
5241 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (vinfo), i, instance)
5242 vect_print_slp_graph (MSG_NOTE, vect_location,
5243 SLP_INSTANCE_TREE (instance), visited);
5244 }
5245 }
5246
5247 release_scalar_stmts_to_slp_tree_map (bst_map);
5248
5249 if (pattern_found && dump_enabled_p ())
5250 {
5251 dump_printf_loc (MSG_NOTE, vect_location,
5252 "Pattern matched SLP tree\n");
5253 hash_set<slp_tree> visited;
5254 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (vinfo), i, instance)
5255 vect_print_slp_graph (MSG_NOTE, vect_location,
5256 SLP_INSTANCE_TREE (instance), visited);
5257 }
5258
5259 return opt_result::success ();
5260 }
5261
5262 /* Estimates the cost of inserting layout changes into the SLP graph.
5263 It can also say that the insertion is impossible. */
5264
5265 struct slpg_layout_cost
5266 {
5267 slpg_layout_cost () = default;
5268 slpg_layout_cost (sreal, bool);
5269
5270 static slpg_layout_cost impossible () { return { sreal::max (), 0 }; }
5271 bool is_possible () const { return depth != sreal::max (); }
5272
5273 bool operator== (const slpg_layout_cost &) const;
5274 bool operator!= (const slpg_layout_cost &) const;
5275
5276 bool is_better_than (const slpg_layout_cost &, bool) const;
5277
5278 void add_parallel_cost (const slpg_layout_cost &);
5279 void add_serial_cost (const slpg_layout_cost &);
5280 void split (unsigned int);
5281
5282 /* The longest sequence of layout changes needed during any traversal
5283 of the partition dag, weighted by execution frequency.
5284
5285 This is the most important metric when optimizing for speed, since
5286 it helps to ensure that we keep the number of operations on
5287 critical paths to a minimum. */
5288 sreal depth = 0;
5289
5290 /* An estimate of the total number of operations needed. It is weighted by
5291 execution frequency when optimizing for speed but not when optimizing for
5292 size. In order to avoid double-counting, a node with a fanout of N will
5293 distribute 1/N of its total cost to each successor.
5294
5295 This is the most important metric when optimizing for size, since
5296 it helps to keep the total number of operations to a minimum, */
5297 sreal total = 0;
5298 };
5299
5300 /* Construct costs for a node with weight WEIGHT. A higher weight
5301 indicates more frequent execution. IS_FOR_SIZE is true if we are
5302 optimizing for size rather than speed. */
5303
5304 slpg_layout_cost::slpg_layout_cost (sreal weight, bool is_for_size)
5305 : depth (weight), total (is_for_size && weight > 0 ? 1 : weight)
5306 {
5307 }
5308
5309 bool
5310 slpg_layout_cost::operator== (const slpg_layout_cost &other) const
5311 {
5312 return depth == other.depth && total == other.total;
5313 }
5314
5315 bool
5316 slpg_layout_cost::operator!= (const slpg_layout_cost &other) const
5317 {
5318 return !operator== (other);
5319 }
5320
5321 /* Return true if these costs are better than OTHER. IS_FOR_SIZE is
5322 true if we are optimizing for size rather than speed. */
5323
5324 bool
5325 slpg_layout_cost::is_better_than (const slpg_layout_cost &other,
5326 bool is_for_size) const
5327 {
5328 if (is_for_size)
5329 {
5330 if (total != other.total)
5331 return total < other.total;
5332 return depth < other.depth;
5333 }
5334 else
5335 {
5336 if (depth != other.depth)
5337 return depth < other.depth;
5338 return total < other.total;
5339 }
5340 }
5341
5342 /* Increase the costs to account for something with cost INPUT_COST
5343 happening in parallel with the current costs. */
5344
5345 void
5346 slpg_layout_cost::add_parallel_cost (const slpg_layout_cost &input_cost)
5347 {
5348 depth = std::max (depth, input_cost.depth);
5349 total += input_cost.total;
5350 }
5351
5352 /* Increase the costs to account for something with cost INPUT_COST
5353 happening in series with the current costs. */
5354
5355 void
5356 slpg_layout_cost::add_serial_cost (const slpg_layout_cost &other)
5357 {
5358 depth += other.depth;
5359 total += other.total;
5360 }
5361
5362 /* Split the total cost among TIMES successors or predecessors. */
5363
5364 void
5365 slpg_layout_cost::split (unsigned int times)
5366 {
5367 if (times > 1)
5368 total /= times;
5369 }
5370
5371 /* Information about one node in the SLP graph, for use during
5372 vect_optimize_slp_pass. */
5373
5374 struct slpg_vertex
5375 {
5376 slpg_vertex (slp_tree node_) : node (node_) {}
5377
5378 /* The node itself. */
5379 slp_tree node;
5380
5381 /* Which partition the node belongs to, or -1 if none. Nodes outside of
5382 partitions are flexible; they can have whichever layout consumers
5383 want them to have. */
5384 int partition = -1;
5385
5386 /* The number of nodes that directly use the result of this one
5387 (i.e. the number of nodes that count this one as a child). */
5388 unsigned int out_degree = 0;
5389
5390 /* The execution frequency of the node. */
5391 sreal weight = 0;
5392
5393 /* The total execution frequency of all nodes that directly use the
5394 result of this one. */
5395 sreal out_weight = 0;
5396 };
5397
5398 /* Information about one partition of the SLP graph, for use during
5399 vect_optimize_slp_pass. */
5400
5401 struct slpg_partition_info
5402 {
5403 /* The nodes in the partition occupy indices [NODE_BEGIN, NODE_END)
5404 of m_partitioned_nodes. */
5405 unsigned int node_begin = 0;
5406 unsigned int node_end = 0;
5407
5408 /* Which layout we've chosen to use for this partition, or -1 if
5409 we haven't picked one yet. */
5410 int layout = -1;
5411
5412 /* The number of predecessors and successors in the partition dag.
5413 The predecessors always have lower partition numbers and the
5414 successors always have higher partition numbers.
5415
5416 Note that the directions of these edges are not necessarily the
5417 same as in the data flow graph. For example, if an SCC has separate
5418 partitions for an inner loop and an outer loop, the inner loop's
5419 partition will have at least two incoming edges from the outer loop's
5420 partition: one for a live-in value and one for a live-out value.
5421 In data flow terms, one of these edges would also be from the outer loop
5422 to the inner loop, but the other would be in the opposite direction. */
5423 unsigned int in_degree = 0;
5424 unsigned int out_degree = 0;
5425 };
5426
5427 /* Information about the costs of using a particular layout for a
5428 particular partition. It can also say that the combination is
5429 impossible. */
5430
5431 struct slpg_partition_layout_costs
5432 {
5433 bool is_possible () const { return internal_cost.is_possible (); }
5434 void mark_impossible () { internal_cost = slpg_layout_cost::impossible (); }
5435
5436 /* The costs inherited from predecessor partitions. */
5437 slpg_layout_cost in_cost;
5438
5439 /* The inherent cost of the layout within the node itself. For example,
5440 this is nonzero for a load if choosing a particular layout would require
5441 the load to permute the loaded elements. It is nonzero for a
5442 VEC_PERM_EXPR if the permutation cannot be eliminated or converted
5443 to full-vector moves. */
5444 slpg_layout_cost internal_cost;
5445
5446 /* The costs inherited from successor partitions. */
5447 slpg_layout_cost out_cost;
5448 };
5449
5450 /* This class tries to optimize the layout of vectors in order to avoid
5451 unnecessary shuffling. At the moment, the set of possible layouts are
5452 restricted to bijective permutations.
5453
5454 The goal of the pass depends on whether we're optimizing for size or
5455 for speed. When optimizing for size, the goal is to reduce the overall
5456 number of layout changes (including layout changes implied by things
5457 like load permutations). When optimizing for speed, the goal is to
5458 reduce the maximum latency attributable to layout changes on any
5459 non-cyclical path through the data flow graph.
5460
5461 For example, when optimizing a loop nest for speed, we will prefer
5462 to make layout changes outside of a loop rather than inside of a loop,
5463 and will prefer to make layout changes in parallel rather than serially,
5464 even if that increases the overall number of layout changes.
5465
5466 The high-level procedure is:
5467
5468 (1) Build a graph in which edges go from uses (parents) to definitions
5469 (children).
5470
5471 (2) Divide the graph into a dag of strongly-connected components (SCCs).
5472
5473 (3) When optimizing for speed, partition the nodes in each SCC based
5474 on their containing cfg loop. When optimizing for size, treat
5475 each SCC as a single partition.
5476
5477 This gives us a dag of partitions. The goal is now to assign a
5478 layout to each partition.
5479
5480 (4) Construct a set of vector layouts that are worth considering.
5481 Record which nodes must keep their current layout.
5482
5483 (5) Perform a forward walk over the partition dag (from loads to stores)
5484 accumulating the "forward" cost of using each layout. When visiting
5485 each partition, assign a tentative choice of layout to the partition
5486 and use that choice when calculating the cost of using a different
5487 layout in successor partitions.
5488
5489 (6) Perform a backward walk over the partition dag (from stores to loads),
5490 accumulating the "backward" cost of using each layout. When visiting
5491 each partition, make a final choice of layout for that partition based
5492 on the accumulated forward costs (from (5)) and backward costs
5493 (from (6)).
5494
5495 (7) Apply the chosen layouts to the SLP graph.
5496
5497 For example, consider the SLP statements:
5498
5499 S1: a_1 = load
5500 loop:
5501 S2: a_2 = PHI<a_1, a_3>
5502 S3: b_1 = load
5503 S4: a_3 = a_2 + b_1
5504 exit:
5505 S5: a_4 = PHI<a_3>
5506 S6: store a_4
5507
5508 S2 and S4 form an SCC and are part of the same loop. Every other
5509 statement is in a singleton SCC. In this example there is a one-to-one
5510 mapping between SCCs and partitions and the partition dag looks like this;
5511
5512 S1 S3
5513 \ /
5514 S2+S4
5515 |
5516 S5
5517 |
5518 S6
5519
5520 S2, S3 and S4 will have a higher execution frequency than the other
5521 statements, so when optimizing for speed, the goal is to avoid any
5522 layout changes:
5523
5524 - within S3
5525 - within S2+S4
5526 - on the S3->S2+S4 edge
5527
5528 For example, if S3 was originally a reversing load, the goal of the
5529 pass is to make it an unreversed load and change the layout on the
5530 S1->S2+S4 and S2+S4->S5 edges to compensate. (Changing the layout
5531 on S1->S2+S4 and S5->S6 would also be acceptable.)
5532
5533 The difference between SCCs and partitions becomes important if we
5534 add an outer loop:
5535
5536 S1: a_1 = ...
5537 loop1:
5538 S2: a_2 = PHI<a_1, a_6>
5539 S3: b_1 = load
5540 S4: a_3 = a_2 + b_1
5541 loop2:
5542 S5: a_4 = PHI<a_3, a_5>
5543 S6: c_1 = load
5544 S7: a_5 = a_4 + c_1
5545 exit2:
5546 S8: a_6 = PHI<a_5>
5547 S9: store a_6
5548 exit1:
5549
5550 Here, S2, S4, S5, S7 and S8 form a single SCC. However, when optimizing
5551 for speed, we usually do not want restrictions in the outer loop to "infect"
5552 the decision for the inner loop. For example, if an outer-loop node
5553 in the SCC contains a statement with a fixed layout, that should not
5554 prevent the inner loop from using a different layout. Conversely,
5555 the inner loop should not dictate a layout to the outer loop: if the
5556 outer loop does a lot of computation, then it may not be efficient to
5557 do all of that computation in the inner loop's preferred layout.
5558
5559 So when optimizing for speed, we partition the SCC into S2+S4+S8 (outer)
5560 and S5+S7 (inner). We also try to arrange partitions so that:
5561
5562 - the partition for an outer loop comes before the partition for
5563 an inner loop
5564
5565 - if a sibling loop A dominates a sibling loop B, A's partition
5566 comes before B's
5567
5568 This gives the following partition dag for the example above:
5569
5570 S1 S3
5571 \ /
5572 S2+S4+S8 S6
5573 | \\ /
5574 | S5+S7
5575 |
5576 S9
5577
5578 There are two edges from S2+S4+S8 to S5+S7: one for the edge S4->S5 and
5579 one for a reversal of the edge S7->S8.
5580
5581 The backward walk picks a layout for S5+S7 before S2+S4+S8. The choice
5582 for S2+S4+S8 therefore has to balance the cost of using the outer loop's
5583 preferred layout against the cost of changing the layout on entry to the
5584 inner loop (S4->S5) and on exit from the inner loop (S7->S8 reversed).
5585
5586 Although this works well when optimizing for speed, it has the downside
5587 when optimizing for size that the choice of layout for S5+S7 is completely
5588 independent of S9, which lessens the chance of reducing the overall number
5589 of permutations. We therefore do not partition SCCs when optimizing
5590 for size.
5591
5592 To give a concrete example of the difference between optimizing
5593 for size and speed, consider:
5594
5595 a[0] = (b[1] << c[3]) - d[1];
5596 a[1] = (b[0] << c[2]) - d[0];
5597 a[2] = (b[3] << c[1]) - d[3];
5598 a[3] = (b[2] << c[0]) - d[2];
5599
5600 There are three different layouts here: one for a, one for b and d,
5601 and one for c. When optimizing for speed it is better to permute each
5602 of b, c and d into the order required by a, since those permutations
5603 happen in parallel. But when optimizing for size, it is better to:
5604
5605 - permute c into the same order as b
5606 - do the arithmetic
5607 - permute the result into the order required by a
5608
5609 This gives 2 permutations rather than 3. */
5610
5611 class vect_optimize_slp_pass
5612 {
5613 public:
5614 vect_optimize_slp_pass (vec_info *vinfo) : m_vinfo (vinfo) {}
5615 void run ();
5616
5617 private:
5618 /* Graph building. */
5619 struct loop *containing_loop (slp_tree);
5620 bool is_cfg_latch_edge (graph_edge *);
5621 void build_vertices (hash_set<slp_tree> &, slp_tree);
5622 void build_vertices ();
5623 void build_graph ();
5624
5625 /* Partitioning. */
5626 void create_partitions ();
5627 template<typename T> void for_each_partition_edge (unsigned int, T);
5628
5629 /* Layout selection. */
5630 bool is_compatible_layout (slp_tree, unsigned int);
5631 int change_layout_cost (slp_tree, unsigned int, unsigned int);
5632 slpg_partition_layout_costs &partition_layout_costs (unsigned int,
5633 unsigned int);
5634 void change_vec_perm_layout (slp_tree, lane_permutation_t &,
5635 int, unsigned int);
5636 int internal_node_cost (slp_tree, int, unsigned int);
5637 void start_choosing_layouts ();
5638
5639 /* Cost propagation. */
5640 slpg_layout_cost edge_layout_cost (graph_edge *, unsigned int,
5641 unsigned int, unsigned int);
5642 slpg_layout_cost total_in_cost (unsigned int);
5643 slpg_layout_cost forward_cost (graph_edge *, unsigned int, unsigned int);
5644 slpg_layout_cost backward_cost (graph_edge *, unsigned int, unsigned int);
5645 void forward_pass ();
5646 void backward_pass ();
5647
5648 /* Rematerialization. */
5649 slp_tree get_result_with_layout (slp_tree, unsigned int);
5650 void materialize ();
5651
5652 /* Clean-up. */
5653 void remove_redundant_permutations ();
5654
5655 /* Masked load lanes discovery. */
5656 void decide_masked_load_lanes ();
5657
5658 void dump ();
5659
5660 vec_info *m_vinfo;
5661
5662 /* True if we should optimize the graph for size, false if we should
5663 optimize it for speed. (It wouldn't be easy to make this decision
5664 more locally.) */
5665 bool m_optimize_size;
5666
5667 /* A graph of all SLP nodes, with edges leading from uses to definitions.
5668 In other words, a node's predecessors are its slp_tree parents and
5669 a node's successors are its slp_tree children. */
5670 graph *m_slpg = nullptr;
5671
5672 /* The vertices of M_SLPG, indexed by slp_tree::vertex. */
5673 auto_vec<slpg_vertex> m_vertices;
5674
5675 /* The list of all leaves of M_SLPG. such as external definitions, constants,
5676 and loads. */
5677 auto_vec<int> m_leafs;
5678
5679 /* This array has one entry for every vector layout that we're considering.
5680 Element 0 is null and indicates "no change". Other entries describe
5681 permutations that are inherent in the current graph and that we would
5682 like to reverse if possible.
5683
5684 For example, a permutation { 1, 2, 3, 0 } means that something has
5685 effectively been permuted in that way, such as a load group
5686 { a[1], a[2], a[3], a[0] } (viewed as a permutation of a[0:3]).
5687 We'd then like to apply the reverse permutation { 3, 0, 1, 2 }
5688 in order to put things "back" in order. */
5689 auto_vec<vec<unsigned> > m_perms;
5690
5691 /* A partitioning of the nodes for which a layout must be chosen.
5692 Each partition represents an <SCC, cfg loop> pair; that is,
5693 nodes in different SCCs belong to different partitions, and nodes
5694 within an SCC can be further partitioned according to a containing
5695 cfg loop. Partition <SCC1, L1> comes before <SCC2, L2> if:
5696
5697 - SCC1 != SCC2 and SCC1 is a predecessor of SCC2 in a forward walk
5698 from leaves (such as loads) to roots (such as stores).
5699
5700 - SCC1 == SCC2 and L1's header strictly dominates L2's header. */
5701 auto_vec<slpg_partition_info> m_partitions;
5702
5703 /* The list of all nodes for which a layout must be chosen. Nodes for
5704 partition P come before the nodes for partition P+1. Nodes within a
5705 partition are in reverse postorder. */
5706 auto_vec<unsigned int> m_partitioned_nodes;
5707
5708 /* Index P * num-layouts + L contains the cost of using layout L
5709 for partition P. */
5710 auto_vec<slpg_partition_layout_costs> m_partition_layout_costs;
5711
5712 /* Index N * num-layouts + L, if nonnull, is a node that provides the
5713 original output of node N adjusted to have layout L. */
5714 auto_vec<slp_tree> m_node_layouts;
5715 };
5716
5717 /* Fill the vertices and leafs vector with all nodes in the SLP graph.
5718 Also record whether we should optimize anything for speed rather
5719 than size. */
5720
5721 void
5722 vect_optimize_slp_pass::build_vertices (hash_set<slp_tree> &visited,
5723 slp_tree node)
5724 {
5725 unsigned i;
5726 slp_tree child;
5727
5728 if (visited.add (node))
5729 return;
5730
5731 if (stmt_vec_info rep = SLP_TREE_REPRESENTATIVE (node))
5732 {
5733 basic_block bb = gimple_bb (vect_orig_stmt (rep)->stmt);
5734 if (optimize_bb_for_speed_p (bb))
5735 m_optimize_size = false;
5736 }
5737
5738 node->vertex = m_vertices.length ();
5739 m_vertices.safe_push (slpg_vertex (node));
5740
5741 bool leaf = true;
5742 bool force_leaf = false;
5743 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
5744 if (child)
5745 {
5746 leaf = false;
5747 build_vertices (visited, child);
5748 }
5749 else
5750 force_leaf = true;
5751 /* Since SLP discovery works along use-def edges all cycles have an
5752 entry - but there's the exception of cycles where we do not handle
5753 the entry explicitely (but with a NULL SLP node), like some reductions
5754 and inductions. Force those SLP PHIs to act as leafs to make them
5755 backwards reachable. */
5756 if (leaf || force_leaf)
5757 m_leafs.safe_push (node->vertex);
5758 }
5759
5760 /* Fill the vertices and leafs vector with all nodes in the SLP graph. */
5761
5762 void
5763 vect_optimize_slp_pass::build_vertices ()
5764 {
5765 hash_set<slp_tree> visited;
5766 unsigned i;
5767 slp_instance instance;
5768 m_vertices.truncate (0);
5769 m_leafs.truncate (0);
5770 FOR_EACH_VEC_ELT (m_vinfo->slp_instances, i, instance)
5771 build_vertices (visited, SLP_INSTANCE_TREE (instance));
5772 }
5773
5774 /* Apply (reverse) bijectite PERM to VEC. */
5775
5776 template <class T>
5777 static void
5778 vect_slp_permute (vec<unsigned> perm,
5779 vec<T> &vec, bool reverse)
5780 {
5781 auto_vec<T, 64> saved;
5782 saved.create (vec.length ());
5783 for (unsigned i = 0; i < vec.length (); ++i)
5784 saved.quick_push (vec[i]);
5785
5786 if (reverse)
5787 {
5788 for (unsigned i = 0; i < vec.length (); ++i)
5789 vec[perm[i]] = saved[i];
5790 for (unsigned i = 0; i < vec.length (); ++i)
5791 gcc_assert (vec[perm[i]] == saved[i]);
5792 }
5793 else
5794 {
5795 for (unsigned i = 0; i < vec.length (); ++i)
5796 vec[i] = saved[perm[i]];
5797 for (unsigned i = 0; i < vec.length (); ++i)
5798 gcc_assert (vec[i] == saved[perm[i]]);
5799 }
5800 }
5801
5802 /* Return the cfg loop that contains NODE. */
5803
5804 struct loop *
5805 vect_optimize_slp_pass::containing_loop (slp_tree node)
5806 {
5807 stmt_vec_info rep = SLP_TREE_REPRESENTATIVE (node);
5808 if (!rep)
5809 return ENTRY_BLOCK_PTR_FOR_FN (cfun)->loop_father;
5810 return gimple_bb (vect_orig_stmt (rep)->stmt)->loop_father;
5811 }
5812
5813 /* Return true if UD (an edge from a use to a definition) is associated
5814 with a loop latch edge in the cfg. */
5815
5816 bool
5817 vect_optimize_slp_pass::is_cfg_latch_edge (graph_edge *ud)
5818 {
5819 slp_tree use = m_vertices[ud->src].node;
5820 slp_tree def = m_vertices[ud->dest].node;
5821 if ((SLP_TREE_DEF_TYPE (use) != vect_internal_def
5822 || SLP_TREE_CODE (use) == VEC_PERM_EXPR)
5823 || SLP_TREE_DEF_TYPE (def) != vect_internal_def)
5824 return false;
5825
5826 stmt_vec_info use_rep = vect_orig_stmt (SLP_TREE_REPRESENTATIVE (use));
5827 return (is_a<gphi *> (use_rep->stmt)
5828 && bb_loop_header_p (gimple_bb (use_rep->stmt))
5829 && containing_loop (def) == containing_loop (use));
5830 }
5831
5832 /* Build the graph. Mark edges that correspond to cfg loop latch edges with
5833 a nonnull data field. */
5834
5835 void
5836 vect_optimize_slp_pass::build_graph ()
5837 {
5838 m_optimize_size = true;
5839 build_vertices ();
5840
5841 m_slpg = new_graph (m_vertices.length ());
5842 for (slpg_vertex &v : m_vertices)
5843 for (slp_tree child : SLP_TREE_CHILDREN (v.node))
5844 if (child)
5845 {
5846 graph_edge *ud = add_edge (m_slpg, v.node->vertex, child->vertex);
5847 if (is_cfg_latch_edge (ud))
5848 ud->data = this;
5849 }
5850 }
5851
5852 /* Return true if E corresponds to a loop latch edge in the cfg. */
5853
5854 static bool
5855 skip_cfg_latch_edges (graph_edge *e)
5856 {
5857 return e->data;
5858 }
5859
5860 /* Create the node partitions. */
5861
5862 void
5863 vect_optimize_slp_pass::create_partitions ()
5864 {
5865 /* Calculate a postorder of the graph, ignoring edges that correspond
5866 to natural latch edges in the cfg. Reading the vector from the end
5867 to the beginning gives the reverse postorder. */
5868 auto_vec<int> initial_rpo;
5869 graphds_dfs (m_slpg, &m_leafs[0], m_leafs.length (), &initial_rpo,
5870 false, NULL, skip_cfg_latch_edges);
5871 gcc_assert (initial_rpo.length () == m_vertices.length ());
5872
5873 /* Calculate the strongly connected components of the graph. */
5874 auto_vec<int> scc_grouping;
5875 unsigned int num_sccs = graphds_scc (m_slpg, NULL, NULL, &scc_grouping);
5876
5877 /* Create a new index order in which all nodes from the same SCC are
5878 consecutive. Use scc_pos to record the index of the first node in
5879 each SCC. */
5880 auto_vec<unsigned int> scc_pos (num_sccs);
5881 int last_component = -1;
5882 unsigned int node_count = 0;
5883 for (unsigned int node_i : scc_grouping)
5884 {
5885 if (last_component != m_slpg->vertices[node_i].component)
5886 {
5887 last_component = m_slpg->vertices[node_i].component;
5888 gcc_assert (last_component == int (scc_pos.length ()));
5889 scc_pos.quick_push (node_count);
5890 }
5891 node_count += 1;
5892 }
5893 gcc_assert (node_count == initial_rpo.length ()
5894 && last_component + 1 == int (num_sccs));
5895
5896 /* Use m_partitioned_nodes to group nodes into SCC order, with the nodes
5897 inside each SCC following the RPO we calculated above. The fact that
5898 we ignored natural latch edges when calculating the RPO should ensure
5899 that, for natural loop nests:
5900
5901 - the first node that we encounter in a cfg loop is the loop header phi
5902 - the loop header phis are in dominance order
5903
5904 Arranging for this is an optimization (see below) rather than a
5905 correctness issue. Unnatural loops with a tangled mess of backedges
5906 will still work correctly, but might give poorer results.
5907
5908 Also update scc_pos so that it gives 1 + the index of the last node
5909 in the SCC. */
5910 m_partitioned_nodes.safe_grow (node_count);
5911 for (unsigned int old_i = initial_rpo.length (); old_i-- > 0;)
5912 {
5913 unsigned int node_i = initial_rpo[old_i];
5914 unsigned int new_i = scc_pos[m_slpg->vertices[node_i].component]++;
5915 m_partitioned_nodes[new_i] = node_i;
5916 }
5917
5918 /* When optimizing for speed, partition each SCC based on the containing
5919 cfg loop. The order we constructed above should ensure that, for natural
5920 cfg loops, we'll create sub-SCC partitions for outer loops before
5921 the corresponding sub-SCC partitions for inner loops. Similarly,
5922 when one sibling loop A dominates another sibling loop B, we should
5923 create a sub-SCC partition for A before a sub-SCC partition for B.
5924
5925 As above, nothing depends for correctness on whether this achieves
5926 a natural nesting, but we should get better results when it does. */
5927 m_partitions.reserve (m_vertices.length ());
5928 unsigned int next_partition_i = 0;
5929 hash_map<struct loop *, int> loop_partitions;
5930 unsigned int rpo_begin = 0;
5931 unsigned int num_partitioned_nodes = 0;
5932 for (unsigned int rpo_end : scc_pos)
5933 {
5934 loop_partitions.empty ();
5935 unsigned int partition_i = next_partition_i;
5936 for (unsigned int rpo_i = rpo_begin; rpo_i < rpo_end; ++rpo_i)
5937 {
5938 /* Handle externals and constants optimistically throughout.
5939 But treat existing vectors as fixed since we do not handle
5940 permuting them. */
5941 unsigned int node_i = m_partitioned_nodes[rpo_i];
5942 auto &vertex = m_vertices[node_i];
5943 if ((SLP_TREE_DEF_TYPE (vertex.node) == vect_external_def
5944 && !SLP_TREE_VEC_DEFS (vertex.node).exists ())
5945 || SLP_TREE_DEF_TYPE (vertex.node) == vect_constant_def)
5946 vertex.partition = -1;
5947 else
5948 {
5949 bool existed;
5950 if (m_optimize_size)
5951 existed = next_partition_i > partition_i;
5952 else
5953 {
5954 struct loop *loop = containing_loop (vertex.node);
5955 auto &entry = loop_partitions.get_or_insert (loop, &existed);
5956 if (!existed)
5957 entry = next_partition_i;
5958 partition_i = entry;
5959 }
5960 if (!existed)
5961 {
5962 m_partitions.quick_push (slpg_partition_info ());
5963 next_partition_i += 1;
5964 }
5965 vertex.partition = partition_i;
5966 num_partitioned_nodes += 1;
5967 m_partitions[partition_i].node_end += 1;
5968 }
5969 }
5970 rpo_begin = rpo_end;
5971 }
5972
5973 /* Assign ranges of consecutive node indices to each partition,
5974 in partition order. Start with node_end being the same as
5975 node_begin so that the next loop can use it as a counter. */
5976 unsigned int node_begin = 0;
5977 for (auto &partition : m_partitions)
5978 {
5979 partition.node_begin = node_begin;
5980 node_begin += partition.node_end;
5981 partition.node_end = partition.node_begin;
5982 }
5983 gcc_assert (node_begin == num_partitioned_nodes);
5984
5985 /* Finally build the list of nodes in partition order. */
5986 m_partitioned_nodes.truncate (num_partitioned_nodes);
5987 for (unsigned int node_i = 0; node_i < m_vertices.length (); ++node_i)
5988 {
5989 int partition_i = m_vertices[node_i].partition;
5990 if (partition_i >= 0)
5991 {
5992 unsigned int order_i = m_partitions[partition_i].node_end++;
5993 m_partitioned_nodes[order_i] = node_i;
5994 }
5995 }
5996 }
5997
5998 /* Look for edges from earlier partitions into node NODE_I and edges from
5999 node NODE_I into later partitions. Call:
6000
6001 FN (ud, other_node_i)
6002
6003 for each such use-to-def edge ud, where other_node_i is the node at the
6004 other end of the edge. */
6005
6006 template<typename T>
6007 void
6008 vect_optimize_slp_pass::for_each_partition_edge (unsigned int node_i, T fn)
6009 {
6010 int partition_i = m_vertices[node_i].partition;
6011 for (graph_edge *pred = m_slpg->vertices[node_i].pred;
6012 pred; pred = pred->pred_next)
6013 {
6014 int src_partition_i = m_vertices[pred->src].partition;
6015 if (src_partition_i >= 0 && src_partition_i != partition_i)
6016 fn (pred, pred->src);
6017 }
6018 for (graph_edge *succ = m_slpg->vertices[node_i].succ;
6019 succ; succ = succ->succ_next)
6020 {
6021 int dest_partition_i = m_vertices[succ->dest].partition;
6022 if (dest_partition_i >= 0 && dest_partition_i != partition_i)
6023 fn (succ, succ->dest);
6024 }
6025 }
6026
6027 /* Return true if layout LAYOUT_I is compatible with the number of SLP lanes
6028 that NODE would operate on. This test is independent of NODE's actual
6029 operation. */
6030
6031 bool
6032 vect_optimize_slp_pass::is_compatible_layout (slp_tree node,
6033 unsigned int layout_i)
6034 {
6035 if (layout_i == 0)
6036 return true;
6037
6038 if (SLP_TREE_LANES (node) != m_perms[layout_i].length ())
6039 return false;
6040
6041 return true;
6042 }
6043
6044 /* Return the cost (in arbtirary units) of going from layout FROM_LAYOUT_I
6045 to layout TO_LAYOUT_I for a node like NODE. Return -1 if either of the
6046 layouts is incompatible with NODE or if the change is not possible for
6047 some other reason.
6048
6049 The properties taken from NODE include the number of lanes and the
6050 vector type. The actual operation doesn't matter. */
6051
6052 int
6053 vect_optimize_slp_pass::change_layout_cost (slp_tree node,
6054 unsigned int from_layout_i,
6055 unsigned int to_layout_i)
6056 {
6057 if (!is_compatible_layout (node, from_layout_i)
6058 || !is_compatible_layout (node, to_layout_i))
6059 return -1;
6060
6061 if (from_layout_i == to_layout_i)
6062 return 0;
6063
6064 auto_vec<slp_tree, 1> children (1);
6065 children.quick_push (node);
6066 auto_lane_permutation_t perm (SLP_TREE_LANES (node));
6067 if (from_layout_i > 0)
6068 for (unsigned int i : m_perms[from_layout_i])
6069 perm.quick_push ({ 0, i });
6070 else
6071 for (unsigned int i = 0; i < SLP_TREE_LANES (node); ++i)
6072 perm.quick_push ({ 0, i });
6073 if (to_layout_i > 0)
6074 vect_slp_permute (m_perms[to_layout_i], perm, true);
6075 auto count = vectorizable_slp_permutation_1 (m_vinfo, nullptr, node, perm,
6076 children, false);
6077 if (count >= 0)
6078 return MAX (count, 1);
6079
6080 /* ??? In principle we could try changing via layout 0, giving two
6081 layout changes rather than 1. Doing that would require
6082 corresponding support in get_result_with_layout. */
6083 return -1;
6084 }
6085
6086 /* Return the costs of assigning layout LAYOUT_I to partition PARTITION_I. */
6087
6088 inline slpg_partition_layout_costs &
6089 vect_optimize_slp_pass::partition_layout_costs (unsigned int partition_i,
6090 unsigned int layout_i)
6091 {
6092 return m_partition_layout_costs[partition_i * m_perms.length () + layout_i];
6093 }
6094
6095 /* Change PERM in one of two ways:
6096
6097 - if IN_LAYOUT_I < 0, accept input operand I in the layout that has been
6098 chosen for child I of NODE.
6099
6100 - if IN_LAYOUT >= 0, accept all inputs operands with that layout.
6101
6102 In both cases, arrange for the output to have layout OUT_LAYOUT_I */
6103
6104 void
6105 vect_optimize_slp_pass::
6106 change_vec_perm_layout (slp_tree node, lane_permutation_t &perm,
6107 int in_layout_i, unsigned int out_layout_i)
6108 {
6109 for (auto &entry : perm)
6110 {
6111 int this_in_layout_i = in_layout_i;
6112 if (this_in_layout_i < 0)
6113 {
6114 slp_tree in_node = SLP_TREE_CHILDREN (node)[entry.first];
6115 unsigned int in_partition_i = m_vertices[in_node->vertex].partition;
6116 if (in_partition_i == -1u)
6117 continue;
6118 this_in_layout_i = m_partitions[in_partition_i].layout;
6119 }
6120 if (this_in_layout_i > 0)
6121 entry.second = m_perms[this_in_layout_i][entry.second];
6122 }
6123 if (out_layout_i > 0)
6124 vect_slp_permute (m_perms[out_layout_i], perm, true);
6125 }
6126
6127 /* Check whether the target allows NODE to be rearranged so that the node's
6128 output has layout OUT_LAYOUT_I. Return the cost of the change if so,
6129 in the same arbitrary units as for change_layout_cost. Return -1 otherwise.
6130
6131 If NODE is a VEC_PERM_EXPR and IN_LAYOUT_I < 0, also check whether
6132 NODE can adapt to the layout changes that have (perhaps provisionally)
6133 been chosen for NODE's children, so that no extra permutations are
6134 needed on either the input or the output of NODE.
6135
6136 If NODE is a VEC_PERM_EXPR and IN_LAYOUT_I >= 0, instead assume
6137 that all inputs will be forced into layout IN_LAYOUT_I beforehand.
6138
6139 IN_LAYOUT_I has no meaning for other types of node.
6140
6141 Keeping the node as-is is always valid. If the target doesn't appear
6142 to support the node as-is, but might realistically support other layouts,
6143 then layout 0 instead has the cost of a worst-case permutation. On the
6144 one hand, this ensures that every node has at least one valid layout,
6145 avoiding what would otherwise be an awkward special case. On the other,
6146 it still encourages the pass to change an invalid pre-existing layout
6147 choice into a valid one. */
6148
6149 int
6150 vect_optimize_slp_pass::internal_node_cost (slp_tree node, int in_layout_i,
6151 unsigned int out_layout_i)
6152 {
6153 const int fallback_cost = 1;
6154
6155 if (SLP_TREE_CODE (node) == VEC_PERM_EXPR)
6156 {
6157 auto_lane_permutation_t tmp_perm;
6158 tmp_perm.safe_splice (SLP_TREE_LANE_PERMUTATION (node));
6159
6160 /* Check that the child nodes support the chosen layout. Checking
6161 the first child is enough, since any second child would have the
6162 same shape. */
6163 auto first_child = SLP_TREE_CHILDREN (node)[0];
6164 if (in_layout_i > 0
6165 && !is_compatible_layout (first_child, in_layout_i))
6166 return -1;
6167
6168 change_vec_perm_layout (node, tmp_perm, in_layout_i, out_layout_i);
6169 int count = vectorizable_slp_permutation_1 (m_vinfo, nullptr,
6170 node, tmp_perm,
6171 SLP_TREE_CHILDREN (node),
6172 false);
6173 if (count < 0)
6174 {
6175 if (in_layout_i == 0 && out_layout_i == 0)
6176 {
6177 /* Use the fallback cost if the node could in principle support
6178 some nonzero layout for both the inputs and the outputs.
6179 Otherwise assume that the node will be rejected later
6180 and rebuilt from scalars. */
6181 if (SLP_TREE_LANES (node) == SLP_TREE_LANES (first_child))
6182 return fallback_cost;
6183 return 0;
6184 }
6185 return -1;
6186 }
6187
6188 /* We currently have no way of telling whether the new layout is cheaper
6189 or more expensive than the old one. But at least in principle,
6190 it should be worth making zero permutations (whole-vector shuffles)
6191 cheaper than real permutations, in case the pass is able to remove
6192 the latter. */
6193 return count == 0 ? 0 : 1;
6194 }
6195
6196 stmt_vec_info rep = SLP_TREE_REPRESENTATIVE (node);
6197 if (rep
6198 && STMT_VINFO_DATA_REF (rep)
6199 && DR_IS_READ (STMT_VINFO_DATA_REF (rep))
6200 && SLP_TREE_LOAD_PERMUTATION (node).exists ())
6201 {
6202 auto_load_permutation_t tmp_perm;
6203 tmp_perm.safe_splice (SLP_TREE_LOAD_PERMUTATION (node));
6204 if (out_layout_i > 0)
6205 vect_slp_permute (m_perms[out_layout_i], tmp_perm, true);
6206
6207 poly_uint64 vf = 1;
6208 if (auto loop_vinfo = dyn_cast<loop_vec_info> (m_vinfo))
6209 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
6210 unsigned int n_perms;
6211 if (!vect_transform_slp_perm_load_1 (m_vinfo, node, tmp_perm, vNULL,
6212 nullptr, vf, true, false, &n_perms))
6213 {
6214 auto rep = SLP_TREE_REPRESENTATIVE (node);
6215 if (out_layout_i == 0)
6216 {
6217 /* Use the fallback cost if the load is an N-to-N permutation.
6218 Otherwise assume that the node will be rejected later
6219 and rebuilt from scalars. */
6220 if (STMT_VINFO_GROUPED_ACCESS (rep)
6221 && (DR_GROUP_SIZE (DR_GROUP_FIRST_ELEMENT (rep))
6222 == SLP_TREE_LANES (node)))
6223 return fallback_cost;
6224 return 0;
6225 }
6226 return -1;
6227 }
6228
6229 /* See the comment above the corresponding VEC_PERM_EXPR handling. */
6230 return n_perms == 0 ? 0 : 1;
6231 }
6232
6233 return 0;
6234 }
6235
6236 /* Decide which element layouts we should consider using. Calculate the
6237 weights associated with inserting layout changes on partition edges.
6238 Also mark partitions that cannot change layout, by setting their
6239 layout to zero. */
6240
6241 void
6242 vect_optimize_slp_pass::start_choosing_layouts ()
6243 {
6244 /* Used to assign unique permutation indices. */
6245 using perm_hash = unbounded_hashmap_traits<
6246 vec_free_hash_base<int_hash_base<unsigned>>,
6247 int_hash<int, -1, -2>
6248 >;
6249 hash_map<vec<unsigned>, int, perm_hash> layout_ids;
6250
6251 /* Layout 0 is "no change". */
6252 m_perms.safe_push (vNULL);
6253
6254 /* Create layouts from existing permutations. */
6255 auto_load_permutation_t tmp_perm;
6256 for (unsigned int node_i : m_partitioned_nodes)
6257 {
6258 /* Leafs also double as entries to the reverse graph. Allow the
6259 layout of those to be changed. */
6260 auto &vertex = m_vertices[node_i];
6261 auto &partition = m_partitions[vertex.partition];
6262 if (!m_slpg->vertices[node_i].succ)
6263 partition.layout = 0;
6264
6265 /* Loads and VEC_PERM_EXPRs are the only things generating permutes. */
6266 slp_tree node = vertex.node;
6267 stmt_vec_info dr_stmt = SLP_TREE_REPRESENTATIVE (node);
6268 slp_tree child;
6269 unsigned HOST_WIDE_INT imin, imax = 0;
6270 bool any_permute = false;
6271 tmp_perm.truncate (0);
6272 if (SLP_TREE_LOAD_PERMUTATION (node).exists ())
6273 {
6274 /* If splitting out a SLP_TREE_LANE_PERMUTATION can make the node
6275 unpermuted, record a layout that reverses this permutation.
6276
6277 We would need more work to cope with loads that are internally
6278 permuted and also have inputs (such as masks for
6279 IFN_MASK_LOADs). */
6280 gcc_assert (partition.layout == 0 && !m_slpg->vertices[node_i].succ);
6281 if (!STMT_VINFO_GROUPED_ACCESS (dr_stmt))
6282 {
6283 partition.layout = -1;
6284 continue;
6285 }
6286 dr_stmt = DR_GROUP_FIRST_ELEMENT (dr_stmt);
6287 imin = DR_GROUP_SIZE (dr_stmt) + 1;
6288 tmp_perm.safe_splice (SLP_TREE_LOAD_PERMUTATION (node));
6289 }
6290 else if (SLP_TREE_CODE (node) == VEC_PERM_EXPR
6291 && SLP_TREE_CHILDREN (node).length () == 1
6292 && (child = SLP_TREE_CHILDREN (node)[0])
6293 && (TYPE_VECTOR_SUBPARTS (SLP_TREE_VECTYPE (child))
6294 .is_constant (&imin)))
6295 {
6296 /* If the child has the same vector size as this node,
6297 reversing the permutation can make the permutation a no-op.
6298 In other cases it can change a true permutation into a
6299 full-vector extract. */
6300 tmp_perm.reserve (SLP_TREE_LANES (node));
6301 for (unsigned j = 0; j < SLP_TREE_LANES (node); ++j)
6302 tmp_perm.quick_push (SLP_TREE_LANE_PERMUTATION (node)[j].second);
6303 }
6304 else
6305 continue;
6306
6307 for (unsigned j = 0; j < SLP_TREE_LANES (node); ++j)
6308 {
6309 unsigned idx = tmp_perm[j];
6310 imin = MIN (imin, idx);
6311 imax = MAX (imax, idx);
6312 if (idx - tmp_perm[0] != j)
6313 any_permute = true;
6314 }
6315 /* If the span doesn't match we'd disrupt VF computation, avoid
6316 that for now. */
6317 if (imax - imin + 1 != SLP_TREE_LANES (node))
6318 continue;
6319 /* If there's no permute no need to split one out. In this case
6320 we can consider turning a load into a permuted load, if that
6321 turns out to be cheaper than alternatives. */
6322 if (!any_permute)
6323 {
6324 partition.layout = -1;
6325 continue;
6326 }
6327
6328 /* For now only handle true permutes, like
6329 vect_attempt_slp_rearrange_stmts did. This allows us to be lazy
6330 when permuting constants and invariants keeping the permute
6331 bijective. */
6332 auto_sbitmap load_index (SLP_TREE_LANES (node));
6333 bitmap_clear (load_index);
6334 for (unsigned j = 0; j < SLP_TREE_LANES (node); ++j)
6335 bitmap_set_bit (load_index, tmp_perm[j] - imin);
6336 unsigned j;
6337 for (j = 0; j < SLP_TREE_LANES (node); ++j)
6338 if (!bitmap_bit_p (load_index, j))
6339 break;
6340 if (j != SLP_TREE_LANES (node))
6341 continue;
6342
6343 vec<unsigned> perm = vNULL;
6344 perm.safe_grow (SLP_TREE_LANES (node), true);
6345 for (unsigned j = 0; j < SLP_TREE_LANES (node); ++j)
6346 perm[j] = tmp_perm[j] - imin;
6347
6348 if (int (m_perms.length ()) >= param_vect_max_layout_candidates)
6349 {
6350 /* Continue to use existing layouts, but don't add any more. */
6351 int *entry = layout_ids.get (perm);
6352 partition.layout = entry ? *entry : 0;
6353 perm.release ();
6354 }
6355 else
6356 {
6357 bool existed;
6358 int &layout_i = layout_ids.get_or_insert (perm, &existed);
6359 if (existed)
6360 perm.release ();
6361 else
6362 {
6363 layout_i = m_perms.length ();
6364 m_perms.safe_push (perm);
6365 }
6366 partition.layout = layout_i;
6367 }
6368 }
6369
6370 /* Initially assume that every layout is possible and has zero cost
6371 in every partition. */
6372 m_partition_layout_costs.safe_grow_cleared (m_partitions.length ()
6373 * m_perms.length ());
6374
6375 /* We have to mark outgoing permutations facing non-associating-reduction
6376 graph entries that are not represented as to be materialized.
6377 slp_inst_kind_bb_reduc currently only covers associatable reductions. */
6378 for (slp_instance instance : m_vinfo->slp_instances)
6379 if (SLP_INSTANCE_KIND (instance) == slp_inst_kind_ctor)
6380 {
6381 unsigned int node_i = SLP_INSTANCE_TREE (instance)->vertex;
6382 m_partitions[m_vertices[node_i].partition].layout = 0;
6383 }
6384 else if (SLP_INSTANCE_KIND (instance) == slp_inst_kind_reduc_chain)
6385 {
6386 stmt_vec_info stmt_info
6387 = SLP_TREE_REPRESENTATIVE (SLP_INSTANCE_TREE (instance));
6388 stmt_vec_info reduc_info = info_for_reduction (m_vinfo, stmt_info);
6389 if (needs_fold_left_reduction_p (TREE_TYPE
6390 (gimple_get_lhs (stmt_info->stmt)),
6391 STMT_VINFO_REDUC_CODE (reduc_info)))
6392 {
6393 unsigned int node_i = SLP_INSTANCE_TREE (instance)->vertex;
6394 m_partitions[m_vertices[node_i].partition].layout = 0;
6395 }
6396 }
6397
6398 /* Check which layouts each node and partition can handle. Calculate the
6399 weights associated with inserting layout changes on edges. */
6400 for (unsigned int node_i : m_partitioned_nodes)
6401 {
6402 auto &vertex = m_vertices[node_i];
6403 auto &partition = m_partitions[vertex.partition];
6404 slp_tree node = vertex.node;
6405
6406 if (stmt_vec_info rep = SLP_TREE_REPRESENTATIVE (node))
6407 {
6408 vertex.weight = vect_slp_node_weight (node);
6409
6410 /* We do not handle stores with a permutation, so all
6411 incoming permutations must have been materialized.
6412
6413 We also don't handle masked grouped loads, which lack a
6414 permutation vector. In this case the memory locations
6415 form an implicit second input to the loads, on top of the
6416 explicit mask input, and the memory input's layout cannot
6417 be changed.
6418
6419 On the other hand, we do support permuting gather loads and
6420 masked gather loads, where each scalar load is independent
6421 of the others. This can be useful if the address/index input
6422 benefits from permutation. */
6423 if (STMT_VINFO_DATA_REF (rep)
6424 && STMT_VINFO_GROUPED_ACCESS (rep)
6425 && !SLP_TREE_LOAD_PERMUTATION (node).exists ())
6426 partition.layout = 0;
6427
6428 /* We cannot change the layout of an operation that is
6429 not independent on lanes. Note this is an explicit
6430 negative list since that's much shorter than the respective
6431 positive one but it's critical to keep maintaining it. */
6432 if (is_gimple_call (STMT_VINFO_STMT (rep)))
6433 switch (gimple_call_combined_fn (STMT_VINFO_STMT (rep)))
6434 {
6435 case CFN_COMPLEX_ADD_ROT90:
6436 case CFN_COMPLEX_ADD_ROT270:
6437 case CFN_COMPLEX_MUL:
6438 case CFN_COMPLEX_MUL_CONJ:
6439 case CFN_VEC_ADDSUB:
6440 case CFN_VEC_FMADDSUB:
6441 case CFN_VEC_FMSUBADD:
6442 partition.layout = 0;
6443 default:;
6444 }
6445 }
6446
6447 auto process_edge = [&](graph_edge *ud, unsigned int other_node_i)
6448 {
6449 auto &other_vertex = m_vertices[other_node_i];
6450
6451 /* Count the number of edges from earlier partitions and the number
6452 of edges to later partitions. */
6453 if (other_vertex.partition < vertex.partition)
6454 partition.in_degree += 1;
6455 else
6456 partition.out_degree += 1;
6457
6458 /* If the current node uses the result of OTHER_NODE_I, accumulate
6459 the effects of that. */
6460 if (ud->src == int (node_i))
6461 {
6462 other_vertex.out_weight += vertex.weight;
6463 other_vertex.out_degree += 1;
6464 }
6465 };
6466 for_each_partition_edge (node_i, process_edge);
6467 }
6468 }
6469
6470 /* Return the incoming costs for node NODE_I, assuming that each input keeps
6471 its current (provisional) choice of layout. The inputs do not necessarily
6472 have the same layout as each other. */
6473
6474 slpg_layout_cost
6475 vect_optimize_slp_pass::total_in_cost (unsigned int node_i)
6476 {
6477 auto &vertex = m_vertices[node_i];
6478 slpg_layout_cost cost;
6479 auto add_cost = [&](graph_edge *, unsigned int other_node_i)
6480 {
6481 auto &other_vertex = m_vertices[other_node_i];
6482 if (other_vertex.partition < vertex.partition)
6483 {
6484 auto &other_partition = m_partitions[other_vertex.partition];
6485 auto &other_costs = partition_layout_costs (other_vertex.partition,
6486 other_partition.layout);
6487 slpg_layout_cost this_cost = other_costs.in_cost;
6488 this_cost.add_serial_cost (other_costs.internal_cost);
6489 this_cost.split (other_partition.out_degree);
6490 cost.add_parallel_cost (this_cost);
6491 }
6492 };
6493 for_each_partition_edge (node_i, add_cost);
6494 return cost;
6495 }
6496
6497 /* Return the cost of switching between layout LAYOUT1_I (at node NODE1_I)
6498 and layout LAYOUT2_I on cross-partition use-to-def edge UD. Return
6499 slpg_layout_cost::impossible () if the change isn't possible. */
6500
6501 slpg_layout_cost
6502 vect_optimize_slp_pass::
6503 edge_layout_cost (graph_edge *ud, unsigned int node1_i, unsigned int layout1_i,
6504 unsigned int layout2_i)
6505 {
6506 auto &def_vertex = m_vertices[ud->dest];
6507 auto &use_vertex = m_vertices[ud->src];
6508 auto def_layout_i = ud->dest == int (node1_i) ? layout1_i : layout2_i;
6509 auto use_layout_i = ud->dest == int (node1_i) ? layout2_i : layout1_i;
6510 auto factor = change_layout_cost (def_vertex.node, def_layout_i,
6511 use_layout_i);
6512 if (factor < 0)
6513 return slpg_layout_cost::impossible ();
6514
6515 /* We have a choice of putting the layout change at the site of the
6516 definition or at the site of the use. Prefer the former when
6517 optimizing for size or when the execution frequency of the
6518 definition is no greater than the combined execution frequencies of
6519 the uses. When putting the layout change at the site of the definition,
6520 divvy up the cost among all consumers. */
6521 if (m_optimize_size || def_vertex.weight <= def_vertex.out_weight)
6522 {
6523 slpg_layout_cost cost = { def_vertex.weight * factor, m_optimize_size };
6524 cost.split (def_vertex.out_degree);
6525 return cost;
6526 }
6527 return { use_vertex.weight * factor, m_optimize_size };
6528 }
6529
6530 /* UD represents a use-def link between FROM_NODE_I and a node in a later
6531 partition; FROM_NODE_I could be the definition node or the use node.
6532 The node at the other end of the link wants to use layout TO_LAYOUT_I.
6533 Return the cost of any necessary fix-ups on edge UD, or return
6534 slpg_layout_cost::impossible () if the change isn't possible.
6535
6536 At this point, FROM_NODE_I's partition has chosen the cheapest
6537 layout based on the information available so far, but this choice
6538 is only provisional. */
6539
6540 slpg_layout_cost
6541 vect_optimize_slp_pass::forward_cost (graph_edge *ud, unsigned int from_node_i,
6542 unsigned int to_layout_i)
6543 {
6544 auto &from_vertex = m_vertices[from_node_i];
6545 unsigned int from_partition_i = from_vertex.partition;
6546 slpg_partition_info &from_partition = m_partitions[from_partition_i];
6547 gcc_assert (from_partition.layout >= 0);
6548
6549 /* First calculate the cost on the assumption that FROM_PARTITION sticks
6550 with its current layout preference. */
6551 slpg_layout_cost cost = slpg_layout_cost::impossible ();
6552 auto edge_cost = edge_layout_cost (ud, from_node_i,
6553 from_partition.layout, to_layout_i);
6554 if (edge_cost.is_possible ())
6555 {
6556 auto &from_costs = partition_layout_costs (from_partition_i,
6557 from_partition.layout);
6558 cost = from_costs.in_cost;
6559 cost.add_serial_cost (from_costs.internal_cost);
6560 cost.split (from_partition.out_degree);
6561 cost.add_serial_cost (edge_cost);
6562 }
6563 else if (from_partition.layout == 0)
6564 /* We must allow the source partition to have layout 0 as a fallback,
6565 in case all other options turn out to be impossible. */
6566 return cost;
6567
6568 /* Take the minimum of that cost and the cost that applies if
6569 FROM_PARTITION instead switches to TO_LAYOUT_I. */
6570 auto &direct_layout_costs = partition_layout_costs (from_partition_i,
6571 to_layout_i);
6572 if (direct_layout_costs.is_possible ())
6573 {
6574 slpg_layout_cost direct_cost = direct_layout_costs.in_cost;
6575 direct_cost.add_serial_cost (direct_layout_costs.internal_cost);
6576 direct_cost.split (from_partition.out_degree);
6577 if (!cost.is_possible ()
6578 || direct_cost.is_better_than (cost, m_optimize_size))
6579 cost = direct_cost;
6580 }
6581
6582 return cost;
6583 }
6584
6585 /* UD represents a use-def link between TO_NODE_I and a node in an earlier
6586 partition; TO_NODE_I could be the definition node or the use node.
6587 The node at the other end of the link wants to use layout FROM_LAYOUT_I;
6588 return the cost of any necessary fix-ups on edge UD, or
6589 slpg_layout_cost::impossible () if the choice cannot be made.
6590
6591 At this point, TO_NODE_I's partition has a fixed choice of layout. */
6592
6593 slpg_layout_cost
6594 vect_optimize_slp_pass::backward_cost (graph_edge *ud, unsigned int to_node_i,
6595 unsigned int from_layout_i)
6596 {
6597 auto &to_vertex = m_vertices[to_node_i];
6598 unsigned int to_partition_i = to_vertex.partition;
6599 slpg_partition_info &to_partition = m_partitions[to_partition_i];
6600 gcc_assert (to_partition.layout >= 0);
6601
6602 /* If TO_NODE_I is a VEC_PERM_EXPR consumer, see whether it can be
6603 adjusted for this input having layout FROM_LAYOUT_I. Assume that
6604 any other inputs keep their current choice of layout. */
6605 auto &to_costs = partition_layout_costs (to_partition_i,
6606 to_partition.layout);
6607 if (ud->src == int (to_node_i)
6608 && SLP_TREE_CODE (to_vertex.node) == VEC_PERM_EXPR)
6609 {
6610 auto &from_partition = m_partitions[m_vertices[ud->dest].partition];
6611 auto old_layout = from_partition.layout;
6612 from_partition.layout = from_layout_i;
6613 int factor = internal_node_cost (to_vertex.node, -1,
6614 to_partition.layout);
6615 from_partition.layout = old_layout;
6616 if (factor >= 0)
6617 {
6618 slpg_layout_cost cost = to_costs.out_cost;
6619 cost.add_serial_cost ({ to_vertex.weight * factor,
6620 m_optimize_size });
6621 cost.split (to_partition.in_degree);
6622 return cost;
6623 }
6624 }
6625
6626 /* Compute the cost if we insert any necessary layout change on edge UD. */
6627 auto edge_cost = edge_layout_cost (ud, to_node_i,
6628 to_partition.layout, from_layout_i);
6629 if (edge_cost.is_possible ())
6630 {
6631 slpg_layout_cost cost = to_costs.out_cost;
6632 cost.add_serial_cost (to_costs.internal_cost);
6633 cost.split (to_partition.in_degree);
6634 cost.add_serial_cost (edge_cost);
6635 return cost;
6636 }
6637
6638 return slpg_layout_cost::impossible ();
6639 }
6640
6641 /* Make a forward pass through the partitions, accumulating input costs.
6642 Make a tentative (provisional) choice of layout for each partition,
6643 ensuring that this choice still allows later partitions to keep
6644 their original layout. */
6645
6646 void
6647 vect_optimize_slp_pass::forward_pass ()
6648 {
6649 for (unsigned int partition_i = 0; partition_i < m_partitions.length ();
6650 ++partition_i)
6651 {
6652 auto &partition = m_partitions[partition_i];
6653
6654 /* If the partition consists of a single VEC_PERM_EXPR, precompute
6655 the incoming cost that would apply if every predecessor partition
6656 keeps its current layout. This is used within the loop below. */
6657 slpg_layout_cost in_cost;
6658 slp_tree single_node = nullptr;
6659 if (partition.node_end == partition.node_begin + 1)
6660 {
6661 unsigned int node_i = m_partitioned_nodes[partition.node_begin];
6662 single_node = m_vertices[node_i].node;
6663 if (SLP_TREE_CODE (single_node) == VEC_PERM_EXPR)
6664 in_cost = total_in_cost (node_i);
6665 }
6666
6667 /* Go through the possible layouts. Decide which ones are valid
6668 for this partition and record which of the valid layouts has
6669 the lowest cost. */
6670 unsigned int min_layout_i = 0;
6671 slpg_layout_cost min_layout_cost = slpg_layout_cost::impossible ();
6672 for (unsigned int layout_i = 0; layout_i < m_perms.length (); ++layout_i)
6673 {
6674 auto &layout_costs = partition_layout_costs (partition_i, layout_i);
6675 if (!layout_costs.is_possible ())
6676 continue;
6677
6678 /* If the recorded layout is already 0 then the layout cannot
6679 change. */
6680 if (partition.layout == 0 && layout_i != 0)
6681 {
6682 layout_costs.mark_impossible ();
6683 continue;
6684 }
6685
6686 bool is_possible = true;
6687 for (unsigned int order_i = partition.node_begin;
6688 order_i < partition.node_end; ++order_i)
6689 {
6690 unsigned int node_i = m_partitioned_nodes[order_i];
6691 auto &vertex = m_vertices[node_i];
6692
6693 /* Reject the layout if it is individually incompatible
6694 with any node in the partition. */
6695 if (!is_compatible_layout (vertex.node, layout_i))
6696 {
6697 is_possible = false;
6698 break;
6699 }
6700
6701 auto add_cost = [&](graph_edge *ud, unsigned int other_node_i)
6702 {
6703 auto &other_vertex = m_vertices[other_node_i];
6704 if (other_vertex.partition < vertex.partition)
6705 {
6706 /* Accumulate the incoming costs from earlier
6707 partitions, plus the cost of any layout changes
6708 on UD itself. */
6709 auto cost = forward_cost (ud, other_node_i, layout_i);
6710 if (!cost.is_possible ())
6711 is_possible = false;
6712 else
6713 layout_costs.in_cost.add_parallel_cost (cost);
6714 }
6715 else
6716 /* Reject the layout if it would make layout 0 impossible
6717 for later partitions. This amounts to testing that the
6718 target supports reversing the layout change on edges
6719 to later partitions.
6720
6721 In principle, it might be possible to push a layout
6722 change all the way down a graph, so that it never
6723 needs to be reversed and so that the target doesn't
6724 need to support the reverse operation. But it would
6725 be awkward to bail out if we hit a partition that
6726 does not support the new layout, especially since
6727 we are not dealing with a lattice. */
6728 is_possible &= edge_layout_cost (ud, other_node_i, 0,
6729 layout_i).is_possible ();
6730 };
6731 for_each_partition_edge (node_i, add_cost);
6732
6733 /* Accumulate the cost of using LAYOUT_I within NODE,
6734 both for the inputs and the outputs. */
6735 int factor = internal_node_cost (vertex.node, layout_i,
6736 layout_i);
6737 if (factor < 0)
6738 {
6739 is_possible = false;
6740 break;
6741 }
6742 else if (factor)
6743 layout_costs.internal_cost.add_serial_cost
6744 ({ vertex.weight * factor, m_optimize_size });
6745 }
6746 if (!is_possible)
6747 {
6748 layout_costs.mark_impossible ();
6749 continue;
6750 }
6751
6752 /* Combine the incoming and partition-internal costs. */
6753 slpg_layout_cost combined_cost = layout_costs.in_cost;
6754 combined_cost.add_serial_cost (layout_costs.internal_cost);
6755
6756 /* If this partition consists of a single VEC_PERM_EXPR, see
6757 if the VEC_PERM_EXPR can be changed to support output layout
6758 LAYOUT_I while keeping all the provisional choices of input
6759 layout. */
6760 if (single_node
6761 && SLP_TREE_CODE (single_node) == VEC_PERM_EXPR)
6762 {
6763 int factor = internal_node_cost (single_node, -1, layout_i);
6764 if (factor >= 0)
6765 {
6766 auto weight = m_vertices[single_node->vertex].weight;
6767 slpg_layout_cost internal_cost
6768 = { weight * factor, m_optimize_size };
6769
6770 slpg_layout_cost alt_cost = in_cost;
6771 alt_cost.add_serial_cost (internal_cost);
6772 if (alt_cost.is_better_than (combined_cost, m_optimize_size))
6773 {
6774 combined_cost = alt_cost;
6775 layout_costs.in_cost = in_cost;
6776 layout_costs.internal_cost = internal_cost;
6777 }
6778 }
6779 }
6780
6781 /* Record the layout with the lowest cost. Prefer layout 0 in
6782 the event of a tie between it and another layout. */
6783 if (!min_layout_cost.is_possible ()
6784 || combined_cost.is_better_than (min_layout_cost,
6785 m_optimize_size))
6786 {
6787 min_layout_i = layout_i;
6788 min_layout_cost = combined_cost;
6789 }
6790 }
6791
6792 /* This loop's handling of earlier partitions should ensure that
6793 choosing the original layout for the current partition is no
6794 less valid than it was in the original graph, even with the
6795 provisional layout choices for those earlier partitions. */
6796 gcc_assert (min_layout_cost.is_possible ());
6797 partition.layout = min_layout_i;
6798 }
6799 }
6800
6801 /* Make a backward pass through the partitions, accumulating output costs.
6802 Make a final choice of layout for each partition. */
6803
6804 void
6805 vect_optimize_slp_pass::backward_pass ()
6806 {
6807 for (unsigned int partition_i = m_partitions.length (); partition_i-- > 0;)
6808 {
6809 auto &partition = m_partitions[partition_i];
6810
6811 unsigned int min_layout_i = 0;
6812 slpg_layout_cost min_layout_cost = slpg_layout_cost::impossible ();
6813 for (unsigned int layout_i = 0; layout_i < m_perms.length (); ++layout_i)
6814 {
6815 auto &layout_costs = partition_layout_costs (partition_i, layout_i);
6816 if (!layout_costs.is_possible ())
6817 continue;
6818
6819 /* Accumulate the costs from successor partitions. */
6820 bool is_possible = true;
6821 for (unsigned int order_i = partition.node_begin;
6822 order_i < partition.node_end; ++order_i)
6823 {
6824 unsigned int node_i = m_partitioned_nodes[order_i];
6825 auto &vertex = m_vertices[node_i];
6826 auto add_cost = [&](graph_edge *ud, unsigned int other_node_i)
6827 {
6828 auto &other_vertex = m_vertices[other_node_i];
6829 auto &other_partition = m_partitions[other_vertex.partition];
6830 if (other_vertex.partition > vertex.partition)
6831 {
6832 /* Accumulate the incoming costs from later
6833 partitions, plus the cost of any layout changes
6834 on UD itself. */
6835 auto cost = backward_cost (ud, other_node_i, layout_i);
6836 if (!cost.is_possible ())
6837 is_possible = false;
6838 else
6839 layout_costs.out_cost.add_parallel_cost (cost);
6840 }
6841 else
6842 /* Make sure that earlier partitions can (if necessary
6843 or beneficial) keep the layout that they chose in
6844 the forward pass. This ensures that there is at
6845 least one valid choice of layout. */
6846 is_possible &= edge_layout_cost (ud, other_node_i,
6847 other_partition.layout,
6848 layout_i).is_possible ();
6849 };
6850 for_each_partition_edge (node_i, add_cost);
6851 }
6852 if (!is_possible)
6853 {
6854 layout_costs.mark_impossible ();
6855 continue;
6856 }
6857
6858 /* Locally combine the costs from the forward and backward passes.
6859 (This combined cost is not passed on, since that would lead
6860 to double counting.) */
6861 slpg_layout_cost combined_cost = layout_costs.in_cost;
6862 combined_cost.add_serial_cost (layout_costs.internal_cost);
6863 combined_cost.add_serial_cost (layout_costs.out_cost);
6864
6865 /* Record the layout with the lowest cost. Prefer layout 0 in
6866 the event of a tie between it and another layout. */
6867 if (!min_layout_cost.is_possible ()
6868 || combined_cost.is_better_than (min_layout_cost,
6869 m_optimize_size))
6870 {
6871 min_layout_i = layout_i;
6872 min_layout_cost = combined_cost;
6873 }
6874 }
6875
6876 gcc_assert (min_layout_cost.is_possible ());
6877 partition.layout = min_layout_i;
6878 }
6879 }
6880
6881 /* Return a node that applies layout TO_LAYOUT_I to the original form of NODE.
6882 NODE already has the layout that was selected for its partition. */
6883
6884 slp_tree
6885 vect_optimize_slp_pass::get_result_with_layout (slp_tree node,
6886 unsigned int to_layout_i)
6887 {
6888 unsigned int result_i = node->vertex * m_perms.length () + to_layout_i;
6889 slp_tree result = m_node_layouts[result_i];
6890 if (result)
6891 return result;
6892
6893 if (SLP_TREE_DEF_TYPE (node) == vect_constant_def
6894 || (SLP_TREE_DEF_TYPE (node) == vect_external_def
6895 /* We can't permute vector defs in place. */
6896 && SLP_TREE_VEC_DEFS (node).is_empty ()))
6897 {
6898 /* If the vector is uniform or unchanged, there's nothing to do. */
6899 if (to_layout_i == 0 || vect_slp_tree_uniform_p (node))
6900 result = node;
6901 else
6902 {
6903 auto scalar_ops = SLP_TREE_SCALAR_OPS (node).copy ();
6904 result = vect_create_new_slp_node (scalar_ops);
6905 vect_slp_permute (m_perms[to_layout_i], scalar_ops, true);
6906 }
6907 }
6908 else
6909 {
6910 unsigned int partition_i = m_vertices[node->vertex].partition;
6911 unsigned int from_layout_i = m_partitions[partition_i].layout;
6912 if (from_layout_i == to_layout_i)
6913 return node;
6914
6915 /* If NODE is itself a VEC_PERM_EXPR, try to create a parallel
6916 permutation instead of a serial one. Leave the new permutation
6917 in TMP_PERM on success. */
6918 auto_lane_permutation_t tmp_perm;
6919 unsigned int num_inputs = 1;
6920 if (SLP_TREE_CODE (node) == VEC_PERM_EXPR)
6921 {
6922 tmp_perm.safe_splice (SLP_TREE_LANE_PERMUTATION (node));
6923 if (from_layout_i != 0)
6924 vect_slp_permute (m_perms[from_layout_i], tmp_perm, false);
6925 if (to_layout_i != 0)
6926 vect_slp_permute (m_perms[to_layout_i], tmp_perm, true);
6927 if (vectorizable_slp_permutation_1 (m_vinfo, nullptr, node,
6928 tmp_perm,
6929 SLP_TREE_CHILDREN (node),
6930 false) >= 0)
6931 num_inputs = SLP_TREE_CHILDREN (node).length ();
6932 else
6933 tmp_perm.truncate (0);
6934 }
6935
6936 if (dump_enabled_p ())
6937 {
6938 if (tmp_perm.length () > 0)
6939 dump_printf_loc (MSG_NOTE, vect_location,
6940 "duplicating permutation node %p with"
6941 " layout %d\n",
6942 (void *) node, to_layout_i);
6943 else
6944 dump_printf_loc (MSG_NOTE, vect_location,
6945 "inserting permutation node in place of %p\n",
6946 (void *) node);
6947 }
6948
6949 unsigned int num_lanes = SLP_TREE_LANES (node);
6950 result = vect_create_new_slp_node (num_inputs, VEC_PERM_EXPR);
6951 if (SLP_TREE_SCALAR_STMTS (node).length ())
6952 {
6953 auto &stmts = SLP_TREE_SCALAR_STMTS (result);
6954 stmts.safe_splice (SLP_TREE_SCALAR_STMTS (node));
6955 if (from_layout_i != 0)
6956 vect_slp_permute (m_perms[from_layout_i], stmts, false);
6957 if (to_layout_i != 0)
6958 vect_slp_permute (m_perms[to_layout_i], stmts, true);
6959 }
6960 SLP_TREE_REPRESENTATIVE (result) = SLP_TREE_REPRESENTATIVE (node);
6961 SLP_TREE_LANES (result) = num_lanes;
6962 SLP_TREE_VECTYPE (result) = SLP_TREE_VECTYPE (node);
6963 result->vertex = -1;
6964
6965 auto &lane_perm = SLP_TREE_LANE_PERMUTATION (result);
6966 if (tmp_perm.length ())
6967 {
6968 lane_perm.safe_splice (tmp_perm);
6969 SLP_TREE_CHILDREN (result).safe_splice (SLP_TREE_CHILDREN (node));
6970 }
6971 else
6972 {
6973 lane_perm.create (num_lanes);
6974 for (unsigned j = 0; j < num_lanes; ++j)
6975 lane_perm.quick_push ({ 0, j });
6976 if (from_layout_i != 0)
6977 vect_slp_permute (m_perms[from_layout_i], lane_perm, false);
6978 if (to_layout_i != 0)
6979 vect_slp_permute (m_perms[to_layout_i], lane_perm, true);
6980 SLP_TREE_CHILDREN (result).safe_push (node);
6981 }
6982 for (slp_tree child : SLP_TREE_CHILDREN (result))
6983 child->refcnt++;
6984 }
6985 m_node_layouts[result_i] = result;
6986 return result;
6987 }
6988
6989 /* Apply the chosen vector layouts to the SLP graph. */
6990
6991 void
6992 vect_optimize_slp_pass::materialize ()
6993 {
6994 /* We no longer need the costs, so avoid having two O(N * P) arrays
6995 live at the same time. */
6996 m_partition_layout_costs.release ();
6997 m_node_layouts.safe_grow_cleared (m_vertices.length () * m_perms.length ());
6998
6999 auto_sbitmap fully_folded (m_vertices.length ());
7000 bitmap_clear (fully_folded);
7001 for (unsigned int node_i : m_partitioned_nodes)
7002 {
7003 auto &vertex = m_vertices[node_i];
7004 slp_tree node = vertex.node;
7005 int layout_i = m_partitions[vertex.partition].layout;
7006 gcc_assert (layout_i >= 0);
7007
7008 /* Rearrange the scalar statements to match the chosen layout. */
7009 if (layout_i > 0)
7010 vect_slp_permute (m_perms[layout_i],
7011 SLP_TREE_SCALAR_STMTS (node), true);
7012
7013 /* Update load and lane permutations. */
7014 if (SLP_TREE_CODE (node) == VEC_PERM_EXPR)
7015 {
7016 /* First try to absorb the input vector layouts. If that fails,
7017 force the inputs to have layout LAYOUT_I too. We checked that
7018 that was possible before deciding to use nonzero output layouts.
7019 (Note that at this stage we don't really have any guarantee that
7020 the target supports the original VEC_PERM_EXPR.) */
7021 auto &perm = SLP_TREE_LANE_PERMUTATION (node);
7022 auto_lane_permutation_t tmp_perm;
7023 tmp_perm.safe_splice (perm);
7024 change_vec_perm_layout (node, tmp_perm, -1, layout_i);
7025 if (vectorizable_slp_permutation_1 (m_vinfo, nullptr, node,
7026 tmp_perm,
7027 SLP_TREE_CHILDREN (node),
7028 false) >= 0)
7029 {
7030 if (dump_enabled_p ()
7031 && !std::equal (tmp_perm.begin (), tmp_perm.end (),
7032 perm.begin ()))
7033 dump_printf_loc (MSG_NOTE, vect_location,
7034 "absorbing input layouts into %p\n",
7035 (void *) node);
7036 std::copy (tmp_perm.begin (), tmp_perm.end (), perm.begin ());
7037 bitmap_set_bit (fully_folded, node_i);
7038 }
7039 else
7040 {
7041 /* Not MSG_MISSED because it would make no sense to users. */
7042 if (dump_enabled_p ())
7043 dump_printf_loc (MSG_NOTE, vect_location,
7044 "failed to absorb input layouts into %p\n",
7045 (void *) node);
7046 change_vec_perm_layout (nullptr, perm, layout_i, layout_i);
7047 }
7048 }
7049 else
7050 {
7051 gcc_assert (!SLP_TREE_LANE_PERMUTATION (node).exists ());
7052 auto &load_perm = SLP_TREE_LOAD_PERMUTATION (node);
7053 if (layout_i > 0)
7054 /* ??? When we handle non-bijective permutes the idea
7055 is that we can force the load-permutation to be
7056 { min, min + 1, min + 2, ... max }. But then the
7057 scalar defs might no longer match the lane content
7058 which means wrong-code with live lane vectorization.
7059 So we possibly have to have NULL entries for those. */
7060 vect_slp_permute (m_perms[layout_i], load_perm, true);
7061 }
7062 }
7063
7064 /* Do this before any nodes disappear, since it involves a walk
7065 over the leaves. */
7066 remove_redundant_permutations ();
7067
7068 /* Replace each child with a correctly laid-out version. */
7069 for (unsigned int node_i : m_partitioned_nodes)
7070 {
7071 /* Skip nodes that have already been handled above. */
7072 if (bitmap_bit_p (fully_folded, node_i))
7073 continue;
7074
7075 auto &vertex = m_vertices[node_i];
7076 int in_layout_i = m_partitions[vertex.partition].layout;
7077 gcc_assert (in_layout_i >= 0);
7078
7079 unsigned j;
7080 slp_tree child;
7081 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (vertex.node), j, child)
7082 {
7083 if (!child)
7084 continue;
7085
7086 slp_tree new_child = get_result_with_layout (child, in_layout_i);
7087 if (new_child != child)
7088 {
7089 vect_free_slp_tree (child);
7090 SLP_TREE_CHILDREN (vertex.node)[j] = new_child;
7091 new_child->refcnt += 1;
7092 }
7093 }
7094 }
7095 }
7096
7097 /* Elide load permutations that are not necessary. Such permutations might
7098 be pre-existing, rather than created by the layout optimizations. */
7099
7100 void
7101 vect_optimize_slp_pass::remove_redundant_permutations ()
7102 {
7103 for (unsigned int node_i : m_leafs)
7104 {
7105 slp_tree node = m_vertices[node_i].node;
7106 if (!SLP_TREE_LOAD_PERMUTATION (node).exists ())
7107 continue;
7108
7109 /* In basic block vectorization we allow any subchain of an interleaving
7110 chain.
7111 FORNOW: not in loop SLP because of realignment complications. */
7112 if (is_a <bb_vec_info> (m_vinfo))
7113 {
7114 bool subchain_p = true;
7115 stmt_vec_info next_load_info = NULL;
7116 stmt_vec_info load_info;
7117 unsigned j;
7118 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), j, load_info)
7119 {
7120 if (j != 0
7121 && (next_load_info != load_info
7122 || ! load_info
7123 || DR_GROUP_GAP (load_info) != 1))
7124 {
7125 subchain_p = false;
7126 break;
7127 }
7128 next_load_info = DR_GROUP_NEXT_ELEMENT (load_info);
7129 }
7130 if (subchain_p)
7131 {
7132 SLP_TREE_LOAD_PERMUTATION (node).release ();
7133 continue;
7134 }
7135 }
7136 else
7137 {
7138 loop_vec_info loop_vinfo = as_a<loop_vec_info> (m_vinfo);
7139 stmt_vec_info load_info;
7140 bool this_load_permuted = false;
7141 unsigned j;
7142 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), j, load_info)
7143 if (SLP_TREE_LOAD_PERMUTATION (node)[j] != j)
7144 {
7145 this_load_permuted = true;
7146 break;
7147 }
7148 /* When this isn't a grouped access we know it's single element
7149 and contiguous. */
7150 if (!STMT_VINFO_GROUPED_ACCESS (SLP_TREE_SCALAR_STMTS (node)[0]))
7151 {
7152 if (!this_load_permuted
7153 && (known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), 1U)
7154 || SLP_TREE_LANES (node) == 1))
7155 SLP_TREE_LOAD_PERMUTATION (node).release ();
7156 continue;
7157 }
7158 stmt_vec_info first_stmt_info
7159 = DR_GROUP_FIRST_ELEMENT (SLP_TREE_SCALAR_STMTS (node)[0]);
7160 if (!this_load_permuted
7161 /* The load requires permutation when unrolling exposes
7162 a gap either because the group is larger than the SLP
7163 group-size or because there is a gap between the groups. */
7164 && (known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), 1U)
7165 || ((SLP_TREE_LANES (node) == DR_GROUP_SIZE (first_stmt_info))
7166 && DR_GROUP_GAP (first_stmt_info) == 0)))
7167 {
7168 SLP_TREE_LOAD_PERMUTATION (node).release ();
7169 continue;
7170 }
7171 }
7172 }
7173 }
7174
7175 /* Print the partition graph and layout information to the dump file. */
7176
7177 void
7178 vect_optimize_slp_pass::dump ()
7179 {
7180 dump_printf_loc (MSG_NOTE, vect_location,
7181 "SLP optimize permutations:\n");
7182 for (unsigned int layout_i = 1; layout_i < m_perms.length (); ++layout_i)
7183 {
7184 dump_printf_loc (MSG_NOTE, vect_location, " %d: { ", layout_i);
7185 const char *sep = "";
7186 for (unsigned int idx : m_perms[layout_i])
7187 {
7188 dump_printf (MSG_NOTE, "%s%d", sep, idx);
7189 sep = ", ";
7190 }
7191 dump_printf (MSG_NOTE, " }\n");
7192 }
7193 dump_printf_loc (MSG_NOTE, vect_location,
7194 "SLP optimize partitions:\n");
7195 for (unsigned int partition_i = 0; partition_i < m_partitions.length ();
7196 ++partition_i)
7197 {
7198 auto &partition = m_partitions[partition_i];
7199 dump_printf_loc (MSG_NOTE, vect_location, " -------------\n");
7200 dump_printf_loc (MSG_NOTE, vect_location,
7201 " partition %d (layout %d):\n",
7202 partition_i, partition.layout);
7203 dump_printf_loc (MSG_NOTE, vect_location, " nodes:\n");
7204 for (unsigned int order_i = partition.node_begin;
7205 order_i < partition.node_end; ++order_i)
7206 {
7207 auto &vertex = m_vertices[m_partitioned_nodes[order_i]];
7208 dump_printf_loc (MSG_NOTE, vect_location, " - %p:\n",
7209 (void *) vertex.node);
7210 dump_printf_loc (MSG_NOTE, vect_location,
7211 " weight: %f\n",
7212 vertex.weight.to_double ());
7213 if (vertex.out_degree)
7214 dump_printf_loc (MSG_NOTE, vect_location,
7215 " out weight: %f (degree %d)\n",
7216 vertex.out_weight.to_double (),
7217 vertex.out_degree);
7218 if (SLP_TREE_CODE (vertex.node) == VEC_PERM_EXPR)
7219 dump_printf_loc (MSG_NOTE, vect_location,
7220 " op: VEC_PERM_EXPR\n");
7221 else if (auto rep = SLP_TREE_REPRESENTATIVE (vertex.node))
7222 dump_printf_loc (MSG_NOTE, vect_location,
7223 " op template: %G", rep->stmt);
7224 }
7225 dump_printf_loc (MSG_NOTE, vect_location, " edges:\n");
7226 for (unsigned int order_i = partition.node_begin;
7227 order_i < partition.node_end; ++order_i)
7228 {
7229 unsigned int node_i = m_partitioned_nodes[order_i];
7230 auto &vertex = m_vertices[node_i];
7231 auto print_edge = [&](graph_edge *, unsigned int other_node_i)
7232 {
7233 auto &other_vertex = m_vertices[other_node_i];
7234 if (other_vertex.partition < vertex.partition)
7235 dump_printf_loc (MSG_NOTE, vect_location,
7236 " - %p [%d] --> %p\n",
7237 (void *) other_vertex.node,
7238 other_vertex.partition,
7239 (void *) vertex.node);
7240 else
7241 dump_printf_loc (MSG_NOTE, vect_location,
7242 " - %p --> [%d] %p\n",
7243 (void *) vertex.node,
7244 other_vertex.partition,
7245 (void *) other_vertex.node);
7246 };
7247 for_each_partition_edge (node_i, print_edge);
7248 }
7249
7250 for (unsigned int layout_i = 0; layout_i < m_perms.length (); ++layout_i)
7251 {
7252 auto &layout_costs = partition_layout_costs (partition_i, layout_i);
7253 if (layout_costs.is_possible ())
7254 {
7255 dump_printf_loc (MSG_NOTE, vect_location,
7256 " layout %d:%s\n", layout_i,
7257 partition.layout == int (layout_i)
7258 ? " (*)" : "");
7259 slpg_layout_cost combined_cost = layout_costs.in_cost;
7260 combined_cost.add_serial_cost (layout_costs.internal_cost);
7261 combined_cost.add_serial_cost (layout_costs.out_cost);
7262 #define TEMPLATE "{depth: %f, total: %f}"
7263 dump_printf_loc (MSG_NOTE, vect_location,
7264 " " TEMPLATE "\n",
7265 layout_costs.in_cost.depth.to_double (),
7266 layout_costs.in_cost.total.to_double ());
7267 dump_printf_loc (MSG_NOTE, vect_location,
7268 " + " TEMPLATE "\n",
7269 layout_costs.internal_cost.depth.to_double (),
7270 layout_costs.internal_cost.total.to_double ());
7271 dump_printf_loc (MSG_NOTE, vect_location,
7272 " + " TEMPLATE "\n",
7273 layout_costs.out_cost.depth.to_double (),
7274 layout_costs.out_cost.total.to_double ());
7275 dump_printf_loc (MSG_NOTE, vect_location,
7276 " = " TEMPLATE "\n",
7277 combined_cost.depth.to_double (),
7278 combined_cost.total.to_double ());
7279 #undef TEMPLATE
7280 }
7281 else
7282 dump_printf_loc (MSG_NOTE, vect_location,
7283 " layout %d: rejected\n", layout_i);
7284 }
7285 }
7286 }
7287
7288 /* Masked load lanes discovery. */
7289
7290 void
7291 vect_optimize_slp_pass::decide_masked_load_lanes ()
7292 {
7293 for (auto v : m_vertices)
7294 {
7295 slp_tree node = v.node;
7296 if (SLP_TREE_DEF_TYPE (node) != vect_internal_def
7297 || SLP_TREE_CODE (node) == VEC_PERM_EXPR)
7298 continue;
7299 stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (node);
7300 if (! STMT_VINFO_GROUPED_ACCESS (stmt_info)
7301 /* The mask has to be uniform. */
7302 || STMT_VINFO_SLP_VECT_ONLY (stmt_info)
7303 || ! is_a <gcall *> (STMT_VINFO_STMT (stmt_info))
7304 || ! gimple_call_internal_p (STMT_VINFO_STMT (stmt_info),
7305 IFN_MASK_LOAD))
7306 continue;
7307 stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
7308 if (STMT_VINFO_STRIDED_P (stmt_info)
7309 || compare_step_with_zero (m_vinfo, stmt_info) <= 0
7310 || vect_load_lanes_supported (SLP_TREE_VECTYPE (node),
7311 DR_GROUP_SIZE (stmt_info),
7312 true) == IFN_LAST)
7313 continue;
7314
7315 /* Uniform masks need to be suitably represented. */
7316 slp_tree mask = SLP_TREE_CHILDREN (node)[0];
7317 if (SLP_TREE_CODE (mask) != VEC_PERM_EXPR
7318 || SLP_TREE_CHILDREN (mask).length () != 1)
7319 continue;
7320 bool match = true;
7321 for (auto perm : SLP_TREE_LANE_PERMUTATION (mask))
7322 if (perm.first != 0 || perm.second != 0)
7323 {
7324 match = false;
7325 break;
7326 }
7327 if (!match)
7328 continue;
7329
7330 /* Now see if the consumer side matches. */
7331 for (graph_edge *pred = m_slpg->vertices[node->vertex].pred;
7332 pred; pred = pred->pred_next)
7333 {
7334 slp_tree pred_node = m_vertices[pred->src].node;
7335 /* All consumers should be a permute with a single outgoing lane. */
7336 if (SLP_TREE_CODE (pred_node) != VEC_PERM_EXPR
7337 || SLP_TREE_LANES (pred_node) != 1)
7338 {
7339 match = false;
7340 break;
7341 }
7342 gcc_assert (SLP_TREE_CHILDREN (pred_node).length () == 1);
7343 }
7344 if (!match)
7345 continue;
7346 /* Now we can mark the nodes as to use load lanes. */
7347 node->ldst_lanes = true;
7348 for (graph_edge *pred = m_slpg->vertices[node->vertex].pred;
7349 pred; pred = pred->pred_next)
7350 m_vertices[pred->src].node->ldst_lanes = true;
7351 /* The catch is we have to massage the mask. We have arranged
7352 analyzed uniform masks to be represented by a splat VEC_PERM
7353 which we can now simply elide as we cannot easily re-do SLP
7354 discovery here. */
7355 slp_tree new_mask = SLP_TREE_CHILDREN (mask)[0];
7356 SLP_TREE_REF_COUNT (new_mask)++;
7357 SLP_TREE_CHILDREN (node)[0] = new_mask;
7358 vect_free_slp_tree (mask);
7359 }
7360 }
7361
7362 /* Main entry point for the SLP graph optimization pass. */
7363
7364 void
7365 vect_optimize_slp_pass::run ()
7366 {
7367 build_graph ();
7368 create_partitions ();
7369 start_choosing_layouts ();
7370 if (m_perms.length () > 1)
7371 {
7372 forward_pass ();
7373 backward_pass ();
7374 if (dump_enabled_p ())
7375 dump ();
7376 materialize ();
7377 while (!m_perms.is_empty ())
7378 m_perms.pop ().release ();
7379 }
7380 else
7381 remove_redundant_permutations ();
7382 free_graph (m_slpg);
7383 build_graph ();
7384 decide_masked_load_lanes ();
7385 free_graph (m_slpg);
7386 }
7387
7388 /* Apply CSE to NODE and its children using BST_MAP. */
7389
7390 static void
7391 vect_cse_slp_nodes (scalar_stmts_to_slp_tree_map_t *bst_map, slp_tree& node)
7392 {
7393 bool put_p = false;
7394 if (SLP_TREE_DEF_TYPE (node) == vect_internal_def
7395 /* Besides some VEC_PERM_EXPR, two-operator nodes also
7396 lack scalar stmts and thus CSE doesn't work via bst_map. Ideally
7397 we'd have sth that works for all internal and external nodes. */
7398 && !SLP_TREE_SCALAR_STMTS (node).is_empty ())
7399 {
7400 slp_tree *leader = bst_map->get (SLP_TREE_SCALAR_STMTS (node));
7401 if (leader)
7402 {
7403 /* We've visited this node already. */
7404 if (!*leader || *leader == node)
7405 return;
7406
7407 if (dump_enabled_p ())
7408 dump_printf_loc (MSG_NOTE, vect_location,
7409 "re-using SLP tree %p for %p\n",
7410 (void *)*leader, (void *)node);
7411 vect_free_slp_tree (node);
7412 (*leader)->refcnt += 1;
7413 node = *leader;
7414 return;
7415 }
7416
7417 /* Avoid creating a cycle by populating the map only after recursion. */
7418 bst_map->put (SLP_TREE_SCALAR_STMTS (node).copy (), nullptr);
7419 node->refcnt += 1;
7420 put_p = true;
7421 /* And recurse. */
7422 }
7423
7424 for (slp_tree &child : SLP_TREE_CHILDREN (node))
7425 if (child)
7426 vect_cse_slp_nodes (bst_map, child);
7427
7428 /* Now record the node for CSE in other siblings. */
7429 if (put_p)
7430 *bst_map->get (SLP_TREE_SCALAR_STMTS (node)) = node;
7431 }
7432
7433 /* Optimize the SLP graph of VINFO. */
7434
7435 void
7436 vect_optimize_slp (vec_info *vinfo)
7437 {
7438 if (vinfo->slp_instances.is_empty ())
7439 return;
7440 vect_optimize_slp_pass (vinfo).run ();
7441
7442 /* Apply CSE again to nodes after permute optimization. */
7443 scalar_stmts_to_slp_tree_map_t *bst_map
7444 = new scalar_stmts_to_slp_tree_map_t ();
7445
7446 for (auto inst : vinfo->slp_instances)
7447 vect_cse_slp_nodes (bst_map, SLP_INSTANCE_TREE (inst));
7448
7449 release_scalar_stmts_to_slp_tree_map (bst_map);
7450 }
7451
7452 /* Gather loads reachable from the individual SLP graph entries. */
7453
7454 void
7455 vect_gather_slp_loads (vec_info *vinfo)
7456 {
7457 unsigned i;
7458 slp_instance instance;
7459 FOR_EACH_VEC_ELT (vinfo->slp_instances, i, instance)
7460 {
7461 hash_set<slp_tree> visited;
7462 vect_gather_slp_loads (SLP_INSTANCE_LOADS (instance),
7463 SLP_INSTANCE_TREE (instance), visited);
7464 }
7465 }
7466
7467 /* For NODE update VF based on the number of lanes and the vector types
7468 used. */
7469
7470 static void
7471 vect_update_slp_vf_for_node (slp_tree node, poly_uint64 &vf,
7472 hash_set<slp_tree> &visited)
7473 {
7474 if (!node || SLP_TREE_DEF_TYPE (node) != vect_internal_def)
7475 return;
7476 if (visited.add (node))
7477 return;
7478
7479 for (slp_tree child : SLP_TREE_CHILDREN (node))
7480 vect_update_slp_vf_for_node (child, vf, visited);
7481
7482 /* We do not visit SLP nodes for constants or externals - those neither
7483 have a vector type set yet (vectorizable_* does this) nor do they
7484 have max_nunits set. Instead we rely on internal nodes max_nunit
7485 to cover constant/external operands.
7486 Note that when we stop using fixed size vectors externs and constants
7487 shouldn't influence the (minimum) vectorization factor, instead
7488 vectorizable_* should honor the vectorization factor when trying to
7489 assign vector types to constants and externals and cause iteration
7490 to a higher vectorization factor when required. */
7491 poly_uint64 node_vf
7492 = calculate_unrolling_factor (node->max_nunits, SLP_TREE_LANES (node));
7493 vf = force_common_multiple (vf, node_vf);
7494
7495 /* For permute nodes that are fed from externs or constants we have to
7496 consider their number of lanes as well. Likewise for store-lanes. */
7497 if (SLP_TREE_CODE (node) == VEC_PERM_EXPR
7498 || node->ldst_lanes)
7499 for (slp_tree child : SLP_TREE_CHILDREN (node))
7500 if (SLP_TREE_DEF_TYPE (child) != vect_internal_def)
7501 {
7502 poly_uint64 child_vf
7503 = calculate_unrolling_factor (node->max_nunits,
7504 SLP_TREE_LANES (child));
7505 vf = force_common_multiple (vf, child_vf);
7506 }
7507 }
7508
7509 /* For each possible SLP instance decide whether to SLP it and calculate overall
7510 unrolling factor needed to SLP the loop. Return TRUE if decided to SLP at
7511 least one instance. */
7512
7513 bool
7514 vect_make_slp_decision (loop_vec_info loop_vinfo)
7515 {
7516 unsigned int i;
7517 poly_uint64 unrolling_factor = 1;
7518 const vec<slp_instance> &slp_instances
7519 = LOOP_VINFO_SLP_INSTANCES (loop_vinfo);
7520 slp_instance instance;
7521 int decided_to_slp = 0;
7522
7523 DUMP_VECT_SCOPE ("vect_make_slp_decision");
7524
7525 hash_set<slp_tree> visited;
7526 FOR_EACH_VEC_ELT (slp_instances, i, instance)
7527 {
7528 /* FORNOW: SLP if you can. */
7529 /* All unroll factors have the form:
7530
7531 GET_MODE_SIZE (vinfo->vector_mode) * X
7532
7533 for some rational X, so they must have a common multiple. */
7534 vect_update_slp_vf_for_node (SLP_INSTANCE_TREE (instance),
7535 unrolling_factor, visited);
7536
7537 /* Mark all the stmts that belong to INSTANCE as PURE_SLP stmts. Later we
7538 call vect_detect_hybrid_slp () to find stmts that need hybrid SLP and
7539 loop-based vectorization. Such stmts will be marked as HYBRID. */
7540 vect_mark_slp_stmts (loop_vinfo, SLP_INSTANCE_TREE (instance));
7541 decided_to_slp++;
7542 }
7543
7544 LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo) = unrolling_factor;
7545
7546 if (decided_to_slp && dump_enabled_p ())
7547 {
7548 dump_printf_loc (MSG_NOTE, vect_location,
7549 "Decided to SLP %d instances. Unrolling factor ",
7550 decided_to_slp);
7551 dump_dec (MSG_NOTE, unrolling_factor);
7552 dump_printf (MSG_NOTE, "\n");
7553 }
7554
7555 return (decided_to_slp > 0);
7556 }
7557
7558 /* Private data for vect_detect_hybrid_slp. */
7559 struct vdhs_data
7560 {
7561 loop_vec_info loop_vinfo;
7562 vec<stmt_vec_info> *worklist;
7563 };
7564
7565 /* Walker for walk_gimple_op. */
7566
7567 static tree
7568 vect_detect_hybrid_slp (tree *tp, int *, void *data)
7569 {
7570 walk_stmt_info *wi = (walk_stmt_info *)data;
7571 vdhs_data *dat = (vdhs_data *)wi->info;
7572
7573 if (wi->is_lhs)
7574 return NULL_TREE;
7575
7576 stmt_vec_info def_stmt_info = dat->loop_vinfo->lookup_def (*tp);
7577 if (!def_stmt_info)
7578 return NULL_TREE;
7579 def_stmt_info = vect_stmt_to_vectorize (def_stmt_info);
7580 if (PURE_SLP_STMT (def_stmt_info))
7581 {
7582 if (dump_enabled_p ())
7583 dump_printf_loc (MSG_NOTE, vect_location, "marking hybrid: %G",
7584 def_stmt_info->stmt);
7585 STMT_SLP_TYPE (def_stmt_info) = hybrid;
7586 dat->worklist->safe_push (def_stmt_info);
7587 }
7588
7589 return NULL_TREE;
7590 }
7591
7592 /* Look if STMT_INFO is consumed by SLP indirectly and mark it pure_slp
7593 if so, otherwise pushing it to WORKLIST. */
7594
7595 static void
7596 maybe_push_to_hybrid_worklist (vec_info *vinfo,
7597 vec<stmt_vec_info> &worklist,
7598 stmt_vec_info stmt_info)
7599 {
7600 if (dump_enabled_p ())
7601 dump_printf_loc (MSG_NOTE, vect_location,
7602 "Processing hybrid candidate : %G", stmt_info->stmt);
7603 stmt_vec_info orig_info = vect_orig_stmt (stmt_info);
7604 imm_use_iterator iter2;
7605 ssa_op_iter iter1;
7606 use_operand_p use_p;
7607 def_operand_p def_p;
7608 bool any_def = false;
7609 FOR_EACH_PHI_OR_STMT_DEF (def_p, orig_info->stmt, iter1, SSA_OP_DEF)
7610 {
7611 any_def = true;
7612 FOR_EACH_IMM_USE_FAST (use_p, iter2, DEF_FROM_PTR (def_p))
7613 {
7614 if (is_gimple_debug (USE_STMT (use_p)))
7615 continue;
7616 stmt_vec_info use_info = vinfo->lookup_stmt (USE_STMT (use_p));
7617 /* An out-of loop use means this is a loop_vect sink. */
7618 if (!use_info)
7619 {
7620 if (dump_enabled_p ())
7621 dump_printf_loc (MSG_NOTE, vect_location,
7622 "Found loop_vect sink: %G", stmt_info->stmt);
7623 worklist.safe_push (stmt_info);
7624 return;
7625 }
7626 else if (!STMT_SLP_TYPE (vect_stmt_to_vectorize (use_info)))
7627 {
7628 if (dump_enabled_p ())
7629 dump_printf_loc (MSG_NOTE, vect_location,
7630 "Found loop_vect use: %G", use_info->stmt);
7631 worklist.safe_push (stmt_info);
7632 return;
7633 }
7634 }
7635 }
7636 /* No def means this is a loop_vect sink. Gimple conditionals also don't have a
7637 def but shouldn't be considered sinks. */
7638 if (!any_def && STMT_VINFO_DEF_TYPE (stmt_info) != vect_condition_def)
7639 {
7640 if (dump_enabled_p ())
7641 dump_printf_loc (MSG_NOTE, vect_location,
7642 "Found loop_vect sink: %G", stmt_info->stmt);
7643 worklist.safe_push (stmt_info);
7644 return;
7645 }
7646 if (dump_enabled_p ())
7647 dump_printf_loc (MSG_NOTE, vect_location,
7648 "Marked SLP consumed stmt pure: %G", stmt_info->stmt);
7649 STMT_SLP_TYPE (stmt_info) = pure_slp;
7650 }
7651
7652 /* Find stmts that must be both vectorized and SLPed. */
7653
7654 void
7655 vect_detect_hybrid_slp (loop_vec_info loop_vinfo)
7656 {
7657 DUMP_VECT_SCOPE ("vect_detect_hybrid_slp");
7658
7659 /* All stmts participating in SLP are marked pure_slp, all other
7660 stmts are loop_vect.
7661 First collect all loop_vect stmts into a worklist.
7662 SLP patterns cause not all original scalar stmts to appear in
7663 SLP_TREE_SCALAR_STMTS and thus not all of them are marked pure_slp.
7664 Rectify this here and do a backward walk over the IL only considering
7665 stmts as loop_vect when they are used by a loop_vect stmt and otherwise
7666 mark them as pure_slp. */
7667 auto_vec<stmt_vec_info> worklist;
7668 for (int i = LOOP_VINFO_LOOP (loop_vinfo)->num_nodes - 1; i >= 0; --i)
7669 {
7670 basic_block bb = LOOP_VINFO_BBS (loop_vinfo)[i];
7671 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
7672 gsi_next (&gsi))
7673 {
7674 gphi *phi = gsi.phi ();
7675 stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (phi);
7676 if (!STMT_SLP_TYPE (stmt_info) && STMT_VINFO_RELEVANT (stmt_info))
7677 maybe_push_to_hybrid_worklist (loop_vinfo,
7678 worklist, stmt_info);
7679 }
7680 for (gimple_stmt_iterator gsi = gsi_last_bb (bb); !gsi_end_p (gsi);
7681 gsi_prev (&gsi))
7682 {
7683 gimple *stmt = gsi_stmt (gsi);
7684 if (is_gimple_debug (stmt))
7685 continue;
7686 stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (stmt);
7687 if (STMT_VINFO_IN_PATTERN_P (stmt_info))
7688 {
7689 for (gimple_stmt_iterator gsi2
7690 = gsi_start (STMT_VINFO_PATTERN_DEF_SEQ (stmt_info));
7691 !gsi_end_p (gsi2); gsi_next (&gsi2))
7692 {
7693 stmt_vec_info patt_info
7694 = loop_vinfo->lookup_stmt (gsi_stmt (gsi2));
7695 if (!STMT_SLP_TYPE (patt_info)
7696 && STMT_VINFO_RELEVANT (patt_info))
7697 maybe_push_to_hybrid_worklist (loop_vinfo,
7698 worklist, patt_info);
7699 }
7700 stmt_info = STMT_VINFO_RELATED_STMT (stmt_info);
7701 }
7702 if (!STMT_SLP_TYPE (stmt_info) && STMT_VINFO_RELEVANT (stmt_info))
7703 maybe_push_to_hybrid_worklist (loop_vinfo,
7704 worklist, stmt_info);
7705 }
7706 }
7707
7708 /* Now we have a worklist of non-SLP stmts, follow use->def chains and
7709 mark any SLP vectorized stmt as hybrid.
7710 ??? We're visiting def stmts N times (once for each non-SLP and
7711 once for each hybrid-SLP use). */
7712 walk_stmt_info wi;
7713 vdhs_data dat;
7714 dat.worklist = &worklist;
7715 dat.loop_vinfo = loop_vinfo;
7716 memset (&wi, 0, sizeof (wi));
7717 wi.info = (void *)&dat;
7718 while (!worklist.is_empty ())
7719 {
7720 stmt_vec_info stmt_info = worklist.pop ();
7721 /* Since SSA operands are not set up for pattern stmts we need
7722 to use walk_gimple_op. */
7723 wi.is_lhs = 0;
7724 walk_gimple_op (stmt_info->stmt, vect_detect_hybrid_slp, &wi);
7725 /* For gather/scatter make sure to walk the offset operand, that
7726 can be a scaling and conversion away. */
7727 gather_scatter_info gs_info;
7728 if (STMT_VINFO_GATHER_SCATTER_P (stmt_info)
7729 && vect_check_gather_scatter (stmt_info, loop_vinfo, &gs_info))
7730 {
7731 int dummy;
7732 vect_detect_hybrid_slp (&gs_info.offset, &dummy, &wi);
7733 }
7734 }
7735 }
7736
7737
7738 /* Initialize a bb_vec_info struct for the statements in BBS basic blocks. */
7739
7740 _bb_vec_info::_bb_vec_info (vec<basic_block> _bbs, vec_info_shared *shared)
7741 : vec_info (vec_info::bb, shared),
7742 roots (vNULL)
7743 {
7744 /* The region we are operating on. bbs[0] is the entry, excluding
7745 its PHI nodes. In the future we might want to track an explicit
7746 entry edge to cover bbs[0] PHI nodes and have a region entry
7747 insert location. */
7748 bbs = _bbs.address ();
7749 nbbs = _bbs.length ();
7750
7751 for (unsigned i = 0; i < nbbs; ++i)
7752 {
7753 if (i != 0)
7754 for (gphi_iterator si = gsi_start_phis (bbs[i]); !gsi_end_p (si);
7755 gsi_next (&si))
7756 {
7757 gphi *phi = si.phi ();
7758 gimple_set_uid (phi, 0);
7759 add_stmt (phi);
7760 }
7761 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
7762 !gsi_end_p (gsi); gsi_next (&gsi))
7763 {
7764 gimple *stmt = gsi_stmt (gsi);
7765 gimple_set_uid (stmt, 0);
7766 if (is_gimple_debug (stmt))
7767 continue;
7768 add_stmt (stmt);
7769 }
7770 }
7771 }
7772
7773
7774 /* Free BB_VINFO struct, as well as all the stmt_vec_info structs of all the
7775 stmts in the basic block. */
7776
7777 _bb_vec_info::~_bb_vec_info ()
7778 {
7779 /* Reset region marker. */
7780 for (unsigned i = 0; i < nbbs; ++i)
7781 {
7782 if (i != 0)
7783 for (gphi_iterator si = gsi_start_phis (bbs[i]); !gsi_end_p (si);
7784 gsi_next (&si))
7785 {
7786 gphi *phi = si.phi ();
7787 gimple_set_uid (phi, -1);
7788 }
7789 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
7790 !gsi_end_p (gsi); gsi_next (&gsi))
7791 {
7792 gimple *stmt = gsi_stmt (gsi);
7793 gimple_set_uid (stmt, -1);
7794 }
7795 }
7796
7797 for (unsigned i = 0; i < roots.length (); ++i)
7798 {
7799 roots[i].stmts.release ();
7800 roots[i].roots.release ();
7801 roots[i].remain.release ();
7802 }
7803 roots.release ();
7804 }
7805
7806 /* Subroutine of vect_slp_analyze_node_operations. Handle the root of NODE,
7807 given then that child nodes have already been processed, and that
7808 their def types currently match their SLP node's def type. */
7809
7810 static bool
7811 vect_slp_analyze_node_operations_1 (vec_info *vinfo, slp_tree node,
7812 slp_instance node_instance,
7813 stmt_vector_for_cost *cost_vec)
7814 {
7815 stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (node);
7816
7817 /* Calculate the number of vector statements to be created for the scalar
7818 stmts in this node. It is the number of scalar elements in one scalar
7819 iteration (DR_GROUP_SIZE) multiplied by VF divided by the number of
7820 elements in a vector. For single-defuse-cycle, lane-reducing op, and
7821 PHI statement that starts reduction comprised of only lane-reducing ops,
7822 the number is more than effective vector statements actually required. */
7823 SLP_TREE_NUMBER_OF_VEC_STMTS (node) = vect_get_num_copies (vinfo, node);
7824
7825 /* Handle purely internal nodes. */
7826 if (SLP_TREE_CODE (node) == VEC_PERM_EXPR)
7827 {
7828 if (!vectorizable_slp_permutation (vinfo, NULL, node, cost_vec))
7829 return false;
7830
7831 stmt_vec_info slp_stmt_info;
7832 unsigned int i;
7833 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, slp_stmt_info)
7834 {
7835 if (slp_stmt_info
7836 && STMT_VINFO_LIVE_P (slp_stmt_info)
7837 && !vectorizable_live_operation (vinfo, slp_stmt_info, node,
7838 node_instance, i,
7839 false, cost_vec))
7840 return false;
7841 }
7842 return true;
7843 }
7844
7845 bool dummy;
7846 return vect_analyze_stmt (vinfo, stmt_info, &dummy,
7847 node, node_instance, cost_vec);
7848 }
7849
7850 static int
7851 sort_ints (const void *a_, const void *b_)
7852 {
7853 int a = *(const int *)a_;
7854 int b = *(const int *)b_;
7855 return a - b;
7856 }
7857
7858 /* Verify if we can externalize a set of internal defs. */
7859
7860 static bool
7861 vect_slp_can_convert_to_external (const vec<stmt_vec_info> &stmts)
7862 {
7863 /* Constant generation uses get_later_stmt which can only handle
7864 defs from the same BB or a set of defs that can be ordered
7865 with a dominance query. */
7866 basic_block bb = NULL;
7867 bool all_same = true;
7868 auto_vec<int> bbs;
7869 bbs.reserve_exact (stmts.length ());
7870 for (stmt_vec_info stmt : stmts)
7871 {
7872 if (!stmt)
7873 return false;
7874 else if (!bb)
7875 bb = gimple_bb (stmt->stmt);
7876 else if (gimple_bb (stmt->stmt) != bb)
7877 all_same = false;
7878 bbs.quick_push (gimple_bb (stmt->stmt)->index);
7879 }
7880 if (all_same)
7881 return true;
7882
7883 /* Produce a vector of unique BB indexes for the defs. */
7884 bbs.qsort (sort_ints);
7885 unsigned i, j;
7886 for (i = 1, j = 1; i < bbs.length (); ++i)
7887 if (bbs[i] != bbs[j-1])
7888 bbs[j++] = bbs[i];
7889 gcc_assert (j >= 2);
7890 bbs.truncate (j);
7891
7892 if (bbs.length () == 2)
7893 return (dominated_by_p (CDI_DOMINATORS,
7894 BASIC_BLOCK_FOR_FN (cfun, bbs[0]),
7895 BASIC_BLOCK_FOR_FN (cfun, bbs[1]))
7896 || dominated_by_p (CDI_DOMINATORS,
7897 BASIC_BLOCK_FOR_FN (cfun, bbs[1]),
7898 BASIC_BLOCK_FOR_FN (cfun, bbs[0])));
7899
7900 /* ??? For more than two BBs we can sort the vector and verify the
7901 result is a total order. But we can't use vec::qsort with a
7902 compare function using a dominance query since there's no way to
7903 signal failure and any fallback for an unordered pair would
7904 fail qsort_chk later.
7905 For now simply hope that ordering after BB index provides the
7906 best candidate total order. If required we can implement our
7907 own mergesort or export an entry without checking. */
7908 for (unsigned i = 1; i < bbs.length (); ++i)
7909 if (!dominated_by_p (CDI_DOMINATORS,
7910 BASIC_BLOCK_FOR_FN (cfun, bbs[i]),
7911 BASIC_BLOCK_FOR_FN (cfun, bbs[i-1])))
7912 return false;
7913
7914 return true;
7915 }
7916
7917 /* Try to build NODE from scalars, returning true on success.
7918 NODE_INSTANCE is the SLP instance that contains NODE. */
7919
7920 static bool
7921 vect_slp_convert_to_external (vec_info *vinfo, slp_tree node,
7922 slp_instance node_instance)
7923 {
7924 stmt_vec_info stmt_info;
7925 unsigned int i;
7926
7927 if (!is_a <bb_vec_info> (vinfo)
7928 || node == SLP_INSTANCE_TREE (node_instance)
7929 || !SLP_TREE_SCALAR_STMTS (node).exists ()
7930 || vect_contains_pattern_stmt_p (SLP_TREE_SCALAR_STMTS (node))
7931 /* Force the mask use to be built from scalars instead. */
7932 || VECTOR_BOOLEAN_TYPE_P (SLP_TREE_VECTYPE (node))
7933 || !vect_slp_can_convert_to_external (SLP_TREE_SCALAR_STMTS (node)))
7934 return false;
7935
7936 if (dump_enabled_p ())
7937 dump_printf_loc (MSG_NOTE, vect_location,
7938 "Building vector operands of %p from scalars instead\n",
7939 (void *) node);
7940
7941 /* Don't remove and free the child nodes here, since they could be
7942 referenced by other structures. The analysis and scheduling phases
7943 (need to) ignore child nodes of anything that isn't vect_internal_def. */
7944 unsigned int group_size = SLP_TREE_LANES (node);
7945 SLP_TREE_DEF_TYPE (node) = vect_external_def;
7946 /* Invariants get their vector type from the uses. */
7947 SLP_TREE_VECTYPE (node) = NULL_TREE;
7948 SLP_TREE_SCALAR_OPS (node).safe_grow (group_size, true);
7949 SLP_TREE_LOAD_PERMUTATION (node).release ();
7950 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
7951 {
7952 tree lhs = gimple_get_lhs (vect_orig_stmt (stmt_info)->stmt);
7953 SLP_TREE_SCALAR_OPS (node)[i] = lhs;
7954 }
7955 return true;
7956 }
7957
7958 /* Return true if all elements of the slice are the same. */
7959 bool
7960 vect_scalar_ops_slice::all_same_p () const
7961 {
7962 for (unsigned int i = 1; i < length; ++i)
7963 if (!operand_equal_p (op (0), op (i)))
7964 return false;
7965 return true;
7966 }
7967
7968 hashval_t
7969 vect_scalar_ops_slice_hash::hash (const value_type &s)
7970 {
7971 hashval_t hash = 0;
7972 for (unsigned i = 0; i < s.length; ++i)
7973 hash = iterative_hash_expr (s.op (i), hash);
7974 return hash;
7975 }
7976
7977 bool
7978 vect_scalar_ops_slice_hash::equal (const value_type &s1,
7979 const compare_type &s2)
7980 {
7981 if (s1.length != s2.length)
7982 return false;
7983 for (unsigned i = 0; i < s1.length; ++i)
7984 if (!operand_equal_p (s1.op (i), s2.op (i)))
7985 return false;
7986 return true;
7987 }
7988
7989 /* Compute the prologue cost for invariant or constant operands represented
7990 by NODE. */
7991
7992 static void
7993 vect_prologue_cost_for_slp (slp_tree node,
7994 stmt_vector_for_cost *cost_vec)
7995 {
7996 /* There's a special case of an existing vector, that costs nothing. */
7997 if (SLP_TREE_SCALAR_OPS (node).length () == 0
7998 && !SLP_TREE_VEC_DEFS (node).is_empty ())
7999 return;
8000 /* Without looking at the actual initializer a vector of
8001 constants can be implemented as load from the constant pool.
8002 When all elements are the same we can use a splat. */
8003 tree vectype = SLP_TREE_VECTYPE (node);
8004 unsigned group_size = SLP_TREE_SCALAR_OPS (node).length ();
8005 unsigned HOST_WIDE_INT const_nunits;
8006 unsigned nelt_limit;
8007 auto ops = &SLP_TREE_SCALAR_OPS (node);
8008 auto_vec<unsigned int> starts (SLP_TREE_NUMBER_OF_VEC_STMTS (node));
8009 if (TYPE_VECTOR_SUBPARTS (vectype).is_constant (&const_nunits)
8010 && ! multiple_p (const_nunits, group_size))
8011 {
8012 nelt_limit = const_nunits;
8013 hash_set<vect_scalar_ops_slice_hash> vector_ops;
8014 for (unsigned int i = 0; i < SLP_TREE_NUMBER_OF_VEC_STMTS (node); ++i)
8015 if (!vector_ops.add ({ ops, i * nelt_limit, nelt_limit }))
8016 starts.quick_push (i * nelt_limit);
8017 }
8018 else
8019 {
8020 /* If either the vector has variable length or the vectors
8021 are composed of repeated whole groups we only need to
8022 cost construction once. All vectors will be the same. */
8023 nelt_limit = group_size;
8024 starts.quick_push (0);
8025 }
8026 /* ??? We're just tracking whether vectors in a single node are the same.
8027 Ideally we'd do something more global. */
8028 bool passed = false;
8029 for (unsigned int start : starts)
8030 {
8031 vect_cost_for_stmt kind;
8032 if (SLP_TREE_DEF_TYPE (node) == vect_constant_def)
8033 kind = vector_load;
8034 else if (vect_scalar_ops_slice { ops, start, nelt_limit }.all_same_p ())
8035 kind = scalar_to_vec;
8036 else
8037 kind = vec_construct;
8038 /* The target cost hook has no idea which part of the SLP node
8039 we are costing so avoid passing it down more than once. Pass
8040 it to the first vec_construct or scalar_to_vec part since for those
8041 the x86 backend tries to account for GPR to XMM register moves. */
8042 record_stmt_cost (cost_vec, 1, kind,
8043 (kind != vector_load && !passed) ? node : nullptr,
8044 vectype, 0, vect_prologue);
8045 if (kind != vector_load)
8046 passed = true;
8047 }
8048 }
8049
8050 /* Analyze statements contained in SLP tree NODE after recursively analyzing
8051 the subtree. NODE_INSTANCE contains NODE and VINFO contains INSTANCE.
8052
8053 Return true if the operations are supported. */
8054
8055 static bool
8056 vect_slp_analyze_node_operations (vec_info *vinfo, slp_tree node,
8057 slp_instance node_instance,
8058 hash_set<slp_tree> &visited_set,
8059 vec<slp_tree> &visited_vec,
8060 stmt_vector_for_cost *cost_vec)
8061 {
8062 int i, j;
8063 slp_tree child;
8064
8065 /* Assume we can code-generate all invariants. */
8066 if (!node
8067 || SLP_TREE_DEF_TYPE (node) == vect_constant_def
8068 || SLP_TREE_DEF_TYPE (node) == vect_external_def)
8069 return true;
8070
8071 if (SLP_TREE_DEF_TYPE (node) == vect_uninitialized_def)
8072 {
8073 if (dump_enabled_p ())
8074 dump_printf_loc (MSG_NOTE, vect_location,
8075 "Failed cyclic SLP reference in %p\n", (void *) node);
8076 return false;
8077 }
8078 gcc_assert (SLP_TREE_DEF_TYPE (node) == vect_internal_def);
8079
8080 /* If we already analyzed the exact same set of scalar stmts we're done.
8081 We share the generated vector stmts for those. */
8082 if (visited_set.add (node))
8083 return true;
8084 visited_vec.safe_push (node);
8085
8086 bool res = true;
8087 unsigned visited_rec_start = visited_vec.length ();
8088 unsigned cost_vec_rec_start = cost_vec->length ();
8089 bool seen_non_constant_child = false;
8090 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
8091 {
8092 res = vect_slp_analyze_node_operations (vinfo, child, node_instance,
8093 visited_set, visited_vec,
8094 cost_vec);
8095 if (!res)
8096 break;
8097 if (child && SLP_TREE_DEF_TYPE (child) != vect_constant_def)
8098 seen_non_constant_child = true;
8099 }
8100 /* We're having difficulties scheduling nodes with just constant
8101 operands and no scalar stmts since we then cannot compute a stmt
8102 insertion place. */
8103 if (res
8104 && !seen_non_constant_child
8105 && SLP_TREE_SCALAR_STMTS (node).is_empty ())
8106 {
8107 if (dump_enabled_p ())
8108 dump_printf_loc (MSG_NOTE, vect_location,
8109 "Cannot vectorize all-constant op node %p\n",
8110 (void *) node);
8111 res = false;
8112 }
8113
8114 if (res)
8115 res = vect_slp_analyze_node_operations_1 (vinfo, node, node_instance,
8116 cost_vec);
8117 /* If analysis failed we have to pop all recursive visited nodes
8118 plus ourselves. */
8119 if (!res)
8120 {
8121 while (visited_vec.length () >= visited_rec_start)
8122 visited_set.remove (visited_vec.pop ());
8123 cost_vec->truncate (cost_vec_rec_start);
8124 }
8125
8126 /* When the node can be vectorized cost invariant nodes it references.
8127 This is not done in DFS order to allow the refering node
8128 vectorizable_* calls to nail down the invariant nodes vector type
8129 and possibly unshare it if it needs a different vector type than
8130 other referrers. */
8131 if (res)
8132 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), j, child)
8133 if (child
8134 && (SLP_TREE_DEF_TYPE (child) == vect_constant_def
8135 || SLP_TREE_DEF_TYPE (child) == vect_external_def)
8136 /* Perform usual caching, note code-generation still
8137 code-gens these nodes multiple times but we expect
8138 to CSE them later. */
8139 && !visited_set.add (child))
8140 {
8141 visited_vec.safe_push (child);
8142 /* ??? After auditing more code paths make a "default"
8143 and push the vector type from NODE to all children
8144 if it is not already set. */
8145 /* Compute the number of vectors to be generated. */
8146 tree vector_type = SLP_TREE_VECTYPE (child);
8147 if (!vector_type)
8148 {
8149 /* Masked loads can have an undefined (default SSA definition)
8150 else operand. We do not need to cost it. */
8151 vec<tree> ops = SLP_TREE_SCALAR_OPS (child);
8152 if ((STMT_VINFO_TYPE (SLP_TREE_REPRESENTATIVE (node))
8153 == load_vec_info_type)
8154 && ((ops.length ()
8155 && TREE_CODE (ops[0]) == SSA_NAME
8156 && SSA_NAME_IS_DEFAULT_DEF (ops[0])
8157 && VAR_P (SSA_NAME_VAR (ops[0])))
8158 || SLP_TREE_DEF_TYPE (child) == vect_constant_def))
8159 continue;
8160
8161 /* For shifts with a scalar argument we don't need
8162 to cost or code-generate anything.
8163 ??? Represent this more explicitely. */
8164 gcc_assert ((STMT_VINFO_TYPE (SLP_TREE_REPRESENTATIVE (node))
8165 == shift_vec_info_type)
8166 && j == 1);
8167 continue;
8168 }
8169
8170 SLP_TREE_NUMBER_OF_VEC_STMTS (child)
8171 = vect_get_num_copies (vinfo, child);
8172 /* And cost them. */
8173 vect_prologue_cost_for_slp (child, cost_vec);
8174 }
8175
8176 /* If this node or any of its children can't be vectorized, try pruning
8177 the tree here rather than felling the whole thing. */
8178 if (!res && vect_slp_convert_to_external (vinfo, node, node_instance))
8179 {
8180 /* We'll need to revisit this for invariant costing and number
8181 of vectorized stmt setting. */
8182 res = true;
8183 }
8184
8185 return res;
8186 }
8187
8188 /* Given a definition DEF, analyze if it will have any live scalar use after
8189 performing SLP vectorization whose information is represented by BB_VINFO,
8190 and record result into hash map SCALAR_USE_MAP as cache for later fast
8191 check. If recursion DEPTH exceeds a limit, stop analysis and make a
8192 conservative assumption. Return 0 if no scalar use, 1 if there is, -1
8193 means recursion is limited. */
8194
8195 static int
8196 vec_slp_has_scalar_use (bb_vec_info bb_vinfo, tree def,
8197 hash_map<tree, int> &scalar_use_map,
8198 int depth = 0)
8199 {
8200 const int depth_limit = 2;
8201 imm_use_iterator use_iter;
8202 gimple *use_stmt;
8203
8204 if (int *res = scalar_use_map.get (def))
8205 return *res;
8206
8207 int scalar_use = 1;
8208
8209 FOR_EACH_IMM_USE_STMT (use_stmt, use_iter, def)
8210 {
8211 if (is_gimple_debug (use_stmt))
8212 continue;
8213
8214 stmt_vec_info use_stmt_info = bb_vinfo->lookup_stmt (use_stmt);
8215
8216 if (!use_stmt_info)
8217 break;
8218
8219 if (PURE_SLP_STMT (vect_stmt_to_vectorize (use_stmt_info)))
8220 continue;
8221
8222 /* Do not step forward when encounter PHI statement, since it may
8223 involve cyclic reference and cause infinite recursive invocation. */
8224 if (gimple_code (use_stmt) == GIMPLE_PHI)
8225 break;
8226
8227 /* When pattern recognition is involved, a statement whose definition is
8228 consumed in some pattern, may not be included in the final replacement
8229 pattern statements, so would be skipped when building SLP graph.
8230
8231 * Original
8232 char a_c = *(char *) a;
8233 char b_c = *(char *) b;
8234 unsigned short a_s = (unsigned short) a_c;
8235 int a_i = (int) a_s;
8236 int b_i = (int) b_c;
8237 int r_i = a_i - b_i;
8238
8239 * After pattern replacement
8240 a_s = (unsigned short) a_c;
8241 a_i = (int) a_s;
8242
8243 patt_b_s = (unsigned short) b_c; // b_i = (int) b_c
8244 patt_b_i = (int) patt_b_s; // b_i = (int) b_c
8245
8246 patt_r_s = widen_minus(a_c, b_c); // r_i = a_i - b_i
8247 patt_r_i = (int) patt_r_s; // r_i = a_i - b_i
8248
8249 The definitions of a_i(original statement) and b_i(pattern statement)
8250 are related to, but actually not part of widen_minus pattern.
8251 Vectorizing the pattern does not cause these definition statements to
8252 be marked as PURE_SLP. For this case, we need to recursively check
8253 whether their uses are all absorbed into vectorized code. But there
8254 is an exception that some use may participate in an vectorized
8255 operation via an external SLP node containing that use as an element.
8256 The parameter "scalar_use_map" tags such kind of SSA as having scalar
8257 use in advance. */
8258 tree lhs = gimple_get_lhs (use_stmt);
8259
8260 if (!lhs || TREE_CODE (lhs) != SSA_NAME)
8261 break;
8262
8263 if (depth_limit && depth >= depth_limit)
8264 return -1;
8265
8266 if ((scalar_use = vec_slp_has_scalar_use (bb_vinfo, lhs, scalar_use_map,
8267 depth + 1)))
8268 break;
8269 }
8270
8271 if (end_imm_use_stmt_p (&use_iter))
8272 scalar_use = 0;
8273
8274 /* If recursion is limited, do not cache result for non-root defs. */
8275 if (!depth || scalar_use >= 0)
8276 {
8277 bool added = scalar_use_map.put (def, scalar_use);
8278 gcc_assert (!added);
8279 }
8280
8281 return scalar_use;
8282 }
8283
8284 /* Mark lanes of NODE that are live outside of the basic-block vectorized
8285 region and that can be vectorized using vectorizable_live_operation
8286 with STMT_VINFO_LIVE_P. Not handled live operations will cause the
8287 scalar code computing it to be retained. */
8288
8289 static void
8290 vect_bb_slp_mark_live_stmts (bb_vec_info bb_vinfo, slp_tree node,
8291 slp_instance instance,
8292 stmt_vector_for_cost *cost_vec,
8293 hash_map<tree, int> &scalar_use_map,
8294 hash_set<stmt_vec_info> &svisited,
8295 hash_set<slp_tree> &visited)
8296 {
8297 if (visited.add (node))
8298 return;
8299
8300 unsigned i;
8301 stmt_vec_info stmt_info;
8302 stmt_vec_info last_stmt = vect_find_last_scalar_stmt_in_slp (node);
8303 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
8304 {
8305 if (!stmt_info || svisited.contains (stmt_info))
8306 continue;
8307 stmt_vec_info orig_stmt_info = vect_orig_stmt (stmt_info);
8308 if (STMT_VINFO_IN_PATTERN_P (orig_stmt_info)
8309 && STMT_VINFO_RELATED_STMT (orig_stmt_info) != stmt_info)
8310 /* Only the pattern root stmt computes the original scalar value. */
8311 continue;
8312 bool mark_visited = true;
8313 gimple *orig_stmt = orig_stmt_info->stmt;
8314 ssa_op_iter op_iter;
8315 def_operand_p def_p;
8316 FOR_EACH_PHI_OR_STMT_DEF (def_p, orig_stmt, op_iter, SSA_OP_DEF)
8317 {
8318 if (vec_slp_has_scalar_use (bb_vinfo, DEF_FROM_PTR (def_p),
8319 scalar_use_map))
8320 {
8321 STMT_VINFO_LIVE_P (stmt_info) = true;
8322 if (vectorizable_live_operation (bb_vinfo, stmt_info, node,
8323 instance, i, false, cost_vec))
8324 /* ??? So we know we can vectorize the live stmt from one SLP
8325 node. If we cannot do so from all or none consistently
8326 we'd have to record which SLP node (and lane) we want to
8327 use for the live operation. So make sure we can
8328 code-generate from all nodes. */
8329 mark_visited = false;
8330 else
8331 STMT_VINFO_LIVE_P (stmt_info) = false;
8332 }
8333
8334 /* We have to verify whether we can insert the lane extract
8335 before all uses. The following is a conservative approximation.
8336 We cannot put this into vectorizable_live_operation because
8337 iterating over all use stmts from inside a FOR_EACH_IMM_USE_STMT
8338 doesn't work.
8339 Note that while the fact that we emit code for loads at the
8340 first load should make this a non-problem leafs we construct
8341 from scalars are vectorized after the last scalar def.
8342 ??? If we'd actually compute the insert location during
8343 analysis we could use sth less conservative than the last
8344 scalar stmt in the node for the dominance check. */
8345 /* ??? What remains is "live" uses in vector CTORs in the same
8346 SLP graph which is where those uses can end up code-generated
8347 right after their definition instead of close to their original
8348 use. But that would restrict us to code-generate lane-extracts
8349 from the latest stmt in a node. So we compensate for this
8350 during code-generation, simply not replacing uses for those
8351 hopefully rare cases. */
8352 imm_use_iterator use_iter;
8353 gimple *use_stmt;
8354 stmt_vec_info use_stmt_info;
8355
8356 if (STMT_VINFO_LIVE_P (stmt_info))
8357 FOR_EACH_IMM_USE_STMT (use_stmt, use_iter, DEF_FROM_PTR (def_p))
8358 if (!is_gimple_debug (use_stmt)
8359 && (!(use_stmt_info = bb_vinfo->lookup_stmt (use_stmt))
8360 || !PURE_SLP_STMT (vect_stmt_to_vectorize (use_stmt_info)))
8361 && !vect_stmt_dominates_stmt_p (last_stmt->stmt, use_stmt))
8362 {
8363 if (dump_enabled_p ())
8364 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8365 "Cannot determine insertion place for "
8366 "lane extract\n");
8367 STMT_VINFO_LIVE_P (stmt_info) = false;
8368 mark_visited = true;
8369 }
8370 }
8371 if (mark_visited)
8372 svisited.add (stmt_info);
8373 }
8374
8375 slp_tree child;
8376 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
8377 if (child && SLP_TREE_DEF_TYPE (child) == vect_internal_def)
8378 vect_bb_slp_mark_live_stmts (bb_vinfo, child, instance, cost_vec,
8379 scalar_use_map, svisited, visited);
8380 }
8381
8382 /* Traverse all slp instances of BB_VINFO, and mark lanes of every node that
8383 are live outside of the basic-block vectorized region and that can be
8384 vectorized using vectorizable_live_operation with STMT_VINFO_LIVE_P. */
8385
8386 static void
8387 vect_bb_slp_mark_live_stmts (bb_vec_info bb_vinfo)
8388 {
8389 if (bb_vinfo->slp_instances.is_empty ())
8390 return;
8391
8392 hash_set<stmt_vec_info> svisited;
8393 hash_set<slp_tree> visited;
8394 hash_map<tree, int> scalar_use_map;
8395 auto_vec<slp_tree> worklist;
8396
8397 for (slp_instance instance : bb_vinfo->slp_instances)
8398 {
8399 if (SLP_INSTANCE_KIND (instance) == slp_inst_kind_bb_reduc)
8400 for (tree op : SLP_INSTANCE_REMAIN_DEFS (instance))
8401 if (TREE_CODE (op) == SSA_NAME)
8402 scalar_use_map.put (op, 1);
8403 if (!visited.add (SLP_INSTANCE_TREE (instance)))
8404 worklist.safe_push (SLP_INSTANCE_TREE (instance));
8405 }
8406
8407 do
8408 {
8409 slp_tree node = worklist.pop ();
8410
8411 if (SLP_TREE_DEF_TYPE (node) == vect_external_def)
8412 {
8413 for (tree op : SLP_TREE_SCALAR_OPS (node))
8414 if (TREE_CODE (op) == SSA_NAME)
8415 scalar_use_map.put (op, 1);
8416 }
8417 else
8418 {
8419 for (slp_tree child : SLP_TREE_CHILDREN (node))
8420 if (child && !visited.add (child))
8421 worklist.safe_push (child);
8422 }
8423 }
8424 while (!worklist.is_empty ());
8425
8426 visited.empty ();
8427
8428 for (slp_instance instance : bb_vinfo->slp_instances)
8429 {
8430 vect_location = instance->location ();
8431 vect_bb_slp_mark_live_stmts (bb_vinfo, SLP_INSTANCE_TREE (instance),
8432 instance, &instance->cost_vec,
8433 scalar_use_map, svisited, visited);
8434 }
8435 }
8436
8437 /* Determine whether we can vectorize the reduction epilogue for INSTANCE. */
8438
8439 static bool
8440 vectorizable_bb_reduc_epilogue (slp_instance instance,
8441 stmt_vector_for_cost *cost_vec)
8442 {
8443 gassign *stmt = as_a <gassign *> (instance->root_stmts[0]->stmt);
8444 enum tree_code reduc_code = gimple_assign_rhs_code (stmt);
8445 if (reduc_code == MINUS_EXPR)
8446 reduc_code = PLUS_EXPR;
8447 internal_fn reduc_fn;
8448 tree vectype = SLP_TREE_VECTYPE (SLP_INSTANCE_TREE (instance));
8449 if (!vectype
8450 || !reduction_fn_for_scalar_code (reduc_code, &reduc_fn)
8451 || reduc_fn == IFN_LAST
8452 || !direct_internal_fn_supported_p (reduc_fn, vectype, OPTIMIZE_FOR_BOTH)
8453 || !useless_type_conversion_p (TREE_TYPE (gimple_assign_lhs (stmt)),
8454 TREE_TYPE (vectype)))
8455 {
8456 if (dump_enabled_p ())
8457 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
8458 "not vectorized: basic block reduction epilogue "
8459 "operation unsupported.\n");
8460 return false;
8461 }
8462
8463 /* There's no way to cost a horizontal vector reduction via REDUC_FN so
8464 cost log2 vector operations plus shuffles and one extraction. */
8465 unsigned steps = floor_log2 (vect_nunits_for_cost (vectype));
8466 record_stmt_cost (cost_vec, steps, vector_stmt, instance->root_stmts[0],
8467 vectype, 0, vect_body);
8468 record_stmt_cost (cost_vec, steps, vec_perm, instance->root_stmts[0],
8469 vectype, 0, vect_body);
8470 record_stmt_cost (cost_vec, 1, vec_to_scalar, instance->root_stmts[0],
8471 vectype, 0, vect_body);
8472
8473 /* Since we replace all stmts of a possibly longer scalar reduction
8474 chain account for the extra scalar stmts for that. */
8475 record_stmt_cost (cost_vec, instance->remain_defs.length (), scalar_stmt,
8476 instance->root_stmts[0], 0, vect_body);
8477 return true;
8478 }
8479
8480 /* Prune from ROOTS all stmts that are computed as part of lanes of NODE
8481 and recurse to children. */
8482
8483 static void
8484 vect_slp_prune_covered_roots (slp_tree node, hash_set<stmt_vec_info> &roots,
8485 hash_set<slp_tree> &visited)
8486 {
8487 if (SLP_TREE_DEF_TYPE (node) != vect_internal_def
8488 || visited.add (node))
8489 return;
8490
8491 stmt_vec_info stmt;
8492 unsigned i;
8493 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt)
8494 if (stmt)
8495 roots.remove (vect_orig_stmt (stmt));
8496
8497 slp_tree child;
8498 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
8499 if (child)
8500 vect_slp_prune_covered_roots (child, roots, visited);
8501 }
8502
8503 /* Analyze statements in SLP instances of VINFO. Return true if the
8504 operations are supported. */
8505
8506 bool
8507 vect_slp_analyze_operations (vec_info *vinfo)
8508 {
8509 slp_instance instance;
8510 int i;
8511
8512 DUMP_VECT_SCOPE ("vect_slp_analyze_operations");
8513
8514 hash_set<slp_tree> visited;
8515 for (i = 0; vinfo->slp_instances.iterate (i, &instance); )
8516 {
8517 auto_vec<slp_tree> visited_vec;
8518 stmt_vector_for_cost cost_vec;
8519 cost_vec.create (2);
8520 if (is_a <bb_vec_info> (vinfo))
8521 vect_location = instance->location ();
8522 if (!vect_slp_analyze_node_operations (vinfo,
8523 SLP_INSTANCE_TREE (instance),
8524 instance, visited, visited_vec,
8525 &cost_vec)
8526 /* CTOR instances require vectorized defs for the SLP tree root. */
8527 || (SLP_INSTANCE_KIND (instance) == slp_inst_kind_ctor
8528 && (SLP_TREE_DEF_TYPE (SLP_INSTANCE_TREE (instance))
8529 != vect_internal_def
8530 /* Make sure we vectorized with the expected type. */
8531 || !useless_type_conversion_p
8532 (TREE_TYPE (TREE_TYPE (gimple_assign_rhs1
8533 (instance->root_stmts[0]->stmt))),
8534 TREE_TYPE (SLP_TREE_VECTYPE
8535 (SLP_INSTANCE_TREE (instance))))))
8536 /* Check we can vectorize the reduction. */
8537 || (SLP_INSTANCE_KIND (instance) == slp_inst_kind_bb_reduc
8538 && !vectorizable_bb_reduc_epilogue (instance, &cost_vec))
8539 /* Check we can vectorize the gcond. */
8540 || (SLP_INSTANCE_KIND (instance) == slp_inst_kind_gcond
8541 && !vectorizable_early_exit (vinfo,
8542 SLP_INSTANCE_ROOT_STMTS (instance)[0],
8543 NULL, NULL,
8544 SLP_INSTANCE_TREE (instance),
8545 &cost_vec)))
8546 {
8547 cost_vec.release ();
8548 slp_tree node = SLP_INSTANCE_TREE (instance);
8549 stmt_vec_info stmt_info;
8550 if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ())
8551 stmt_info = SLP_INSTANCE_ROOT_STMTS (instance)[0];
8552 else
8553 stmt_info = SLP_TREE_SCALAR_STMTS (node)[0];
8554 if (is_a <loop_vec_info> (vinfo))
8555 {
8556 if (dump_enabled_p ())
8557 dump_printf_loc (MSG_NOTE, vect_location,
8558 "unsupported SLP instance starting from: %G",
8559 stmt_info->stmt);
8560 return false;
8561 }
8562 if (dump_enabled_p ())
8563 dump_printf_loc (MSG_NOTE, vect_location,
8564 "removing SLP instance operations starting from: %G",
8565 stmt_info->stmt);
8566 vect_free_slp_instance (instance);
8567 vinfo->slp_instances.ordered_remove (i);
8568 while (!visited_vec.is_empty ())
8569 visited.remove (visited_vec.pop ());
8570 }
8571 else
8572 {
8573 i++;
8574 if (loop_vec_info loop_vinfo = dyn_cast<loop_vec_info> (vinfo))
8575 {
8576 add_stmt_costs (loop_vinfo->vector_costs, &cost_vec);
8577 cost_vec.release ();
8578 }
8579 else
8580 /* For BB vectorization remember the SLP graph entry
8581 cost for later. */
8582 instance->cost_vec = cost_vec;
8583 }
8584 }
8585
8586 /* Now look for SLP instances with a root that are covered by other
8587 instances and remove them. */
8588 hash_set<stmt_vec_info> roots;
8589 for (i = 0; vinfo->slp_instances.iterate (i, &instance); ++i)
8590 if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ())
8591 roots.add (SLP_INSTANCE_ROOT_STMTS (instance)[0]);
8592 if (!roots.is_empty ())
8593 {
8594 visited.empty ();
8595 for (i = 0; vinfo->slp_instances.iterate (i, &instance); ++i)
8596 vect_slp_prune_covered_roots (SLP_INSTANCE_TREE (instance), roots,
8597 visited);
8598 for (i = 0; vinfo->slp_instances.iterate (i, &instance); )
8599 if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ()
8600 && !roots.contains (SLP_INSTANCE_ROOT_STMTS (instance)[0]))
8601 {
8602 stmt_vec_info root = SLP_INSTANCE_ROOT_STMTS (instance)[0];
8603 if (dump_enabled_p ())
8604 dump_printf_loc (MSG_NOTE, vect_location,
8605 "removing SLP instance operations starting "
8606 "from: %G", root->stmt);
8607 vect_free_slp_instance (instance);
8608 vinfo->slp_instances.ordered_remove (i);
8609 }
8610 else
8611 ++i;
8612 }
8613
8614 /* Compute vectorizable live stmts. */
8615 if (bb_vec_info bb_vinfo = dyn_cast <bb_vec_info> (vinfo))
8616 vect_bb_slp_mark_live_stmts (bb_vinfo);
8617
8618 return !vinfo->slp_instances.is_empty ();
8619 }
8620
8621 /* Get the SLP instance leader from INSTANCE_LEADER thereby transitively
8622 closing the eventual chain. */
8623
8624 static slp_instance
8625 get_ultimate_leader (slp_instance instance,
8626 hash_map<slp_instance, slp_instance> &instance_leader)
8627 {
8628 auto_vec<slp_instance *, 8> chain;
8629 slp_instance *tem;
8630 while (*(tem = instance_leader.get (instance)) != instance)
8631 {
8632 chain.safe_push (tem);
8633 instance = *tem;
8634 }
8635 while (!chain.is_empty ())
8636 *chain.pop () = instance;
8637 return instance;
8638 }
8639
8640 namespace {
8641 /* Subroutine of vect_bb_partition_graph_r. Map KEY to INSTANCE in
8642 KEY_TO_INSTANCE, making INSTANCE the leader of any previous mapping
8643 for KEY. Return true if KEY was already in KEY_TO_INSTANCE.
8644
8645 INSTANCE_LEADER is as for get_ultimate_leader. */
8646
8647 template<typename T>
8648 bool
8649 vect_map_to_instance (slp_instance instance, T key,
8650 hash_map<T, slp_instance> &key_to_instance,
8651 hash_map<slp_instance, slp_instance> &instance_leader)
8652 {
8653 bool existed_p;
8654 slp_instance &key_instance = key_to_instance.get_or_insert (key, &existed_p);
8655 if (!existed_p)
8656 ;
8657 else if (key_instance != instance)
8658 {
8659 /* If we're running into a previously marked key make us the
8660 leader of the current ultimate leader. This keeps the
8661 leader chain acyclic and works even when the current instance
8662 connects two previously independent graph parts. */
8663 slp_instance key_leader
8664 = get_ultimate_leader (key_instance, instance_leader);
8665 if (key_leader != instance)
8666 instance_leader.put (key_leader, instance);
8667 }
8668 key_instance = instance;
8669 return existed_p;
8670 }
8671 }
8672
8673 /* Worker of vect_bb_partition_graph, recurse on NODE. */
8674
8675 static void
8676 vect_bb_partition_graph_r (bb_vec_info bb_vinfo,
8677 slp_instance instance, slp_tree node,
8678 hash_map<stmt_vec_info, slp_instance> &stmt_to_instance,
8679 hash_map<slp_tree, slp_instance> &node_to_instance,
8680 hash_map<slp_instance, slp_instance> &instance_leader)
8681 {
8682 stmt_vec_info stmt_info;
8683 unsigned i;
8684
8685 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
8686 if (stmt_info)
8687 vect_map_to_instance (instance, stmt_info, stmt_to_instance,
8688 instance_leader);
8689
8690 if (vect_map_to_instance (instance, node, node_to_instance,
8691 instance_leader))
8692 return;
8693
8694 slp_tree child;
8695 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
8696 if (child && SLP_TREE_DEF_TYPE (child) == vect_internal_def)
8697 vect_bb_partition_graph_r (bb_vinfo, instance, child, stmt_to_instance,
8698 node_to_instance, instance_leader);
8699 }
8700
8701 /* Partition the SLP graph into pieces that can be costed independently. */
8702
8703 static void
8704 vect_bb_partition_graph (bb_vec_info bb_vinfo)
8705 {
8706 DUMP_VECT_SCOPE ("vect_bb_partition_graph");
8707
8708 /* First walk the SLP graph assigning each involved scalar stmt a
8709 corresponding SLP graph entry and upon visiting a previously
8710 marked stmt, make the stmts leader the current SLP graph entry. */
8711 hash_map<stmt_vec_info, slp_instance> stmt_to_instance;
8712 hash_map<slp_tree, slp_instance> node_to_instance;
8713 hash_map<slp_instance, slp_instance> instance_leader;
8714 slp_instance instance;
8715 for (unsigned i = 0; bb_vinfo->slp_instances.iterate (i, &instance); ++i)
8716 {
8717 instance_leader.put (instance, instance);
8718 vect_bb_partition_graph_r (bb_vinfo,
8719 instance, SLP_INSTANCE_TREE (instance),
8720 stmt_to_instance, node_to_instance,
8721 instance_leader);
8722 }
8723
8724 /* Then collect entries to each independent subgraph. */
8725 for (unsigned i = 0; bb_vinfo->slp_instances.iterate (i, &instance); ++i)
8726 {
8727 slp_instance leader = get_ultimate_leader (instance, instance_leader);
8728 leader->subgraph_entries.safe_push (instance);
8729 if (dump_enabled_p ()
8730 && leader != instance)
8731 dump_printf_loc (MSG_NOTE, vect_location,
8732 "instance %p is leader of %p\n",
8733 (void *) leader, (void *) instance);
8734 }
8735 }
8736
8737 /* Compute the set of scalar stmts participating in internal and external
8738 nodes. */
8739
8740 static void
8741 vect_slp_gather_vectorized_scalar_stmts (vec_info *vinfo, slp_tree node,
8742 hash_set<slp_tree> &visited,
8743 hash_set<stmt_vec_info> &vstmts,
8744 hash_set<stmt_vec_info> &estmts)
8745 {
8746 int i;
8747 stmt_vec_info stmt_info;
8748 slp_tree child;
8749
8750 if (visited.add (node))
8751 return;
8752
8753 if (SLP_TREE_DEF_TYPE (node) == vect_internal_def)
8754 {
8755 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
8756 if (stmt_info)
8757 vstmts.add (stmt_info);
8758
8759 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
8760 if (child)
8761 vect_slp_gather_vectorized_scalar_stmts (vinfo, child, visited,
8762 vstmts, estmts);
8763 }
8764 else
8765 for (tree def : SLP_TREE_SCALAR_OPS (node))
8766 {
8767 stmt_vec_info def_stmt = vinfo->lookup_def (def);
8768 if (def_stmt)
8769 estmts.add (def_stmt);
8770 }
8771 }
8772
8773
8774 /* Compute the scalar cost of the SLP node NODE and its children
8775 and return it. Do not account defs that are marked in LIFE and
8776 update LIFE according to uses of NODE. */
8777
8778 static void
8779 vect_bb_slp_scalar_cost (vec_info *vinfo,
8780 slp_tree node, vec<bool, va_heap> *life,
8781 stmt_vector_for_cost *cost_vec,
8782 hash_set<stmt_vec_info> &vectorized_scalar_stmts,
8783 hash_set<stmt_vec_info> &scalar_stmts_in_externs,
8784 hash_set<slp_tree> &visited)
8785 {
8786 unsigned i;
8787 stmt_vec_info stmt_info;
8788 slp_tree child;
8789
8790 if (visited.add (node))
8791 return;
8792
8793 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
8794 {
8795 ssa_op_iter op_iter;
8796 def_operand_p def_p;
8797
8798 if (!stmt_info
8799 || (*life)[i]
8800 /* Defs also used in external nodes are not in the
8801 vectorized_scalar_stmts set as they need to be preserved.
8802 Honor that. */
8803 || scalar_stmts_in_externs.contains (stmt_info))
8804 continue;
8805
8806 stmt_vec_info orig_stmt_info = vect_orig_stmt (stmt_info);
8807 gimple *orig_stmt = orig_stmt_info->stmt;
8808
8809 /* If there is a non-vectorized use of the defs then the scalar
8810 stmt is kept live in which case we do not account it or any
8811 required defs in the SLP children in the scalar cost. This
8812 way we make the vectorization more costly when compared to
8813 the scalar cost. */
8814 if (!STMT_VINFO_LIVE_P (stmt_info))
8815 {
8816 auto_vec<gimple *, 8> worklist;
8817 hash_set<gimple *> *worklist_visited = NULL;
8818 worklist.quick_push (orig_stmt);
8819 do
8820 {
8821 gimple *work_stmt = worklist.pop ();
8822 FOR_EACH_PHI_OR_STMT_DEF (def_p, work_stmt, op_iter, SSA_OP_DEF)
8823 {
8824 imm_use_iterator use_iter;
8825 gimple *use_stmt;
8826 FOR_EACH_IMM_USE_STMT (use_stmt, use_iter,
8827 DEF_FROM_PTR (def_p))
8828 if (!is_gimple_debug (use_stmt))
8829 {
8830 stmt_vec_info use_stmt_info
8831 = vinfo->lookup_stmt (use_stmt);
8832 if (!use_stmt_info
8833 || !vectorized_scalar_stmts.contains (use_stmt_info))
8834 {
8835 if (use_stmt_info
8836 && STMT_VINFO_IN_PATTERN_P (use_stmt_info))
8837 {
8838 /* For stmts participating in patterns we have
8839 to check its uses recursively. */
8840 if (!worklist_visited)
8841 worklist_visited = new hash_set<gimple *> ();
8842 if (!worklist_visited->add (use_stmt))
8843 worklist.safe_push (use_stmt);
8844 continue;
8845 }
8846 (*life)[i] = true;
8847 goto next_lane;
8848 }
8849 }
8850 }
8851 }
8852 while (!worklist.is_empty ());
8853 next_lane:
8854 if (worklist_visited)
8855 delete worklist_visited;
8856 if ((*life)[i])
8857 continue;
8858 }
8859
8860 /* Count scalar stmts only once. */
8861 if (gimple_visited_p (orig_stmt))
8862 continue;
8863 gimple_set_visited (orig_stmt, true);
8864
8865 vect_cost_for_stmt kind;
8866 if (STMT_VINFO_DATA_REF (orig_stmt_info))
8867 {
8868 data_reference_p dr = STMT_VINFO_DATA_REF (orig_stmt_info);
8869 tree base = get_base_address (DR_REF (dr));
8870 /* When the scalar access is to a non-global not address-taken
8871 decl that is not BLKmode assume we can access it with a single
8872 non-load/store instruction. */
8873 if (DECL_P (base)
8874 && !is_global_var (base)
8875 && !TREE_ADDRESSABLE (base)
8876 && DECL_MODE (base) != BLKmode)
8877 kind = scalar_stmt;
8878 else if (DR_IS_READ (STMT_VINFO_DATA_REF (orig_stmt_info)))
8879 kind = scalar_load;
8880 else
8881 kind = scalar_store;
8882 }
8883 else if (vect_nop_conversion_p (orig_stmt_info))
8884 continue;
8885 /* For single-argument PHIs assume coalescing which means zero cost
8886 for the scalar and the vector PHIs. This avoids artificially
8887 favoring the vector path (but may pessimize it in some cases). */
8888 else if (is_a <gphi *> (orig_stmt_info->stmt)
8889 && gimple_phi_num_args
8890 (as_a <gphi *> (orig_stmt_info->stmt)) == 1)
8891 continue;
8892 else
8893 kind = scalar_stmt;
8894 record_stmt_cost (cost_vec, 1, kind, orig_stmt_info,
8895 SLP_TREE_VECTYPE (node), 0, vect_body);
8896 }
8897
8898 auto_vec<bool, 20> subtree_life;
8899 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
8900 {
8901 if (child && SLP_TREE_DEF_TYPE (child) == vect_internal_def)
8902 {
8903 /* Do not directly pass LIFE to the recursive call, copy it to
8904 confine changes in the callee to the current child/subtree. */
8905 if (SLP_TREE_CODE (node) == VEC_PERM_EXPR)
8906 {
8907 subtree_life.safe_grow_cleared (SLP_TREE_LANES (child), true);
8908 for (unsigned j = 0;
8909 j < SLP_TREE_LANE_PERMUTATION (node).length (); ++j)
8910 {
8911 auto perm = SLP_TREE_LANE_PERMUTATION (node)[j];
8912 if (perm.first == i)
8913 subtree_life[perm.second] = (*life)[j];
8914 }
8915 }
8916 else
8917 {
8918 gcc_assert (SLP_TREE_LANES (node) == SLP_TREE_LANES (child));
8919 subtree_life.safe_splice (*life);
8920 }
8921 vect_bb_slp_scalar_cost (vinfo, child, &subtree_life, cost_vec,
8922 vectorized_scalar_stmts,
8923 scalar_stmts_in_externs, visited);
8924 subtree_life.truncate (0);
8925 }
8926 }
8927 }
8928
8929 /* Comparator for the loop-index sorted cost vectors. */
8930
8931 static int
8932 li_cost_vec_cmp (const void *a_, const void *b_)
8933 {
8934 auto *a = (const std::pair<unsigned, stmt_info_for_cost *> *)a_;
8935 auto *b = (const std::pair<unsigned, stmt_info_for_cost *> *)b_;
8936 if (a->first < b->first)
8937 return -1;
8938 else if (a->first == b->first)
8939 return 0;
8940 return 1;
8941 }
8942
8943 /* Check if vectorization of the basic block is profitable for the
8944 subgraph denoted by SLP_INSTANCES. */
8945
8946 static bool
8947 vect_bb_vectorization_profitable_p (bb_vec_info bb_vinfo,
8948 vec<slp_instance> slp_instances,
8949 loop_p orig_loop)
8950 {
8951 slp_instance instance;
8952 int i;
8953 unsigned int vec_inside_cost = 0, vec_outside_cost = 0, scalar_cost = 0;
8954 unsigned int vec_prologue_cost = 0, vec_epilogue_cost = 0;
8955
8956 if (dump_enabled_p ())
8957 {
8958 dump_printf_loc (MSG_NOTE, vect_location, "Costing subgraph: \n");
8959 hash_set<slp_tree> visited;
8960 FOR_EACH_VEC_ELT (slp_instances, i, instance)
8961 vect_print_slp_graph (MSG_NOTE, vect_location,
8962 SLP_INSTANCE_TREE (instance), visited);
8963 }
8964
8965 /* Compute the set of scalar stmts we know will go away 'locally' when
8966 vectorizing. This used to be tracked with just PURE_SLP_STMT but that's
8967 not accurate for nodes promoted extern late or for scalar stmts that
8968 are used both in extern defs and in vectorized defs. */
8969 hash_set<stmt_vec_info> vectorized_scalar_stmts;
8970 hash_set<stmt_vec_info> scalar_stmts_in_externs;
8971 hash_set<slp_tree> visited;
8972 FOR_EACH_VEC_ELT (slp_instances, i, instance)
8973 {
8974 vect_slp_gather_vectorized_scalar_stmts (bb_vinfo,
8975 SLP_INSTANCE_TREE (instance),
8976 visited,
8977 vectorized_scalar_stmts,
8978 scalar_stmts_in_externs);
8979 for (stmt_vec_info rstmt : SLP_INSTANCE_ROOT_STMTS (instance))
8980 vectorized_scalar_stmts.add (rstmt);
8981 }
8982 /* Scalar stmts used as defs in external nodes need to be preseved, so
8983 remove them from vectorized_scalar_stmts. */
8984 for (stmt_vec_info stmt : scalar_stmts_in_externs)
8985 vectorized_scalar_stmts.remove (stmt);
8986
8987 /* Calculate scalar cost and sum the cost for the vector stmts
8988 previously collected. */
8989 stmt_vector_for_cost scalar_costs = vNULL;
8990 stmt_vector_for_cost vector_costs = vNULL;
8991 visited.empty ();
8992 FOR_EACH_VEC_ELT (slp_instances, i, instance)
8993 {
8994 auto_vec<bool, 20> life;
8995 life.safe_grow_cleared (SLP_TREE_LANES (SLP_INSTANCE_TREE (instance)),
8996 true);
8997 if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ())
8998 record_stmt_cost (&scalar_costs,
8999 SLP_INSTANCE_ROOT_STMTS (instance).length (),
9000 scalar_stmt,
9001 SLP_INSTANCE_ROOT_STMTS (instance)[0], 0, vect_body);
9002 vect_bb_slp_scalar_cost (bb_vinfo,
9003 SLP_INSTANCE_TREE (instance),
9004 &life, &scalar_costs, vectorized_scalar_stmts,
9005 scalar_stmts_in_externs, visited);
9006 vector_costs.safe_splice (instance->cost_vec);
9007 instance->cost_vec.release ();
9008 }
9009
9010 if (dump_enabled_p ())
9011 dump_printf_loc (MSG_NOTE, vect_location, "Cost model analysis: \n");
9012
9013 /* When costing non-loop vectorization we need to consider each covered
9014 loop independently and make sure vectorization is profitable. For
9015 now we assume a loop may be not entered or executed an arbitrary
9016 number of iterations (??? static information can provide more
9017 precise info here) which means we can simply cost each containing
9018 loops stmts separately. */
9019
9020 /* First produce cost vectors sorted by loop index. */
9021 auto_vec<std::pair<unsigned, stmt_info_for_cost *> >
9022 li_scalar_costs (scalar_costs.length ());
9023 auto_vec<std::pair<unsigned, stmt_info_for_cost *> >
9024 li_vector_costs (vector_costs.length ());
9025 stmt_info_for_cost *cost;
9026 FOR_EACH_VEC_ELT (scalar_costs, i, cost)
9027 {
9028 unsigned l = gimple_bb (cost->stmt_info->stmt)->loop_father->num;
9029 li_scalar_costs.quick_push (std::make_pair (l, cost));
9030 }
9031 /* Use a random used loop as fallback in case the first vector_costs
9032 entry does not have a stmt_info associated with it. */
9033 unsigned l = li_scalar_costs[0].first;
9034 FOR_EACH_VEC_ELT (vector_costs, i, cost)
9035 {
9036 /* We inherit from the previous COST, invariants, externals and
9037 extracts immediately follow the cost for the related stmt. */
9038 if (cost->stmt_info)
9039 l = gimple_bb (cost->stmt_info->stmt)->loop_father->num;
9040 li_vector_costs.quick_push (std::make_pair (l, cost));
9041 }
9042 li_scalar_costs.qsort (li_cost_vec_cmp);
9043 li_vector_costs.qsort (li_cost_vec_cmp);
9044
9045 /* Now cost the portions individually. */
9046 unsigned vi = 0;
9047 unsigned si = 0;
9048 bool profitable = true;
9049 while (si < li_scalar_costs.length ()
9050 && vi < li_vector_costs.length ())
9051 {
9052 unsigned sl = li_scalar_costs[si].first;
9053 unsigned vl = li_vector_costs[vi].first;
9054 if (sl != vl)
9055 {
9056 if (dump_enabled_p ())
9057 dump_printf_loc (MSG_NOTE, vect_location,
9058 "Scalar %d and vector %d loop part do not "
9059 "match up, skipping scalar part\n", sl, vl);
9060 /* Skip the scalar part, assuming zero cost on the vector side. */
9061 do
9062 {
9063 si++;
9064 }
9065 while (si < li_scalar_costs.length ()
9066 && li_scalar_costs[si].first == sl);
9067 continue;
9068 }
9069
9070 class vector_costs *scalar_target_cost_data = init_cost (bb_vinfo, true);
9071 do
9072 {
9073 add_stmt_cost (scalar_target_cost_data, li_scalar_costs[si].second);
9074 si++;
9075 }
9076 while (si < li_scalar_costs.length ()
9077 && li_scalar_costs[si].first == sl);
9078 scalar_target_cost_data->finish_cost (nullptr);
9079 scalar_cost = scalar_target_cost_data->body_cost ();
9080
9081 /* Complete the target-specific vector cost calculation. */
9082 class vector_costs *vect_target_cost_data = init_cost (bb_vinfo, false);
9083 do
9084 {
9085 add_stmt_cost (vect_target_cost_data, li_vector_costs[vi].second);
9086 vi++;
9087 }
9088 while (vi < li_vector_costs.length ()
9089 && li_vector_costs[vi].first == vl);
9090 vect_target_cost_data->finish_cost (scalar_target_cost_data);
9091 vec_prologue_cost = vect_target_cost_data->prologue_cost ();
9092 vec_inside_cost = vect_target_cost_data->body_cost ();
9093 vec_epilogue_cost = vect_target_cost_data->epilogue_cost ();
9094 delete scalar_target_cost_data;
9095 delete vect_target_cost_data;
9096
9097 vec_outside_cost = vec_prologue_cost + vec_epilogue_cost;
9098
9099 if (dump_enabled_p ())
9100 {
9101 dump_printf_loc (MSG_NOTE, vect_location,
9102 "Cost model analysis for part in loop %d:\n", sl);
9103 dump_printf (MSG_NOTE, " Vector cost: %d\n",
9104 vec_inside_cost + vec_outside_cost);
9105 dump_printf (MSG_NOTE, " Scalar cost: %d\n", scalar_cost);
9106 }
9107
9108 /* Vectorization is profitable if its cost is more than the cost of scalar
9109 version. Note that we err on the vector side for equal cost because
9110 the cost estimate is otherwise quite pessimistic (constant uses are
9111 free on the scalar side but cost a load on the vector side for
9112 example). */
9113 if (vec_outside_cost + vec_inside_cost > scalar_cost)
9114 {
9115 profitable = false;
9116 break;
9117 }
9118 }
9119 if (profitable && vi < li_vector_costs.length ())
9120 {
9121 if (dump_enabled_p ())
9122 dump_printf_loc (MSG_NOTE, vect_location,
9123 "Excess vector cost for part in loop %d:\n",
9124 li_vector_costs[vi].first);
9125 profitable = false;
9126 }
9127
9128 /* Unset visited flag. This is delayed when the subgraph is profitable
9129 and we process the loop for remaining unvectorized if-converted code. */
9130 if (!orig_loop || !profitable)
9131 FOR_EACH_VEC_ELT (scalar_costs, i, cost)
9132 gimple_set_visited (cost->stmt_info->stmt, false);
9133
9134 scalar_costs.release ();
9135 vector_costs.release ();
9136
9137 return profitable;
9138 }
9139
9140 /* qsort comparator for lane defs. */
9141
9142 static int
9143 vld_cmp (const void *a_, const void *b_)
9144 {
9145 auto *a = (const std::pair<unsigned, tree> *)a_;
9146 auto *b = (const std::pair<unsigned, tree> *)b_;
9147 return a->first - b->first;
9148 }
9149
9150 /* Return true if USE_STMT is a vector lane insert into VEC and set
9151 *THIS_LANE to the lane number that is set. */
9152
9153 static bool
9154 vect_slp_is_lane_insert (gimple *use_stmt, tree vec, unsigned *this_lane)
9155 {
9156 gassign *use_ass = dyn_cast <gassign *> (use_stmt);
9157 if (!use_ass
9158 || gimple_assign_rhs_code (use_ass) != BIT_INSERT_EXPR
9159 || (vec
9160 ? gimple_assign_rhs1 (use_ass) != vec
9161 : ((vec = gimple_assign_rhs1 (use_ass)), false))
9162 || !useless_type_conversion_p (TREE_TYPE (TREE_TYPE (vec)),
9163 TREE_TYPE (gimple_assign_rhs2 (use_ass)))
9164 || !constant_multiple_p
9165 (tree_to_poly_uint64 (gimple_assign_rhs3 (use_ass)),
9166 tree_to_poly_uint64 (TYPE_SIZE (TREE_TYPE (TREE_TYPE (vec)))),
9167 this_lane))
9168 return false;
9169 return true;
9170 }
9171
9172 /* Find any vectorizable constructors and add them to the grouped_store
9173 array. */
9174
9175 static void
9176 vect_slp_check_for_roots (bb_vec_info bb_vinfo)
9177 {
9178 for (unsigned i = 0; i < bb_vinfo->nbbs; ++i)
9179 for (gimple_stmt_iterator gsi = gsi_start_bb (bb_vinfo->bbs[i]);
9180 !gsi_end_p (gsi); gsi_next (&gsi))
9181 {
9182 gassign *assign = dyn_cast<gassign *> (gsi_stmt (gsi));
9183 /* This can be used to start SLP discovery for early breaks for BB early breaks
9184 when we get that far. */
9185 if (!assign)
9186 continue;
9187
9188 tree rhs = gimple_assign_rhs1 (assign);
9189 enum tree_code code = gimple_assign_rhs_code (assign);
9190 use_operand_p use_p;
9191 gimple *use_stmt;
9192 if (code == CONSTRUCTOR)
9193 {
9194 if (!VECTOR_TYPE_P (TREE_TYPE (rhs))
9195 || maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)),
9196 CONSTRUCTOR_NELTS (rhs))
9197 || VECTOR_TYPE_P (TREE_TYPE (CONSTRUCTOR_ELT (rhs, 0)->value))
9198 || uniform_vector_p (rhs))
9199 continue;
9200
9201 unsigned j;
9202 tree val;
9203 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), j, val)
9204 if (TREE_CODE (val) != SSA_NAME
9205 || !bb_vinfo->lookup_def (val))
9206 break;
9207 if (j != CONSTRUCTOR_NELTS (rhs))
9208 continue;
9209
9210 vec<stmt_vec_info> roots = vNULL;
9211 roots.safe_push (bb_vinfo->lookup_stmt (assign));
9212 vec<stmt_vec_info> stmts;
9213 stmts.create (CONSTRUCTOR_NELTS (rhs));
9214 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), j, val)
9215 stmts.quick_push
9216 (vect_stmt_to_vectorize (bb_vinfo->lookup_def (val)));
9217 bb_vinfo->roots.safe_push (slp_root (slp_inst_kind_ctor,
9218 stmts, roots));
9219 }
9220 else if (code == BIT_INSERT_EXPR
9221 && VECTOR_TYPE_P (TREE_TYPE (rhs))
9222 && TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)).is_constant ()
9223 && TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)).to_constant () > 1
9224 && integer_zerop (gimple_assign_rhs3 (assign))
9225 && useless_type_conversion_p
9226 (TREE_TYPE (TREE_TYPE (rhs)),
9227 TREE_TYPE (gimple_assign_rhs2 (assign)))
9228 && bb_vinfo->lookup_def (gimple_assign_rhs2 (assign)))
9229 {
9230 /* We start to match on insert to lane zero but since the
9231 inserts need not be ordered we'd have to search both
9232 the def and the use chains. */
9233 tree vectype = TREE_TYPE (rhs);
9234 unsigned nlanes = TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
9235 auto_vec<std::pair<unsigned, tree> > lane_defs (nlanes);
9236 auto_sbitmap lanes (nlanes);
9237 bitmap_clear (lanes);
9238 bitmap_set_bit (lanes, 0);
9239 tree def = gimple_assign_lhs (assign);
9240 lane_defs.quick_push
9241 (std::make_pair (0, gimple_assign_rhs2 (assign)));
9242 unsigned lanes_found = 1;
9243 /* Start with the use chains, the last stmt will be the root. */
9244 stmt_vec_info last = bb_vinfo->lookup_stmt (assign);
9245 vec<stmt_vec_info> roots = vNULL;
9246 roots.safe_push (last);
9247 do
9248 {
9249 use_operand_p use_p;
9250 gimple *use_stmt;
9251 if (!single_imm_use (def, &use_p, &use_stmt))
9252 break;
9253 unsigned this_lane;
9254 if (!bb_vinfo->lookup_stmt (use_stmt)
9255 || !vect_slp_is_lane_insert (use_stmt, def, &this_lane)
9256 || !bb_vinfo->lookup_def (gimple_assign_rhs2 (use_stmt)))
9257 break;
9258 if (bitmap_bit_p (lanes, this_lane))
9259 break;
9260 lanes_found++;
9261 bitmap_set_bit (lanes, this_lane);
9262 gassign *use_ass = as_a <gassign *> (use_stmt);
9263 lane_defs.quick_push (std::make_pair
9264 (this_lane, gimple_assign_rhs2 (use_ass)));
9265 last = bb_vinfo->lookup_stmt (use_ass);
9266 roots.safe_push (last);
9267 def = gimple_assign_lhs (use_ass);
9268 }
9269 while (lanes_found < nlanes);
9270 if (roots.length () > 1)
9271 std::swap(roots[0], roots[roots.length () - 1]);
9272 if (lanes_found < nlanes)
9273 {
9274 /* Now search the def chain. */
9275 def = gimple_assign_rhs1 (assign);
9276 do
9277 {
9278 if (TREE_CODE (def) != SSA_NAME
9279 || !has_single_use (def))
9280 break;
9281 gimple *def_stmt = SSA_NAME_DEF_STMT (def);
9282 unsigned this_lane;
9283 if (!bb_vinfo->lookup_stmt (def_stmt)
9284 || !vect_slp_is_lane_insert (def_stmt,
9285 NULL_TREE, &this_lane)
9286 || !bb_vinfo->lookup_def (gimple_assign_rhs2 (def_stmt)))
9287 break;
9288 if (bitmap_bit_p (lanes, this_lane))
9289 break;
9290 lanes_found++;
9291 bitmap_set_bit (lanes, this_lane);
9292 lane_defs.quick_push (std::make_pair
9293 (this_lane,
9294 gimple_assign_rhs2 (def_stmt)));
9295 roots.safe_push (bb_vinfo->lookup_stmt (def_stmt));
9296 def = gimple_assign_rhs1 (def_stmt);
9297 }
9298 while (lanes_found < nlanes);
9299 }
9300 if (lanes_found == nlanes)
9301 {
9302 /* Sort lane_defs after the lane index and register the root. */
9303 lane_defs.qsort (vld_cmp);
9304 vec<stmt_vec_info> stmts;
9305 stmts.create (nlanes);
9306 for (unsigned i = 0; i < nlanes; ++i)
9307 stmts.quick_push (bb_vinfo->lookup_def (lane_defs[i].second));
9308 bb_vinfo->roots.safe_push (slp_root (slp_inst_kind_ctor,
9309 stmts, roots));
9310 }
9311 else
9312 roots.release ();
9313 }
9314 else if (!VECTOR_TYPE_P (TREE_TYPE (rhs))
9315 && (associative_tree_code (code) || code == MINUS_EXPR)
9316 /* ??? This pessimizes a two-element reduction. PR54400.
9317 ??? In-order reduction could be handled if we only
9318 traverse one operand chain in vect_slp_linearize_chain. */
9319 && !needs_fold_left_reduction_p (TREE_TYPE (rhs), code)
9320 /* Ops with constants at the tail can be stripped here. */
9321 && TREE_CODE (rhs) == SSA_NAME
9322 && TREE_CODE (gimple_assign_rhs2 (assign)) == SSA_NAME
9323 /* Should be the chain end. */
9324 && (!single_imm_use (gimple_assign_lhs (assign),
9325 &use_p, &use_stmt)
9326 || !is_gimple_assign (use_stmt)
9327 || (gimple_assign_rhs_code (use_stmt) != code
9328 && ((code != PLUS_EXPR && code != MINUS_EXPR)
9329 || (gimple_assign_rhs_code (use_stmt)
9330 != (code == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR))))))
9331 {
9332 /* We start the match at the end of a possible association
9333 chain. */
9334 auto_vec<chain_op_t> chain;
9335 auto_vec<std::pair<tree_code, gimple *> > worklist;
9336 auto_vec<gimple *> chain_stmts;
9337 gimple *code_stmt = NULL, *alt_code_stmt = NULL;
9338 if (code == MINUS_EXPR)
9339 code = PLUS_EXPR;
9340 internal_fn reduc_fn;
9341 if (!reduction_fn_for_scalar_code (code, &reduc_fn)
9342 || reduc_fn == IFN_LAST)
9343 continue;
9344 vect_slp_linearize_chain (bb_vinfo, worklist, chain, code, assign,
9345 /* ??? */
9346 code_stmt, alt_code_stmt, &chain_stmts);
9347 if (chain.length () > 1)
9348 {
9349 /* Sort the chain according to def_type and operation. */
9350 chain.sort (dt_sort_cmp, bb_vinfo);
9351 /* ??? Now we'd want to strip externals and constants
9352 but record those to be handled in the epilogue. */
9353 /* ??? For now do not allow mixing ops or externs/constants. */
9354 bool invalid = false;
9355 unsigned remain_cnt = 0;
9356 unsigned last_idx = 0;
9357 for (unsigned i = 0; i < chain.length (); ++i)
9358 {
9359 if (chain[i].code != code)
9360 {
9361 invalid = true;
9362 break;
9363 }
9364 if (chain[i].dt != vect_internal_def
9365 /* Avoid stmts where the def is not the LHS, like
9366 ASMs. */
9367 || (gimple_get_lhs (bb_vinfo->lookup_def
9368 (chain[i].op)->stmt)
9369 != chain[i].op))
9370 remain_cnt++;
9371 else
9372 last_idx = i;
9373 }
9374 /* Make sure to have an even number of lanes as we later do
9375 all-or-nothing discovery, not trying to split further. */
9376 if ((chain.length () - remain_cnt) & 1)
9377 remain_cnt++;
9378 if (!invalid && chain.length () - remain_cnt > 1)
9379 {
9380 vec<stmt_vec_info> stmts;
9381 vec<tree> remain = vNULL;
9382 stmts.create (chain.length ());
9383 if (remain_cnt > 0)
9384 remain.create (remain_cnt);
9385 for (unsigned i = 0; i < chain.length (); ++i)
9386 {
9387 stmt_vec_info stmt_info;
9388 if (chain[i].dt == vect_internal_def
9389 && ((stmt_info = bb_vinfo->lookup_def (chain[i].op)),
9390 gimple_get_lhs (stmt_info->stmt) == chain[i].op)
9391 && (i != last_idx
9392 || (stmts.length () & 1)))
9393 stmts.quick_push (stmt_info);
9394 else
9395 remain.quick_push (chain[i].op);
9396 }
9397 vec<stmt_vec_info> roots;
9398 roots.create (chain_stmts.length ());
9399 for (unsigned i = 0; i < chain_stmts.length (); ++i)
9400 roots.quick_push (bb_vinfo->lookup_stmt (chain_stmts[i]));
9401 bb_vinfo->roots.safe_push (slp_root (slp_inst_kind_bb_reduc,
9402 stmts, roots, remain));
9403 }
9404 }
9405 }
9406 }
9407 }
9408
9409 /* Walk the grouped store chains and replace entries with their
9410 pattern variant if any. */
9411
9412 static void
9413 vect_fixup_store_groups_with_patterns (vec_info *vinfo)
9414 {
9415 stmt_vec_info first_element;
9416 unsigned i;
9417
9418 FOR_EACH_VEC_ELT (vinfo->grouped_stores, i, first_element)
9419 {
9420 /* We also have CTORs in this array. */
9421 if (!STMT_VINFO_GROUPED_ACCESS (first_element))
9422 continue;
9423 if (STMT_VINFO_IN_PATTERN_P (first_element))
9424 {
9425 stmt_vec_info orig = first_element;
9426 first_element = STMT_VINFO_RELATED_STMT (first_element);
9427 DR_GROUP_FIRST_ELEMENT (first_element) = first_element;
9428 DR_GROUP_SIZE (first_element) = DR_GROUP_SIZE (orig);
9429 DR_GROUP_GAP (first_element) = DR_GROUP_GAP (orig);
9430 DR_GROUP_NEXT_ELEMENT (first_element) = DR_GROUP_NEXT_ELEMENT (orig);
9431 vinfo->grouped_stores[i] = first_element;
9432 }
9433 stmt_vec_info prev = first_element;
9434 while (DR_GROUP_NEXT_ELEMENT (prev))
9435 {
9436 stmt_vec_info elt = DR_GROUP_NEXT_ELEMENT (prev);
9437 if (STMT_VINFO_IN_PATTERN_P (elt))
9438 {
9439 stmt_vec_info orig = elt;
9440 elt = STMT_VINFO_RELATED_STMT (elt);
9441 DR_GROUP_NEXT_ELEMENT (prev) = elt;
9442 DR_GROUP_GAP (elt) = DR_GROUP_GAP (orig);
9443 DR_GROUP_NEXT_ELEMENT (elt) = DR_GROUP_NEXT_ELEMENT (orig);
9444 }
9445 DR_GROUP_FIRST_ELEMENT (elt) = first_element;
9446 prev = elt;
9447 }
9448 }
9449 }
9450
9451 /* Check if the region described by BB_VINFO can be vectorized, returning
9452 true if so. When returning false, set FATAL to true if the same failure
9453 would prevent vectorization at other vector sizes, false if it is still
9454 worth trying other sizes. N_STMTS is the number of statements in the
9455 region. */
9456
9457 static bool
9458 vect_slp_analyze_bb_1 (bb_vec_info bb_vinfo, int n_stmts, bool &fatal,
9459 vec<int> *dataref_groups)
9460 {
9461 DUMP_VECT_SCOPE ("vect_slp_analyze_bb");
9462
9463 slp_instance instance;
9464 int i;
9465 poly_uint64 min_vf = 2;
9466
9467 /* The first group of checks is independent of the vector size. */
9468 fatal = true;
9469
9470 /* Analyze the data references. */
9471
9472 if (!vect_analyze_data_refs (bb_vinfo, &min_vf, NULL))
9473 {
9474 if (dump_enabled_p ())
9475 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9476 "not vectorized: unhandled data-ref in basic "
9477 "block.\n");
9478 return false;
9479 }
9480
9481 if (!vect_analyze_data_ref_accesses (bb_vinfo, dataref_groups))
9482 {
9483 if (dump_enabled_p ())
9484 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9485 "not vectorized: unhandled data access in "
9486 "basic block.\n");
9487 return false;
9488 }
9489
9490 vect_slp_check_for_roots (bb_vinfo);
9491
9492 /* If there are no grouped stores and no constructors in the region
9493 there is no need to continue with pattern recog as vect_analyze_slp
9494 will fail anyway. */
9495 if (bb_vinfo->grouped_stores.is_empty ()
9496 && bb_vinfo->roots.is_empty ())
9497 {
9498 if (dump_enabled_p ())
9499 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9500 "not vectorized: no grouped stores in "
9501 "basic block.\n");
9502 return false;
9503 }
9504
9505 /* While the rest of the analysis below depends on it in some way. */
9506 fatal = false;
9507
9508 vect_pattern_recog (bb_vinfo);
9509
9510 /* Update store groups from pattern processing. */
9511 vect_fixup_store_groups_with_patterns (bb_vinfo);
9512
9513 /* Check the SLP opportunities in the basic block, analyze and build SLP
9514 trees. */
9515 if (!vect_analyze_slp (bb_vinfo, n_stmts, false))
9516 {
9517 if (dump_enabled_p ())
9518 {
9519 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9520 "Failed to SLP the basic block.\n");
9521 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9522 "not vectorized: failed to find SLP opportunities "
9523 "in basic block.\n");
9524 }
9525 return false;
9526 }
9527
9528 /* Optimize permutations. */
9529 vect_optimize_slp (bb_vinfo);
9530
9531 /* Gather the loads reachable from the SLP graph entries. */
9532 vect_gather_slp_loads (bb_vinfo);
9533
9534 vect_record_base_alignments (bb_vinfo);
9535
9536 /* Analyze and verify the alignment of data references and the
9537 dependence in the SLP instances. */
9538 for (i = 0; BB_VINFO_SLP_INSTANCES (bb_vinfo).iterate (i, &instance); )
9539 {
9540 vect_location = instance->location ();
9541 if (! vect_slp_analyze_instance_alignment (bb_vinfo, instance)
9542 || ! vect_slp_analyze_instance_dependence (bb_vinfo, instance))
9543 {
9544 slp_tree node = SLP_INSTANCE_TREE (instance);
9545 stmt_vec_info stmt_info = SLP_TREE_SCALAR_STMTS (node)[0];
9546 if (dump_enabled_p ())
9547 dump_printf_loc (MSG_NOTE, vect_location,
9548 "removing SLP instance operations starting from: %G",
9549 stmt_info->stmt);
9550 vect_free_slp_instance (instance);
9551 BB_VINFO_SLP_INSTANCES (bb_vinfo).ordered_remove (i);
9552 continue;
9553 }
9554
9555 /* Mark all the statements that we want to vectorize as pure SLP and
9556 relevant. */
9557 vect_mark_slp_stmts (bb_vinfo, SLP_INSTANCE_TREE (instance));
9558 vect_mark_slp_stmts_relevant (SLP_INSTANCE_TREE (instance));
9559 unsigned j;
9560 stmt_vec_info root;
9561 /* Likewise consider instance root stmts as vectorized. */
9562 FOR_EACH_VEC_ELT (SLP_INSTANCE_ROOT_STMTS (instance), j, root)
9563 STMT_SLP_TYPE (root) = pure_slp;
9564
9565 i++;
9566 }
9567 if (! BB_VINFO_SLP_INSTANCES (bb_vinfo).length ())
9568 return false;
9569
9570 if (!vect_slp_analyze_operations (bb_vinfo))
9571 {
9572 if (dump_enabled_p ())
9573 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9574 "not vectorized: bad operation in basic block.\n");
9575 return false;
9576 }
9577
9578 vect_bb_partition_graph (bb_vinfo);
9579
9580 return true;
9581 }
9582
9583 /* Subroutine of vect_slp_bb. Try to vectorize the statements for all
9584 basic blocks in BBS, returning true on success.
9585 The region has N_STMTS statements and has the datarefs given by DATAREFS. */
9586
9587 static bool
9588 vect_slp_region (vec<basic_block> bbs, vec<data_reference_p> datarefs,
9589 vec<int> *dataref_groups, unsigned int n_stmts,
9590 loop_p orig_loop)
9591 {
9592 bb_vec_info bb_vinfo;
9593 auto_vector_modes vector_modes;
9594
9595 /* Autodetect first vector size we try. */
9596 machine_mode next_vector_mode = VOIDmode;
9597 targetm.vectorize.autovectorize_vector_modes (&vector_modes, false);
9598 unsigned int mode_i = 0;
9599
9600 vec_info_shared shared;
9601
9602 machine_mode autodetected_vector_mode = VOIDmode;
9603 while (1)
9604 {
9605 bool vectorized = false;
9606 bool fatal = false;
9607 bb_vinfo = new _bb_vec_info (bbs, &shared);
9608
9609 bool first_time_p = shared.datarefs.is_empty ();
9610 BB_VINFO_DATAREFS (bb_vinfo) = datarefs;
9611 if (first_time_p)
9612 bb_vinfo->shared->save_datarefs ();
9613 else
9614 bb_vinfo->shared->check_datarefs ();
9615 bb_vinfo->vector_mode = next_vector_mode;
9616
9617 if (vect_slp_analyze_bb_1 (bb_vinfo, n_stmts, fatal, dataref_groups))
9618 {
9619 if (dump_enabled_p ())
9620 {
9621 dump_printf_loc (MSG_NOTE, vect_location,
9622 "***** Analysis succeeded with vector mode"
9623 " %s\n", GET_MODE_NAME (bb_vinfo->vector_mode));
9624 dump_printf_loc (MSG_NOTE, vect_location, "SLPing BB part\n");
9625 }
9626
9627 bb_vinfo->shared->check_datarefs ();
9628
9629 bool force_clear = false;
9630 auto_vec<slp_instance> profitable_subgraphs;
9631 for (slp_instance instance : BB_VINFO_SLP_INSTANCES (bb_vinfo))
9632 {
9633 if (instance->subgraph_entries.is_empty ())
9634 continue;
9635
9636 dump_user_location_t saved_vect_location = vect_location;
9637 vect_location = instance->location ();
9638 if (!unlimited_cost_model (NULL)
9639 && !vect_bb_vectorization_profitable_p
9640 (bb_vinfo, instance->subgraph_entries, orig_loop))
9641 {
9642 if (dump_enabled_p ())
9643 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9644 "not vectorized: vectorization is not "
9645 "profitable.\n");
9646 vect_location = saved_vect_location;
9647 continue;
9648 }
9649
9650 vect_location = saved_vect_location;
9651 if (!dbg_cnt (vect_slp))
9652 {
9653 force_clear = true;
9654 continue;
9655 }
9656
9657 profitable_subgraphs.safe_push (instance);
9658 }
9659
9660 /* When we're vectorizing an if-converted loop body make sure
9661 we vectorized all if-converted code. */
9662 if ((!profitable_subgraphs.is_empty () || force_clear) && orig_loop)
9663 {
9664 gcc_assert (bb_vinfo->nbbs == 1);
9665 for (gimple_stmt_iterator gsi = gsi_start_bb (bb_vinfo->bbs[0]);
9666 !gsi_end_p (gsi); gsi_next (&gsi))
9667 {
9668 /* The costing above left us with DCEable vectorized scalar
9669 stmts having the visited flag set on profitable
9670 subgraphs. Do the delayed clearing of the flag here. */
9671 if (gimple_visited_p (gsi_stmt (gsi)))
9672 {
9673 gimple_set_visited (gsi_stmt (gsi), false);
9674 continue;
9675 }
9676 if (flag_vect_cost_model == VECT_COST_MODEL_UNLIMITED)
9677 continue;
9678
9679 if (gassign *ass = dyn_cast <gassign *> (gsi_stmt (gsi)))
9680 if (gimple_assign_rhs_code (ass) == COND_EXPR)
9681 {
9682 if (!profitable_subgraphs.is_empty ()
9683 && dump_enabled_p ())
9684 dump_printf_loc (MSG_NOTE, vect_location,
9685 "not profitable because of "
9686 "unprofitable if-converted scalar "
9687 "code\n");
9688 profitable_subgraphs.truncate (0);
9689 }
9690 }
9691 }
9692
9693 /* Finally schedule the profitable subgraphs. */
9694 for (slp_instance instance : profitable_subgraphs)
9695 {
9696 if (!vectorized && dump_enabled_p ())
9697 dump_printf_loc (MSG_NOTE, vect_location,
9698 "Basic block will be vectorized "
9699 "using SLP\n");
9700 vectorized = true;
9701
9702 /* Dump before scheduling as store vectorization will remove
9703 the original stores and mess with the instance tree
9704 so querying its location will eventually ICE. */
9705 if (flag_checking)
9706 for (slp_instance sub : instance->subgraph_entries)
9707 gcc_assert (SLP_TREE_VECTYPE (SLP_INSTANCE_TREE (sub)));
9708 unsigned HOST_WIDE_INT bytes;
9709 if (dump_enabled_p ())
9710 for (slp_instance sub : instance->subgraph_entries)
9711 {
9712 tree vtype = SLP_TREE_VECTYPE (SLP_INSTANCE_TREE (sub));
9713 if (GET_MODE_SIZE (TYPE_MODE (vtype)).is_constant (&bytes))
9714 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
9715 sub->location (),
9716 "basic block part vectorized using %wu "
9717 "byte vectors\n", bytes);
9718 else
9719 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
9720 sub->location (),
9721 "basic block part vectorized using "
9722 "variable length vectors\n");
9723 }
9724
9725 dump_user_location_t saved_vect_location = vect_location;
9726 vect_location = instance->location ();
9727
9728 vect_schedule_slp (bb_vinfo, instance->subgraph_entries);
9729
9730 vect_location = saved_vect_location;
9731 }
9732
9733
9734 /* Generate the invariant statements. */
9735 if (!gimple_seq_empty_p (bb_vinfo->inv_pattern_def_seq))
9736 {
9737 if (dump_enabled_p ())
9738 dump_printf_loc (MSG_NOTE, vect_location,
9739 "------>generating invariant statements\n");
9740
9741 bb_vinfo->insert_seq_on_entry (NULL,
9742 bb_vinfo->inv_pattern_def_seq);
9743 }
9744 }
9745 else
9746 {
9747 if (dump_enabled_p ())
9748 dump_printf_loc (MSG_NOTE, vect_location,
9749 "***** Analysis failed with vector mode %s\n",
9750 GET_MODE_NAME (bb_vinfo->vector_mode));
9751 }
9752
9753 if (mode_i == 0)
9754 autodetected_vector_mode = bb_vinfo->vector_mode;
9755
9756 if (!fatal)
9757 while (mode_i < vector_modes.length ()
9758 && vect_chooses_same_modes_p (bb_vinfo, vector_modes[mode_i]))
9759 {
9760 if (dump_enabled_p ())
9761 dump_printf_loc (MSG_NOTE, vect_location,
9762 "***** The result for vector mode %s would"
9763 " be the same\n",
9764 GET_MODE_NAME (vector_modes[mode_i]));
9765 mode_i += 1;
9766 }
9767
9768 delete bb_vinfo;
9769
9770 if (mode_i < vector_modes.length ()
9771 && VECTOR_MODE_P (autodetected_vector_mode)
9772 && (related_vector_mode (vector_modes[mode_i],
9773 GET_MODE_INNER (autodetected_vector_mode))
9774 == autodetected_vector_mode)
9775 && (related_vector_mode (autodetected_vector_mode,
9776 GET_MODE_INNER (vector_modes[mode_i]))
9777 == vector_modes[mode_i]))
9778 {
9779 if (dump_enabled_p ())
9780 dump_printf_loc (MSG_NOTE, vect_location,
9781 "***** Skipping vector mode %s, which would"
9782 " repeat the analysis for %s\n",
9783 GET_MODE_NAME (vector_modes[mode_i]),
9784 GET_MODE_NAME (autodetected_vector_mode));
9785 mode_i += 1;
9786 }
9787
9788 if (vectorized
9789 || mode_i == vector_modes.length ()
9790 || autodetected_vector_mode == VOIDmode
9791 /* If vect_slp_analyze_bb_1 signaled that analysis for all
9792 vector sizes will fail do not bother iterating. */
9793 || fatal)
9794 return vectorized;
9795
9796 /* Try the next biggest vector size. */
9797 next_vector_mode = vector_modes[mode_i++];
9798 if (dump_enabled_p ())
9799 dump_printf_loc (MSG_NOTE, vect_location,
9800 "***** Re-trying analysis with vector mode %s\n",
9801 GET_MODE_NAME (next_vector_mode));
9802 }
9803 }
9804
9805
9806 /* Main entry for the BB vectorizer. Analyze and transform BBS, returns
9807 true if anything in the basic-block was vectorized. */
9808
9809 static bool
9810 vect_slp_bbs (const vec<basic_block> &bbs, loop_p orig_loop)
9811 {
9812 vec<data_reference_p> datarefs = vNULL;
9813 auto_vec<int> dataref_groups;
9814 int insns = 0;
9815 int current_group = 0;
9816
9817 for (unsigned i = 0; i < bbs.length (); i++)
9818 {
9819 basic_block bb = bbs[i];
9820 for (gimple_stmt_iterator gsi = gsi_after_labels (bb); !gsi_end_p (gsi);
9821 gsi_next (&gsi))
9822 {
9823 gimple *stmt = gsi_stmt (gsi);
9824 if (is_gimple_debug (stmt))
9825 continue;
9826
9827 insns++;
9828
9829 if (gimple_location (stmt) != UNKNOWN_LOCATION)
9830 vect_location = stmt;
9831
9832 if (!vect_find_stmt_data_reference (NULL, stmt, &datarefs,
9833 &dataref_groups, current_group))
9834 ++current_group;
9835 }
9836 /* New BBs always start a new DR group. */
9837 ++current_group;
9838 }
9839
9840 return vect_slp_region (bbs, datarefs, &dataref_groups, insns, orig_loop);
9841 }
9842
9843 /* Special entry for the BB vectorizer. Analyze and transform a single
9844 if-converted BB with ORIG_LOOPs body being the not if-converted
9845 representation. Returns true if anything in the basic-block was
9846 vectorized. */
9847
9848 bool
9849 vect_slp_if_converted_bb (basic_block bb, loop_p orig_loop)
9850 {
9851 auto_vec<basic_block> bbs;
9852 bbs.safe_push (bb);
9853 return vect_slp_bbs (bbs, orig_loop);
9854 }
9855
9856 /* Main entry for the BB vectorizer. Analyze and transform BB, returns
9857 true if anything in the basic-block was vectorized. */
9858
9859 bool
9860 vect_slp_function (function *fun)
9861 {
9862 bool r = false;
9863 int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (fun));
9864 auto_bitmap exit_bbs;
9865 bitmap_set_bit (exit_bbs, EXIT_BLOCK);
9866 edge entry = single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (fun));
9867 unsigned n = rev_post_order_and_mark_dfs_back_seme (fun, entry, exit_bbs,
9868 true, rpo, NULL);
9869
9870 /* For the moment split the function into pieces to avoid making
9871 the iteration on the vector mode moot. Split at points we know
9872 to not handle well which is CFG merges (SLP discovery doesn't
9873 handle non-loop-header PHIs) and loop exits. Since pattern
9874 recog requires reverse iteration to visit uses before defs
9875 simply chop RPO into pieces. */
9876 auto_vec<basic_block> bbs;
9877 for (unsigned i = 0; i < n; i++)
9878 {
9879 basic_block bb = BASIC_BLOCK_FOR_FN (fun, rpo[i]);
9880 bool split = false;
9881
9882 /* Split when a BB is not dominated by the first block. */
9883 if (!bbs.is_empty ()
9884 && !dominated_by_p (CDI_DOMINATORS, bb, bbs[0]))
9885 {
9886 if (dump_enabled_p ())
9887 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9888 "splitting region at dominance boundary bb%d\n",
9889 bb->index);
9890 split = true;
9891 }
9892 /* Split when the loop determined by the first block
9893 is exited. This is because we eventually insert
9894 invariants at region begin. */
9895 else if (!bbs.is_empty ()
9896 && bbs[0]->loop_father != bb->loop_father
9897 && !flow_loop_nested_p (bbs[0]->loop_father, bb->loop_father))
9898 {
9899 if (dump_enabled_p ())
9900 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9901 "splitting region at loop %d exit at bb%d\n",
9902 bbs[0]->loop_father->num, bb->index);
9903 split = true;
9904 }
9905 else if (!bbs.is_empty ()
9906 && bb->loop_father->header == bb
9907 && bb->loop_father->dont_vectorize)
9908 {
9909 if (dump_enabled_p ())
9910 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9911 "splitting region at dont-vectorize loop %d "
9912 "entry at bb%d\n",
9913 bb->loop_father->num, bb->index);
9914 split = true;
9915 }
9916
9917 if (split && !bbs.is_empty ())
9918 {
9919 r |= vect_slp_bbs (bbs, NULL);
9920 bbs.truncate (0);
9921 }
9922
9923 if (bbs.is_empty ())
9924 {
9925 /* We need to be able to insert at the head of the region which
9926 we cannot for region starting with a returns-twice call. */
9927 if (gcall *first = safe_dyn_cast <gcall *> (first_stmt (bb)))
9928 if (gimple_call_flags (first) & ECF_RETURNS_TWICE)
9929 {
9930 if (dump_enabled_p ())
9931 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9932 "skipping bb%d as start of region as it "
9933 "starts with returns-twice call\n",
9934 bb->index);
9935 continue;
9936 }
9937 /* If the loop this BB belongs to is marked as not to be vectorized
9938 honor that also for BB vectorization. */
9939 if (bb->loop_father->dont_vectorize)
9940 continue;
9941 }
9942
9943 bbs.safe_push (bb);
9944
9945 /* When we have a stmt ending this block and defining a
9946 value we have to insert on edges when inserting after it for
9947 a vector containing its definition. Avoid this for now. */
9948 if (gimple *last = *gsi_last_bb (bb))
9949 if (gimple_get_lhs (last)
9950 && is_ctrl_altering_stmt (last))
9951 {
9952 if (dump_enabled_p ())
9953 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
9954 "splitting region at control altering "
9955 "definition %G", last);
9956 r |= vect_slp_bbs (bbs, NULL);
9957 bbs.truncate (0);
9958 }
9959 }
9960
9961 if (!bbs.is_empty ())
9962 r |= vect_slp_bbs (bbs, NULL);
9963
9964 free (rpo);
9965
9966 return r;
9967 }
9968
9969 /* Build a variable-length vector in which the elements in ELTS are repeated
9970 to a fill NRESULTS vectors of type VECTOR_TYPE. Store the vectors in
9971 RESULTS and add any new instructions to SEQ.
9972
9973 The approach we use is:
9974
9975 (1) Find a vector mode VM with integer elements of mode IM.
9976
9977 (2) Replace ELTS[0:NELTS] with ELTS'[0:NELTS'], where each element of
9978 ELTS' has mode IM. This involves creating NELTS' VIEW_CONVERT_EXPRs
9979 from small vectors to IM.
9980
9981 (3) Duplicate each ELTS'[I] into a vector of mode VM.
9982
9983 (4) Use a tree of interleaving VEC_PERM_EXPRs to create VMs with the
9984 correct byte contents.
9985
9986 (5) Use VIEW_CONVERT_EXPR to cast the final VMs to the required type.
9987
9988 We try to find the largest IM for which this sequence works, in order
9989 to cut down on the number of interleaves. */
9990
9991 void
9992 duplicate_and_interleave (vec_info *vinfo, gimple_seq *seq, tree vector_type,
9993 const vec<tree> &elts, unsigned int nresults,
9994 vec<tree> &results)
9995 {
9996 unsigned int nelts = elts.length ();
9997 tree element_type = TREE_TYPE (vector_type);
9998
9999 /* (1) Find a vector mode VM with integer elements of mode IM. */
10000 unsigned int nvectors = 1;
10001 tree new_vector_type;
10002 tree permutes[2];
10003 if (!can_duplicate_and_interleave_p (vinfo, nelts, element_type,
10004 &nvectors, &new_vector_type,
10005 permutes))
10006 gcc_unreachable ();
10007
10008 /* Get a vector type that holds ELTS[0:NELTS/NELTS']. */
10009 unsigned int partial_nelts = nelts / nvectors;
10010 tree partial_vector_type = build_vector_type (element_type, partial_nelts);
10011
10012 tree_vector_builder partial_elts;
10013 auto_vec<tree, 32> pieces (nvectors * 2);
10014 pieces.quick_grow_cleared (nvectors * 2);
10015 for (unsigned int i = 0; i < nvectors; ++i)
10016 {
10017 /* (2) Replace ELTS[0:NELTS] with ELTS'[0:NELTS'], where each element of
10018 ELTS' has mode IM. */
10019 partial_elts.new_vector (partial_vector_type, partial_nelts, 1);
10020 for (unsigned int j = 0; j < partial_nelts; ++j)
10021 partial_elts.quick_push (elts[i * partial_nelts + j]);
10022 tree t = gimple_build_vector (seq, &partial_elts);
10023 t = gimple_build (seq, VIEW_CONVERT_EXPR,
10024 TREE_TYPE (new_vector_type), t);
10025
10026 /* (3) Duplicate each ELTS'[I] into a vector of mode VM. */
10027 pieces[i] = gimple_build_vector_from_val (seq, new_vector_type, t);
10028 }
10029
10030 /* (4) Use a tree of VEC_PERM_EXPRs to create a single VM with the
10031 correct byte contents.
10032
10033 Conceptually, we need to repeat the following operation log2(nvectors)
10034 times, where hi_start = nvectors / 2:
10035
10036 out[i * 2] = VEC_PERM_EXPR (in[i], in[i + hi_start], lo_permute);
10037 out[i * 2 + 1] = VEC_PERM_EXPR (in[i], in[i + hi_start], hi_permute);
10038
10039 However, if each input repeats every N elements and the VF is
10040 a multiple of N * 2, the HI result is the same as the LO result.
10041 This will be true for the first N1 iterations of the outer loop,
10042 followed by N2 iterations for which both the LO and HI results
10043 are needed. I.e.:
10044
10045 N1 + N2 = log2(nvectors)
10046
10047 Each "N1 iteration" doubles the number of redundant vectors and the
10048 effect of the process as a whole is to have a sequence of nvectors/2**N1
10049 vectors that repeats 2**N1 times. Rather than generate these redundant
10050 vectors, we halve the number of vectors for each N1 iteration. */
10051 unsigned int in_start = 0;
10052 unsigned int out_start = nvectors;
10053 unsigned int new_nvectors = nvectors;
10054 for (unsigned int in_repeat = 1; in_repeat < nvectors; in_repeat *= 2)
10055 {
10056 unsigned int hi_start = new_nvectors / 2;
10057 unsigned int out_i = 0;
10058 for (unsigned int in_i = 0; in_i < new_nvectors; ++in_i)
10059 {
10060 if ((in_i & 1) != 0
10061 && multiple_p (TYPE_VECTOR_SUBPARTS (new_vector_type),
10062 2 * in_repeat))
10063 continue;
10064
10065 tree output = make_ssa_name (new_vector_type);
10066 tree input1 = pieces[in_start + (in_i / 2)];
10067 tree input2 = pieces[in_start + (in_i / 2) + hi_start];
10068 gassign *stmt = gimple_build_assign (output, VEC_PERM_EXPR,
10069 input1, input2,
10070 permutes[in_i & 1]);
10071 gimple_seq_add_stmt (seq, stmt);
10072 pieces[out_start + out_i] = output;
10073 out_i += 1;
10074 }
10075 std::swap (in_start, out_start);
10076 new_nvectors = out_i;
10077 }
10078
10079 /* (5) Use VIEW_CONVERT_EXPR to cast the final VM to the required type. */
10080 results.reserve (nresults);
10081 for (unsigned int i = 0; i < nresults; ++i)
10082 if (i < new_nvectors)
10083 results.quick_push (gimple_build (seq, VIEW_CONVERT_EXPR, vector_type,
10084 pieces[in_start + i]));
10085 else
10086 results.quick_push (results[i - new_nvectors]);
10087 }
10088
10089
10090 /* For constant and loop invariant defs in OP_NODE this function creates
10091 vector defs that will be used in the vectorized stmts and stores them
10092 to SLP_TREE_VEC_DEFS of OP_NODE. */
10093
10094 static void
10095 vect_create_constant_vectors (vec_info *vinfo, slp_tree op_node)
10096 {
10097 unsigned HOST_WIDE_INT nunits;
10098 tree vec_cst;
10099 unsigned j, number_of_places_left_in_vector;
10100 tree vector_type;
10101 tree vop;
10102 int group_size = op_node->ops.length ();
10103 unsigned int vec_num, i;
10104 unsigned number_of_copies = 1;
10105 bool constant_p;
10106 gimple_seq ctor_seq = NULL;
10107 auto_vec<tree, 16> permute_results;
10108
10109 /* We always want SLP_TREE_VECTYPE (op_node) here correctly set. */
10110 vector_type = SLP_TREE_VECTYPE (op_node);
10111
10112 unsigned int number_of_vectors = SLP_TREE_NUMBER_OF_VEC_STMTS (op_node);
10113 SLP_TREE_VEC_DEFS (op_node).create (number_of_vectors);
10114 auto_vec<tree> voprnds (number_of_vectors);
10115
10116 /* NUMBER_OF_COPIES is the number of times we need to use the same values in
10117 created vectors. It is greater than 1 if unrolling is performed.
10118
10119 For example, we have two scalar operands, s1 and s2 (e.g., group of
10120 strided accesses of size two), while NUNITS is four (i.e., four scalars
10121 of this type can be packed in a vector). The output vector will contain
10122 two copies of each scalar operand: {s1, s2, s1, s2}. (NUMBER_OF_COPIES
10123 will be 2).
10124
10125 If GROUP_SIZE > NUNITS, the scalars will be split into several vectors
10126 containing the operands.
10127
10128 For example, NUNITS is four as before, and the group size is 8
10129 (s1, s2, ..., s8). We will create two vectors {s1, s2, s3, s4} and
10130 {s5, s6, s7, s8}. */
10131
10132 /* When using duplicate_and_interleave, we just need one element for
10133 each scalar statement. */
10134 if (!TYPE_VECTOR_SUBPARTS (vector_type).is_constant (&nunits))
10135 nunits = group_size;
10136
10137 number_of_copies = nunits * number_of_vectors / group_size;
10138
10139 number_of_places_left_in_vector = nunits;
10140 constant_p = true;
10141 tree uniform_elt = NULL_TREE;
10142 tree_vector_builder elts (vector_type, nunits, 1);
10143 elts.quick_grow (nunits);
10144 stmt_vec_info insert_after = NULL;
10145 for (j = 0; j < number_of_copies; j++)
10146 {
10147 tree op;
10148 for (i = group_size - 1; op_node->ops.iterate (i, &op); i--)
10149 {
10150 /* Create 'vect_ = {op0,op1,...,opn}'. */
10151 tree orig_op = op;
10152 if (number_of_places_left_in_vector == nunits)
10153 uniform_elt = op;
10154 else if (uniform_elt && operand_equal_p (uniform_elt, op))
10155 op = elts[number_of_places_left_in_vector];
10156 else
10157 uniform_elt = NULL_TREE;
10158 number_of_places_left_in_vector--;
10159 if (!types_compatible_p (TREE_TYPE (vector_type), TREE_TYPE (op)))
10160 {
10161 if (CONSTANT_CLASS_P (op))
10162 {
10163 if (VECTOR_BOOLEAN_TYPE_P (vector_type))
10164 {
10165 /* Can't use VIEW_CONVERT_EXPR for booleans because
10166 of possibly different sizes of scalar value and
10167 vector element. */
10168 if (integer_zerop (op))
10169 op = build_int_cst (TREE_TYPE (vector_type), 0);
10170 else if (integer_onep (op))
10171 op = build_all_ones_cst (TREE_TYPE (vector_type));
10172 else
10173 gcc_unreachable ();
10174 }
10175 else
10176 op = fold_unary (VIEW_CONVERT_EXPR,
10177 TREE_TYPE (vector_type), op);
10178 gcc_assert (op && CONSTANT_CLASS_P (op));
10179 }
10180 else
10181 {
10182 tree new_temp = make_ssa_name (TREE_TYPE (vector_type));
10183 gimple *init_stmt;
10184 if (VECTOR_BOOLEAN_TYPE_P (vector_type))
10185 {
10186 tree true_val
10187 = build_all_ones_cst (TREE_TYPE (vector_type));
10188 tree false_val
10189 = build_zero_cst (TREE_TYPE (vector_type));
10190 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (op)));
10191 init_stmt = gimple_build_assign (new_temp, COND_EXPR,
10192 op, true_val,
10193 false_val);
10194 }
10195 else
10196 {
10197 op = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (vector_type),
10198 op);
10199 init_stmt
10200 = gimple_build_assign (new_temp, VIEW_CONVERT_EXPR,
10201 op);
10202 }
10203 gimple_seq_add_stmt (&ctor_seq, init_stmt);
10204 op = new_temp;
10205 }
10206 }
10207 elts[number_of_places_left_in_vector] = op;
10208 if (!CONSTANT_CLASS_P (op))
10209 constant_p = false;
10210 /* For BB vectorization we have to compute an insert location
10211 when a def is inside the analyzed region since we cannot
10212 simply insert at the BB start in this case. */
10213 stmt_vec_info opdef;
10214 if (TREE_CODE (orig_op) == SSA_NAME
10215 && !SSA_NAME_IS_DEFAULT_DEF (orig_op)
10216 && is_a <bb_vec_info> (vinfo)
10217 && (opdef = vinfo->lookup_def (orig_op)))
10218 {
10219 if (!insert_after)
10220 insert_after = opdef;
10221 else
10222 insert_after = get_later_stmt (insert_after, opdef);
10223 }
10224
10225 if (number_of_places_left_in_vector == 0)
10226 {
10227 auto type_nunits = TYPE_VECTOR_SUBPARTS (vector_type);
10228 if (uniform_elt)
10229 vec_cst = gimple_build_vector_from_val (&ctor_seq, vector_type,
10230 elts[0]);
10231 else if (constant_p
10232 ? multiple_p (type_nunits, nunits)
10233 : known_eq (type_nunits, nunits))
10234 vec_cst = gimple_build_vector (&ctor_seq, &elts);
10235 else
10236 {
10237 if (permute_results.is_empty ())
10238 duplicate_and_interleave (vinfo, &ctor_seq, vector_type,
10239 elts, number_of_vectors,
10240 permute_results);
10241 vec_cst = permute_results[number_of_vectors - j - 1];
10242 }
10243 if (!gimple_seq_empty_p (ctor_seq))
10244 {
10245 if (insert_after)
10246 {
10247 gimple_stmt_iterator gsi;
10248 if (gimple_code (insert_after->stmt) == GIMPLE_PHI)
10249 {
10250 gsi = gsi_after_labels (gimple_bb (insert_after->stmt));
10251 gsi_insert_seq_before (&gsi, ctor_seq,
10252 GSI_CONTINUE_LINKING);
10253 }
10254 else if (!stmt_ends_bb_p (insert_after->stmt))
10255 {
10256 gsi = gsi_for_stmt (insert_after->stmt);
10257 gsi_insert_seq_after (&gsi, ctor_seq,
10258 GSI_CONTINUE_LINKING);
10259 }
10260 else
10261 {
10262 /* When we want to insert after a def where the
10263 defining stmt throws then insert on the fallthru
10264 edge. */
10265 edge e = find_fallthru_edge
10266 (gimple_bb (insert_after->stmt)->succs);
10267 basic_block new_bb
10268 = gsi_insert_seq_on_edge_immediate (e, ctor_seq);
10269 gcc_assert (!new_bb);
10270 }
10271 }
10272 else
10273 vinfo->insert_seq_on_entry (NULL, ctor_seq);
10274 ctor_seq = NULL;
10275 }
10276 voprnds.quick_push (vec_cst);
10277 insert_after = NULL;
10278 number_of_places_left_in_vector = nunits;
10279 constant_p = true;
10280 elts.new_vector (vector_type, nunits, 1);
10281 elts.quick_grow (nunits);
10282 }
10283 }
10284 }
10285
10286 /* Since the vectors are created in the reverse order, we should invert
10287 them. */
10288 vec_num = voprnds.length ();
10289 for (j = vec_num; j != 0; j--)
10290 {
10291 vop = voprnds[j - 1];
10292 SLP_TREE_VEC_DEFS (op_node).quick_push (vop);
10293 }
10294
10295 /* In case that VF is greater than the unrolling factor needed for the SLP
10296 group of stmts, NUMBER_OF_VECTORS to be created is greater than
10297 NUMBER_OF_SCALARS/NUNITS or NUNITS/NUMBER_OF_SCALARS, and hence we have
10298 to replicate the vectors. */
10299 while (number_of_vectors > SLP_TREE_VEC_DEFS (op_node).length ())
10300 for (i = 0; SLP_TREE_VEC_DEFS (op_node).iterate (i, &vop) && i < vec_num;
10301 i++)
10302 SLP_TREE_VEC_DEFS (op_node).quick_push (vop);
10303 }
10304
10305 /* Get the scalar definition of the Nth lane from SLP_NODE or NULL_TREE
10306 if there is no definition for it in the scalar IL or it is not known. */
10307
10308 tree
10309 vect_get_slp_scalar_def (slp_tree slp_node, unsigned n)
10310 {
10311 if (SLP_TREE_DEF_TYPE (slp_node) == vect_internal_def)
10312 {
10313 if (!SLP_TREE_SCALAR_STMTS (slp_node).exists ())
10314 return NULL_TREE;
10315 stmt_vec_info def = SLP_TREE_SCALAR_STMTS (slp_node)[n];
10316 if (!def)
10317 return NULL_TREE;
10318 return gimple_get_lhs (STMT_VINFO_STMT (def));
10319 }
10320 else
10321 return SLP_TREE_SCALAR_OPS (slp_node)[n];
10322 }
10323
10324 /* Get the Ith vectorized definition from SLP_NODE. */
10325
10326 tree
10327 vect_get_slp_vect_def (slp_tree slp_node, unsigned i)
10328 {
10329 return SLP_TREE_VEC_DEFS (slp_node)[i];
10330 }
10331
10332 /* Get the vectorized definitions of SLP_NODE in *VEC_DEFS. */
10333
10334 void
10335 vect_get_slp_defs (slp_tree slp_node, vec<tree> *vec_defs)
10336 {
10337 vec_defs->create (SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node));
10338 vec_defs->splice (SLP_TREE_VEC_DEFS (slp_node));
10339 }
10340
10341 /* Get N vectorized definitions for SLP_NODE. */
10342
10343 void
10344 vect_get_slp_defs (vec_info *,
10345 slp_tree slp_node, vec<vec<tree> > *vec_oprnds, unsigned n)
10346 {
10347 if (n == -1U)
10348 n = SLP_TREE_CHILDREN (slp_node).length ();
10349
10350 for (unsigned i = 0; i < n; ++i)
10351 {
10352 slp_tree child = SLP_TREE_CHILDREN (slp_node)[i];
10353 vec<tree> vec_defs = vNULL;
10354 vect_get_slp_defs (child, &vec_defs);
10355 vec_oprnds->quick_push (vec_defs);
10356 }
10357 }
10358
10359 /* A subroutine of vect_transform_slp_perm_load with two extra arguments:
10360 - PERM gives the permutation that the caller wants to use for NODE,
10361 which might be different from SLP_LOAD_PERMUTATION.
10362 - DUMP_P controls whether the function dumps information. */
10363
10364 static bool
10365 vect_transform_slp_perm_load_1 (vec_info *vinfo, slp_tree node,
10366 load_permutation_t &perm,
10367 const vec<tree> &dr_chain,
10368 gimple_stmt_iterator *gsi, poly_uint64 vf,
10369 bool analyze_only, bool dump_p,
10370 unsigned *n_perms, unsigned int *n_loads,
10371 bool dce_chain)
10372 {
10373 stmt_vec_info stmt_info = SLP_TREE_SCALAR_STMTS (node)[0];
10374 int vec_index = 0;
10375 tree vectype = SLP_TREE_VECTYPE (node);
10376 unsigned int group_size = SLP_TREE_SCALAR_STMTS (node).length ();
10377 unsigned int mask_element;
10378 unsigned dr_group_size;
10379 machine_mode mode;
10380
10381 if (!STMT_VINFO_GROUPED_ACCESS (stmt_info))
10382 dr_group_size = 1;
10383 else
10384 {
10385 stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
10386 dr_group_size = DR_GROUP_SIZE (stmt_info);
10387 }
10388
10389 mode = TYPE_MODE (vectype);
10390 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
10391 unsigned int nstmts = SLP_TREE_NUMBER_OF_VEC_STMTS (node);
10392
10393 /* Initialize the vect stmts of NODE to properly insert the generated
10394 stmts later. */
10395 if (! analyze_only)
10396 for (unsigned i = SLP_TREE_VEC_DEFS (node).length (); i < nstmts; i++)
10397 SLP_TREE_VEC_DEFS (node).quick_push (NULL_TREE);
10398
10399 /* Generate permutation masks for every NODE. Number of masks for each NODE
10400 is equal to GROUP_SIZE.
10401 E.g., we have a group of three nodes with three loads from the same
10402 location in each node, and the vector size is 4. I.e., we have a
10403 a0b0c0a1b1c1... sequence and we need to create the following vectors:
10404 for a's: a0a0a0a1 a1a1a2a2 a2a3a3a3
10405 for b's: b0b0b0b1 b1b1b2b2 b2b3b3b3
10406 ...
10407
10408 The masks for a's should be: {0,0,0,3} {3,3,6,6} {6,9,9,9}.
10409 The last mask is illegal since we assume two operands for permute
10410 operation, and the mask element values can't be outside that range.
10411 Hence, the last mask must be converted into {2,5,5,5}.
10412 For the first two permutations we need the first and the second input
10413 vectors: {a0,b0,c0,a1} and {b1,c1,a2,b2}, and for the last permutation
10414 we need the second and the third vectors: {b1,c1,a2,b2} and
10415 {c2,a3,b3,c3}. */
10416
10417 int vect_stmts_counter = 0;
10418 unsigned int index = 0;
10419 int first_vec_index = -1;
10420 int second_vec_index = -1;
10421 bool noop_p = true;
10422 *n_perms = 0;
10423
10424 vec_perm_builder mask;
10425 unsigned int nelts_to_build;
10426 unsigned int nvectors_per_build;
10427 unsigned int in_nlanes;
10428 bool repeating_p = (group_size == dr_group_size
10429 && multiple_p (nunits, group_size));
10430 if (repeating_p)
10431 {
10432 /* A single vector contains a whole number of copies of the node, so:
10433 (a) all permutes can use the same mask; and
10434 (b) the permutes only need a single vector input. */
10435 mask.new_vector (nunits, group_size, 3);
10436 nelts_to_build = mask.encoded_nelts ();
10437 /* It's possible to obtain zero nstmts during analyze_only, so make
10438 it at least one to ensure the later computation for n_perms
10439 proceed. */
10440 nvectors_per_build = nstmts > 0 ? nstmts : 1;
10441 in_nlanes = dr_group_size * 3;
10442 }
10443 else
10444 {
10445 /* We need to construct a separate mask for each vector statement. */
10446 unsigned HOST_WIDE_INT const_nunits, const_vf;
10447 if (!nunits.is_constant (&const_nunits)
10448 || !vf.is_constant (&const_vf))
10449 return false;
10450 mask.new_vector (const_nunits, const_nunits, 1);
10451 nelts_to_build = const_vf * group_size;
10452 nvectors_per_build = 1;
10453 in_nlanes = const_vf * dr_group_size;
10454 }
10455 auto_sbitmap used_in_lanes (in_nlanes);
10456 bitmap_clear (used_in_lanes);
10457 auto_bitmap used_defs;
10458
10459 unsigned int count = mask.encoded_nelts ();
10460 mask.quick_grow (count);
10461 vec_perm_indices indices;
10462
10463 for (unsigned int j = 0; j < nelts_to_build; j++)
10464 {
10465 unsigned int iter_num = j / group_size;
10466 unsigned int stmt_num = j % group_size;
10467 unsigned int i = (iter_num * dr_group_size + perm[stmt_num]);
10468 bitmap_set_bit (used_in_lanes, i);
10469 if (repeating_p)
10470 {
10471 first_vec_index = 0;
10472 mask_element = i;
10473 }
10474 else
10475 {
10476 /* Enforced before the loop when !repeating_p. */
10477 unsigned int const_nunits = nunits.to_constant ();
10478 vec_index = i / const_nunits;
10479 mask_element = i % const_nunits;
10480 if (vec_index == first_vec_index
10481 || first_vec_index == -1)
10482 {
10483 first_vec_index = vec_index;
10484 }
10485 else if (vec_index == second_vec_index
10486 || second_vec_index == -1)
10487 {
10488 second_vec_index = vec_index;
10489 mask_element += const_nunits;
10490 }
10491 else
10492 {
10493 if (dump_p)
10494 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10495 "permutation requires at "
10496 "least three vectors %G",
10497 stmt_info->stmt);
10498 gcc_assert (analyze_only);
10499 return false;
10500 }
10501
10502 gcc_assert (mask_element < 2 * const_nunits);
10503 }
10504
10505 if (mask_element != index)
10506 noop_p = false;
10507 mask[index++] = mask_element;
10508
10509 if (index == count)
10510 {
10511 if (!noop_p)
10512 {
10513 indices.new_vector (mask, second_vec_index == -1 ? 1 : 2, nunits);
10514 if (!can_vec_perm_const_p (mode, mode, indices))
10515 {
10516 if (dump_p)
10517 {
10518 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10519 "unsupported vect permute { ");
10520 for (i = 0; i < count; ++i)
10521 {
10522 dump_dec (MSG_MISSED_OPTIMIZATION, mask[i]);
10523 dump_printf (MSG_MISSED_OPTIMIZATION, " ");
10524 }
10525 dump_printf (MSG_MISSED_OPTIMIZATION, "}\n");
10526 }
10527 gcc_assert (analyze_only);
10528 return false;
10529 }
10530
10531 tree mask_vec = NULL_TREE;
10532 if (!analyze_only)
10533 mask_vec = vect_gen_perm_mask_checked (vectype, indices);
10534
10535 if (second_vec_index == -1)
10536 second_vec_index = first_vec_index;
10537
10538 for (unsigned int ri = 0; ri < nvectors_per_build; ++ri)
10539 {
10540 ++*n_perms;
10541 if (analyze_only)
10542 continue;
10543 /* Generate the permute statement if necessary. */
10544 tree first_vec = dr_chain[first_vec_index + ri];
10545 tree second_vec = dr_chain[second_vec_index + ri];
10546 gassign *stmt = as_a<gassign *> (stmt_info->stmt);
10547 tree perm_dest
10548 = vect_create_destination_var (gimple_assign_lhs (stmt),
10549 vectype);
10550 perm_dest = make_ssa_name (perm_dest);
10551 gimple *perm_stmt
10552 = gimple_build_assign (perm_dest, VEC_PERM_EXPR, first_vec,
10553 second_vec, mask_vec);
10554 vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt,
10555 gsi);
10556 if (dce_chain)
10557 {
10558 bitmap_set_bit (used_defs, first_vec_index + ri);
10559 bitmap_set_bit (used_defs, second_vec_index + ri);
10560 }
10561
10562 /* Store the vector statement in NODE. */
10563 SLP_TREE_VEC_DEFS (node)[vect_stmts_counter++] = perm_dest;
10564 }
10565 }
10566 else if (!analyze_only)
10567 {
10568 for (unsigned int ri = 0; ri < nvectors_per_build; ++ri)
10569 {
10570 tree first_vec = dr_chain[first_vec_index + ri];
10571 /* If mask was NULL_TREE generate the requested
10572 identity transform. */
10573 if (dce_chain)
10574 bitmap_set_bit (used_defs, first_vec_index + ri);
10575
10576 /* Store the vector statement in NODE. */
10577 SLP_TREE_VEC_DEFS (node)[vect_stmts_counter++] = first_vec;
10578 }
10579 }
10580
10581 index = 0;
10582 first_vec_index = -1;
10583 second_vec_index = -1;
10584 noop_p = true;
10585 }
10586 }
10587
10588 if (n_loads)
10589 {
10590 if (repeating_p)
10591 *n_loads = SLP_TREE_NUMBER_OF_VEC_STMTS (node);
10592 else
10593 {
10594 /* Enforced above when !repeating_p. */
10595 unsigned int const_nunits = nunits.to_constant ();
10596 *n_loads = 0;
10597 bool load_seen = false;
10598 for (unsigned i = 0; i < in_nlanes; ++i)
10599 {
10600 if (i % const_nunits == 0)
10601 {
10602 if (load_seen)
10603 *n_loads += 1;
10604 load_seen = false;
10605 }
10606 if (bitmap_bit_p (used_in_lanes, i))
10607 load_seen = true;
10608 }
10609 if (load_seen)
10610 *n_loads += 1;
10611 }
10612 }
10613
10614 if (dce_chain)
10615 for (unsigned i = 0; i < dr_chain.length (); ++i)
10616 if (!bitmap_bit_p (used_defs, i))
10617 {
10618 tree def = dr_chain[i];
10619 do
10620 {
10621 gimple *stmt = SSA_NAME_DEF_STMT (def);
10622 if (is_gimple_assign (stmt)
10623 && (gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR
10624 || gimple_assign_rhs_code (stmt) == CONSTRUCTOR))
10625 def = single_ssa_tree_operand (stmt, SSA_OP_USE);
10626 else
10627 def = NULL;
10628 gimple_stmt_iterator rgsi = gsi_for_stmt (stmt);
10629 gsi_remove (&rgsi, true);
10630 release_defs (stmt);
10631 }
10632 while (def);
10633 }
10634
10635 return true;
10636 }
10637
10638 /* Generate vector permute statements from a list of loads in DR_CHAIN.
10639 If ANALYZE_ONLY is TRUE, only check that it is possible to create valid
10640 permute statements for the SLP node NODE. Store the number of vector
10641 permute instructions in *N_PERMS and the number of vector load
10642 instructions in *N_LOADS. If DCE_CHAIN is true, remove all definitions
10643 that were not needed. */
10644
10645 bool
10646 vect_transform_slp_perm_load (vec_info *vinfo,
10647 slp_tree node, const vec<tree> &dr_chain,
10648 gimple_stmt_iterator *gsi, poly_uint64 vf,
10649 bool analyze_only, unsigned *n_perms,
10650 unsigned int *n_loads, bool dce_chain)
10651 {
10652 return vect_transform_slp_perm_load_1 (vinfo, node,
10653 SLP_TREE_LOAD_PERMUTATION (node),
10654 dr_chain, gsi, vf, analyze_only,
10655 dump_enabled_p (), n_perms, n_loads,
10656 dce_chain);
10657 }
10658
10659 /* Produce the next vector result for SLP permutation NODE by adding a vector
10660 statement at GSI. If MASK_VEC is nonnull, add:
10661
10662 <new SSA name> = VEC_PERM_EXPR <FIRST_DEF, SECOND_DEF, MASK_VEC>
10663
10664 otherwise add:
10665
10666 <new SSA name> = VEC_PERM_EXPR <FIRST_DEF, SECOND_DEF,
10667 { N, N+1, N+2, ... }>
10668
10669 where N == IDENTITY_OFFSET which is either zero or equal to the
10670 number of elements of the result. */
10671
10672 static void
10673 vect_add_slp_permutation (vec_info *vinfo, gimple_stmt_iterator *gsi,
10674 slp_tree node, tree first_def, tree second_def,
10675 tree mask_vec, poly_uint64 identity_offset)
10676 {
10677 tree vectype = SLP_TREE_VECTYPE (node);
10678
10679 /* ??? We SLP match existing vector element extracts but
10680 allow punning which we need to re-instantiate at uses
10681 but have no good way of explicitly representing. */
10682 if (operand_equal_p (TYPE_SIZE (TREE_TYPE (first_def)), TYPE_SIZE (vectype))
10683 && !types_compatible_p (TREE_TYPE (first_def), vectype))
10684 {
10685 gassign *conv_stmt
10686 = gimple_build_assign (make_ssa_name (vectype),
10687 build1 (VIEW_CONVERT_EXPR, vectype, first_def));
10688 vect_finish_stmt_generation (vinfo, NULL, conv_stmt, gsi);
10689 first_def = gimple_assign_lhs (conv_stmt);
10690 }
10691 gassign *perm_stmt;
10692 tree perm_dest = make_ssa_name (vectype);
10693 if (mask_vec)
10694 {
10695 if (operand_equal_p (TYPE_SIZE (TREE_TYPE (first_def)),
10696 TYPE_SIZE (vectype))
10697 && !types_compatible_p (TREE_TYPE (second_def), vectype))
10698 {
10699 gassign *conv_stmt
10700 = gimple_build_assign (make_ssa_name (vectype),
10701 build1 (VIEW_CONVERT_EXPR,
10702 vectype, second_def));
10703 vect_finish_stmt_generation (vinfo, NULL, conv_stmt, gsi);
10704 second_def = gimple_assign_lhs (conv_stmt);
10705 }
10706 perm_stmt = gimple_build_assign (perm_dest, VEC_PERM_EXPR,
10707 first_def, second_def,
10708 mask_vec);
10709 }
10710 else
10711 {
10712 auto def_nunits = TYPE_VECTOR_SUBPARTS (TREE_TYPE (first_def));
10713 unsigned HOST_WIDE_INT vecno;
10714 poly_uint64 eltno;
10715 if (!can_div_trunc_p (poly_uint64 (identity_offset), def_nunits,
10716 &vecno, &eltno))
10717 gcc_unreachable ();
10718 tree def = vecno & 1 ? second_def : first_def;
10719 if (!types_compatible_p (TREE_TYPE (def), vectype))
10720 {
10721 /* For identity permutes we still need to handle the case
10722 of offsetted extracts or concats. */
10723 unsigned HOST_WIDE_INT c;
10724 if (known_le (TYPE_VECTOR_SUBPARTS (vectype), def_nunits))
10725 {
10726 unsigned HOST_WIDE_INT elsz
10727 = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (def))));
10728 tree lowpart = build3 (BIT_FIELD_REF, vectype, def,
10729 TYPE_SIZE (vectype),
10730 bitsize_int (eltno * elsz));
10731 perm_stmt = gimple_build_assign (perm_dest, lowpart);
10732 }
10733 else if (constant_multiple_p (TYPE_VECTOR_SUBPARTS (vectype),
10734 def_nunits, &c) && c == 2)
10735 {
10736 gcc_assert (known_eq (identity_offset, 0U));
10737 tree ctor = build_constructor_va (vectype, 2,
10738 NULL_TREE, first_def,
10739 NULL_TREE, second_def);
10740 perm_stmt = gimple_build_assign (perm_dest, ctor);
10741 }
10742 else
10743 gcc_unreachable ();
10744 }
10745 else
10746 {
10747 /* We need a copy here in case the def was external. */
10748 gcc_assert (known_eq (eltno, 0U));
10749 perm_stmt = gimple_build_assign (perm_dest, def);
10750 }
10751 }
10752 vect_finish_stmt_generation (vinfo, NULL, perm_stmt, gsi);
10753 /* Store the vector statement in NODE. */
10754 node->push_vec_def (perm_stmt);
10755 }
10756
10757 /* Subroutine of vectorizable_slp_permutation. Check whether the target
10758 can perform permutation PERM on the (1 or 2) input nodes in CHILDREN.
10759 If GSI is nonnull, emit the permutation there.
10760
10761 When GSI is null, the only purpose of NODE is to give properties
10762 of the result, such as the vector type and number of SLP lanes.
10763 The node does not need to be a VEC_PERM_EXPR.
10764
10765 If the target supports the operation, return the number of individual
10766 VEC_PERM_EXPRs needed, otherwise return -1. Print information to the
10767 dump file if DUMP_P is true. */
10768
10769 static int
10770 vectorizable_slp_permutation_1 (vec_info *vinfo, gimple_stmt_iterator *gsi,
10771 slp_tree node, lane_permutation_t &perm,
10772 vec<slp_tree> &children, bool dump_p)
10773 {
10774 tree vectype = SLP_TREE_VECTYPE (node);
10775
10776 /* ??? We currently only support all same vector input types
10777 while the SLP IL should really do a concat + select and thus accept
10778 arbitrary mismatches. */
10779 slp_tree child;
10780 unsigned i;
10781 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
10782 bool repeating_p = multiple_p (nunits, SLP_TREE_LANES (node));
10783 /* True if we're permuting a single input of 2N vectors down
10784 to N vectors. This case doesn't generalize beyond 2 since
10785 VEC_PERM_EXPR only takes 2 inputs. */
10786 bool pack_p = false;
10787 /* If we're permuting inputs of N vectors each into X*N outputs,
10788 this is the value of X, otherwise it is 1. */
10789 unsigned int unpack_factor = 1;
10790 tree op_vectype = NULL_TREE;
10791 FOR_EACH_VEC_ELT (children, i, child)
10792 if (SLP_TREE_VECTYPE (child))
10793 {
10794 op_vectype = SLP_TREE_VECTYPE (child);
10795 break;
10796 }
10797 if (!op_vectype)
10798 op_vectype = vectype;
10799 FOR_EACH_VEC_ELT (children, i, child)
10800 {
10801 if ((SLP_TREE_DEF_TYPE (child) != vect_internal_def
10802 && !vect_maybe_update_slp_op_vectype (child, op_vectype))
10803 || !types_compatible_p (SLP_TREE_VECTYPE (child), op_vectype)
10804 || !types_compatible_p (TREE_TYPE (vectype), TREE_TYPE (op_vectype)))
10805 {
10806 if (dump_p)
10807 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10808 "Unsupported vector types in lane permutation\n");
10809 return -1;
10810 }
10811 auto op_nunits = TYPE_VECTOR_SUBPARTS (op_vectype);
10812 unsigned int this_unpack_factor;
10813 /* Detect permutations of external, pre-existing vectors. The external
10814 node's SLP_TREE_LANES stores the total number of units in the vector,
10815 or zero if the vector has variable length.
10816
10817 We are expected to keep the original VEC_PERM_EXPR for such cases.
10818 There is no repetition to model. */
10819 if (SLP_TREE_DEF_TYPE (child) == vect_external_def
10820 && SLP_TREE_SCALAR_OPS (child).is_empty ())
10821 repeating_p = false;
10822 /* Check whether the input has twice as many lanes per vector. */
10823 else if (children.length () == 1
10824 && known_eq (SLP_TREE_LANES (child) * nunits,
10825 SLP_TREE_LANES (node) * op_nunits * 2))
10826 pack_p = true;
10827 /* Check whether the output has N times as many lanes per vector. */
10828 else if (constant_multiple_p (SLP_TREE_LANES (node) * op_nunits,
10829 SLP_TREE_LANES (child) * nunits,
10830 &this_unpack_factor)
10831 && (i == 0 || unpack_factor == this_unpack_factor))
10832 unpack_factor = this_unpack_factor;
10833 else
10834 repeating_p = false;
10835 }
10836
10837 gcc_assert (perm.length () == SLP_TREE_LANES (node));
10838
10839 /* Load-lanes permute. This permute only acts as a forwarder to
10840 select the correct vector def of the load-lanes load which
10841 has the permuted vectors in its vector defs like
10842 { v0, w0, r0, v1, w1, r1 ... } for a ld3. All costs are
10843 accounted for in the costing for the actual load so we
10844 return zero here. */
10845 if (node->ldst_lanes)
10846 {
10847 gcc_assert (children.length () == 1);
10848 if (!gsi)
10849 /* This is a trivial op always supported. */
10850 return 0;
10851 slp_tree child = children[0];
10852 unsigned vec_idx = (SLP_TREE_LANE_PERMUTATION (node)[0].second
10853 / SLP_TREE_LANES (node));
10854 unsigned vec_num = SLP_TREE_LANES (child) / SLP_TREE_LANES (node);
10855 for (unsigned i = 0; i < SLP_TREE_NUMBER_OF_VEC_STMTS (node); ++i)
10856 {
10857 tree def = SLP_TREE_VEC_DEFS (child)[i * vec_num + vec_idx];
10858 node->push_vec_def (def);
10859 }
10860 return 0;
10861 }
10862
10863 /* Set REPEATING_P to true if the permutations are cylical wrt UNPACK_FACTOR
10864 and if we can generate the vectors in a vector-length agnostic way.
10865 This requires UNPACK_STEP == NUNITS / UNPACK_FACTOR to be known at
10866 compile time.
10867
10868 The significance of UNPACK_STEP is that, when PACK_P is false,
10869 output vector I operates on a window of UNPACK_STEP elements from each
10870 input, starting at lane UNPACK_STEP * (I % UNPACK_FACTOR). For example,
10871 when UNPACK_FACTOR is 2, the first output vector operates on lanes
10872 [0, NUNITS / 2 - 1] of each input vector and the second output vector
10873 operates on lanes [NUNITS / 2, NUNITS - 1] of each input vector.
10874
10875 When REPEATING_P is true, NOUTPUTS holds the total number of outputs
10876 that we actually need to generate. */
10877 uint64_t noutputs = 0;
10878 poly_uint64 unpack_step = 0;
10879 loop_vec_info linfo = dyn_cast <loop_vec_info> (vinfo);
10880 if (!linfo
10881 || !multiple_p (nunits, unpack_factor, &unpack_step)
10882 || !constant_multiple_p (LOOP_VINFO_VECT_FACTOR (linfo)
10883 * SLP_TREE_LANES (node), nunits, &noutputs))
10884 repeating_p = false;
10885
10886 /* We can handle the conditions described for REPEATING_P above for
10887 both variable- and constant-length vectors. The fallback requires
10888 us to generate every element of every permute vector explicitly,
10889 which is only possible for constant-length permute vectors.
10890
10891 Set:
10892
10893 - NPATTERNS and NELTS_PER_PATTERN to the encoding of the permute
10894 mask vectors that we want to build.
10895
10896 - NCOPIES to the number of copies of PERM that we need in order
10897 to build the necessary permute mask vectors. */
10898 uint64_t npatterns;
10899 unsigned nelts_per_pattern;
10900 uint64_t ncopies;
10901 if (repeating_p)
10902 {
10903 /* We need permute mask vectors that have the form:
10904
10905 { X1, ..., Xn, X1 + n, ..., Xn + n, X1 + 2n, ..., Xn + 2n, ... }
10906
10907 In other words, the original n-element permute in PERM is
10908 "unrolled" to fill a full vector. The stepped vector encoding
10909 that we use for permutes requires 3n elements. */
10910 npatterns = SLP_TREE_LANES (node);
10911 nelts_per_pattern = ncopies = 3;
10912 }
10913 else
10914 {
10915 /* Calculate every element of every permute mask vector explicitly,
10916 instead of relying on the pattern described above. */
10917 if (!nunits.is_constant (&npatterns)
10918 || !TYPE_VECTOR_SUBPARTS (op_vectype).is_constant ())
10919 {
10920 if (dump_p)
10921 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10922 "unsupported permutation %p on variable-length"
10923 " vectors\n", (void *) node);
10924 return -1;
10925 }
10926 nelts_per_pattern = ncopies = 1;
10927 if (linfo && !LOOP_VINFO_VECT_FACTOR (linfo).is_constant (&ncopies))
10928 {
10929 if (dump_p)
10930 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
10931 "unsupported permutation %p for variable VF\n",
10932 (void *) node);
10933 return -1;
10934 }
10935 pack_p = false;
10936 unpack_factor = 1;
10937 }
10938 unsigned olanes = unpack_factor * ncopies * SLP_TREE_LANES (node);
10939 gcc_assert (repeating_p || multiple_p (olanes, nunits));
10940
10941 /* Compute the { { SLP operand, vector index}, lane } permutation sequence
10942 from the { SLP operand, scalar lane } permutation as recorded in the
10943 SLP node as intermediate step. This part should already work
10944 with SLP children with arbitrary number of lanes. */
10945 auto_vec<std::pair<std::pair<unsigned, unsigned>, poly_uint64>> vperm;
10946 auto_vec<poly_uint64> active_lane;
10947 vperm.create (olanes);
10948 active_lane.safe_grow_cleared (children.length (), true);
10949 for (unsigned int ui = 0; ui < unpack_factor; ++ui)
10950 {
10951 for (unsigned j = 0; j < children.length (); ++j)
10952 active_lane[j] = ui * unpack_step;
10953 for (unsigned i = 0; i < ncopies; ++i)
10954 {
10955 for (unsigned pi = 0; pi < perm.length (); ++pi)
10956 {
10957 std::pair<unsigned, unsigned> p = perm[pi];
10958 tree vtype = SLP_TREE_VECTYPE (children[p.first]);
10959 if (repeating_p)
10960 vperm.quick_push ({{p.first, 0},
10961 p.second + active_lane[p.first]});
10962 else
10963 {
10964 /* We checked above that the vectors are constant-length. */
10965 unsigned vnunits = TYPE_VECTOR_SUBPARTS (vtype)
10966 .to_constant ();
10967 unsigned lane = active_lane[p.first].to_constant ();
10968 unsigned vi = (lane + p.second) / vnunits;
10969 unsigned vl = (lane + p.second) % vnunits;
10970 vperm.quick_push ({{p.first, vi}, vl});
10971 }
10972 }
10973 /* Advance to the next group. */
10974 for (unsigned j = 0; j < children.length (); ++j)
10975 active_lane[j] += SLP_TREE_LANES (children[j]);
10976 }
10977 }
10978
10979 if (dump_p)
10980 {
10981 dump_printf_loc (MSG_NOTE, vect_location,
10982 "vectorizing permutation %p", (void *)node);
10983 for (unsigned i = 0; i < perm.length (); ++i)
10984 dump_printf (MSG_NOTE, " op%u[%u]", perm[i].first, perm[i].second);
10985 if (repeating_p)
10986 dump_printf (MSG_NOTE, " (repeat %d)", SLP_TREE_LANES (node));
10987 dump_printf (MSG_NOTE, "\n");
10988 dump_printf_loc (MSG_NOTE, vect_location, "as");
10989 for (unsigned i = 0; i < vperm.length (); ++i)
10990 {
10991 if (i != 0
10992 && (repeating_p
10993 ? multiple_p (i, npatterns)
10994 : multiple_p (i, TYPE_VECTOR_SUBPARTS (vectype))))
10995 dump_printf (MSG_NOTE, ",");
10996 dump_printf (MSG_NOTE, " vops%u[%u][",
10997 vperm[i].first.first, vperm[i].first.second);
10998 dump_dec (MSG_NOTE, vperm[i].second);
10999 dump_printf (MSG_NOTE, "]");
11000 }
11001 dump_printf (MSG_NOTE, "\n");
11002 }
11003
11004 /* We can only handle two-vector permutes, everything else should
11005 be lowered on the SLP level. The following is closely inspired
11006 by vect_transform_slp_perm_load and is supposed to eventually
11007 replace it.
11008 ??? As intermediate step do code-gen in the SLP tree representation
11009 somehow? */
11010 std::pair<unsigned, unsigned> first_vec = std::make_pair (-1U, -1U);
11011 std::pair<unsigned, unsigned> second_vec = std::make_pair (-1U, -1U);
11012 unsigned int index = 0;
11013 poly_uint64 mask_element;
11014 vec_perm_builder mask;
11015 mask.new_vector (nunits, npatterns, nelts_per_pattern);
11016 unsigned int count = mask.encoded_nelts ();
11017 mask.quick_grow (count);
11018 vec_perm_indices indices;
11019 unsigned nperms = 0;
11020 /* When REPEATING_P is true, we only have UNPACK_FACTOR unique permute
11021 vectors to check during analysis, but we need to generate NOUTPUTS
11022 vectors during transformation. */
11023 unsigned total_nelts = olanes;
11024 unsigned process_nelts = olanes;
11025 if (repeating_p)
11026 {
11027 total_nelts = (total_nelts / unpack_factor) * noutputs;
11028 if (gsi)
11029 process_nelts = total_nelts;
11030 }
11031 unsigned last_ei = (total_nelts - 1) % process_nelts;
11032 for (unsigned i = 0; i < process_nelts; ++i)
11033 {
11034 /* VI is the input vector index when generating code for REPEATING_P. */
11035 unsigned vi = i / olanes * (pack_p ? 2 : 1);
11036 unsigned ei = i % olanes;
11037 mask_element = vperm[ei].second;
11038 if (pack_p)
11039 {
11040 /* In this case, we have N outputs and the single child provides 2N
11041 inputs. Output X permutes inputs 2X and 2X+1.
11042
11043 The mask indices are taken directly from the SLP permutation node.
11044 Index X selects from the first vector if (X / NUNITS) % 2 == 0;
11045 X selects from the second vector otherwise. These conditions
11046 are only known at compile time for constant-length vectors. */
11047 first_vec = std::make_pair (0, 0);
11048 second_vec = std::make_pair (0, 1);
11049 }
11050 else if (first_vec.first == -1U
11051 || first_vec == vperm[ei].first)
11052 first_vec = vperm[ei].first;
11053 else if (second_vec.first == -1U
11054 || second_vec == vperm[ei].first)
11055 {
11056 second_vec = vperm[ei].first;
11057 mask_element += nunits;
11058 }
11059 else
11060 {
11061 if (dump_p)
11062 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
11063 "permutation requires at "
11064 "least three vectors\n");
11065 gcc_assert (!gsi);
11066 return -1;
11067 }
11068
11069 mask[index++] = mask_element;
11070
11071 if (index == count)
11072 {
11073 indices.new_vector (mask, second_vec.first == -1U ? 1 : 2,
11074 TYPE_VECTOR_SUBPARTS (op_vectype));
11075 bool identity_p = (indices.series_p (0, 1, mask[0], 1)
11076 && constant_multiple_p (mask[0], nunits));
11077 machine_mode vmode = TYPE_MODE (vectype);
11078 machine_mode op_vmode = TYPE_MODE (op_vectype);
11079 unsigned HOST_WIDE_INT c;
11080 if ((!identity_p
11081 && !can_vec_perm_const_p (vmode, op_vmode, indices))
11082 || (identity_p
11083 && !known_le (nunits,
11084 TYPE_VECTOR_SUBPARTS (op_vectype))
11085 && (!constant_multiple_p (nunits,
11086 TYPE_VECTOR_SUBPARTS (op_vectype),
11087 &c) || c != 2)))
11088 {
11089 if (dump_p)
11090 {
11091 dump_printf_loc (MSG_MISSED_OPTIMIZATION,
11092 vect_location,
11093 "unsupported vect permute { ");
11094 for (i = 0; i < count; ++i)
11095 {
11096 dump_dec (MSG_MISSED_OPTIMIZATION, mask[i]);
11097 dump_printf (MSG_MISSED_OPTIMIZATION, " ");
11098 }
11099 dump_printf (MSG_MISSED_OPTIMIZATION, "}\n");
11100 }
11101 gcc_assert (!gsi);
11102 return -1;
11103 }
11104
11105 if (!identity_p)
11106 nperms += CEIL (total_nelts, process_nelts) - (ei > last_ei);
11107 if (gsi)
11108 {
11109 if (second_vec.first == -1U)
11110 second_vec = first_vec;
11111
11112 slp_tree
11113 first_node = children[first_vec.first],
11114 second_node = children[second_vec.first];
11115
11116 tree mask_vec = NULL_TREE;
11117 if (!identity_p)
11118 mask_vec = vect_gen_perm_mask_checked (vectype, indices);
11119
11120 tree first_def
11121 = vect_get_slp_vect_def (first_node, first_vec.second + vi);
11122 tree second_def
11123 = vect_get_slp_vect_def (second_node, second_vec.second + vi);
11124 vect_add_slp_permutation (vinfo, gsi, node, first_def,
11125 second_def, mask_vec, mask[0]);
11126 }
11127
11128 index = 0;
11129 first_vec = std::make_pair (-1U, -1U);
11130 second_vec = std::make_pair (-1U, -1U);
11131 }
11132 }
11133
11134 return nperms;
11135 }
11136
11137 /* Vectorize the SLP permutations in NODE as specified
11138 in SLP_TREE_LANE_PERMUTATION which is a vector of pairs of SLP
11139 child number and lane number.
11140 Interleaving of two two-lane two-child SLP subtrees (not supported):
11141 [ { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } ]
11142 A blend of two four-lane two-child SLP subtrees:
11143 [ { 0, 0 }, { 1, 1 }, { 0, 2 }, { 1, 3 } ]
11144 Highpart of a four-lane one-child SLP subtree (not supported):
11145 [ { 0, 2 }, { 0, 3 } ]
11146 Where currently only a subset is supported by code generating below. */
11147
11148 static bool
11149 vectorizable_slp_permutation (vec_info *vinfo, gimple_stmt_iterator *gsi,
11150 slp_tree node, stmt_vector_for_cost *cost_vec)
11151 {
11152 tree vectype = SLP_TREE_VECTYPE (node);
11153 lane_permutation_t &perm = SLP_TREE_LANE_PERMUTATION (node);
11154 int nperms = vectorizable_slp_permutation_1 (vinfo, gsi, node, perm,
11155 SLP_TREE_CHILDREN (node),
11156 dump_enabled_p ());
11157 if (nperms < 0)
11158 return false;
11159
11160 if (!gsi)
11161 record_stmt_cost (cost_vec, nperms, vec_perm, node, vectype, 0, vect_body);
11162
11163 return true;
11164 }
11165
11166 /* Vectorize SLP NODE. */
11167
11168 static void
11169 vect_schedule_slp_node (vec_info *vinfo,
11170 slp_tree node, slp_instance instance)
11171 {
11172 gimple_stmt_iterator si;
11173 int i;
11174 slp_tree child;
11175
11176 /* Vectorize externals and constants. */
11177 if (SLP_TREE_DEF_TYPE (node) == vect_constant_def
11178 || SLP_TREE_DEF_TYPE (node) == vect_external_def)
11179 {
11180 /* ??? vectorizable_shift can end up using a scalar operand which is
11181 currently denoted as !SLP_TREE_VECTYPE. No need to vectorize the
11182 node in this case. */
11183 if (!SLP_TREE_VECTYPE (node))
11184 return;
11185
11186 /* There are two reasons vector defs might already exist. The first
11187 is that we are vectorizing an existing vector def. The second is
11188 when performing BB vectorization shared constant/external nodes
11189 are not split apart during partitioning so during the code-gen
11190 DFS walk we can end up visiting them twice. */
11191 if (! SLP_TREE_VEC_DEFS (node).exists ())
11192 vect_create_constant_vectors (vinfo, node);
11193 return;
11194 }
11195
11196 gcc_assert (SLP_TREE_VEC_DEFS (node).is_empty ());
11197
11198 stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (node);
11199
11200 gcc_assert (SLP_TREE_NUMBER_OF_VEC_STMTS (node) != 0);
11201 SLP_TREE_VEC_DEFS (node).create (SLP_TREE_NUMBER_OF_VEC_STMTS (node));
11202
11203 if (SLP_TREE_CODE (node) != VEC_PERM_EXPR
11204 && STMT_VINFO_DATA_REF (stmt_info))
11205 {
11206 /* Vectorized loads go before the first scalar load to make it
11207 ready early, vectorized stores go before the last scalar
11208 stmt which is where all uses are ready. */
11209 stmt_vec_info last_stmt_info = NULL;
11210 if (DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)))
11211 last_stmt_info = vect_find_first_scalar_stmt_in_slp (node);
11212 else /* DR_IS_WRITE */
11213 last_stmt_info = vect_find_last_scalar_stmt_in_slp (node);
11214 si = gsi_for_stmt (last_stmt_info->stmt);
11215 }
11216 else if (SLP_TREE_CODE (node) != VEC_PERM_EXPR
11217 && (STMT_VINFO_TYPE (stmt_info) == cycle_phi_info_type
11218 || STMT_VINFO_TYPE (stmt_info) == induc_vec_info_type
11219 || STMT_VINFO_TYPE (stmt_info) == phi_info_type))
11220 {
11221 /* For PHI node vectorization we do not use the insertion iterator. */
11222 si = gsi_none ();
11223 }
11224 else
11225 {
11226 /* Emit other stmts after the children vectorized defs which is
11227 earliest possible. */
11228 gimple *last_stmt = NULL;
11229 bool seen_vector_def = false;
11230 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
11231 if (SLP_TREE_DEF_TYPE (child) == vect_internal_def)
11232 {
11233 /* For fold-left reductions we are retaining the scalar
11234 reduction PHI but we still have SLP_TREE_NUM_VEC_STMTS
11235 set so the representation isn't perfect. Resort to the
11236 last scalar def here. */
11237 if (SLP_TREE_VEC_DEFS (child).is_empty ())
11238 {
11239 gcc_assert (STMT_VINFO_TYPE (SLP_TREE_REPRESENTATIVE (child))
11240 == cycle_phi_info_type);
11241 gphi *phi = as_a <gphi *>
11242 (vect_find_last_scalar_stmt_in_slp (child)->stmt);
11243 if (!last_stmt)
11244 last_stmt = phi;
11245 else if (vect_stmt_dominates_stmt_p (last_stmt, phi))
11246 last_stmt = phi;
11247 else if (vect_stmt_dominates_stmt_p (phi, last_stmt))
11248 ;
11249 else
11250 gcc_unreachable ();
11251 }
11252 /* We are emitting all vectorized stmts in the same place and
11253 the last one is the last.
11254 ??? Unless we have a load permutation applied and that
11255 figures to re-use an earlier generated load. */
11256 unsigned j;
11257 tree vdef;
11258 FOR_EACH_VEC_ELT (SLP_TREE_VEC_DEFS (child), j, vdef)
11259 {
11260 gimple *vstmt = SSA_NAME_DEF_STMT (vdef);
11261 if (!last_stmt)
11262 last_stmt = vstmt;
11263 else if (vect_stmt_dominates_stmt_p (last_stmt, vstmt))
11264 last_stmt = vstmt;
11265 else if (vect_stmt_dominates_stmt_p (vstmt, last_stmt))
11266 ;
11267 else
11268 gcc_unreachable ();
11269 }
11270 }
11271 else if (!SLP_TREE_VECTYPE (child))
11272 {
11273 /* For externals we use unvectorized at all scalar defs. */
11274 unsigned j;
11275 tree def;
11276 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_OPS (child), j, def)
11277 if (TREE_CODE (def) == SSA_NAME
11278 && !SSA_NAME_IS_DEFAULT_DEF (def))
11279 {
11280 gimple *stmt = SSA_NAME_DEF_STMT (def);
11281 if (gimple_uid (stmt) == -1u)
11282 /* If the stmt is not inside the region do not
11283 use it as possible insertion point. */
11284 ;
11285 else if (!last_stmt)
11286 last_stmt = stmt;
11287 else if (vect_stmt_dominates_stmt_p (last_stmt, stmt))
11288 last_stmt = stmt;
11289 else if (vect_stmt_dominates_stmt_p (stmt, last_stmt))
11290 ;
11291 else
11292 gcc_unreachable ();
11293 }
11294 }
11295 else
11296 {
11297 /* For externals we have to look at all defs since their
11298 insertion place is decided per vector. But beware
11299 of pre-existing vectors where we need to make sure
11300 we do not insert before the region boundary. */
11301 if (SLP_TREE_SCALAR_OPS (child).is_empty ()
11302 && !vinfo->lookup_def (SLP_TREE_VEC_DEFS (child)[0]))
11303 seen_vector_def = true;
11304 else
11305 {
11306 unsigned j;
11307 tree vdef;
11308 FOR_EACH_VEC_ELT (SLP_TREE_VEC_DEFS (child), j, vdef)
11309 if (TREE_CODE (vdef) == SSA_NAME
11310 && !SSA_NAME_IS_DEFAULT_DEF (vdef))
11311 {
11312 gimple *vstmt = SSA_NAME_DEF_STMT (vdef);
11313 if (!last_stmt)
11314 last_stmt = vstmt;
11315 else if (vect_stmt_dominates_stmt_p (last_stmt, vstmt))
11316 last_stmt = vstmt;
11317 else if (vect_stmt_dominates_stmt_p (vstmt, last_stmt))
11318 ;
11319 else
11320 gcc_unreachable ();
11321 }
11322 }
11323 }
11324 /* This can happen when all children are pre-existing vectors or
11325 constants. */
11326 if (!last_stmt)
11327 last_stmt = vect_find_first_scalar_stmt_in_slp (node)->stmt;
11328 if (!last_stmt)
11329 {
11330 gcc_assert (seen_vector_def);
11331 si = gsi_after_labels (vinfo->bbs[0]);
11332 }
11333 else if (is_ctrl_altering_stmt (last_stmt))
11334 {
11335 /* We split regions to vectorize at control altering stmts
11336 with a definition so this must be an external which
11337 we can insert at the start of the region. */
11338 si = gsi_after_labels (vinfo->bbs[0]);
11339 }
11340 else if (is_a <bb_vec_info> (vinfo)
11341 && SLP_TREE_CODE (node) != VEC_PERM_EXPR
11342 && gimple_bb (last_stmt) != gimple_bb (stmt_info->stmt)
11343 && gimple_could_trap_p (stmt_info->stmt))
11344 {
11345 /* We've constrained possibly trapping operations to all come
11346 from the same basic-block, if vectorized defs would allow earlier
11347 scheduling still force vectorized stmts to the original block.
11348 This is only necessary for BB vectorization since for loop vect
11349 all operations are in a single BB and scalar stmt based
11350 placement doesn't play well with epilogue vectorization. */
11351 gcc_assert (dominated_by_p (CDI_DOMINATORS,
11352 gimple_bb (stmt_info->stmt),
11353 gimple_bb (last_stmt)));
11354 si = gsi_after_labels (gimple_bb (stmt_info->stmt));
11355 }
11356 else if (is_a <gphi *> (last_stmt))
11357 si = gsi_after_labels (gimple_bb (last_stmt));
11358 else
11359 {
11360 si = gsi_for_stmt (last_stmt);
11361 gsi_next (&si);
11362
11363 /* Avoid scheduling internal defs outside of the loop when
11364 we might have only implicitly tracked loop mask/len defs. */
11365 if (auto loop_vinfo = dyn_cast <loop_vec_info> (vinfo))
11366 if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
11367 || LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
11368 {
11369 gimple_stmt_iterator si2
11370 = gsi_after_labels (LOOP_VINFO_LOOP (loop_vinfo)->header);
11371 if ((gsi_end_p (si2)
11372 && (LOOP_VINFO_LOOP (loop_vinfo)->header
11373 != gimple_bb (last_stmt))
11374 && dominated_by_p (CDI_DOMINATORS,
11375 LOOP_VINFO_LOOP (loop_vinfo)->header,
11376 gimple_bb (last_stmt)))
11377 || (!gsi_end_p (si2)
11378 && last_stmt != *si2
11379 && vect_stmt_dominates_stmt_p (last_stmt, *si2)))
11380 si = si2;
11381 }
11382 }
11383 }
11384
11385 /* Handle purely internal nodes. */
11386 if (SLP_TREE_CODE (node) == VEC_PERM_EXPR)
11387 {
11388 if (dump_enabled_p ())
11389 dump_printf_loc (MSG_NOTE, vect_location,
11390 "------>vectorizing SLP permutation node\n");
11391 /* ??? the transform kind is stored to STMT_VINFO_TYPE which might
11392 be shared with different SLP nodes (but usually it's the same
11393 operation apart from the case the stmt is only there for denoting
11394 the actual scalar lane defs ...). So do not call vect_transform_stmt
11395 but open-code it here (partly). */
11396 bool done = vectorizable_slp_permutation (vinfo, &si, node, NULL);
11397 gcc_assert (done);
11398 stmt_vec_info slp_stmt_info;
11399 unsigned int i;
11400 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, slp_stmt_info)
11401 if (slp_stmt_info && STMT_VINFO_LIVE_P (slp_stmt_info))
11402 {
11403 done = vectorizable_live_operation (vinfo, slp_stmt_info, node,
11404 instance, i, true, NULL);
11405 gcc_assert (done);
11406 }
11407 }
11408 else
11409 {
11410 if (dump_enabled_p ())
11411 dump_printf_loc (MSG_NOTE, vect_location,
11412 "------>vectorizing SLP node starting from: %G",
11413 stmt_info->stmt);
11414 vect_transform_stmt (vinfo, stmt_info, &si, node, instance);
11415 }
11416 }
11417
11418 /* Replace scalar calls from SLP node NODE with setting of their lhs to zero.
11419 For loop vectorization this is done in vectorizable_call, but for SLP
11420 it needs to be deferred until end of vect_schedule_slp, because multiple
11421 SLP instances may refer to the same scalar stmt. */
11422
11423 static void
11424 vect_remove_slp_scalar_calls (vec_info *vinfo,
11425 slp_tree node, hash_set<slp_tree> &visited)
11426 {
11427 gimple *new_stmt;
11428 gimple_stmt_iterator gsi;
11429 int i;
11430 slp_tree child;
11431 tree lhs;
11432 stmt_vec_info stmt_info;
11433
11434 if (!node || SLP_TREE_DEF_TYPE (node) != vect_internal_def)
11435 return;
11436
11437 if (visited.add (node))
11438 return;
11439
11440 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
11441 vect_remove_slp_scalar_calls (vinfo, child, visited);
11442
11443 FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
11444 {
11445 if (!stmt_info)
11446 continue;
11447 gcall *stmt = dyn_cast <gcall *> (stmt_info->stmt);
11448 if (!stmt || gimple_bb (stmt) == NULL)
11449 continue;
11450 if (is_pattern_stmt_p (stmt_info)
11451 || !PURE_SLP_STMT (stmt_info))
11452 continue;
11453 lhs = gimple_call_lhs (stmt);
11454 if (lhs)
11455 new_stmt = gimple_build_assign (lhs, build_zero_cst (TREE_TYPE (lhs)));
11456 else
11457 new_stmt = gimple_build_nop ();
11458 unlink_stmt_vdef (stmt_info->stmt);
11459 gsi = gsi_for_stmt (stmt);
11460 vinfo->replace_stmt (&gsi, stmt_info, new_stmt);
11461 if (lhs)
11462 SSA_NAME_DEF_STMT (lhs) = new_stmt;
11463 }
11464 }
11465
11466 static void
11467 vect_remove_slp_scalar_calls (vec_info *vinfo, slp_tree node)
11468 {
11469 hash_set<slp_tree> visited;
11470 vect_remove_slp_scalar_calls (vinfo, node, visited);
11471 }
11472
11473 /* Vectorize the instance root. */
11474
11475 void
11476 vectorize_slp_instance_root_stmt (vec_info *vinfo, slp_tree node, slp_instance instance)
11477 {
11478 gassign *rstmt = NULL;
11479
11480 if (instance->kind == slp_inst_kind_ctor)
11481 {
11482 if (SLP_TREE_NUMBER_OF_VEC_STMTS (node) == 1)
11483 {
11484 tree vect_lhs = SLP_TREE_VEC_DEFS (node)[0];
11485 tree root_lhs = gimple_get_lhs (instance->root_stmts[0]->stmt);
11486 if (!useless_type_conversion_p (TREE_TYPE (root_lhs),
11487 TREE_TYPE (vect_lhs)))
11488 vect_lhs = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (root_lhs),
11489 vect_lhs);
11490 rstmt = gimple_build_assign (root_lhs, vect_lhs);
11491 }
11492 else if (SLP_TREE_NUMBER_OF_VEC_STMTS (node) > 1)
11493 {
11494 int nelts = SLP_TREE_NUMBER_OF_VEC_STMTS (node);
11495 tree child_def;
11496 int j;
11497 vec<constructor_elt, va_gc> *v;
11498 vec_alloc (v, nelts);
11499
11500 /* A CTOR can handle V16HI composition from VNx8HI so we
11501 do not need to convert vector elements if the types
11502 do not match. */
11503 FOR_EACH_VEC_ELT (SLP_TREE_VEC_DEFS (node), j, child_def)
11504 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, child_def);
11505 tree lhs = gimple_get_lhs (instance->root_stmts[0]->stmt);
11506 tree rtype
11507 = TREE_TYPE (gimple_assign_rhs1 (instance->root_stmts[0]->stmt));
11508 tree r_constructor = build_constructor (rtype, v);
11509 rstmt = gimple_build_assign (lhs, r_constructor);
11510 }
11511 }
11512 else if (instance->kind == slp_inst_kind_bb_reduc)
11513 {
11514 /* Largely inspired by reduction chain epilogue handling in
11515 vect_create_epilog_for_reduction. */
11516 vec<tree> vec_defs = vNULL;
11517 vect_get_slp_defs (node, &vec_defs);
11518 enum tree_code reduc_code
11519 = gimple_assign_rhs_code (instance->root_stmts[0]->stmt);
11520 /* ??? We actually have to reflect signs somewhere. */
11521 if (reduc_code == MINUS_EXPR)
11522 reduc_code = PLUS_EXPR;
11523 gimple_seq epilogue = NULL;
11524 /* We may end up with more than one vector result, reduce them
11525 to one vector. */
11526 tree vec_def = vec_defs[0];
11527 tree vectype = TREE_TYPE (vec_def);
11528 tree compute_vectype = vectype;
11529 bool pun_for_overflow_p = (ANY_INTEGRAL_TYPE_P (vectype)
11530 && TYPE_OVERFLOW_UNDEFINED (vectype)
11531 && operation_can_overflow (reduc_code));
11532 if (pun_for_overflow_p)
11533 {
11534 compute_vectype = unsigned_type_for (vectype);
11535 vec_def = gimple_build (&epilogue, VIEW_CONVERT_EXPR,
11536 compute_vectype, vec_def);
11537 }
11538 for (unsigned i = 1; i < vec_defs.length (); ++i)
11539 {
11540 tree def = vec_defs[i];
11541 if (pun_for_overflow_p)
11542 def = gimple_build (&epilogue, VIEW_CONVERT_EXPR,
11543 compute_vectype, def);
11544 vec_def = gimple_build (&epilogue, reduc_code, compute_vectype,
11545 vec_def, def);
11546 }
11547 vec_defs.release ();
11548 /* ??? Support other schemes than direct internal fn. */
11549 internal_fn reduc_fn;
11550 if (!reduction_fn_for_scalar_code (reduc_code, &reduc_fn)
11551 || reduc_fn == IFN_LAST)
11552 gcc_unreachable ();
11553 tree scalar_def = gimple_build (&epilogue, as_combined_fn (reduc_fn),
11554 TREE_TYPE (compute_vectype), vec_def);
11555 if (!SLP_INSTANCE_REMAIN_DEFS (instance).is_empty ())
11556 {
11557 tree rem_def = NULL_TREE;
11558 for (auto def : SLP_INSTANCE_REMAIN_DEFS (instance))
11559 {
11560 def = gimple_convert (&epilogue, TREE_TYPE (scalar_def), def);
11561 if (!rem_def)
11562 rem_def = def;
11563 else
11564 rem_def = gimple_build (&epilogue, reduc_code,
11565 TREE_TYPE (scalar_def),
11566 rem_def, def);
11567 }
11568 scalar_def = gimple_build (&epilogue, reduc_code,
11569 TREE_TYPE (scalar_def),
11570 scalar_def, rem_def);
11571 }
11572 scalar_def = gimple_convert (&epilogue,
11573 TREE_TYPE (vectype), scalar_def);
11574 gimple_stmt_iterator rgsi = gsi_for_stmt (instance->root_stmts[0]->stmt);
11575 gsi_insert_seq_before (&rgsi, epilogue, GSI_SAME_STMT);
11576 gimple_assign_set_rhs_from_tree (&rgsi, scalar_def);
11577 update_stmt (gsi_stmt (rgsi));
11578 return;
11579 }
11580 else if (instance->kind == slp_inst_kind_gcond)
11581 {
11582 /* Only support a single root for now as we can't codegen CFG yet and so we
11583 can't support lane > 1 at this time. */
11584 gcc_assert (instance->root_stmts.length () == 1);
11585 auto root_stmt_info = instance->root_stmts[0];
11586 auto last_stmt = STMT_VINFO_STMT (vect_orig_stmt (root_stmt_info));
11587 gimple_stmt_iterator rgsi = gsi_for_stmt (last_stmt);
11588 gimple *vec_stmt = NULL;
11589 gcc_assert (!SLP_TREE_VEC_DEFS (node).is_empty ());
11590 bool res = vectorizable_early_exit (vinfo, root_stmt_info, &rgsi,
11591 &vec_stmt, node, NULL);
11592 gcc_assert (res);
11593 return;
11594 }
11595 else
11596 gcc_unreachable ();
11597
11598 gcc_assert (rstmt);
11599
11600 gimple_stmt_iterator rgsi = gsi_for_stmt (instance->root_stmts[0]->stmt);
11601 gsi_replace (&rgsi, rstmt, true);
11602 }
11603
11604 struct slp_scc_info
11605 {
11606 bool on_stack;
11607 int dfs;
11608 int lowlink;
11609 };
11610
11611 /* Schedule the SLP INSTANCE doing a DFS walk and collecting SCCs. */
11612
11613 static void
11614 vect_schedule_scc (vec_info *vinfo, slp_tree node, slp_instance instance,
11615 hash_map<slp_tree, slp_scc_info> &scc_info,
11616 int &maxdfs, vec<slp_tree> &stack)
11617 {
11618 bool existed_p;
11619 slp_scc_info *info = &scc_info.get_or_insert (node, &existed_p);
11620 gcc_assert (!existed_p);
11621 info->dfs = maxdfs;
11622 info->lowlink = maxdfs;
11623 maxdfs++;
11624
11625 /* Leaf. */
11626 if (SLP_TREE_DEF_TYPE (node) != vect_internal_def)
11627 {
11628 info->on_stack = false;
11629 vect_schedule_slp_node (vinfo, node, instance);
11630 return;
11631 }
11632
11633 info->on_stack = true;
11634 stack.safe_push (node);
11635
11636 unsigned i;
11637 slp_tree child;
11638 /* DFS recurse. */
11639 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
11640 {
11641 if (!child)
11642 continue;
11643 slp_scc_info *child_info = scc_info.get (child);
11644 if (!child_info)
11645 {
11646 vect_schedule_scc (vinfo, child, instance, scc_info, maxdfs, stack);
11647 /* Recursion might have re-allocated the node. */
11648 info = scc_info.get (node);
11649 child_info = scc_info.get (child);
11650 info->lowlink = MIN (info->lowlink, child_info->lowlink);
11651 }
11652 else if (child_info->on_stack)
11653 info->lowlink = MIN (info->lowlink, child_info->dfs);
11654 }
11655 if (info->lowlink != info->dfs)
11656 return;
11657
11658 auto_vec<slp_tree, 4> phis_to_fixup;
11659
11660 /* Singleton. */
11661 if (stack.last () == node)
11662 {
11663 stack.pop ();
11664 info->on_stack = false;
11665 vect_schedule_slp_node (vinfo, node, instance);
11666 if (SLP_TREE_CODE (node) != VEC_PERM_EXPR
11667 && is_a <gphi *> (SLP_TREE_REPRESENTATIVE (node)->stmt))
11668 phis_to_fixup.quick_push (node);
11669 }
11670 else
11671 {
11672 /* SCC. */
11673 int last_idx = stack.length () - 1;
11674 while (stack[last_idx] != node)
11675 last_idx--;
11676 /* We can break the cycle at PHIs who have at least one child
11677 code generated. Then we could re-start the DFS walk until
11678 all nodes in the SCC are covered (we might have new entries
11679 for only back-reachable nodes). But it's simpler to just
11680 iterate and schedule those that are ready. */
11681 unsigned todo = stack.length () - last_idx;
11682 do
11683 {
11684 for (int idx = stack.length () - 1; idx >= last_idx; --idx)
11685 {
11686 slp_tree entry = stack[idx];
11687 if (!entry)
11688 continue;
11689 bool phi = (SLP_TREE_CODE (entry) != VEC_PERM_EXPR
11690 && is_a <gphi *> (SLP_TREE_REPRESENTATIVE (entry)->stmt));
11691 bool ready = !phi;
11692 FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (entry), i, child)
11693 if (!child)
11694 {
11695 gcc_assert (phi);
11696 ready = true;
11697 break;
11698 }
11699 else if (scc_info.get (child)->on_stack)
11700 {
11701 if (!phi)
11702 {
11703 ready = false;
11704 break;
11705 }
11706 }
11707 else
11708 {
11709 if (phi)
11710 {
11711 ready = true;
11712 break;
11713 }
11714 }
11715 if (ready)
11716 {
11717 vect_schedule_slp_node (vinfo, entry, instance);
11718 scc_info.get (entry)->on_stack = false;
11719 stack[idx] = NULL;
11720 todo--;
11721 if (phi)
11722 phis_to_fixup.safe_push (entry);
11723 }
11724 }
11725 }
11726 while (todo != 0);
11727
11728 /* Pop the SCC. */
11729 stack.truncate (last_idx);
11730 }
11731
11732 /* Now fixup the backedge def of the vectorized PHIs in this SCC. */
11733 slp_tree phi_node;
11734 FOR_EACH_VEC_ELT (phis_to_fixup, i, phi_node)
11735 {
11736 gphi *phi = as_a <gphi *> (SLP_TREE_REPRESENTATIVE (phi_node)->stmt);
11737 edge_iterator ei;
11738 edge e;
11739 FOR_EACH_EDGE (e, ei, gimple_bb (phi)->preds)
11740 {
11741 unsigned dest_idx = e->dest_idx;
11742 child = SLP_TREE_CHILDREN (phi_node)[dest_idx];
11743 if (!child || SLP_TREE_DEF_TYPE (child) != vect_internal_def)
11744 continue;
11745 unsigned n = SLP_TREE_VEC_DEFS (phi_node).length ();
11746 /* Simply fill all args. */
11747 if (STMT_VINFO_DEF_TYPE (SLP_TREE_REPRESENTATIVE (phi_node))
11748 != vect_first_order_recurrence)
11749 for (unsigned i = 0; i < n; ++i)
11750 {
11751 tree phidef = SLP_TREE_VEC_DEFS (phi_node)[i];
11752 gphi *phi = as_a <gphi *> (SSA_NAME_DEF_STMT (phidef));
11753 add_phi_arg (phi, vect_get_slp_vect_def (child, i),
11754 e, gimple_phi_arg_location (phi, dest_idx));
11755 }
11756 else
11757 {
11758 /* Unless it is a first order recurrence which needs
11759 args filled in for both the PHI node and the permutes. */
11760 gimple *perm
11761 = SSA_NAME_DEF_STMT (SLP_TREE_VEC_DEFS (phi_node)[0]);
11762 gimple *rphi = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (perm));
11763 add_phi_arg (as_a <gphi *> (rphi),
11764 vect_get_slp_vect_def (child, n - 1),
11765 e, gimple_phi_arg_location (phi, dest_idx));
11766 for (unsigned i = 0; i < n; ++i)
11767 {
11768 gimple *perm
11769 = SSA_NAME_DEF_STMT (SLP_TREE_VEC_DEFS (phi_node)[i]);
11770 if (i > 0)
11771 gimple_assign_set_rhs1 (perm,
11772 vect_get_slp_vect_def (child, i - 1));
11773 gimple_assign_set_rhs2 (perm,
11774 vect_get_slp_vect_def (child, i));
11775 update_stmt (perm);
11776 }
11777 }
11778 }
11779 }
11780 }
11781
11782 /* Generate vector code for SLP_INSTANCES in the loop/basic block. */
11783
11784 void
11785 vect_schedule_slp (vec_info *vinfo, const vec<slp_instance> &slp_instances)
11786 {
11787 slp_instance instance;
11788 unsigned int i;
11789
11790 hash_map<slp_tree, slp_scc_info> scc_info;
11791 int maxdfs = 0;
11792 FOR_EACH_VEC_ELT (slp_instances, i, instance)
11793 {
11794 slp_tree node = SLP_INSTANCE_TREE (instance);
11795 if (dump_enabled_p ())
11796 {
11797 dump_printf_loc (MSG_NOTE, vect_location,
11798 "Vectorizing SLP tree:\n");
11799 /* ??? Dump all? */
11800 if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ())
11801 dump_printf_loc (MSG_NOTE, vect_location, "Root stmt: %G",
11802 SLP_INSTANCE_ROOT_STMTS (instance)[0]->stmt);
11803 vect_print_slp_graph (MSG_NOTE, vect_location,
11804 SLP_INSTANCE_TREE (instance));
11805 }
11806 /* Schedule the tree of INSTANCE, scheduling SCCs in a way to
11807 have a PHI be the node breaking the cycle. */
11808 auto_vec<slp_tree> stack;
11809 if (!scc_info.get (node))
11810 vect_schedule_scc (vinfo, node, instance, scc_info, maxdfs, stack);
11811
11812 if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ())
11813 vectorize_slp_instance_root_stmt (vinfo, node, instance);
11814
11815 if (dump_enabled_p ())
11816 dump_printf_loc (MSG_NOTE, vect_location,
11817 "vectorizing stmts using SLP.\n");
11818 }
11819
11820 FOR_EACH_VEC_ELT (slp_instances, i, instance)
11821 {
11822 slp_tree root = SLP_INSTANCE_TREE (instance);
11823 stmt_vec_info store_info;
11824 unsigned int j;
11825
11826 /* Remove scalar call stmts. Do not do this for basic-block
11827 vectorization as not all uses may be vectorized.
11828 ??? Why should this be necessary? DCE should be able to
11829 remove the stmts itself.
11830 ??? For BB vectorization we can as well remove scalar
11831 stmts starting from the SLP tree root if they have no
11832 uses. */
11833 if (is_a <loop_vec_info> (vinfo))
11834 vect_remove_slp_scalar_calls (vinfo, root);
11835
11836 /* Remove vectorized stores original scalar stmts. */
11837 for (j = 0; SLP_TREE_SCALAR_STMTS (root).iterate (j, &store_info); j++)
11838 {
11839 if (!STMT_VINFO_DATA_REF (store_info)
11840 || !DR_IS_WRITE (STMT_VINFO_DATA_REF (store_info)))
11841 break;
11842
11843 store_info = vect_orig_stmt (store_info);
11844 /* Free the attached stmt_vec_info and remove the stmt. */
11845 vinfo->remove_stmt (store_info);
11846
11847 /* Invalidate SLP_TREE_REPRESENTATIVE in case we released it
11848 to not crash in vect_free_slp_tree later. */
11849 if (SLP_TREE_REPRESENTATIVE (root) == store_info)
11850 SLP_TREE_REPRESENTATIVE (root) = NULL;
11851 }
11852 }
11853 }