I rewrote the patch trying to keep closer to what we already have as 
well as integrating IFN_COND_LEN_ANY_ACTIVE.  Not sure I was terribly 
successful in simplifying things, but the -1 discussion can be set aside 
with this.  A wall of text for vect_early_break_index_based_p tries to 
give a rationale for as well as a sketch of the new approach.
The patch also doesn't have the enum anymore but still uses the "index 
based" naming.

Regards
 Robin


[PATCH] vect: Index-based early-break approach.

This patch adds an "index-based" early-break approach that RVV can use
more naturally than the current mask-based one with VCOND_MASK_LEN.
The issue is that RVV's mask producers cannot ensure zero in inactive
tail elements.  Therefore, it's necessary to length-mask the early-break
masks to a boolean that is fed to the early-break branch.
In the exit block we extract the active elemeent by getting the first
active index in a similar fashion and then use a variable-index vector
extract.  The in-loop reduction uses IFN_COND_LEN_ANY_ACTIVE which was
introduced in the previous patch.

I attempted to bundle the mechanism in a couple of new functions but
didn't entirely succeed in keeping existing code clean.  I still hope
it's a bit clearer than before.

gcc/ChangeLog:

        * tree-vect-loop.cc (vectorizable_live_operation): Check for
        var_idx extract.
        (vect_early_break_index_based_p): New function.
        (vect_build_len_mask_reduction): Likewise.
        (vect_can_build_early_break_index_p): Likewise.
        (vect_build_early_break_index): Likewise.
        (vect_update_ivs_after_vectorizer_for_early_breaks): Use
        vect_build_early_break_index.
        * tree-vect-stmts.cc (vectorizable_early_exit): Add index-based
        approach.
        * tree-vectorizer.h (vect_early_break_index_based_p): Declare.
        (vect_can_build_early_break_index_p): Declare.
        (vect_build_len_mask_reduction): Declare.
        (vect_build_early_break_index): Declare.
---
 gcc/tree-vect-loop.cc  | 203 +++++++++++++++++++++++++++++++++++------
 gcc/tree-vect-stmts.cc |  57 +++++++-----
 gcc/tree-vectorizer.h  |   6 ++
 3 files changed, 216 insertions(+), 50 deletions(-)

