testsuite: powerpc/vec_reve_1.c requires VSX.
[official-gcc.git] / gcc / tree-vectorizer.c
blobf4a2873a91eed9fa0641686632426edc98313dc5
1 /* Vectorizer
2 Copyright (C) 2003-2021 Free Software Foundation, Inc.
3 Contributed by Dorit Naishlos <dorit@il.ibm.com>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* Loop and basic block vectorizer.
23 This file contains drivers for the three vectorizers:
24 (1) loop vectorizer (inter-iteration parallelism),
25 (2) loop-aware SLP (intra-iteration parallelism) (invoked by the loop
26 vectorizer)
27 (3) BB vectorizer (out-of-loops), aka SLP
29 The rest of the vectorizer's code is organized as follows:
30 - tree-vect-loop.c - loop specific parts such as reductions, etc. These are
31 used by drivers (1) and (2).
32 - tree-vect-loop-manip.c - vectorizer's loop control-flow utilities, used by
33 drivers (1) and (2).
34 - tree-vect-slp.c - BB vectorization specific analysis and transformation,
35 used by drivers (2) and (3).
36 - tree-vect-stmts.c - statements analysis and transformation (used by all).
37 - tree-vect-data-refs.c - vectorizer specific data-refs analysis and
38 manipulations (used by all).
39 - tree-vect-patterns.c - vectorizable code patterns detector (used by all)
41 Here's a poor attempt at illustrating that:
43 tree-vectorizer.c:
44 loop_vect() loop_aware_slp() slp_vect()
45 | / \ /
46 | / \ /
47 tree-vect-loop.c tree-vect-slp.c
48 | \ \ / / |
49 | \ \/ / |
50 | \ /\ / |
51 | \ / \ / |
52 tree-vect-stmts.c tree-vect-data-refs.c
53 \ /
54 tree-vect-patterns.c
57 #include "config.h"
58 #include "system.h"
59 #include "coretypes.h"
60 #include "backend.h"
61 #include "tree.h"
62 #include "gimple.h"
63 #include "predict.h"
64 #include "tree-pass.h"
65 #include "ssa.h"
66 #include "cgraph.h"
67 #include "fold-const.h"
68 #include "stor-layout.h"
69 #include "gimple-iterator.h"
70 #include "gimple-walk.h"
71 #include "tree-ssa-loop-manip.h"
72 #include "tree-ssa-loop-niter.h"
73 #include "tree-cfg.h"
74 #include "cfgloop.h"
75 #include "tree-vectorizer.h"
76 #include "tree-ssa-propagate.h"
77 #include "dbgcnt.h"
78 #include "tree-scalar-evolution.h"
79 #include "stringpool.h"
80 #include "attribs.h"
81 #include "gimple-pretty-print.h"
82 #include "opt-problem.h"
83 #include "internal-fn.h"
84 #include "tree-ssa-sccvn.h"
86 /* Loop or bb location, with hotness information. */
87 dump_user_location_t vect_location;
89 /* auto_purge_vect_location's dtor: reset the vect_location
90 global, to avoid stale location_t values that could reference
91 GC-ed blocks. */
93 auto_purge_vect_location::~auto_purge_vect_location ()
95 vect_location = dump_user_location_t ();
98 /* Dump a cost entry according to args to F. */
100 void
101 dump_stmt_cost (FILE *f, int count, enum vect_cost_for_stmt kind,
102 stmt_vec_info stmt_info, tree, int misalign, unsigned cost,
103 enum vect_cost_model_location where)
105 if (stmt_info)
107 print_gimple_expr (f, STMT_VINFO_STMT (stmt_info), 0, TDF_SLIM);
108 fprintf (f, " ");
110 else
111 fprintf (f, "<unknown> ");
112 fprintf (f, "%d times ", count);
113 const char *ks = "unknown";
114 switch (kind)
116 case scalar_stmt:
117 ks = "scalar_stmt";
118 break;
119 case scalar_load:
120 ks = "scalar_load";
121 break;
122 case scalar_store:
123 ks = "scalar_store";
124 break;
125 case vector_stmt:
126 ks = "vector_stmt";
127 break;
128 case vector_load:
129 ks = "vector_load";
130 break;
131 case vector_gather_load:
132 ks = "vector_gather_load";
133 break;
134 case unaligned_load:
135 ks = "unaligned_load";
136 break;
137 case unaligned_store:
138 ks = "unaligned_store";
139 break;
140 case vector_store:
141 ks = "vector_store";
142 break;
143 case vector_scatter_store:
144 ks = "vector_scatter_store";
145 break;
146 case vec_to_scalar:
147 ks = "vec_to_scalar";
148 break;
149 case scalar_to_vec:
150 ks = "scalar_to_vec";
151 break;
152 case cond_branch_not_taken:
153 ks = "cond_branch_not_taken";
154 break;
155 case cond_branch_taken:
156 ks = "cond_branch_taken";
157 break;
158 case vec_perm:
159 ks = "vec_perm";
160 break;
161 case vec_promote_demote:
162 ks = "vec_promote_demote";
163 break;
164 case vec_construct:
165 ks = "vec_construct";
166 break;
168 fprintf (f, "%s ", ks);
169 if (kind == unaligned_load || kind == unaligned_store)
170 fprintf (f, "(misalign %d) ", misalign);
171 fprintf (f, "costs %u ", cost);
172 const char *ws = "unknown";
173 switch (where)
175 case vect_prologue:
176 ws = "prologue";
177 break;
178 case vect_body:
179 ws = "body";
180 break;
181 case vect_epilogue:
182 ws = "epilogue";
183 break;
185 fprintf (f, "in %s\n", ws);
188 /* For mapping simduid to vectorization factor. */
190 class simduid_to_vf : public free_ptr_hash<simduid_to_vf>
192 public:
193 unsigned int simduid;
194 poly_uint64 vf;
196 /* hash_table support. */
197 static inline hashval_t hash (const simduid_to_vf *);
198 static inline int equal (const simduid_to_vf *, const simduid_to_vf *);
201 inline hashval_t
202 simduid_to_vf::hash (const simduid_to_vf *p)
204 return p->simduid;
207 inline int
208 simduid_to_vf::equal (const simduid_to_vf *p1, const simduid_to_vf *p2)
210 return p1->simduid == p2->simduid;
213 /* This hash maps the OMP simd array to the corresponding simduid used
214 to index into it. Like thus,
216 _7 = GOMP_SIMD_LANE (simduid.0)
219 D.1737[_7] = stuff;
222 This hash maps from the OMP simd array (D.1737[]) to DECL_UID of
223 simduid.0. */
225 struct simd_array_to_simduid : free_ptr_hash<simd_array_to_simduid>
227 tree decl;
228 unsigned int simduid;
230 /* hash_table support. */
231 static inline hashval_t hash (const simd_array_to_simduid *);
232 static inline int equal (const simd_array_to_simduid *,
233 const simd_array_to_simduid *);
236 inline hashval_t
237 simd_array_to_simduid::hash (const simd_array_to_simduid *p)
239 return DECL_UID (p->decl);
242 inline int
243 simd_array_to_simduid::equal (const simd_array_to_simduid *p1,
244 const simd_array_to_simduid *p2)
246 return p1->decl == p2->decl;
249 /* Fold IFN_GOMP_SIMD_LANE, IFN_GOMP_SIMD_VF, IFN_GOMP_SIMD_LAST_LANE,
250 into their corresponding constants and remove
251 IFN_GOMP_SIMD_ORDERED_{START,END}. */
253 static void
254 adjust_simduid_builtins (hash_table<simduid_to_vf> *htab, function *fun)
256 basic_block bb;
258 FOR_EACH_BB_FN (bb, fun)
260 gimple_stmt_iterator i;
262 for (i = gsi_start_bb (bb); !gsi_end_p (i); )
264 poly_uint64 vf = 1;
265 enum internal_fn ifn;
266 gimple *stmt = gsi_stmt (i);
267 tree t;
268 if (!is_gimple_call (stmt)
269 || !gimple_call_internal_p (stmt))
271 gsi_next (&i);
272 continue;
274 ifn = gimple_call_internal_fn (stmt);
275 switch (ifn)
277 case IFN_GOMP_SIMD_LANE:
278 case IFN_GOMP_SIMD_VF:
279 case IFN_GOMP_SIMD_LAST_LANE:
280 break;
281 case IFN_GOMP_SIMD_ORDERED_START:
282 case IFN_GOMP_SIMD_ORDERED_END:
283 if (integer_onep (gimple_call_arg (stmt, 0)))
285 enum built_in_function bcode
286 = (ifn == IFN_GOMP_SIMD_ORDERED_START
287 ? BUILT_IN_GOMP_ORDERED_START
288 : BUILT_IN_GOMP_ORDERED_END);
289 gimple *g
290 = gimple_build_call (builtin_decl_explicit (bcode), 0);
291 gimple_move_vops (g, stmt);
292 gsi_replace (&i, g, true);
293 continue;
295 gsi_remove (&i, true);
296 unlink_stmt_vdef (stmt);
297 continue;
298 default:
299 gsi_next (&i);
300 continue;
302 tree arg = gimple_call_arg (stmt, 0);
303 gcc_assert (arg != NULL_TREE);
304 gcc_assert (TREE_CODE (arg) == SSA_NAME);
305 simduid_to_vf *p = NULL, data;
306 data.simduid = DECL_UID (SSA_NAME_VAR (arg));
307 /* Need to nullify loop safelen field since it's value is not
308 valid after transformation. */
309 if (bb->loop_father && bb->loop_father->safelen > 0)
310 bb->loop_father->safelen = 0;
311 if (htab)
313 p = htab->find (&data);
314 if (p)
315 vf = p->vf;
317 switch (ifn)
319 case IFN_GOMP_SIMD_VF:
320 t = build_int_cst (unsigned_type_node, vf);
321 break;
322 case IFN_GOMP_SIMD_LANE:
323 t = build_int_cst (unsigned_type_node, 0);
324 break;
325 case IFN_GOMP_SIMD_LAST_LANE:
326 t = gimple_call_arg (stmt, 1);
327 break;
328 default:
329 gcc_unreachable ();
331 tree lhs = gimple_call_lhs (stmt);
332 if (lhs)
333 replace_uses_by (lhs, t);
334 release_defs (stmt);
335 gsi_remove (&i, true);
340 /* Helper structure for note_simd_array_uses. */
342 struct note_simd_array_uses_struct
344 hash_table<simd_array_to_simduid> **htab;
345 unsigned int simduid;
348 /* Callback for note_simd_array_uses, called through walk_gimple_op. */
350 static tree
351 note_simd_array_uses_cb (tree *tp, int *walk_subtrees, void *data)
353 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
354 struct note_simd_array_uses_struct *ns
355 = (struct note_simd_array_uses_struct *) wi->info;
357 if (TYPE_P (*tp))
358 *walk_subtrees = 0;
359 else if (VAR_P (*tp)
360 && lookup_attribute ("omp simd array", DECL_ATTRIBUTES (*tp))
361 && DECL_CONTEXT (*tp) == current_function_decl)
363 simd_array_to_simduid data;
364 if (!*ns->htab)
365 *ns->htab = new hash_table<simd_array_to_simduid> (15);
366 data.decl = *tp;
367 data.simduid = ns->simduid;
368 simd_array_to_simduid **slot = (*ns->htab)->find_slot (&data, INSERT);
369 if (*slot == NULL)
371 simd_array_to_simduid *p = XNEW (simd_array_to_simduid);
372 *p = data;
373 *slot = p;
375 else if ((*slot)->simduid != ns->simduid)
376 (*slot)->simduid = -1U;
377 *walk_subtrees = 0;
379 return NULL_TREE;
382 /* Find "omp simd array" temporaries and map them to corresponding
383 simduid. */
385 static void
386 note_simd_array_uses (hash_table<simd_array_to_simduid> **htab, function *fun)
388 basic_block bb;
389 gimple_stmt_iterator gsi;
390 struct walk_stmt_info wi;
391 struct note_simd_array_uses_struct ns;
393 memset (&wi, 0, sizeof (wi));
394 wi.info = &ns;
395 ns.htab = htab;
397 FOR_EACH_BB_FN (bb, fun)
398 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
400 gimple *stmt = gsi_stmt (gsi);
401 if (!is_gimple_call (stmt) || !gimple_call_internal_p (stmt))
402 continue;
403 switch (gimple_call_internal_fn (stmt))
405 case IFN_GOMP_SIMD_LANE:
406 case IFN_GOMP_SIMD_VF:
407 case IFN_GOMP_SIMD_LAST_LANE:
408 break;
409 default:
410 continue;
412 tree lhs = gimple_call_lhs (stmt);
413 if (lhs == NULL_TREE)
414 continue;
415 imm_use_iterator use_iter;
416 gimple *use_stmt;
417 ns.simduid = DECL_UID (SSA_NAME_VAR (gimple_call_arg (stmt, 0)));
418 FOR_EACH_IMM_USE_STMT (use_stmt, use_iter, lhs)
419 if (!is_gimple_debug (use_stmt))
420 walk_gimple_op (use_stmt, note_simd_array_uses_cb, &wi);
424 /* Shrink arrays with "omp simd array" attribute to the corresponding
425 vectorization factor. */
427 static void
428 shrink_simd_arrays
429 (hash_table<simd_array_to_simduid> *simd_array_to_simduid_htab,
430 hash_table<simduid_to_vf> *simduid_to_vf_htab)
432 for (hash_table<simd_array_to_simduid>::iterator iter
433 = simd_array_to_simduid_htab->begin ();
434 iter != simd_array_to_simduid_htab->end (); ++iter)
435 if ((*iter)->simduid != -1U)
437 tree decl = (*iter)->decl;
438 poly_uint64 vf = 1;
439 if (simduid_to_vf_htab)
441 simduid_to_vf *p = NULL, data;
442 data.simduid = (*iter)->simduid;
443 p = simduid_to_vf_htab->find (&data);
444 if (p)
445 vf = p->vf;
447 tree atype
448 = build_array_type_nelts (TREE_TYPE (TREE_TYPE (decl)), vf);
449 TREE_TYPE (decl) = atype;
450 relayout_decl (decl);
453 delete simd_array_to_simduid_htab;
456 /* Initialize the vec_info with kind KIND_IN and target cost data
457 TARGET_COST_DATA_IN. */
459 vec_info::vec_info (vec_info::vec_kind kind_in, vec_info_shared *shared_)
460 : kind (kind_in),
461 shared (shared_),
462 stmt_vec_info_ro (false)
464 stmt_vec_infos.create (50);
467 vec_info::~vec_info ()
469 for (slp_instance &instance : slp_instances)
470 vect_free_slp_instance (instance);
472 free_stmt_vec_infos ();
475 vec_info_shared::vec_info_shared ()
476 : n_stmts (0),
477 datarefs (vNULL),
478 datarefs_copy (vNULL),
479 ddrs (vNULL)
483 vec_info_shared::~vec_info_shared ()
485 free_data_refs (datarefs);
486 free_dependence_relations (ddrs);
487 datarefs_copy.release ();
490 void
491 vec_info_shared::save_datarefs ()
493 if (!flag_checking)
494 return;
495 datarefs_copy.reserve_exact (datarefs.length ());
496 for (unsigned i = 0; i < datarefs.length (); ++i)
497 datarefs_copy.quick_push (*datarefs[i]);
500 void
501 vec_info_shared::check_datarefs ()
503 if (!flag_checking)
504 return;
505 gcc_assert (datarefs.length () == datarefs_copy.length ());
506 for (unsigned i = 0; i < datarefs.length (); ++i)
507 if (memcmp (&datarefs_copy[i], datarefs[i],
508 offsetof (data_reference, alt_indices)) != 0)
509 gcc_unreachable ();
512 /* Record that STMT belongs to the vectorizable region. Create and return
513 an associated stmt_vec_info. */
515 stmt_vec_info
516 vec_info::add_stmt (gimple *stmt)
518 stmt_vec_info res = new_stmt_vec_info (stmt);
519 set_vinfo_for_stmt (stmt, res);
520 return res;
523 /* Record that STMT belongs to the vectorizable region. Create a new
524 stmt_vec_info and mark VECINFO as being related and return the new
525 stmt_vec_info. */
527 stmt_vec_info
528 vec_info::add_pattern_stmt (gimple *stmt, stmt_vec_info stmt_info)
530 stmt_vec_info res = new_stmt_vec_info (stmt);
531 set_vinfo_for_stmt (stmt, res, false);
532 STMT_VINFO_RELATED_STMT (res) = stmt_info;
533 return res;
536 /* If STMT has an associated stmt_vec_info, return that vec_info, otherwise
537 return null. It is safe to call this function on any statement, even if
538 it might not be part of the vectorizable region. */
540 stmt_vec_info
541 vec_info::lookup_stmt (gimple *stmt)
543 unsigned int uid = gimple_uid (stmt);
544 if (uid > 0 && uid - 1 < stmt_vec_infos.length ())
546 stmt_vec_info res = stmt_vec_infos[uid - 1];
547 if (res && res->stmt == stmt)
548 return res;
550 return NULL;
553 /* If NAME is an SSA_NAME and its definition has an associated stmt_vec_info,
554 return that stmt_vec_info, otherwise return null. It is safe to call
555 this on arbitrary operands. */
557 stmt_vec_info
558 vec_info::lookup_def (tree name)
560 if (TREE_CODE (name) == SSA_NAME
561 && !SSA_NAME_IS_DEFAULT_DEF (name))
562 return lookup_stmt (SSA_NAME_DEF_STMT (name));
563 return NULL;
566 /* See whether there is a single non-debug statement that uses LHS and
567 whether that statement has an associated stmt_vec_info. Return the
568 stmt_vec_info if so, otherwise return null. */
570 stmt_vec_info
571 vec_info::lookup_single_use (tree lhs)
573 use_operand_p dummy;
574 gimple *use_stmt;
575 if (single_imm_use (lhs, &dummy, &use_stmt))
576 return lookup_stmt (use_stmt);
577 return NULL;
580 /* Return vectorization information about DR. */
582 dr_vec_info *
583 vec_info::lookup_dr (data_reference *dr)
585 stmt_vec_info stmt_info = lookup_stmt (DR_STMT (dr));
586 /* DR_STMT should never refer to a stmt in a pattern replacement. */
587 gcc_checking_assert (!is_pattern_stmt_p (stmt_info));
588 return STMT_VINFO_DR_INFO (stmt_info->dr_aux.stmt);
591 /* Record that NEW_STMT_INFO now implements the same data reference
592 as OLD_STMT_INFO. */
594 void
595 vec_info::move_dr (stmt_vec_info new_stmt_info, stmt_vec_info old_stmt_info)
597 gcc_assert (!is_pattern_stmt_p (old_stmt_info));
598 STMT_VINFO_DR_INFO (old_stmt_info)->stmt = new_stmt_info;
599 new_stmt_info->dr_aux = old_stmt_info->dr_aux;
600 STMT_VINFO_DR_WRT_VEC_LOOP (new_stmt_info)
601 = STMT_VINFO_DR_WRT_VEC_LOOP (old_stmt_info);
602 STMT_VINFO_GATHER_SCATTER_P (new_stmt_info)
603 = STMT_VINFO_GATHER_SCATTER_P (old_stmt_info);
606 /* Permanently remove the statement described by STMT_INFO from the
607 function. */
609 void
610 vec_info::remove_stmt (stmt_vec_info stmt_info)
612 gcc_assert (!stmt_info->pattern_stmt_p);
613 set_vinfo_for_stmt (stmt_info->stmt, NULL);
614 unlink_stmt_vdef (stmt_info->stmt);
615 gimple_stmt_iterator si = gsi_for_stmt (stmt_info->stmt);
616 gsi_remove (&si, true);
617 release_defs (stmt_info->stmt);
618 free_stmt_vec_info (stmt_info);
621 /* Replace the statement at GSI by NEW_STMT, both the vectorization
622 information and the function itself. STMT_INFO describes the statement
623 at GSI. */
625 void
626 vec_info::replace_stmt (gimple_stmt_iterator *gsi, stmt_vec_info stmt_info,
627 gimple *new_stmt)
629 gimple *old_stmt = stmt_info->stmt;
630 gcc_assert (!stmt_info->pattern_stmt_p && old_stmt == gsi_stmt (*gsi));
631 gimple_set_uid (new_stmt, gimple_uid (old_stmt));
632 stmt_info->stmt = new_stmt;
633 gsi_replace (gsi, new_stmt, true);
636 /* Insert stmts in SEQ on the VEC_INFO region entry. If CONTEXT is
637 not NULL it specifies whether to use the sub-region entry
638 determined by it, currently used for loop vectorization to insert
639 on the inner loop entry vs. the outer loop entry. */
641 void
642 vec_info::insert_seq_on_entry (stmt_vec_info context, gimple_seq seq)
644 if (loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (this))
646 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
647 basic_block new_bb;
648 edge pe;
650 if (context && nested_in_vect_loop_p (loop, context))
651 loop = loop->inner;
653 pe = loop_preheader_edge (loop);
654 new_bb = gsi_insert_seq_on_edge_immediate (pe, seq);
655 gcc_assert (!new_bb);
657 else
659 bb_vec_info bb_vinfo = as_a <bb_vec_info> (this);
660 gimple_stmt_iterator gsi_region_begin
661 = gsi_after_labels (bb_vinfo->bbs[0]);
662 gsi_insert_seq_before (&gsi_region_begin, seq, GSI_SAME_STMT);
666 /* Like insert_seq_on_entry but just inserts the single stmt NEW_STMT. */
668 void
669 vec_info::insert_on_entry (stmt_vec_info context, gimple *new_stmt)
671 gimple_seq seq = NULL;
672 gimple_stmt_iterator gsi = gsi_start (seq);
673 gsi_insert_before_without_update (&gsi, new_stmt, GSI_SAME_STMT);
674 insert_seq_on_entry (context, seq);
677 /* Create and initialize a new stmt_vec_info struct for STMT. */
679 stmt_vec_info
680 vec_info::new_stmt_vec_info (gimple *stmt)
682 stmt_vec_info res = XCNEW (class _stmt_vec_info);
683 res->stmt = stmt;
685 STMT_VINFO_TYPE (res) = undef_vec_info_type;
686 STMT_VINFO_RELEVANT (res) = vect_unused_in_scope;
687 STMT_VINFO_VECTORIZABLE (res) = true;
688 STMT_VINFO_REDUC_TYPE (res) = TREE_CODE_REDUCTION;
689 STMT_VINFO_REDUC_CODE (res) = ERROR_MARK;
690 STMT_VINFO_REDUC_FN (res) = IFN_LAST;
691 STMT_VINFO_REDUC_IDX (res) = -1;
692 STMT_VINFO_SLP_VECT_ONLY (res) = false;
693 STMT_VINFO_SLP_VECT_ONLY_PATTERN (res) = false;
694 STMT_VINFO_VEC_STMTS (res) = vNULL;
695 res->reduc_initial_values = vNULL;
696 res->reduc_scalar_results = vNULL;
698 if (is_a <loop_vec_info> (this)
699 && gimple_code (stmt) == GIMPLE_PHI
700 && is_loop_header_bb_p (gimple_bb (stmt)))
701 STMT_VINFO_DEF_TYPE (res) = vect_unknown_def_type;
702 else
703 STMT_VINFO_DEF_TYPE (res) = vect_internal_def;
705 STMT_SLP_TYPE (res) = loop_vect;
707 /* This is really "uninitialized" until vect_compute_data_ref_alignment. */
708 res->dr_aux.misalignment = DR_MISALIGNMENT_UNINITIALIZED;
710 return res;
713 /* Associate STMT with INFO. */
715 void
716 vec_info::set_vinfo_for_stmt (gimple *stmt, stmt_vec_info info, bool check_ro)
718 unsigned int uid = gimple_uid (stmt);
719 if (uid == 0)
721 gcc_assert (!check_ro || !stmt_vec_info_ro);
722 gcc_checking_assert (info);
723 uid = stmt_vec_infos.length () + 1;
724 gimple_set_uid (stmt, uid);
725 stmt_vec_infos.safe_push (info);
727 else
729 gcc_checking_assert (info == NULL);
730 stmt_vec_infos[uid - 1] = info;
734 /* Free the contents of stmt_vec_infos. */
736 void
737 vec_info::free_stmt_vec_infos (void)
739 for (stmt_vec_info &info : stmt_vec_infos)
740 if (info != NULL)
741 free_stmt_vec_info (info);
742 stmt_vec_infos.release ();
745 /* Free STMT_INFO. */
747 void
748 vec_info::free_stmt_vec_info (stmt_vec_info stmt_info)
750 if (stmt_info->pattern_stmt_p)
752 gimple_set_bb (stmt_info->stmt, NULL);
753 tree lhs = gimple_get_lhs (stmt_info->stmt);
754 if (lhs && TREE_CODE (lhs) == SSA_NAME)
755 release_ssa_name (lhs);
758 stmt_info->reduc_initial_values.release ();
759 stmt_info->reduc_scalar_results.release ();
760 STMT_VINFO_SIMD_CLONE_INFO (stmt_info).release ();
761 STMT_VINFO_VEC_STMTS (stmt_info).release ();
762 free (stmt_info);
765 /* Returns true if S1 dominates S2. */
767 bool
768 vect_stmt_dominates_stmt_p (gimple *s1, gimple *s2)
770 basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
772 /* If bb1 is NULL, it should be a GIMPLE_NOP def stmt of an (D)
773 SSA_NAME. Assume it lives at the beginning of function and
774 thus dominates everything. */
775 if (!bb1 || s1 == s2)
776 return true;
778 /* If bb2 is NULL, it doesn't dominate any stmt with a bb. */
779 if (!bb2)
780 return false;
782 if (bb1 != bb2)
783 return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
785 /* PHIs in the same basic block are assumed to be
786 executed all in parallel, if only one stmt is a PHI,
787 it dominates the other stmt in the same basic block. */
788 if (gimple_code (s1) == GIMPLE_PHI)
789 return true;
791 if (gimple_code (s2) == GIMPLE_PHI)
792 return false;
794 /* Inserted vectorized stmts all have UID 0 while the original stmts
795 in the IL have UID increasing within a BB. Walk from both sides
796 until we find the other stmt or a stmt with UID != 0. */
797 gimple_stmt_iterator gsi1 = gsi_for_stmt (s1);
798 while (gimple_uid (gsi_stmt (gsi1)) == 0)
800 gsi_next (&gsi1);
801 if (gsi_end_p (gsi1))
802 return false;
803 if (gsi_stmt (gsi1) == s2)
804 return true;
806 if (gimple_uid (gsi_stmt (gsi1)) == -1u)
807 return false;
809 gimple_stmt_iterator gsi2 = gsi_for_stmt (s2);
810 while (gimple_uid (gsi_stmt (gsi2)) == 0)
812 gsi_prev (&gsi2);
813 if (gsi_end_p (gsi2))
814 return false;
815 if (gsi_stmt (gsi2) == s1)
816 return true;
818 if (gimple_uid (gsi_stmt (gsi2)) == -1u)
819 return false;
821 if (gimple_uid (gsi_stmt (gsi1)) <= gimple_uid (gsi_stmt (gsi2)))
822 return true;
823 return false;
826 /* A helper function to free scev and LOOP niter information, as well as
827 clear loop constraint LOOP_C_FINITE. */
829 void
830 vect_free_loop_info_assumptions (class loop *loop)
832 scev_reset_htab ();
833 /* We need to explicitly reset upper bound information since they are
834 used even after free_numbers_of_iterations_estimates. */
835 loop->any_upper_bound = false;
836 loop->any_likely_upper_bound = false;
837 free_numbers_of_iterations_estimates (loop);
838 loop_constraint_clear (loop, LOOP_C_FINITE);
841 /* If LOOP has been versioned during ifcvt, return the internal call
842 guarding it. */
844 gimple *
845 vect_loop_vectorized_call (class loop *loop, gcond **cond)
847 basic_block bb = loop_preheader_edge (loop)->src;
848 gimple *g;
851 g = last_stmt (bb);
852 if ((g && gimple_code (g) == GIMPLE_COND)
853 || !single_succ_p (bb))
854 break;
855 if (!single_pred_p (bb))
856 break;
857 bb = single_pred (bb);
859 while (1);
860 if (g && gimple_code (g) == GIMPLE_COND)
862 if (cond)
863 *cond = as_a <gcond *> (g);
864 gimple_stmt_iterator gsi = gsi_for_stmt (g);
865 gsi_prev (&gsi);
866 if (!gsi_end_p (gsi))
868 g = gsi_stmt (gsi);
869 if (gimple_call_internal_p (g, IFN_LOOP_VECTORIZED)
870 && (tree_to_shwi (gimple_call_arg (g, 0)) == loop->num
871 || tree_to_shwi (gimple_call_arg (g, 1)) == loop->num))
872 return g;
875 return NULL;
878 /* If LOOP has been versioned during loop distribution, return the gurading
879 internal call. */
881 static gimple *
882 vect_loop_dist_alias_call (class loop *loop, function *fun)
884 basic_block bb;
885 basic_block entry;
886 class loop *outer, *orig;
887 gimple_stmt_iterator gsi;
888 gimple *g;
890 if (loop->orig_loop_num == 0)
891 return NULL;
893 orig = get_loop (fun, loop->orig_loop_num);
894 if (orig == NULL)
896 /* The original loop is somehow destroyed. Clear the information. */
897 loop->orig_loop_num = 0;
898 return NULL;
901 if (loop != orig)
902 bb = nearest_common_dominator (CDI_DOMINATORS, loop->header, orig->header);
903 else
904 bb = loop_preheader_edge (loop)->src;
906 outer = bb->loop_father;
907 entry = ENTRY_BLOCK_PTR_FOR_FN (fun);
909 /* Look upward in dominance tree. */
910 for (; bb != entry && flow_bb_inside_loop_p (outer, bb);
911 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
913 g = last_stmt (bb);
914 if (g == NULL || gimple_code (g) != GIMPLE_COND)
915 continue;
917 gsi = gsi_for_stmt (g);
918 gsi_prev (&gsi);
919 if (gsi_end_p (gsi))
920 continue;
922 g = gsi_stmt (gsi);
923 /* The guarding internal function call must have the same distribution
924 alias id. */
925 if (gimple_call_internal_p (g, IFN_LOOP_DIST_ALIAS)
926 && (tree_to_shwi (gimple_call_arg (g, 0)) == loop->orig_loop_num))
927 return g;
929 return NULL;
932 /* Set the uids of all the statements in basic blocks inside loop
933 represented by LOOP_VINFO. LOOP_VECTORIZED_CALL is the internal
934 call guarding the loop which has been if converted. */
935 static void
936 set_uid_loop_bbs (loop_vec_info loop_vinfo, gimple *loop_vectorized_call,
937 function *fun)
939 tree arg = gimple_call_arg (loop_vectorized_call, 1);
940 basic_block *bbs;
941 unsigned int i;
942 class loop *scalar_loop = get_loop (fun, tree_to_shwi (arg));
944 LOOP_VINFO_SCALAR_LOOP (loop_vinfo) = scalar_loop;
945 gcc_checking_assert (vect_loop_vectorized_call (scalar_loop)
946 == loop_vectorized_call);
947 /* If we are going to vectorize outer loop, prevent vectorization
948 of the inner loop in the scalar loop - either the scalar loop is
949 thrown away, so it is a wasted work, or is used only for
950 a few iterations. */
951 if (scalar_loop->inner)
953 gimple *g = vect_loop_vectorized_call (scalar_loop->inner);
954 if (g)
956 arg = gimple_call_arg (g, 0);
957 get_loop (fun, tree_to_shwi (arg))->dont_vectorize = true;
958 fold_loop_internal_call (g, boolean_false_node);
961 bbs = get_loop_body (scalar_loop);
962 for (i = 0; i < scalar_loop->num_nodes; i++)
964 basic_block bb = bbs[i];
965 gimple_stmt_iterator gsi;
966 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
968 gimple *phi = gsi_stmt (gsi);
969 gimple_set_uid (phi, 0);
971 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
973 gimple *stmt = gsi_stmt (gsi);
974 gimple_set_uid (stmt, 0);
977 free (bbs);
980 /* Generate vectorized code for LOOP and its epilogues. */
982 static void
983 vect_transform_loops (hash_table<simduid_to_vf> *&simduid_to_vf_htab,
984 loop_p loop, gimple *loop_vectorized_call,
985 function *fun)
987 loop_vec_info loop_vinfo = loop_vec_info_for_loop (loop);
989 if (loop_vectorized_call)
990 set_uid_loop_bbs (loop_vinfo, loop_vectorized_call, fun);
992 unsigned HOST_WIDE_INT bytes;
993 if (dump_enabled_p ())
995 if (GET_MODE_SIZE (loop_vinfo->vector_mode).is_constant (&bytes))
996 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, vect_location,
997 "loop vectorized using %wu byte vectors\n", bytes);
998 else
999 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, vect_location,
1000 "loop vectorized using variable length vectors\n");
1003 loop_p new_loop = vect_transform_loop (loop_vinfo,
1004 loop_vectorized_call);
1005 /* Now that the loop has been vectorized, allow it to be unrolled
1006 etc. */
1007 loop->force_vectorize = false;
1009 if (loop->simduid)
1011 simduid_to_vf *simduid_to_vf_data = XNEW (simduid_to_vf);
1012 if (!simduid_to_vf_htab)
1013 simduid_to_vf_htab = new hash_table<simduid_to_vf> (15);
1014 simduid_to_vf_data->simduid = DECL_UID (loop->simduid);
1015 simduid_to_vf_data->vf = loop_vinfo->vectorization_factor;
1016 *simduid_to_vf_htab->find_slot (simduid_to_vf_data, INSERT)
1017 = simduid_to_vf_data;
1020 /* Epilogue of vectorized loop must be vectorized too. */
1021 if (new_loop)
1022 vect_transform_loops (simduid_to_vf_htab, new_loop, NULL, fun);
1025 /* Try to vectorize LOOP. */
1027 static unsigned
1028 try_vectorize_loop_1 (hash_table<simduid_to_vf> *&simduid_to_vf_htab,
1029 unsigned *num_vectorized_loops, loop_p loop,
1030 gimple *loop_vectorized_call,
1031 gimple *loop_dist_alias_call,
1032 function *fun)
1034 unsigned ret = 0;
1035 vec_info_shared shared;
1036 auto_purge_vect_location sentinel;
1037 vect_location = find_loop_location (loop);
1039 if (LOCATION_LOCUS (vect_location.get_location_t ()) != UNKNOWN_LOCATION
1040 && dump_enabled_p ())
1041 dump_printf (MSG_NOTE | MSG_PRIORITY_INTERNALS,
1042 "\nAnalyzing loop at %s:%d\n",
1043 LOCATION_FILE (vect_location.get_location_t ()),
1044 LOCATION_LINE (vect_location.get_location_t ()));
1046 /* Try to analyze the loop, retaining an opt_problem if dump_enabled_p. */
1047 opt_loop_vec_info loop_vinfo = vect_analyze_loop (loop, &shared);
1048 loop->aux = loop_vinfo;
1050 if (!loop_vinfo)
1051 if (dump_enabled_p ())
1052 if (opt_problem *problem = loop_vinfo.get_problem ())
1054 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1055 "couldn't vectorize loop\n");
1056 problem->emit_and_clear ();
1059 if (!loop_vinfo || !LOOP_VINFO_VECTORIZABLE_P (loop_vinfo))
1061 /* Free existing information if loop is analyzed with some
1062 assumptions. */
1063 if (loop_constraint_set_p (loop, LOOP_C_FINITE))
1064 vect_free_loop_info_assumptions (loop);
1066 /* If we applied if-conversion then try to vectorize the
1067 BB of innermost loops.
1068 ??? Ideally BB vectorization would learn to vectorize
1069 control flow by applying if-conversion on-the-fly, the
1070 following retains the if-converted loop body even when
1071 only non-if-converted parts took part in BB vectorization. */
1072 if (flag_tree_slp_vectorize != 0
1073 && loop_vectorized_call
1074 && ! loop->inner)
1076 basic_block bb = loop->header;
1077 bool require_loop_vectorize = false;
1078 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
1079 !gsi_end_p (gsi); gsi_next (&gsi))
1081 gimple *stmt = gsi_stmt (gsi);
1082 gcall *call = dyn_cast <gcall *> (stmt);
1083 if (call && gimple_call_internal_p (call))
1085 internal_fn ifn = gimple_call_internal_fn (call);
1086 if (ifn == IFN_MASK_LOAD || ifn == IFN_MASK_STORE
1087 /* Don't keep the if-converted parts when the ifn with
1088 specifc type is not supported by the backend. */
1089 || (direct_internal_fn_p (ifn)
1090 && !direct_internal_fn_supported_p
1091 (call, OPTIMIZE_FOR_SPEED)))
1093 require_loop_vectorize = true;
1094 break;
1097 gimple_set_uid (stmt, -1);
1098 gimple_set_visited (stmt, false);
1100 if (!require_loop_vectorize)
1102 tree arg = gimple_call_arg (loop_vectorized_call, 1);
1103 class loop *scalar_loop = get_loop (fun, tree_to_shwi (arg));
1104 if (vect_slp_if_converted_bb (bb, scalar_loop))
1106 fold_loop_internal_call (loop_vectorized_call,
1107 boolean_true_node);
1108 loop_vectorized_call = NULL;
1109 ret |= TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
1113 /* If outer loop vectorization fails for LOOP_VECTORIZED guarded
1114 loop, don't vectorize its inner loop; we'll attempt to
1115 vectorize LOOP_VECTORIZED guarded inner loop of the scalar
1116 loop version. */
1117 if (loop_vectorized_call && loop->inner)
1118 loop->inner->dont_vectorize = true;
1119 return ret;
1122 if (!dbg_cnt (vect_loop))
1124 /* Free existing information if loop is analyzed with some
1125 assumptions. */
1126 if (loop_constraint_set_p (loop, LOOP_C_FINITE))
1127 vect_free_loop_info_assumptions (loop);
1128 return ret;
1131 (*num_vectorized_loops)++;
1132 /* Transform LOOP and its epilogues. */
1133 vect_transform_loops (simduid_to_vf_htab, loop, loop_vectorized_call, fun);
1135 if (loop_vectorized_call)
1137 fold_loop_internal_call (loop_vectorized_call, boolean_true_node);
1138 ret |= TODO_cleanup_cfg;
1140 if (loop_dist_alias_call)
1142 tree value = gimple_call_arg (loop_dist_alias_call, 1);
1143 fold_loop_internal_call (loop_dist_alias_call, value);
1144 ret |= TODO_cleanup_cfg;
1147 return ret;
1150 /* Try to vectorize LOOP. */
1152 static unsigned
1153 try_vectorize_loop (hash_table<simduid_to_vf> *&simduid_to_vf_htab,
1154 unsigned *num_vectorized_loops, loop_p loop,
1155 function *fun)
1157 if (!((flag_tree_loop_vectorize
1158 && optimize_loop_nest_for_speed_p (loop))
1159 || loop->force_vectorize))
1160 return 0;
1162 return try_vectorize_loop_1 (simduid_to_vf_htab, num_vectorized_loops, loop,
1163 vect_loop_vectorized_call (loop),
1164 vect_loop_dist_alias_call (loop, fun), fun);
1168 /* Loop autovectorization. */
1170 namespace {
1172 const pass_data pass_data_vectorize =
1174 GIMPLE_PASS, /* type */
1175 "vect", /* name */
1176 OPTGROUP_LOOP | OPTGROUP_VEC, /* optinfo_flags */
1177 TV_TREE_VECTORIZATION, /* tv_id */
1178 ( PROP_cfg | PROP_ssa ), /* properties_required */
1179 0, /* properties_provided */
1180 0, /* properties_destroyed */
1181 0, /* todo_flags_start */
1182 0, /* todo_flags_finish */
1185 class pass_vectorize : public gimple_opt_pass
1187 public:
1188 pass_vectorize (gcc::context *ctxt)
1189 : gimple_opt_pass (pass_data_vectorize, ctxt)
1192 /* opt_pass methods: */
1193 virtual bool gate (function *fun)
1195 return flag_tree_loop_vectorize || fun->has_force_vectorize_loops;
1198 virtual unsigned int execute (function *);
1200 }; // class pass_vectorize
1202 /* Function vectorize_loops.
1204 Entry point to loop vectorization phase. */
1206 unsigned
1207 pass_vectorize::execute (function *fun)
1209 unsigned int i;
1210 unsigned int num_vectorized_loops = 0;
1211 unsigned int vect_loops_num;
1212 hash_table<simduid_to_vf> *simduid_to_vf_htab = NULL;
1213 hash_table<simd_array_to_simduid> *simd_array_to_simduid_htab = NULL;
1214 bool any_ifcvt_loops = false;
1215 unsigned ret = 0;
1217 vect_loops_num = number_of_loops (fun);
1219 /* Bail out if there are no loops. */
1220 if (vect_loops_num <= 1)
1221 return 0;
1223 vect_slp_init ();
1225 if (fun->has_simduid_loops)
1226 note_simd_array_uses (&simd_array_to_simduid_htab, fun);
1228 /* ----------- Analyze loops. ----------- */
1230 /* If some loop was duplicated, it gets bigger number
1231 than all previously defined loops. This fact allows us to run
1232 only over initial loops skipping newly generated ones. */
1233 for (auto loop : loops_list (fun, 0))
1234 if (loop->dont_vectorize)
1236 any_ifcvt_loops = true;
1237 /* If-conversion sometimes versions both the outer loop
1238 (for the case when outer loop vectorization might be
1239 desirable) as well as the inner loop in the scalar version
1240 of the loop. So we have:
1241 if (LOOP_VECTORIZED (1, 3))
1243 loop1
1244 loop2
1246 else
1247 loop3 (copy of loop1)
1248 if (LOOP_VECTORIZED (4, 5))
1249 loop4 (copy of loop2)
1250 else
1251 loop5 (copy of loop4)
1252 If loops' iteration gives us loop3 first (which has
1253 dont_vectorize set), make sure to process loop1 before loop4;
1254 so that we can prevent vectorization of loop4 if loop1
1255 is successfully vectorized. */
1256 if (loop->inner)
1258 gimple *loop_vectorized_call
1259 = vect_loop_vectorized_call (loop);
1260 if (loop_vectorized_call
1261 && vect_loop_vectorized_call (loop->inner))
1263 tree arg = gimple_call_arg (loop_vectorized_call, 0);
1264 class loop *vector_loop
1265 = get_loop (fun, tree_to_shwi (arg));
1266 if (vector_loop && vector_loop != loop)
1268 /* Make sure we don't vectorize it twice. */
1269 vector_loop->dont_vectorize = true;
1270 ret |= try_vectorize_loop (simduid_to_vf_htab,
1271 &num_vectorized_loops,
1272 vector_loop, fun);
1277 else
1278 ret |= try_vectorize_loop (simduid_to_vf_htab, &num_vectorized_loops,
1279 loop, fun);
1281 vect_location = dump_user_location_t ();
1283 statistics_counter_event (fun, "Vectorized loops", num_vectorized_loops);
1284 if (dump_enabled_p ()
1285 || (num_vectorized_loops > 0 && dump_enabled_p ()))
1286 dump_printf_loc (MSG_NOTE, vect_location,
1287 "vectorized %u loops in function.\n",
1288 num_vectorized_loops);
1290 /* ----------- Finalize. ----------- */
1292 if (any_ifcvt_loops)
1293 for (i = 1; i < number_of_loops (fun); i++)
1295 class loop *loop = get_loop (fun, i);
1296 if (loop && loop->dont_vectorize)
1298 gimple *g = vect_loop_vectorized_call (loop);
1299 if (g)
1301 fold_loop_internal_call (g, boolean_false_node);
1302 ret |= TODO_cleanup_cfg;
1303 g = NULL;
1305 else
1306 g = vect_loop_dist_alias_call (loop, fun);
1308 if (g)
1310 fold_loop_internal_call (g, boolean_false_node);
1311 ret |= TODO_cleanup_cfg;
1316 /* Fold IFN_GOMP_SIMD_{VF,LANE,LAST_LANE,ORDERED_{START,END}} builtins. */
1317 if (fun->has_simduid_loops)
1319 adjust_simduid_builtins (simduid_to_vf_htab, fun);
1320 /* Avoid stale SCEV cache entries for the SIMD_LANE defs. */
1321 scev_reset ();
1323 /* Shrink any "omp array simd" temporary arrays to the
1324 actual vectorization factors. */
1325 if (simd_array_to_simduid_htab)
1326 shrink_simd_arrays (simd_array_to_simduid_htab, simduid_to_vf_htab);
1327 delete simduid_to_vf_htab;
1328 fun->has_simduid_loops = false;
1330 if (num_vectorized_loops > 0)
1332 /* If we vectorized any loop only virtual SSA form needs to be updated.
1333 ??? Also while we try hard to update loop-closed SSA form we fail
1334 to properly do this in some corner-cases (see PR56286). */
1335 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa_only_virtuals);
1336 ret |= TODO_cleanup_cfg;
1339 for (i = 1; i < number_of_loops (fun); i++)
1341 loop_vec_info loop_vinfo;
1342 bool has_mask_store;
1344 class loop *loop = get_loop (fun, i);
1345 if (!loop || !loop->aux)
1346 continue;
1347 loop_vinfo = (loop_vec_info) loop->aux;
1348 has_mask_store = LOOP_VINFO_HAS_MASK_STORE (loop_vinfo);
1349 delete loop_vinfo;
1350 if (has_mask_store
1351 && targetm.vectorize.empty_mask_is_expensive (IFN_MASK_STORE))
1352 optimize_mask_stores (loop);
1354 auto_bitmap exit_bbs;
1355 /* Perform local CSE, this esp. helps because we emit code for
1356 predicates that need to be shared for optimal predicate usage.
1357 However reassoc will re-order them and prevent CSE from working
1358 as it should. CSE only the loop body, not the entry. */
1359 bitmap_set_bit (exit_bbs, single_exit (loop)->dest->index);
1361 edge entry = EDGE_PRED (loop_preheader_edge (loop)->src, 0);
1362 do_rpo_vn (fun, entry, exit_bbs);
1364 loop->aux = NULL;
1367 vect_slp_fini ();
1369 return ret;
1372 } // anon namespace
1374 gimple_opt_pass *
1375 make_pass_vectorize (gcc::context *ctxt)
1377 return new pass_vectorize (ctxt);
1380 /* Entry point to the simduid cleanup pass. */
1382 namespace {
1384 const pass_data pass_data_simduid_cleanup =
1386 GIMPLE_PASS, /* type */
1387 "simduid", /* name */
1388 OPTGROUP_NONE, /* optinfo_flags */
1389 TV_NONE, /* tv_id */
1390 ( PROP_ssa | PROP_cfg ), /* properties_required */
1391 0, /* properties_provided */
1392 0, /* properties_destroyed */
1393 0, /* todo_flags_start */
1394 0, /* todo_flags_finish */
1397 class pass_simduid_cleanup : public gimple_opt_pass
1399 public:
1400 pass_simduid_cleanup (gcc::context *ctxt)
1401 : gimple_opt_pass (pass_data_simduid_cleanup, ctxt)
1404 /* opt_pass methods: */
1405 opt_pass * clone () { return new pass_simduid_cleanup (m_ctxt); }
1406 virtual bool gate (function *fun) { return fun->has_simduid_loops; }
1407 virtual unsigned int execute (function *);
1409 }; // class pass_simduid_cleanup
1411 unsigned int
1412 pass_simduid_cleanup::execute (function *fun)
1414 hash_table<simd_array_to_simduid> *simd_array_to_simduid_htab = NULL;
1416 note_simd_array_uses (&simd_array_to_simduid_htab, fun);
1418 /* Fold IFN_GOMP_SIMD_{VF,LANE,LAST_LANE,ORDERED_{START,END}} builtins. */
1419 adjust_simduid_builtins (NULL, fun);
1421 /* Shrink any "omp array simd" temporary arrays to the
1422 actual vectorization factors. */
1423 if (simd_array_to_simduid_htab)
1424 shrink_simd_arrays (simd_array_to_simduid_htab, NULL);
1425 fun->has_simduid_loops = false;
1426 return 0;
1429 } // anon namespace
1431 gimple_opt_pass *
1432 make_pass_simduid_cleanup (gcc::context *ctxt)
1434 return new pass_simduid_cleanup (ctxt);
1438 /* Entry point to basic block SLP phase. */
1440 namespace {
1442 const pass_data pass_data_slp_vectorize =
1444 GIMPLE_PASS, /* type */
1445 "slp", /* name */
1446 OPTGROUP_LOOP | OPTGROUP_VEC, /* optinfo_flags */
1447 TV_TREE_SLP_VECTORIZATION, /* tv_id */
1448 ( PROP_ssa | PROP_cfg ), /* properties_required */
1449 0, /* properties_provided */
1450 0, /* properties_destroyed */
1451 0, /* todo_flags_start */
1452 TODO_update_ssa, /* todo_flags_finish */
1455 class pass_slp_vectorize : public gimple_opt_pass
1457 public:
1458 pass_slp_vectorize (gcc::context *ctxt)
1459 : gimple_opt_pass (pass_data_slp_vectorize, ctxt)
1462 /* opt_pass methods: */
1463 opt_pass * clone () { return new pass_slp_vectorize (m_ctxt); }
1464 virtual bool gate (function *) { return flag_tree_slp_vectorize != 0; }
1465 virtual unsigned int execute (function *);
1467 }; // class pass_slp_vectorize
1469 unsigned int
1470 pass_slp_vectorize::execute (function *fun)
1472 auto_purge_vect_location sentinel;
1473 basic_block bb;
1475 bool in_loop_pipeline = scev_initialized_p ();
1476 if (!in_loop_pipeline)
1478 loop_optimizer_init (LOOPS_NORMAL);
1479 scev_initialize ();
1482 /* Mark all stmts as not belonging to the current region and unvisited. */
1483 FOR_EACH_BB_FN (bb, fun)
1485 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1486 gsi_next (&gsi))
1488 gphi *stmt = gsi.phi ();
1489 gimple_set_uid (stmt, -1);
1490 gimple_set_visited (stmt, false);
1492 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
1493 gsi_next (&gsi))
1495 gimple *stmt = gsi_stmt (gsi);
1496 gimple_set_uid (stmt, -1);
1497 gimple_set_visited (stmt, false);
1501 vect_slp_init ();
1503 vect_slp_function (fun);
1505 vect_slp_fini ();
1507 if (!in_loop_pipeline)
1509 scev_finalize ();
1510 loop_optimizer_finalize ();
1513 return 0;
1516 } // anon namespace
1518 gimple_opt_pass *
1519 make_pass_slp_vectorize (gcc::context *ctxt)
1521 return new pass_slp_vectorize (ctxt);
1525 /* Increase alignment of global arrays to improve vectorization potential.
1526 TODO:
1527 - Consider also structs that have an array field.
1528 - Use ipa analysis to prune arrays that can't be vectorized?
1529 This should involve global alignment analysis and in the future also
1530 array padding. */
1532 static unsigned get_vec_alignment_for_type (tree);
1533 static hash_map<tree, unsigned> *type_align_map;
1535 /* Return alignment of array's vector type corresponding to scalar type.
1536 0 if no vector type exists. */
1537 static unsigned
1538 get_vec_alignment_for_array_type (tree type)
1540 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
1541 poly_uint64 array_size, vector_size;
1543 tree scalar_type = strip_array_types (type);
1544 tree vectype = get_related_vectype_for_scalar_type (VOIDmode, scalar_type);
1545 if (!vectype
1546 || !poly_int_tree_p (TYPE_SIZE (type), &array_size)
1547 || !poly_int_tree_p (TYPE_SIZE (vectype), &vector_size)
1548 || maybe_lt (array_size, vector_size))
1549 return 0;
1551 return TYPE_ALIGN (vectype);
1554 /* Return alignment of field having maximum alignment of vector type
1555 corresponding to it's scalar type. For now, we only consider fields whose
1556 offset is a multiple of it's vector alignment.
1557 0 if no suitable field is found. */
1558 static unsigned
1559 get_vec_alignment_for_record_type (tree type)
1561 gcc_assert (TREE_CODE (type) == RECORD_TYPE);
1563 unsigned max_align = 0, alignment;
1564 HOST_WIDE_INT offset;
1565 tree offset_tree;
1567 if (TYPE_PACKED (type))
1568 return 0;
1570 unsigned *slot = type_align_map->get (type);
1571 if (slot)
1572 return *slot;
1574 for (tree field = first_field (type);
1575 field != NULL_TREE;
1576 field = DECL_CHAIN (field))
1578 /* Skip if not FIELD_DECL or if alignment is set by user. */
1579 if (TREE_CODE (field) != FIELD_DECL
1580 || DECL_USER_ALIGN (field)
1581 || DECL_ARTIFICIAL (field))
1582 continue;
1584 /* We don't need to process the type further if offset is variable,
1585 since the offsets of remaining members will also be variable. */
1586 if (TREE_CODE (DECL_FIELD_OFFSET (field)) != INTEGER_CST
1587 || TREE_CODE (DECL_FIELD_BIT_OFFSET (field)) != INTEGER_CST)
1588 break;
1590 /* Similarly stop processing the type if offset_tree
1591 does not fit in unsigned HOST_WIDE_INT. */
1592 offset_tree = bit_position (field);
1593 if (!tree_fits_uhwi_p (offset_tree))
1594 break;
1596 offset = tree_to_uhwi (offset_tree);
1597 alignment = get_vec_alignment_for_type (TREE_TYPE (field));
1599 /* Get maximum alignment of vectorized field/array among those members
1600 whose offset is multiple of the vector alignment. */
1601 if (alignment
1602 && (offset % alignment == 0)
1603 && (alignment > max_align))
1604 max_align = alignment;
1607 type_align_map->put (type, max_align);
1608 return max_align;
1611 /* Return alignment of vector type corresponding to decl's scalar type
1612 or 0 if it doesn't exist or the vector alignment is lesser than
1613 decl's alignment. */
1614 static unsigned
1615 get_vec_alignment_for_type (tree type)
1617 if (type == NULL_TREE)
1618 return 0;
1620 gcc_assert (TYPE_P (type));
1622 static unsigned alignment = 0;
1623 switch (TREE_CODE (type))
1625 case ARRAY_TYPE:
1626 alignment = get_vec_alignment_for_array_type (type);
1627 break;
1628 case RECORD_TYPE:
1629 alignment = get_vec_alignment_for_record_type (type);
1630 break;
1631 default:
1632 alignment = 0;
1633 break;
1636 return (alignment > TYPE_ALIGN (type)) ? alignment : 0;
1639 /* Entry point to increase_alignment pass. */
1640 static unsigned int
1641 increase_alignment (void)
1643 varpool_node *vnode;
1645 vect_location = dump_user_location_t ();
1646 type_align_map = new hash_map<tree, unsigned>;
1648 /* Increase the alignment of all global arrays for vectorization. */
1649 FOR_EACH_DEFINED_VARIABLE (vnode)
1651 tree decl = vnode->decl;
1652 unsigned int alignment;
1654 if ((decl_in_symtab_p (decl)
1655 && !symtab_node::get (decl)->can_increase_alignment_p ())
1656 || DECL_USER_ALIGN (decl) || DECL_ARTIFICIAL (decl))
1657 continue;
1659 alignment = get_vec_alignment_for_type (TREE_TYPE (decl));
1660 if (alignment && vect_can_force_dr_alignment_p (decl, alignment))
1662 vnode->increase_alignment (alignment);
1663 if (dump_enabled_p ())
1664 dump_printf (MSG_NOTE, "Increasing alignment of decl: %T\n", decl);
1668 delete type_align_map;
1669 return 0;
1673 namespace {
1675 const pass_data pass_data_ipa_increase_alignment =
1677 SIMPLE_IPA_PASS, /* type */
1678 "increase_alignment", /* name */
1679 OPTGROUP_LOOP | OPTGROUP_VEC, /* optinfo_flags */
1680 TV_IPA_OPT, /* tv_id */
1681 0, /* properties_required */
1682 0, /* properties_provided */
1683 0, /* properties_destroyed */
1684 0, /* todo_flags_start */
1685 0, /* todo_flags_finish */
1688 class pass_ipa_increase_alignment : public simple_ipa_opt_pass
1690 public:
1691 pass_ipa_increase_alignment (gcc::context *ctxt)
1692 : simple_ipa_opt_pass (pass_data_ipa_increase_alignment, ctxt)
1695 /* opt_pass methods: */
1696 virtual bool gate (function *)
1698 return flag_section_anchors && flag_tree_loop_vectorize;
1701 virtual unsigned int execute (function *) { return increase_alignment (); }
1703 }; // class pass_ipa_increase_alignment
1705 } // anon namespace
1707 simple_ipa_opt_pass *
1708 make_pass_ipa_increase_alignment (gcc::context *ctxt)
1710 return new pass_ipa_increase_alignment (ctxt);
1713 /* If the condition represented by T is a comparison or the SSA name
1714 result of a comparison, extract the comparison's operands. Represent
1715 T as NE_EXPR <T, 0> otherwise. */
1717 void
1718 scalar_cond_masked_key::get_cond_ops_from_tree (tree t)
1720 if (TREE_CODE_CLASS (TREE_CODE (t)) == tcc_comparison)
1722 this->code = TREE_CODE (t);
1723 this->op0 = TREE_OPERAND (t, 0);
1724 this->op1 = TREE_OPERAND (t, 1);
1725 this->inverted_p = false;
1726 return;
1729 if (TREE_CODE (t) == SSA_NAME)
1730 if (gassign *stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (t)))
1732 tree_code code = gimple_assign_rhs_code (stmt);
1733 if (TREE_CODE_CLASS (code) == tcc_comparison)
1735 this->code = code;
1736 this->op0 = gimple_assign_rhs1 (stmt);
1737 this->op1 = gimple_assign_rhs2 (stmt);
1738 this->inverted_p = false;
1739 return;
1741 else if (code == BIT_NOT_EXPR)
1743 tree n_op = gimple_assign_rhs1 (stmt);
1744 if ((stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (n_op))))
1746 code = gimple_assign_rhs_code (stmt);
1747 if (TREE_CODE_CLASS (code) == tcc_comparison)
1749 this->code = code;
1750 this->op0 = gimple_assign_rhs1 (stmt);
1751 this->op1 = gimple_assign_rhs2 (stmt);
1752 this->inverted_p = true;
1753 return;
1759 this->code = NE_EXPR;
1760 this->op0 = t;
1761 this->op1 = build_zero_cst (TREE_TYPE (t));
1762 this->inverted_p = false;
1765 /* See the comment above the declaration for details. */
1767 unsigned int
1768 vector_costs::add_stmt_cost (int count, vect_cost_for_stmt kind,
1769 stmt_vec_info stmt_info, tree vectype,
1770 int misalign, vect_cost_model_location where)
1772 unsigned int cost
1773 = builtin_vectorization_cost (kind, vectype, misalign) * count;
1774 return record_stmt_cost (stmt_info, where, cost);
1777 /* See the comment above the declaration for details. */
1779 void
1780 vector_costs::finish_cost (const vector_costs *)
1782 gcc_assert (!m_finished);
1783 m_finished = true;
1786 /* Record a base cost of COST units against WHERE. If STMT_INFO is
1787 nonnull, use it to adjust the cost based on execution frequency
1788 (where appropriate). */
1790 unsigned int
1791 vector_costs::record_stmt_cost (stmt_vec_info stmt_info,
1792 vect_cost_model_location where,
1793 unsigned int cost)
1795 cost = adjust_cost_for_freq (stmt_info, where, cost);
1796 m_costs[where] += cost;
1797 return cost;
1800 /* COST is the base cost we have calculated for an operation in location WHERE.
1801 If STMT_INFO is nonnull, use it to adjust the cost based on execution
1802 frequency (where appropriate). Return the adjusted cost. */
1804 unsigned int
1805 vector_costs::adjust_cost_for_freq (stmt_vec_info stmt_info,
1806 vect_cost_model_location where,
1807 unsigned int cost)
1809 /* Statements in an inner loop relative to the loop being
1810 vectorized are weighted more heavily. The value here is
1811 arbitrary and could potentially be improved with analysis. */
1812 if (where == vect_body
1813 && stmt_info
1814 && stmt_in_inner_loop_p (m_vinfo, stmt_info))
1816 loop_vec_info loop_vinfo = as_a<loop_vec_info> (m_vinfo);
1817 cost *= LOOP_VINFO_INNER_LOOP_COST_FACTOR (loop_vinfo);
1819 return cost;
1822 /* See the comment above the declaration for details. */
1824 bool
1825 vector_costs::better_main_loop_than_p (const vector_costs *other) const
1827 int diff = compare_inside_loop_cost (other);
1828 if (diff != 0)
1829 return diff < 0;
1831 /* If there's nothing to choose between the loop bodies, see whether
1832 there's a difference in the prologue and epilogue costs. */
1833 diff = compare_outside_loop_cost (other);
1834 if (diff != 0)
1835 return diff < 0;
1837 return false;
1841 /* See the comment above the declaration for details. */
1843 bool
1844 vector_costs::better_epilogue_loop_than_p (const vector_costs *other,
1845 loop_vec_info main_loop) const
1847 loop_vec_info this_loop_vinfo = as_a<loop_vec_info> (this->m_vinfo);
1848 loop_vec_info other_loop_vinfo = as_a<loop_vec_info> (other->m_vinfo);
1850 poly_int64 this_vf = LOOP_VINFO_VECT_FACTOR (this_loop_vinfo);
1851 poly_int64 other_vf = LOOP_VINFO_VECT_FACTOR (other_loop_vinfo);
1853 poly_uint64 main_poly_vf = LOOP_VINFO_VECT_FACTOR (main_loop);
1854 unsigned HOST_WIDE_INT main_vf;
1855 unsigned HOST_WIDE_INT other_factor, this_factor, other_cost, this_cost;
1856 /* If we can determine how many iterations are left for the epilogue
1857 loop, that is if both the main loop's vectorization factor and number
1858 of iterations are constant, then we use them to calculate the cost of
1859 the epilogue loop together with a 'likely value' for the epilogues
1860 vectorization factor. Otherwise we use the main loop's vectorization
1861 factor and the maximum poly value for the epilogue's. If the target
1862 has not provided with a sensible upper bound poly vectorization
1863 factors are likely to be favored over constant ones. */
1864 if (main_poly_vf.is_constant (&main_vf)
1865 && LOOP_VINFO_NITERS_KNOWN_P (main_loop))
1867 unsigned HOST_WIDE_INT niters
1868 = LOOP_VINFO_INT_NITERS (main_loop) % main_vf;
1869 HOST_WIDE_INT other_likely_vf
1870 = estimated_poly_value (other_vf, POLY_VALUE_LIKELY);
1871 HOST_WIDE_INT this_likely_vf
1872 = estimated_poly_value (this_vf, POLY_VALUE_LIKELY);
1874 /* If the epilogue is using partial vectors we account for the
1875 partial iteration here too. */
1876 other_factor = niters / other_likely_vf;
1877 if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (other_loop_vinfo)
1878 && niters % other_likely_vf != 0)
1879 other_factor++;
1881 this_factor = niters / this_likely_vf;
1882 if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (this_loop_vinfo)
1883 && niters % this_likely_vf != 0)
1884 this_factor++;
1886 else
1888 unsigned HOST_WIDE_INT main_vf_max
1889 = estimated_poly_value (main_poly_vf, POLY_VALUE_MAX);
1891 other_factor = main_vf_max / estimated_poly_value (other_vf,
1892 POLY_VALUE_MAX);
1893 this_factor = main_vf_max / estimated_poly_value (this_vf,
1894 POLY_VALUE_MAX);
1896 /* If the loop is not using partial vectors then it will iterate one
1897 time less than one that does. It is safe to subtract one here,
1898 because the main loop's vf is always at least 2x bigger than that
1899 of an epilogue. */
1900 if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (other_loop_vinfo))
1901 other_factor -= 1;
1902 if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (this_loop_vinfo))
1903 this_factor -= 1;
1906 /* Compute the costs by multiplying the inside costs with the factor and
1907 add the outside costs for a more complete picture. The factor is the
1908 amount of times we are expecting to iterate this epilogue. */
1909 other_cost = other->body_cost () * other_factor;
1910 this_cost = this->body_cost () * this_factor;
1911 other_cost += other->outside_cost ();
1912 this_cost += this->outside_cost ();
1913 return this_cost < other_cost;
1916 /* A <=>-style subroutine of better_main_loop_than_p. Check whether we can
1917 determine the return value of better_main_loop_than_p by comparing the
1918 inside (loop body) costs of THIS and OTHER. Return:
1920 * -1 if better_main_loop_than_p should return true.
1921 * 1 if better_main_loop_than_p should return false.
1922 * 0 if we can't decide. */
1925 vector_costs::compare_inside_loop_cost (const vector_costs *other) const
1927 loop_vec_info this_loop_vinfo = as_a<loop_vec_info> (this->m_vinfo);
1928 loop_vec_info other_loop_vinfo = as_a<loop_vec_info> (other->m_vinfo);
1930 struct loop *loop = LOOP_VINFO_LOOP (this_loop_vinfo);
1931 gcc_assert (LOOP_VINFO_LOOP (other_loop_vinfo) == loop);
1933 poly_int64 this_vf = LOOP_VINFO_VECT_FACTOR (this_loop_vinfo);
1934 poly_int64 other_vf = LOOP_VINFO_VECT_FACTOR (other_loop_vinfo);
1936 /* Limit the VFs to what is likely to be the maximum number of iterations,
1937 to handle cases in which at least one loop_vinfo is fully-masked. */
1938 HOST_WIDE_INT estimated_max_niter = likely_max_stmt_executions_int (loop);
1939 if (estimated_max_niter != -1)
1941 if (known_le (estimated_max_niter, this_vf))
1942 this_vf = estimated_max_niter;
1943 if (known_le (estimated_max_niter, other_vf))
1944 other_vf = estimated_max_niter;
1947 /* Check whether the (fractional) cost per scalar iteration is lower or
1948 higher: this_inside_cost / this_vf vs. other_inside_cost / other_vf. */
1949 poly_int64 rel_this = this_loop_vinfo->vector_costs->body_cost () * other_vf;
1950 poly_int64 rel_other
1951 = other_loop_vinfo->vector_costs->body_cost () * this_vf;
1953 HOST_WIDE_INT est_rel_this_min
1954 = estimated_poly_value (rel_this, POLY_VALUE_MIN);
1955 HOST_WIDE_INT est_rel_this_max
1956 = estimated_poly_value (rel_this, POLY_VALUE_MAX);
1958 HOST_WIDE_INT est_rel_other_min
1959 = estimated_poly_value (rel_other, POLY_VALUE_MIN);
1960 HOST_WIDE_INT est_rel_other_max
1961 = estimated_poly_value (rel_other, POLY_VALUE_MAX);
1963 /* Check first if we can make out an unambigous total order from the minimum
1964 and maximum estimates. */
1965 if (est_rel_this_min < est_rel_other_min
1966 && est_rel_this_max < est_rel_other_max)
1967 return -1;
1969 if (est_rel_other_min < est_rel_this_min
1970 && est_rel_other_max < est_rel_this_max)
1971 return 1;
1973 /* When other_loop_vinfo uses a variable vectorization factor,
1974 we know that it has a lower cost for at least one runtime VF.
1975 However, we don't know how likely that VF is.
1977 One option would be to compare the costs for the estimated VFs.
1978 The problem is that that can put too much pressure on the cost
1979 model. E.g. if the estimated VF is also the lowest possible VF,
1980 and if other_loop_vinfo is 1 unit worse than this_loop_vinfo
1981 for the estimated VF, we'd then choose this_loop_vinfo even
1982 though (a) this_loop_vinfo might not actually be better than
1983 other_loop_vinfo for that VF and (b) it would be significantly
1984 worse at larger VFs.
1986 Here we go for a hacky compromise: pick this_loop_vinfo if it is
1987 no more expensive than other_loop_vinfo even after doubling the
1988 estimated other_loop_vinfo VF. For all but trivial loops, this
1989 ensures that we only pick this_loop_vinfo if it is significantly
1990 better than other_loop_vinfo at the estimated VF. */
1991 if (est_rel_other_min != est_rel_this_min
1992 || est_rel_other_max != est_rel_this_max)
1994 HOST_WIDE_INT est_rel_this_likely
1995 = estimated_poly_value (rel_this, POLY_VALUE_LIKELY);
1996 HOST_WIDE_INT est_rel_other_likely
1997 = estimated_poly_value (rel_other, POLY_VALUE_LIKELY);
1999 return est_rel_this_likely * 2 <= est_rel_other_likely ? -1 : 1;
2002 return 0;
2005 /* A <=>-style subroutine of better_main_loop_than_p, used when there is
2006 nothing to choose between the inside (loop body) costs of THIS and OTHER.
2007 Check whether we can determine the return value of better_main_loop_than_p
2008 by comparing the outside (prologue and epilogue) costs of THIS and OTHER.
2009 Return:
2011 * -1 if better_main_loop_than_p should return true.
2012 * 1 if better_main_loop_than_p should return false.
2013 * 0 if we can't decide. */
2016 vector_costs::compare_outside_loop_cost (const vector_costs *other) const
2018 auto this_outside_cost = this->outside_cost ();
2019 auto other_outside_cost = other->outside_cost ();
2020 if (this_outside_cost != other_outside_cost)
2021 return this_outside_cost < other_outside_cost ? -1 : 1;
2023 return 0;