Debian Codegraph @

gcc/config/riscv/riscv-avlprop.cc

raw
1 /* AVL propagation pass for RISC-V 'V' Extension for GNU compiler.
2 Copyright (C) 2023-2025 Free Software Foundation, Inc.
3 Contributed by Juzhe Zhong ([email protected]), RiVAI Technologies Ltd.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or(at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
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/>. */
20
21 /* Pre-RA RTL_SSA-based pass propagates AVL for RVV instructions.
22 A standalone AVL propagation pass is designed because:
23
24 - Better code maintain:
25 Current LCM-based VSETVL pass is so complicated that codes
26 there will become even harder to maintain. A straight forward
27 AVL propagation PASS is much easier to maintain.
28
29 - Reduce scalar register pressure:
30 A type of AVL propagation is we propagate AVL from NON-VLMAX
31 instruction to VLMAX instruction.
32 Note: VLMAX instruction should be ignore tail elements (TA)
33 and the result should be used by the NON-VLMAX instruction.
34 This optimization is mostly for auto-vectorization codes:
35
36 vsetvli r136, r137 --- SELECT_VL
37 vle8.v (use avl = r136) --- IFN_MASK_LEN_LOAD
38 vadd.vv (use VLMAX) --- PLUS_EXPR
39 vse8.v (use avl = r136) --- IFN_MASK_LEN_STORE
40
41 NO AVL propagation:
42
43 vsetvli a5, a4, ta
44 vle8.v v1
45 vsetvli t0, zero, ta
46 vadd.vv v2, v1, v1
47 vse8.v v2
48
49 We can propagate the AVL to 'vadd.vv' since its result
50 is consumed by a 'vse8.v' which has AVL = a5 and its
51 tail elements are agnostic.
52
53 We DON'T do this optimization on VSETVL pass since it is a
54 post-RA pass that consumed 't0' already wheras a standalone
55 pre-RA AVL propagation pass allows us elide the consumption
56 of the pseudo register of 't0' then we can reduce scalar
57 register pressure.
58
59 - More AVL propagation opportunities:
60 A pre-RA pass is more flexible for AVL REG def-use chain,
61 thus we will get more potential AVL propagation as long as
62 it doesn't increase the scalar register pressure.
63 */
64
65 #define IN_TARGET_CODE 1
66 #define INCLUDE_ALGORITHM
67 #define INCLUDE_FUNCTIONAL
68 #define INCLUDE_ARRAY
69
70 #include "config.h"
71 #include "system.h"
72 #include "coretypes.h"
73 #include "tm.h"
74 #include "backend.h"
75 #include "rtl.h"
76 #include "target.h"
77 #include "tree-pass.h"
78 #include "df.h"
79 #include "rtl-ssa.h"
80 #include "cfgcleanup.h"
81 #include "insn-attr.h"
82 #include "tm-constrs.h"
83 #include "insn-opinit.h"
84
85 using namespace rtl_ssa;
86 using namespace riscv_vector;
87
88 enum avlprop_type
89 {
90 /* VLMAX AVL and tail agnostic candidates. */
91 AVLPROP_VLMAX_TA,
92 AVLPROP_NONE
93 };
94
95 /* dump helper functions */
96 static const char *
97 avlprop_type_to_str (enum avlprop_type type)
98 {
99 switch (type)
100 {
101 case AVLPROP_VLMAX_TA:
102 return "vlmax_ta";
103
104 default:
105 gcc_unreachable ();
106 }
107 }
108
109 /* Return true if the AVL of the INSN can be propagated. */
110 static bool
111 avl_can_be_propagated_p (rtx_insn *rinsn)
112 {
113 /* We can't do AVL propagation when the instruction is potentially
114 touching the element with i > AVL. So, we don't do AVL propagation
115 on these following situations:
116
117 vgather:
118 - The index of "vrgather dest, source, index" may pick up the
119 element which has index >= AVL, so we can't strip the elements
120 that has index >= AVL of source register.
121 vslide1down:
122 - The last element of vslide1down is AVL + 1 according to RVV ISA:
123 vstart <= i < vl-1 vd[i] = vs2[i+1] if v0.mask[i] enabled
124 - The last multiple elements of vslidedown can be the element
125 has index >= AVL according to RVV ISA:
126 0 <= i+OFFSET < VLMAX src[i] = vs2[i+OFFSET]
127 vstart <= i < vl vd[i] = src[i] if v0.mask[i] enabled.
128 vcompress:
129 - According to the ISA, the first vl elements of vector register
130 group vs2 should be extracted and packed for vcompress. And the
131 highest element of vs2 vector may be touched by the mask. For
132 example, given vlmax = 4 here.
133 v0 = 0b1000
134 v1 = {0x1, 0x2, 0x3, 0x4}
135 v2 = {0x5, 0x6, 0x7, 0x8}
136 vcompress v1, v2, v0 with avl = 4, v1 = {0x8, 0x2, 0x3, 0x4}.
137 vcompress v1, v2, v0 with avl = 2, v1 will be unchanged.
138 Thus, we cannot propagate avl of vcompress because it may has
139 semantics change to the result. */
140 return get_attr_type (rinsn) != TYPE_VGATHER
141 && get_attr_type (rinsn) != TYPE_VSLIDEDOWN
142 && get_attr_type (rinsn) != TYPE_VISLIDE1DOWN
143 && get_attr_type (rinsn) != TYPE_VFSLIDE1DOWN
144 && get_attr_type (rinsn) != TYPE_VCOMPRESS;
145 }
146
147 static bool
148 vlmax_ta_p (rtx_insn *rinsn)
149 {
150 return vlmax_avl_type_p (rinsn) && tail_agnostic_p (rinsn);
151 }
152
153 static machine_mode
154 get_insn_vtype_mode (rtx_insn *rinsn)
155 {
156 extract_insn_cached (rinsn);
157 int mode_idx = get_attr_mode_idx (rinsn);
158 gcc_assert (mode_idx != INVALID_ATTRIBUTE);
159 gcc_assert (mode_idx < recog_data.n_operands);
160 return GET_MODE (recog_data.operand[mode_idx]);
161 }
162
163 /* Return new pattern for AVL propagation.
164 Normally, we just replace AVL operand only for most
165 of the instructions. However, for instructions like
166 fault load which use AVL TYPE twice in the pattern which
167 will cause ICE in the later AVL TYPE change so we regenerate
168 the whole pattern for such instructions. */
169 static rtx
170 simplify_replace_avl (rtx_insn *rinsn, rtx new_avl)
171 {
172 /* Replace AVL operand. */
173 extract_insn_cached (rinsn);
174 rtx avl = recog_data.operand[get_attr_vl_op_idx (rinsn)];
175 int count = count_regno_occurrences (rinsn, REGNO (avl));
176 gcc_assert (count == 1);
177 rtx new_pat = simplify_replace_rtx (PATTERN (rinsn), avl, new_avl);
178 if (get_attr_type (rinsn) == TYPE_VLDFF
179 || get_attr_type (rinsn) == TYPE_VLSEGDFF)
180 new_pat
181 = gen_pred_fault_load (recog_data.operand_mode[0], recog_data.operand[0],
182 recog_data.operand[1], recog_data.operand[2],
183 recog_data.operand[3], new_avl,
184 recog_data.operand[5], recog_data.operand[6],
185 get_avl_type_rtx (avl_type::NONVLMAX));
186 else
187 new_pat = simplify_replace_rtx (PATTERN (rinsn), avl, new_avl);
188 return new_pat;
189 }
190
191 static void
192 simplify_replace_vlmax_avl (rtx_insn *rinsn, rtx new_avl)
193 {
194 if (dump_file && (dump_flags & TDF_DETAILS))
195 {
196 fprintf (dump_file, "\nPropagating AVL: ");
197 print_rtl_single (dump_file, new_avl);
198 fprintf (dump_file, "into: ");
199 print_rtl_single (dump_file, rinsn);
200 }
201 rtx new_pat = simplify_replace_avl (rinsn, new_avl);
202 validate_change_or_fail (rinsn, &PATTERN (rinsn), new_pat, false);
203
204 /* Change AVL TYPE into NONVLMAX if it is VLMAX. */
205 if (vlmax_avl_type_p (rinsn))
206 {
207 int index = get_attr_avl_type_idx (rinsn);
208 gcc_assert (index != INVALID_ATTRIBUTE);
209 gcc_assert (index < recog_data.n_operands);
210 validate_change_or_fail (rinsn, recog_data.operand_loc[index],
211 get_avl_type_rtx (avl_type::NONVLMAX), false);
212 }
213 if (dump_file && (dump_flags & TDF_DETAILS))
214 {
215 fprintf (dump_file, "Successfully to match this instruction: ");
216 print_rtl_single (dump_file, rinsn);
217 }
218 }
219
220 const pass_data pass_data_avlprop = {
221 RTL_PASS, /* type */
222 "avlprop", /* name */
223 OPTGROUP_NONE, /* optinfo_flags */
224 TV_NONE, /* tv_id */
225 0, /* properties_required */
226 0, /* properties_provided */
227 0, /* properties_destroyed */
228 0, /* todo_flags_start */
229 0, /* todo_flags_finish */
230 };
231
232 class pass_avlprop : public rtl_opt_pass
233 {
234 public:
235 pass_avlprop (gcc::context *ctxt) : rtl_opt_pass (pass_data_avlprop, ctxt) {}
236
237 /* opt_pass methods: */
238 virtual bool gate (function *) final override
239 {
240 return TARGET_VECTOR && optimize > 0;
241 }
242 virtual unsigned int execute (function *) final override;
243
244 private:
245 /* The AVL propagation instructions and corresponding preferred AVL.
246 It will be updated during the analysis. */
247 hash_map<insn_info *, rtx> *m_avl_propagations;
248
249 /* Potential feasible AVL propagation candidates. */
250 auto_vec<std::pair<enum avlprop_type, insn_info *>> m_candidates;
251
252 rtx get_preferred_avl (const std::pair<enum avlprop_type, insn_info *>) const;
253 rtx get_vlmax_ta_preferred_avl (insn_info *) const;
254 rtx get_nonvlmax_avl (insn_info *) const;
255
256 void avlprop_init (function *);
257 void avlprop_done (void);
258 }; // class pass_avlprop
259
260 void
261 pass_avlprop::avlprop_init (function *fn)
262 {
263 calculate_dominance_info (CDI_DOMINATORS);
264 df_analyze ();
265 crtl->ssa = new function_info (fn);
266 m_avl_propagations = new hash_map<insn_info *, rtx>;
267 }
268
269 void
270 pass_avlprop::avlprop_done (void)
271 {
272 free_dominance_info (CDI_DOMINATORS);
273 if (crtl->ssa->perform_pending_updates ())
274 cleanup_cfg (0);
275 delete crtl->ssa;
276 crtl->ssa = nullptr;
277 delete m_avl_propagations;
278 m_avl_propagations = NULL;
279 if (!m_candidates.is_empty ())
280 m_candidates.release ();
281 }
282
283 /* If we have a preferred AVL to propagate, return the AVL.
284 Otherwise, return NULL_RTX as we don't need have any preferred
285 AVL. */
286
287 rtx
288 pass_avlprop::get_preferred_avl (
289 const std::pair<enum avlprop_type, insn_info *> candidate) const
290 {
291 switch (candidate.first)
292 {
293 case AVLPROP_VLMAX_TA:
294 return get_vlmax_ta_preferred_avl (candidate.second);
295 default:
296 gcc_unreachable ();
297 }
298 return NULL_RTX;
299 }
300
301 /* This is a straight forward pattern ALWAYS in partial auto-vectorization:
302
303 VL = SELECT_AVL (AVL, ...)
304 V0 = MASK_LEN_LOAD (..., VL)
305 V1 = MASK_LEN_LOAD (..., VL)
306 V2 = V0 + V1 --- Missed LEN information.
307 MASK_LEN_STORE (..., V2, VL)
308
309 We prefer PLUS_EXPR (V0 + V1) instead of COND_LEN_ADD (V0, V1, dummy LEN)
310 because:
311
312 - Few code changes in Loop Vectorizer.
313 - Reuse the current clean flow of partial vectorization, That is, apply
314 predicate LEN or MASK into LOAD/STORE operations and other special
315 arithmetic operations (e.d. DIV), then do the whole vector register
316 operation if it DON'T affect the correctness.
317 Such flow is used by all other targets like x86, sve, s390, ... etc.
318 - PLUS_EXPR has better gimple optimizations than COND_LEN_ADD.
319
320 We propagate AVL from NON-VLMAX to VLMAX for gimple IR like PLUS_EXPR which
321 generates the VLMAX instruction due to missed LEN information. The later
322 VSETVL PASS will elided the redundant vsetvls.
323 */
324
325 rtx
326 pass_avlprop::get_vlmax_ta_preferred_avl (insn_info *insn) const
327 {
328 if (!avl_can_be_propagated_p (insn->rtl ()))
329 return NULL_RTX;
330 int sew = get_sew (insn->rtl ());
331 enum vlmul_type vlmul = get_vlmul (insn->rtl ());
332 int ratio = calculate_ratio (sew, vlmul);
333
334 rtx use_avl = NULL_RTX;
335 for (def_info *def : insn->defs ())
336 {
337 if (!is_a<set_info *> (def) || def->is_mem ())
338 return NULL_RTX;
339 const auto *set = dyn_cast<set_info *> (def);
340
341 /* FIXME: Stop AVL propagation if any USE is not a RVV real
342 instruction. It should be totally enough for vectorized codes since
343 they always locate at extended blocks.
344
345 TODO: We can extend PHI checking for intrinsic codes if it
346 necessary in the future. */
347 if (!set->is_local_to_ebb ())
348 return NULL_RTX;
349
350 for (use_info *use : set->nondebug_insn_uses ())
351 {
352 insn_info *use_insn = use->insn ();
353 if (!use_insn->can_be_optimized () || use_insn->is_asm ()
354 || use_insn->is_call () || use_insn->has_volatile_refs ()
355 || use_insn->has_pre_post_modify ()
356 || !has_vl_op (use_insn->rtl ())
357 || !avl_can_be_propagated_p (use_insn->rtl ()))
358 return NULL_RTX;
359
360 /* We should only propagate non-VLMAX AVL into VLMAX insn when
361 such insn potential tail elements (after propagation) are
362 not used. So, we should make sure the outcome of VLMAX insn
363 is not depend on. */
364 extract_insn_cached (use_insn->rtl ());
365 int merge_op_idx = get_attr_merge_op_idx (use_insn->rtl ());
366 gcc_assert (merge_op_idx == INVALID_ATTRIBUTE
367 || merge_op_idx < recog_data.n_operands);
368 if (merge_op_idx != INVALID_ATTRIBUTE
369 && !satisfies_constraint_vu (recog_data.operand[merge_op_idx])
370 && refers_to_regno_p (set->regno (),
371 recog_data.operand[merge_op_idx])
372 && !tail_agnostic_p (use_insn->rtl ()))
373 return NULL_RTX;
374
375 int new_sew = get_sew (use_insn->rtl ());
376 enum vlmul_type new_vlmul = get_vlmul (use_insn->rtl ());
377 int new_ratio = calculate_ratio (new_sew, new_vlmul);
378 if (new_ratio != ratio)
379 return NULL_RTX;
380
381 rtx new_use_avl = get_nonvlmax_avl (use_insn);
382 if (!new_use_avl || SUBREG_P (new_use_avl))
383 return NULL_RTX;
384 if (REG_P (new_use_avl))
385 {
386 resource_info resource = full_register (REGNO (new_use_avl));
387 def_lookup dl = crtl->ssa->find_def (resource, use_insn);
388 if (dl.matching_set ())
389 return NULL_RTX;
390 def_info *def1 = dl.prev_def (insn);
391 def_info *def2 = dl.prev_def (use_insn);
392 if (!def1 || !def2 || def1 != def2)
393 return NULL_RTX;
394 /* For vectorized codes, we always use SELECT_VL/MIN_EXPR to
395 calculate the loop len at the header of the loop.
396 We only allow AVL propagation for real instruction for now.
397 TODO: We may enhance it for intrinsic codes if it is necessary.
398 */
399 if (!def1->insn ()->is_real ())
400 return NULL_RTX;
401
402 /* FIXME: We only all AVL propagation within a block which should
403 be totally enough for vectorized codes.
404
405 TODO: We can enhance it here for intrinsic codes in the future
406 if it is necessary. */
407 if (def1->insn ()->bb () != insn->bb ()
408 && !dominated_by_p (CDI_DOMINATORS, insn->bb ()->cfg_bb (),
409 def1->insn ()->bb ()->cfg_bb ()))
410 return NULL_RTX;
411 if (def1->insn ()->bb () == insn->bb ()
412 && def1->insn ()->compare_with (insn) >= 0)
413 return NULL_RTX;
414 }
415
416 if (!use_avl)
417 use_avl = new_use_avl;
418 else if (!rtx_equal_p (use_avl, new_use_avl))
419 return NULL_RTX;
420 }
421 }
422
423 return use_avl;
424 }
425
426 /* Try to get the NONVLMAX AVL of the INSN.
427 INSN can be either NON-VLMAX AVL itself or VLMAX AVL INSN
428 before the PASS but has been propagated a NON-VLMAX AVL
429 in the before round propagation. */
430 rtx
431 pass_avlprop::get_nonvlmax_avl (insn_info *insn) const
432 {
433 if (m_avl_propagations->get (insn))
434 return (*m_avl_propagations->get (insn));
435 else if (nonvlmax_avl_type_p (insn->rtl ()))
436 {
437 extract_insn_cached (insn->rtl ());
438 return recog_data.operand[get_attr_vl_op_idx (insn->rtl ())];
439 }
440
441 return NULL_RTX;
442 }
443
444 /* Main entry point for this pass. */
445 unsigned int
446 pass_avlprop::execute (function *fn)
447 {
448 avlprop_init (fn);
449
450 /* Iterate the whole function in reverse order (which could speed the
451 convergence) to collect all potential candidates that could be AVL
452 propagated.
453
454 Note that: **NOT** all the candidates will be successfully AVL propagated.
455 */
456 for (bb_info *bb : crtl->ssa->reverse_bbs ())
457 {
458 for (insn_info *insn : bb->reverse_real_nondebug_insns ())
459 {
460 /* We only forward AVL to the instruction that has AVL/VL operand
461 and can be optimized in RTL_SSA level. */
462 if (!insn->can_be_optimized () || !has_vl_op (insn->rtl ()))
463 continue;
464
465 /* TODO: We only do AVL propagation for VLMAX AVL with tail
466 agnostic policy since we have missed-LEN information partial
467 autovectorization. We could add more AVL propagation
468 for intrinsic codes in the future. */
469 if (vlmax_ta_p (insn->rtl ()))
470 m_candidates.safe_push (std::make_pair (AVLPROP_VLMAX_TA, insn));
471 }
472 }
473
474 if (dump_file && (dump_flags & TDF_DETAILS))
475 {
476 fprintf (dump_file, "\nNumber of potential AVL propagations: %d\n",
477 m_candidates.length ());
478 for (const auto &candidate : m_candidates)
479 {
480 fprintf (dump_file, "\nAVL propagation type: %s\n",
481 avlprop_type_to_str (candidate.first));
482 print_rtl_single (dump_file, candidate.second->rtl ());
483 }
484 }
485
486 /* Go through all the candidates looking for AVL that we could propagate. */
487 bool change_p = true;
488 while (change_p)
489 {
490 change_p = false;
491 for (auto &candidate : m_candidates)
492 {
493 rtx new_avl = get_preferred_avl (candidate);
494 if (new_avl)
495 {
496 gcc_assert (!vlmax_avl_p (new_avl));
497 auto &update
498 = m_avl_propagations->get_or_insert (candidate.second);
499 change_p = !rtx_equal_p (update, new_avl);
500 update = new_avl;
501 }
502 }
503 }
504
505 if (dump_file && (dump_flags & TDF_DETAILS))
506 fprintf (dump_file, "\nNumber of successful AVL propagations: %d\n\n",
507 (int) m_avl_propagations->elements ());
508
509 for (const auto prop : *m_avl_propagations)
510 {
511 rtx_insn *rinsn = prop.first->rtl ();
512 simplify_replace_vlmax_avl (rinsn, prop.second);
513 }
514
515 if (rvv_vector_bits == RVV_VECTOR_BITS_ZVL && !TARGET_XTHEADVECTOR)
516 {
517 /* Simplify VLMAX AVL into immediate AVL.
518 E.g. Simplify this following case:
519
520 vsetvl a5, zero, e32, m1
521 vadd.vv
522
523 into:
524
525 vsetvl zero, 4, e32, m1
526 vadd.vv
527 if GET_MODE_NUNITS (RVVM1SImode) == 4. */
528 if (dump_file && (dump_flags & TDF_DETAILS))
529 fprintf (dump_file, "\nSimplifying VLMAX AVL into IMM AVL\n\n");
530 for (auto &candidate : m_candidates)
531 {
532 rtx_insn *rinsn = candidate.second->rtl ();
533 machine_mode vtype_mode = get_insn_vtype_mode (rinsn);
534 if (candidate.first == AVLPROP_VLMAX_TA
535 && !m_avl_propagations->get (candidate.second)
536 && imm_avl_p (vtype_mode))
537 {
538 rtx new_avl = gen_int_mode (GET_MODE_NUNITS (vtype_mode), Pmode);
539 simplify_replace_vlmax_avl (rinsn, new_avl);
540 }
541 }
542 }
543
544 avlprop_done ();
545 return 0;
546 }
547
548 rtl_opt_pass *
549 make_pass_avlprop (gcc::context *ctxt)
550 {
551 return new pass_avlprop (ctxt);
552 }