diff --git a/gcc/tree-vect-loop.cc b/gcc/tree-vect-loop.cc
index b34fe615781..5148f4118d9 100644
--- a/gcc/tree-vect-loop.cc
+++ b/gcc/tree-vect-loop.cc
@@ -10536,7 +10536,11 @@ vectorizable_live_operation (vec_info *vinfo, 
stmt_vec_info stmt_info,
        {
          if (!live_early_break_iv_p
              && !direct_internal_fn_supported_p (IFN_EXTRACT_FIRST_ACTIVE,
-                                                 vectype, OPTIMIZE_FOR_BOTH))
+                                                 vectype, OPTIMIZE_FOR_BOTH)
+             && !(can_vec_extract_var_idx_p (TYPE_MODE (vectype),
+                                             TYPE_MODE (TREE_TYPE (vectype)))
+                  && vect_can_build_early_break_index_p
+                       (truth_type_for (vectype))))
            {
              if (dump_enabled_p ())
                dump_printf_loc (
@@ -10691,9 +10695,10 @@ vectorizable_live_operation (vec_info *vinfo, 
stmt_vec_info stmt_info,
                  data_reference *dr = STMT_VINFO_DATA_REF (stmt_info);
                  gassign *load = NULL;
                  if (single_pred_p (e->dest)
-                     && direct_internal_fn_supported_p
-                          (IFN_INDEX_FIRST_ACTIVE, TREE_TYPE (cmp_op),
-                           OPTIMIZE_FOR_BOTH)
+                     && (direct_internal_fn_supported_p
+                           (IFN_INDEX_FIRST_ACTIVE, TREE_TYPE (cmp_op),
+                            OPTIMIZE_FOR_BOTH)
+                         || vect_early_break_index_based_p (TREE_TYPE 
(cmp_op)))
                      && dr
                      && TREE_CODE (tmp_vec_lhs) == SSA_NAME
                      && (load = dyn_cast<gassign *>
@@ -10714,10 +10719,9 @@ vectorizable_live_operation (vec_info *vinfo, 
stmt_vec_info stmt_info,
 
                      if (reload_vuse)
                        {
-                         tree first = gimple_build (&stmts,
-                                                    IFN_INDEX_FIRST_ACTIVE,
-                                                    unsigned_intDI_type_node,
-                                                    cmp_op);
+                         tree first
+                           = vect_build_early_break_index (loop_vinfo, &stmts,
+                                                           cmp_op);
                          tree offset = gimple_convert (&stmts, sizetype,
                                                        first);
                          offset
@@ -10754,9 +10758,17 @@ vectorizable_live_operation (vec_info *vinfo, 
stmt_vec_info stmt_info,
                    {
                      /* Convert the extracted vector element to the scalar
                         type.  */
-                     tree tmp = gimple_build (&stmts, CFN_EXTRACT_FIRST_ACTIVE,
-                                              TREE_TYPE (vectype),
-                                              cmp_op, tmp_vec_lhs);
+                     tree tmp
+                       = (direct_internal_fn_supported_p
+                            (IFN_EXTRACT_FIRST_ACTIVE, vectype,
+                             OPTIMIZE_FOR_BOTH)
+                          ? gimple_build (&stmts, CFN_EXTRACT_FIRST_ACTIVE,
+                                          TREE_TYPE (vectype), cmp_op,
+                                          tmp_vec_lhs)
+                          : gimple_build (&stmts, CFN_VEC_EXTRACT,
+                                          TREE_TYPE (vectype), tmp_vec_lhs,
+                                          vect_build_early_break_index
+                                            (loop_vinfo, &stmts, cmp_op)));
                      new_tree = gimple_convert (&stmts, lhs_type, tmp);
                    }
 
@@ -11231,6 +11243,153 @@ vect_get_loop_len (loop_vec_info loop_vinfo, 
gimple_stmt_iterator *gsi,
   return loop_len;
 }
 
+/* The index-based approach requires us to be able to reduce a mask
+   to a boolean via (length-controlled) ANY_ACTIVE.  Similarly, we need to be
+   able to obtain the index of the first active element in a mask.
+   Return true if both are supported and false otherwise.
+
+   ??? Naming and concept are somewhat blurred.
+   The two approaches are very roughly:
+
+   (1) SVE
+    loop:
+      vexit = data CMP key
+      vexit = vexit & loop_mask
+      if (vexit != 0)
+       goto exit1
+      ...
+    exit1:
+      idx = INDEX_FIRST_ACTIVE (vexit)
+      out = EXTRACT_FIRST_ACTIVE (data, vexit)
+
+   (2a) RVV "index based"
+    loop:
+      vexit = data CMP key
+      any = COND_LEN_ANY_ACTIVE (vexit)           #3 = (vfirst >= 0)
+      if (any != 0)
+       goto exit1
+      ...
+    exit1:
+      idx = COND_LEN_INDEX_FIRST_ACTIVE (vexit)   #4 = vfirst
+      out = VEC_EXTRACT (data, idx)
+
+   (2b) RVV "index direct"
+    loop:
+      vexit = data CMP key
+      idx = COND_LEN_INDEX_FIRST_ACTIVE (vexit)   # = vfirst, -1 if mask empty
+      if (idx > -1)
+       goto exit1
+      ...
+    exit1:
+      out = VEC_EXTRACT (data, idx)
+
+   (1) has vexit as vector mask and its IFNs reduce the mask, while
+   (2a) and (2b) reduce to a scalar flag/index inside the loop.
+   In (2a) we use COND_LEN_ANY_ACTIVE inside the loop and
+   COND_LEN_INDEX_FIRST_ACTIVE in the exit block which both map to vfirst
+   internally.
+   (2b) would be feasible if we could stipulate COND_LEN_INDEX_FIRST_ACTIVE's
+   return value to -1 for an empty mask but that would pessimize other targets
+   which cannot directly return -1.  For that reason as well as for consistency
+   with (1), we go with (2a).
+   #4 can be elided by RTL CSE later on, as long as it has the exact same
+   RTL expansion as #3.  That's also the reason we emit
+   COND_LEN_INDEX_FIRST_ACTIVE rather than INDEX_FIRST_ACTIVE.  The latter
+   is sufficient but results in a different RTL pattern and couldn't be elided.
+
+   Currently, RVV is the only target that prefers the index approach, hence
+   (2a)'s code is entangled in length masking.  */
+
+bool
+vect_early_break_index_based_p (tree mask_type)
+{
+  return (direct_internal_fn_supported_p (IFN_COND_LEN_ANY_ACTIVE, mask_type,
+                                         OPTIMIZE_FOR_BOTH)
+         && direct_internal_fn_supported_p (IFN_COND_LEN_INDEX_FIRST_ACTIVE,
+                                            mask_type, OPTIMIZE_FOR_BOTH));
+}
+
+/* Build a length-masked call to IFN, where IFN is either
+   IFN_COND_LEN_ANY_ACTIVE (MASK) or IFN_COND_LEN_INDEX_FIRST_ACTIVE (MASK)
+   and add the necessary statements to SEQ.  NVECTORS and INDEX refer to
+   the LOOP_VINFO's length-mask index. */
+
+tree
+vect_build_len_mask_reduction (loop_vec_info loop_vinfo, gimple_seq *seq,
+                              internal_fn ifn, tree mask,
+                              unsigned int nvectors, unsigned int index)
+{
+  gcc_assert (ifn == IFN_COND_LEN_ANY_ACTIVE
+             || ifn == IFN_COND_LEN_INDEX_FIRST_ACTIVE);
+
+  tree mask_type = TREE_TYPE (mask);
+  tree len = size_int (TYPE_VECTOR_SUBPARTS (mask_type));
+  gimple_stmt_iterator gsi = gsi_end (*seq);
+  if (LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
+    len = vect_get_loop_len (loop_vinfo, &gsi, &LOOP_VINFO_LENS (loop_vinfo),
+                            nvectors, mask_type, index, 1, true);
+  tree bias = build_int_cst (intQI_type_node,
+                            LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo));
+  tree res = make_temp_ssa_name (unsigned_intDI_type_node, NULL, "vexit");
+  gcall *call = gimple_build_call_internal (ifn, 4,
+                                           build_all_ones_cst (mask_type),
+                                           mask, len, bias);
+  gimple_call_set_lhs (call, res);
+  gimple_seq_add_stmt (seq, call);
+  return res;
+}
+
+/* Return true if vect_build_early_break_index can compute the index of
+   the first active element of a mask of type MASK_TYPE.  */
+
+bool
+vect_can_build_early_break_index_p (tree mask_type)
+{
+  return (vect_early_break_index_based_p (mask_type)
+         || direct_internal_fn_supported_p (IFN_INDEX_FIRST_ACTIVE, mask_type,
+                                            OPTIMIZE_FOR_BOTH)
+         || (direct_internal_fn_supported_p (IFN_TAKE_EXCL_ACTIVE, mask_type,
+                                             OPTIMIZE_FOR_BOTH)
+             && direct_internal_fn_supported_p (IFN_COUNT_ACTIVE, mask_type,
+                                                OPTIMIZE_FOR_BOTH)));
+}
+
+/* Build the first active index for both mask-based and index-based
+   approaches and return it, adding statements to SEQ.  To be used for
+   live outs and related after the loop.*/
+
+tree
+vect_build_early_break_index (loop_vec_info loop_vinfo, gimple_seq *seq,
+                             tree mask)
+{
+  tree mask_type = TREE_TYPE (mask);
+  tree idx_type = unsigned_intDI_type_node;
+
+  if (vect_early_break_index_based_p (mask_type))
+    {
+      /* This is supposed to be called in an exit block and we don't actually
+        need INDEX_FIRST_ACTIVE to be length controlled at that point as we
+        know the exit was taken.  Elements past the length cannot spoil that
+        result anymore so a simple IFN_INDEX_FIRST_ACTIVE would suffice.
+        But we need to make sure to emit the exact same operation as inside
+        the loop in order to be able to rely on CSE to elide the operation we
+        emit here.  COND_LEN_INDEX_FIRST_ACTIVE and INDEX_FIRST_ACTIVE have
+        different RTL representations and wouldn't be treated as similar.  */
+      return vect_build_len_mask_reduction
+       (loop_vinfo, seq, IFN_COND_LEN_INDEX_FIRST_ACTIVE, mask, 1, 0);
+    }
+
+  if (direct_internal_fn_supported_p (IFN_INDEX_FIRST_ACTIVE, mask_type,
+                                     OPTIMIZE_FOR_BOTH))
+    return gimple_build (seq, IFN_INDEX_FIRST_ACTIVE, idx_type, mask);
+
+  tree pred = make_temp_ssa_name (mask_type, NULL, "pred");
+  gcall *p_call = gimple_build_call_internal (IFN_TAKE_EXCL_ACTIVE, 1, mask);
+  gimple_call_set_lhs (p_call, pred);
+  gimple_seq_add_stmt (seq, p_call);
+  return gimple_build (seq, IFN_COUNT_ACTIVE, idx_type, pred);
+}
+
 /* Generate the tree for the loop len mask and return it.  Given the lens,
    nvectors, vectype, index and factor to gen the len mask as below.
 
@@ -11682,7 +11841,6 @@ vect_update_ivs_after_vectorizer_for_early_breaks 
(loop_vec_info loop_vinfo)
            continue;
          auto bb = gcond->bb;
          tree cmp_op = *LOOP_VINFO_EARLY_BRK_DEPS (loop_vinfo)->get (bb);
-         tree mask_type = TREE_TYPE (cmp_op);
          /* Now rewrite the code to use the new IV for linear IVs.  */
          edge exit_e = EDGE_SUCC (bb, 0);
          if (flow_bb_inside_loop_p (loop, exit_e->dest))
@@ -11705,19 +11863,10 @@ vect_update_ivs_after_vectorizer_for_early_breaks 
(loop_vec_info loop_vinfo)
 
             This distinction lets targets choose either a direct first-active
             operation or a partition-and-count sequence.  */
-         internal_fn active_fn = IFN_INDEX_FIRST_ACTIVE;
-         tree active_mask = cmp_op;
-         if (!direct_internal_fn_supported_p (active_fn, mask_type,
-                                              OPTIMIZE_FOR_BOTH))
-           {
-             active_mask = make_temp_ssa_name (mask_type, NULL, "pred");
-             gcall *p_call
-               = gimple_build_call_internal (IFN_TAKE_EXCL_ACTIVE, 1,
-                                             cmp_op);
-             gimple_call_set_lhs (p_call, active_mask);
-             gsi_insert_before (&last_gsi, p_call, GSI_SAME_STMT);
-             active_fn = IFN_COUNT_ACTIVE;
-           }
+         gimple_seq idx_stmts = NULL;
+         tree first_idx
+           = vect_build_early_break_index (loop_vinfo, &idx_stmts, cmp_op);
+         gsi_insert_seq_before (&last_gsi, idx_stmts, GSI_SAME_STMT);
 
          gphi_iterator gsi1;
          for (gsi1 = gsi_start_phis (update_bb); !gsi_end_p (gsi1);)
@@ -11791,9 +11940,7 @@ vect_update_ivs_after_vectorizer_for_early_breaks 
(loop_vec_info loop_vinfo)
                                 (gimple *) phi);
 
              tree res = PHI_RESULT (phi1);
-             tree reduc_iv = gimple_build (&stmts, active_fn,
-                                           unsigned_intDI_type_node,
-                                           active_mask);
+             tree reduc_iv = first_idx;
 
              tree stype = TREE_TYPE (step_expr);
              /* The offset can overflow even when every scalar IV value is
diff --git a/gcc/tree-vect-stmts.cc b/gcc/tree-vect-stmts.cc
index c20e870b28f..5c75155a05c 100644
--- a/gcc/tree-vect-stmts.cc
+++ b/gcc/tree-vect-stmts.cc
@@ -12934,17 +12934,23 @@ vectorizable_early_exit (loop_vec_info loop_vinfo, 
stmt_vec_info stmt_info,
        }
     }
 
+  tree mask_vectype = (VECTOR_BOOLEAN_TYPE_P (vectype)
+                      ? vectype : truth_type_for (vectype));
+  bool index_based_p = vect_early_break_index_based_p (mask_vectype);
+
   /* Analyze only.  */
   if (cost_vec)
     {
-      if (!addhn_supported_p
+      if (!index_based_p
+         && !addhn_supported_p
          && !supports_vector_compare_and_branch (loop_vinfo, mode))
        {
          if (dump_enabled_p ())
-             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
-                              "can't vectorize early exit because the "
-                              "target doesn't support flag setting vector "
-                              "comparisons.\n");
+           dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
+                            "can't vectorize early exit because the "
+                            "target supports neither a vector compare and "
+                            "branch nor a length-controlled reduction of the "
+                            "exit mask to a scalar.\n");
          return false;
        }
 
@@ -12957,8 +12963,9 @@ vectorizable_early_exit (loop_vec_info loop_vinfo, 
stmt_vec_info stmt_info,
 
       if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
        {
-         if (direct_internal_fn_supported_p (IFN_VCOND_MASK_LEN, vectype,
-                                             OPTIMIZE_FOR_SPEED))
+         if (index_based_p
+             || direct_internal_fn_supported_p (IFN_VCOND_MASK_LEN, vectype,
+                                                OPTIMIZE_FOR_SPEED))
            vect_record_loop_len (loop_vinfo, lens, vec_num, vectype, 1);
          else
            vect_record_loop_mask (loop_vinfo, masks, vec_num, vectype, NULL);
@@ -12967,9 +12974,6 @@ vectorizable_early_exit (loop_vec_info loop_vinfo, 
stmt_vec_info stmt_info,
       if (!vect_compute_type_for_early_break_scalar_iv (loop_vinfo))
        return false;
 
-      tree mask_vectype = (VECTOR_BOOLEAN_TYPE_P (vectype)
-                          ? vectype : truth_type_for (vectype));
-
       if (!LOOP_VINFO_EARLY_BREAKS_LIVE_IVS (loop_vinfo).is_empty ()
          && !LOOP_VINFO_EARLY_BRK_NEEDS_EPILOG (loop_vinfo))
        {
@@ -12979,15 +12983,7 @@ vectorizable_early_exit (loop_vec_info loop_vinfo, 
stmt_vec_info stmt_info,
             provide a predicate for the lanes before the first active lane and
             then count those lanes.  This lets the vector loop update a live IV
             without replaying the iteration in a scalar epilogue.  */
-         if (!direct_internal_fn_supported_p (IFN_INDEX_FIRST_ACTIVE,
-                                              mask_vectype,
-                                              OPTIMIZE_FOR_BOTH)
-             && (!direct_internal_fn_supported_p (IFN_TAKE_EXCL_ACTIVE,
-                                                  mask_vectype,
-                                                  OPTIMIZE_FOR_BOTH)
-                 || !direct_internal_fn_supported_p (IFN_COUNT_ACTIVE,
-                                                     mask_vectype,
-                                                     OPTIMIZE_FOR_BOTH)))
+         if (!vect_can_build_early_break_index_p (mask_vectype))
            {
              if (dump_enabled_p ())
                dump_printf_loc (
@@ -13078,7 +13074,9 @@ vectorizable_early_exit (loop_vec_info loop_vinfo, 
stmt_vec_info stmt_info,
     }
 
   /* Determine if we need to reduce the final value.  */
-  if (stmts.length () > 1)
+  if (index_based_p)
+    new_temp = stmts[0];
+  else if (stmts.length () > 1)
     {
       /* We build the reductions in a way to maintain as much parallelism as
         possible.  */
@@ -13165,11 +13163,26 @@ vectorizable_early_exit (loop_vec_info loop_vinfo, 
stmt_vec_info stmt_info,
        }
       new_stmt = gimple_build_assign (cmp_op, new_temp);
       vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt,
-                                   &cond_gsi);
+                                  &cond_gsi);
       new_temp = cmp_op;
     }
 
-  tree cst = build_zero_cst (vectype_out);
+  if (index_based_p)
+    {
+      gimple_seq seq = NULL;
+      unsigned int nvectors = stmts.length ();
+      for (unsigned int i = 0; i < nvectors; i++)
+       {
+         tree any = vect_build_len_mask_reduction
+           (loop_vinfo, &seq, IFN_COND_LEN_ANY_ACTIVE, stmts[i], nvectors, i);
+         new_temp = (i == 0 ? any
+                     : gimple_build (&seq, BIT_IOR_EXPR, TREE_TYPE (any),
+                                     new_temp, any));
+       }
+      gsi_insert_seq_before (&cond_gsi, seq, GSI_SAME_STMT);
+    }
+
+  tree cst = build_zero_cst (TREE_TYPE (new_temp));
   gimple_cond_set_condition (cond_stmt, NE_EXPR, new_temp, cst);
   update_stmt (orig_stmt);
 
diff --git a/gcc/tree-vectorizer.h b/gcc/tree-vectorizer.h
index a86bf2b0da9..24c40556068 100644
--- a/gcc/tree-vectorizer.h
+++ b/gcc/tree-vectorizer.h
@@ -2736,6 +2736,12 @@ extern tree vect_get_loop_mask (loop_vec_info, 
gimple_stmt_iterator *,
                                unsigned int, tree, unsigned int);
 extern void vect_record_loop_len (loop_vec_info, vec_loop_lens *, unsigned int,
                                  tree, unsigned int);
+extern bool vect_early_break_index_based_p (tree);
+extern bool vect_can_build_early_break_index_p (tree);
+extern tree vect_build_len_mask_reduction (loop_vec_info, gimple_seq *,
+                                             internal_fn, tree,
+                                             unsigned int, unsigned int);
+extern tree vect_build_early_break_index (loop_vec_info, gimple_seq *, tree);
 extern tree vect_get_loop_len (loop_vec_info, gimple_stmt_iterator *,
                               vec_loop_lens *, unsigned int, tree,
                               unsigned int, unsigned int, bool);
-- 
2.56.0

Reply via email to