LLVM 19.0.0git
RISCVInsertVSETVLI.cpp
Go to the documentation of this file.
1//===- RISCVInsertVSETVLI.cpp - Insert VSETVLI instructions ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements a function pass that inserts VSETVLI instructions where
10// needed and expands the vl outputs of VLEFF/VLSEGFF to PseudoReadVL
11// instructions.
12//
13// This pass consists of 3 phases:
14//
15// Phase 1 collects how each basic block affects VL/VTYPE.
16//
17// Phase 2 uses the information from phase 1 to do a data flow analysis to
18// propagate the VL/VTYPE changes through the function. This gives us the
19// VL/VTYPE at the start of each basic block.
20//
21// Phase 3 inserts VSETVLI instructions in each basic block. Information from
22// phase 2 is used to prevent inserting a VSETVLI before the first vector
23// instruction in the block if possible.
24//
25//===----------------------------------------------------------------------===//
26
27#include "RISCV.h"
28#include "RISCVSubtarget.h"
29#include "llvm/ADT/Statistic.h"
34#include <queue>
35using namespace llvm;
36
37#define DEBUG_TYPE "riscv-insert-vsetvli"
38#define RISCV_INSERT_VSETVLI_NAME "RISC-V Insert VSETVLI pass"
39#define RISCV_COALESCE_VSETVLI_NAME "RISC-V Coalesce VSETVLI pass"
40
41STATISTIC(NumInsertedVSETVL, "Number of VSETVL inst inserted");
42STATISTIC(NumCoalescedVSETVL, "Number of VSETVL inst coalesced");
43
45 "riscv-disable-insert-vsetvl-phi-opt", cl::init(false), cl::Hidden,
46 cl::desc("Disable looking through phis when inserting vsetvlis."));
47
48namespace {
49
50/// Given a virtual register \p Reg, return the corresponding VNInfo for it.
51/// This should never return nullptr.
52static VNInfo *getVNInfoFromReg(Register Reg, const MachineInstr &MI,
53 const LiveIntervals *LIS) {
54 assert(Reg.isVirtual());
55 auto &LI = LIS->getInterval(Reg);
56 SlotIndex SI = LIS->getSlotIndexes()->getInstructionIndex(MI);
57 VNInfo *VNI = LI.getVNInfoBefore(SI);
58 assert(VNI);
59 return VNI;
60}
61
62static unsigned getVLOpNum(const MachineInstr &MI) {
63 return RISCVII::getVLOpNum(MI.getDesc());
64}
65
66static unsigned getSEWOpNum(const MachineInstr &MI) {
67 return RISCVII::getSEWOpNum(MI.getDesc());
68}
69
70static bool isVectorConfigInstr(const MachineInstr &MI) {
71 return MI.getOpcode() == RISCV::PseudoVSETVLI ||
72 MI.getOpcode() == RISCV::PseudoVSETVLIX0 ||
73 MI.getOpcode() == RISCV::PseudoVSETIVLI;
74}
75
76/// Return true if this is 'vsetvli x0, x0, vtype' which preserves
77/// VL and only sets VTYPE.
78static bool isVLPreservingConfig(const MachineInstr &MI) {
79 if (MI.getOpcode() != RISCV::PseudoVSETVLIX0)
80 return false;
81 assert(RISCV::X0 == MI.getOperand(1).getReg());
82 return RISCV::X0 == MI.getOperand(0).getReg();
83}
84
85static bool isFloatScalarMoveOrScalarSplatInstr(const MachineInstr &MI) {
86 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
87 default:
88 return false;
89 case RISCV::VFMV_S_F:
90 case RISCV::VFMV_V_F:
91 return true;
92 }
93}
94
95static bool isScalarExtractInstr(const MachineInstr &MI) {
96 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
97 default:
98 return false;
99 case RISCV::VMV_X_S:
100 case RISCV::VFMV_F_S:
101 return true;
102 }
103}
104
105static bool isScalarInsertInstr(const MachineInstr &MI) {
106 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
107 default:
108 return false;
109 case RISCV::VMV_S_X:
110 case RISCV::VFMV_S_F:
111 return true;
112 }
113}
114
115static bool isScalarSplatInstr(const MachineInstr &MI) {
116 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
117 default:
118 return false;
119 case RISCV::VMV_V_I:
120 case RISCV::VMV_V_X:
121 case RISCV::VFMV_V_F:
122 return true;
123 }
124}
125
126static bool isVSlideInstr(const MachineInstr &MI) {
127 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
128 default:
129 return false;
130 case RISCV::VSLIDEDOWN_VX:
131 case RISCV::VSLIDEDOWN_VI:
132 case RISCV::VSLIDEUP_VX:
133 case RISCV::VSLIDEUP_VI:
134 return true;
135 }
136}
137
138/// Get the EEW for a load or store instruction. Return std::nullopt if MI is
139/// not a load or store which ignores SEW.
140static std::optional<unsigned> getEEWForLoadStore(const MachineInstr &MI) {
141 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
142 default:
143 return std::nullopt;
144 case RISCV::VLE8_V:
145 case RISCV::VLSE8_V:
146 case RISCV::VSE8_V:
147 case RISCV::VSSE8_V:
148 return 8;
149 case RISCV::VLE16_V:
150 case RISCV::VLSE16_V:
151 case RISCV::VSE16_V:
152 case RISCV::VSSE16_V:
153 return 16;
154 case RISCV::VLE32_V:
155 case RISCV::VLSE32_V:
156 case RISCV::VSE32_V:
157 case RISCV::VSSE32_V:
158 return 32;
159 case RISCV::VLE64_V:
160 case RISCV::VLSE64_V:
161 case RISCV::VSE64_V:
162 case RISCV::VSSE64_V:
163 return 64;
164 }
165}
166
167static bool isNonZeroLoadImmediate(const MachineInstr &MI) {
168 return MI.getOpcode() == RISCV::ADDI &&
169 MI.getOperand(1).isReg() && MI.getOperand(2).isImm() &&
170 MI.getOperand(1).getReg() == RISCV::X0 &&
171 MI.getOperand(2).getImm() != 0;
172}
173
174/// Return true if this is an operation on mask registers. Note that
175/// this includes both arithmetic/logical ops and load/store (vlm/vsm).
176static bool isMaskRegOp(const MachineInstr &MI) {
177 if (!RISCVII::hasSEWOp(MI.getDesc().TSFlags))
178 return false;
179 const unsigned Log2SEW = MI.getOperand(getSEWOpNum(MI)).getImm();
180 // A Log2SEW of 0 is an operation on mask registers only.
181 return Log2SEW == 0;
182}
183
184/// Return true if the inactive elements in the result are entirely undefined.
185/// Note that this is different from "agnostic" as defined by the vector
186/// specification. Agnostic requires each lane to either be undisturbed, or
187/// take the value -1; no other value is allowed.
188static bool hasUndefinedMergeOp(const MachineInstr &MI) {
189
190 unsigned UseOpIdx;
191 if (!MI.isRegTiedToUseOperand(0, &UseOpIdx))
192 // If there is no passthrough operand, then the pass through
193 // lanes are undefined.
194 return true;
195
196 // All undefined passthrus should be $noreg: see
197 // RISCVDAGToDAGISel::doPeepholeNoRegPassThru
198 const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
199 return UseMO.getReg() == RISCV::NoRegister || UseMO.isUndef();
200}
201
202/// Which subfields of VL or VTYPE have values we need to preserve?
203struct DemandedFields {
204 // Some unknown property of VL is used. If demanded, must preserve entire
205 // value.
206 bool VLAny = false;
207 // Only zero vs non-zero is used. If demanded, can change non-zero values.
208 bool VLZeroness = false;
209 // What properties of SEW we need to preserve.
210 enum : uint8_t {
211 SEWEqual = 3, // The exact value of SEW needs to be preserved.
212 SEWGreaterThanOrEqual = 2, // SEW can be changed as long as it's greater
213 // than or equal to the original value.
214 SEWGreaterThanOrEqualAndLessThan64 =
215 1, // SEW can be changed as long as it's greater
216 // than or equal to the original value, but must be less
217 // than 64.
218 SEWNone = 0 // We don't need to preserve SEW at all.
219 } SEW = SEWNone;
220 bool LMUL = false;
221 bool SEWLMULRatio = false;
222 bool TailPolicy = false;
223 bool MaskPolicy = false;
224
225 // Return true if any part of VTYPE was used
226 bool usedVTYPE() const {
227 return SEW || LMUL || SEWLMULRatio || TailPolicy || MaskPolicy;
228 }
229
230 // Return true if any property of VL was used
231 bool usedVL() {
232 return VLAny || VLZeroness;
233 }
234
235 // Mark all VTYPE subfields and properties as demanded
236 void demandVTYPE() {
237 SEW = SEWEqual;
238 LMUL = true;
239 SEWLMULRatio = true;
240 TailPolicy = true;
241 MaskPolicy = true;
242 }
243
244 // Mark all VL properties as demanded
245 void demandVL() {
246 VLAny = true;
247 VLZeroness = true;
248 }
249
250 // Make this the result of demanding both the fields in this and B.
251 void doUnion(const DemandedFields &B) {
252 VLAny |= B.VLAny;
253 VLZeroness |= B.VLZeroness;
254 SEW = std::max(SEW, B.SEW);
255 LMUL |= B.LMUL;
256 SEWLMULRatio |= B.SEWLMULRatio;
257 TailPolicy |= B.TailPolicy;
258 MaskPolicy |= B.MaskPolicy;
259 }
260
261#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
262 /// Support for debugging, callable in GDB: V->dump()
263 LLVM_DUMP_METHOD void dump() const {
264 print(dbgs());
265 dbgs() << "\n";
266 }
267
268 /// Implement operator<<.
269 void print(raw_ostream &OS) const {
270 OS << "{";
271 OS << "VLAny=" << VLAny << ", ";
272 OS << "VLZeroness=" << VLZeroness << ", ";
273 OS << "SEW=";
274 switch (SEW) {
275 case SEWEqual:
276 OS << "SEWEqual";
277 break;
278 case SEWGreaterThanOrEqual:
279 OS << "SEWGreaterThanOrEqual";
280 break;
281 case SEWGreaterThanOrEqualAndLessThan64:
282 OS << "SEWGreaterThanOrEqualAndLessThan64";
283 break;
284 case SEWNone:
285 OS << "SEWNone";
286 break;
287 };
288 OS << ", ";
289 OS << "LMUL=" << LMUL << ", ";
290 OS << "SEWLMULRatio=" << SEWLMULRatio << ", ";
291 OS << "TailPolicy=" << TailPolicy << ", ";
292 OS << "MaskPolicy=" << MaskPolicy;
293 OS << "}";
294 }
295#endif
296};
297
298#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
300inline raw_ostream &operator<<(raw_ostream &OS, const DemandedFields &DF) {
301 DF.print(OS);
302 return OS;
303}
304#endif
305
306/// Return true if moving from CurVType to NewVType is
307/// indistinguishable from the perspective of an instruction (or set
308/// of instructions) which use only the Used subfields and properties.
309static bool areCompatibleVTYPEs(uint64_t CurVType, uint64_t NewVType,
310 const DemandedFields &Used) {
311 switch (Used.SEW) {
312 case DemandedFields::SEWNone:
313 break;
314 case DemandedFields::SEWEqual:
315 if (RISCVVType::getSEW(CurVType) != RISCVVType::getSEW(NewVType))
316 return false;
317 break;
318 case DemandedFields::SEWGreaterThanOrEqual:
319 if (RISCVVType::getSEW(NewVType) < RISCVVType::getSEW(CurVType))
320 return false;
321 break;
322 case DemandedFields::SEWGreaterThanOrEqualAndLessThan64:
323 if (RISCVVType::getSEW(NewVType) < RISCVVType::getSEW(CurVType) ||
324 RISCVVType::getSEW(NewVType) >= 64)
325 return false;
326 break;
327 }
328
329 if (Used.LMUL &&
330 RISCVVType::getVLMUL(CurVType) != RISCVVType::getVLMUL(NewVType))
331 return false;
332
333 if (Used.SEWLMULRatio) {
334 auto Ratio1 = RISCVVType::getSEWLMULRatio(RISCVVType::getSEW(CurVType),
335 RISCVVType::getVLMUL(CurVType));
336 auto Ratio2 = RISCVVType::getSEWLMULRatio(RISCVVType::getSEW(NewVType),
337 RISCVVType::getVLMUL(NewVType));
338 if (Ratio1 != Ratio2)
339 return false;
340 }
341
342 if (Used.TailPolicy && RISCVVType::isTailAgnostic(CurVType) !=
344 return false;
345 if (Used.MaskPolicy && RISCVVType::isMaskAgnostic(CurVType) !=
347 return false;
348 return true;
349}
350
351/// Return the fields and properties demanded by the provided instruction.
352DemandedFields getDemanded(const MachineInstr &MI, const RISCVSubtarget *ST) {
353 // Warning: This function has to work on both the lowered (i.e. post
354 // emitVSETVLIs) and pre-lowering forms. The main implication of this is
355 // that it can't use the value of a SEW, VL, or Policy operand as they might
356 // be stale after lowering.
357
358 // Most instructions don't use any of these subfeilds.
359 DemandedFields Res;
360 // Start conservative if registers are used
361 if (MI.isCall() || MI.isInlineAsm() ||
362 MI.readsRegister(RISCV::VL, /*TRI=*/nullptr))
363 Res.demandVL();
364 if (MI.isCall() || MI.isInlineAsm() ||
365 MI.readsRegister(RISCV::VTYPE, /*TRI=*/nullptr))
366 Res.demandVTYPE();
367 // Start conservative on the unlowered form too
368 uint64_t TSFlags = MI.getDesc().TSFlags;
369 if (RISCVII::hasSEWOp(TSFlags)) {
370 Res.demandVTYPE();
371 if (RISCVII::hasVLOp(TSFlags))
372 Res.demandVL();
373
374 // Behavior is independent of mask policy.
375 if (!RISCVII::usesMaskPolicy(TSFlags))
376 Res.MaskPolicy = false;
377 }
378
379 // Loads and stores with implicit EEW do not demand SEW or LMUL directly.
380 // They instead demand the ratio of the two which is used in computing
381 // EMUL, but which allows us the flexibility to change SEW and LMUL
382 // provided we don't change the ratio.
383 // Note: We assume that the instructions initial SEW is the EEW encoded
384 // in the opcode. This is asserted when constructing the VSETVLIInfo.
385 if (getEEWForLoadStore(MI)) {
386 Res.SEW = DemandedFields::SEWNone;
387 Res.LMUL = false;
388 }
389
390 // Store instructions don't use the policy fields.
391 if (RISCVII::hasSEWOp(TSFlags) && MI.getNumExplicitDefs() == 0) {
392 Res.TailPolicy = false;
393 Res.MaskPolicy = false;
394 }
395
396 // If this is a mask reg operation, it only cares about VLMAX.
397 // TODO: Possible extensions to this logic
398 // * Probably ok if available VLMax is larger than demanded
399 // * The policy bits can probably be ignored..
400 if (isMaskRegOp(MI)) {
401 Res.SEW = DemandedFields::SEWNone;
402 Res.LMUL = false;
403 }
404
405 // For vmv.s.x and vfmv.s.f, there are only two behaviors, VL = 0 and VL > 0.
406 if (isScalarInsertInstr(MI)) {
407 Res.LMUL = false;
408 Res.SEWLMULRatio = false;
409 Res.VLAny = false;
410 // For vmv.s.x and vfmv.s.f, if the merge operand is *undefined*, we don't
411 // need to preserve any other bits and are thus compatible with any larger,
412 // etype and can disregard policy bits. Warning: It's tempting to try doing
413 // this for any tail agnostic operation, but we can't as TA requires
414 // tail lanes to either be the original value or -1. We are writing
415 // unknown bits to the lanes here.
416 if (hasUndefinedMergeOp(MI)) {
417 if (isFloatScalarMoveOrScalarSplatInstr(MI) && !ST->hasVInstructionsF64())
418 Res.SEW = DemandedFields::SEWGreaterThanOrEqualAndLessThan64;
419 else
420 Res.SEW = DemandedFields::SEWGreaterThanOrEqual;
421 Res.TailPolicy = false;
422 }
423 }
424
425 // vmv.x.s, and vmv.f.s are unconditional and ignore everything except SEW.
426 if (isScalarExtractInstr(MI)) {
427 assert(!RISCVII::hasVLOp(TSFlags));
428 Res.LMUL = false;
429 Res.SEWLMULRatio = false;
430 Res.TailPolicy = false;
431 Res.MaskPolicy = false;
432 }
433
434 return Res;
435}
436
437/// Defines the abstract state with which the forward dataflow models the
438/// values of the VL and VTYPE registers after insertion.
439class VSETVLIInfo {
440 struct AVLDef {
441 // Every AVLDef should have a VNInfo.
442 const VNInfo *ValNo;
443 Register DefReg;
444 };
445 union {
446 AVLDef AVLRegDef;
447 unsigned AVLImm;
448 };
449
450 enum : uint8_t {
452 AVLIsReg,
453 AVLIsImm,
454 AVLIsVLMAX,
455 AVLIsIgnored,
456 Unknown,
457 } State = Uninitialized;
458
459 // Fields from VTYPE.
461 uint8_t SEW = 0;
462 uint8_t TailAgnostic : 1;
463 uint8_t MaskAgnostic : 1;
464 uint8_t SEWLMULRatioOnly : 1;
465
466public:
467 VSETVLIInfo()
468 : AVLImm(0), TailAgnostic(false), MaskAgnostic(false),
469 SEWLMULRatioOnly(false) {}
470
471 static VSETVLIInfo getUnknown() {
472 VSETVLIInfo Info;
473 Info.setUnknown();
474 return Info;
475 }
476
477 bool isValid() const { return State != Uninitialized; }
478 void setUnknown() { State = Unknown; }
479 bool isUnknown() const { return State == Unknown; }
480
483 AVLRegDef.ValNo = VNInfo;
484 AVLRegDef.DefReg = AVLReg;
485 State = AVLIsReg;
486 }
487
488 void setAVLImm(unsigned Imm) {
489 AVLImm = Imm;
490 State = AVLIsImm;
491 }
492
493 void setAVLVLMAX() { State = AVLIsVLMAX; }
494
495 void setAVLIgnored() { State = AVLIsIgnored; }
496
497 bool hasAVLImm() const { return State == AVLIsImm; }
498 bool hasAVLReg() const { return State == AVLIsReg; }
499 bool hasAVLVLMAX() const { return State == AVLIsVLMAX; }
500 bool hasAVLIgnored() const { return State == AVLIsIgnored; }
501 Register getAVLReg() const {
502 assert(hasAVLReg() && AVLRegDef.DefReg.isVirtual());
503 return AVLRegDef.DefReg;
504 }
505 unsigned getAVLImm() const {
506 assert(hasAVLImm());
507 return AVLImm;
508 }
509 const VNInfo *getAVLVNInfo() const {
510 assert(hasAVLReg());
511 return AVLRegDef.ValNo;
512 }
513 // Most AVLIsReg infos will have a single defining MachineInstr, unless it was
514 // a PHI node. In that case getAVLVNInfo()->def will point to the block
515 // boundary slot.
516 const MachineInstr *getAVLDefMI(const LiveIntervals *LIS) const {
517 assert(hasAVLReg());
518 auto *MI = LIS->getInstructionFromIndex(getAVLVNInfo()->def);
519 assert(!(getAVLVNInfo()->isPHIDef() && MI));
520 return MI;
521 }
522
523 void setAVL(VSETVLIInfo Info) {
524 assert(Info.isValid());
525 if (Info.isUnknown())
526 setUnknown();
527 else if (Info.hasAVLReg())
528 setAVLRegDef(Info.getAVLVNInfo(), Info.getAVLReg());
529 else if (Info.hasAVLVLMAX())
530 setAVLVLMAX();
531 else if (Info.hasAVLIgnored())
532 setAVLIgnored();
533 else {
534 assert(Info.hasAVLImm());
535 setAVLImm(Info.getAVLImm());
536 }
537 }
538
539 unsigned getSEW() const { return SEW; }
540 RISCVII::VLMUL getVLMUL() const { return VLMul; }
541 bool getTailAgnostic() const { return TailAgnostic; }
542 bool getMaskAgnostic() const { return MaskAgnostic; }
543
544 bool hasNonZeroAVL(const LiveIntervals *LIS) const {
545 if (hasAVLImm())
546 return getAVLImm() > 0;
547 if (hasAVLReg()) {
548 if (auto *DefMI = getAVLDefMI(LIS))
549 return isNonZeroLoadImmediate(*DefMI);
550 }
551 if (hasAVLVLMAX())
552 return true;
553 if (hasAVLIgnored())
554 return false;
555 return false;
556 }
557
558 bool hasEquallyZeroAVL(const VSETVLIInfo &Other,
559 const LiveIntervals *LIS) const {
560 if (hasSameAVL(Other))
561 return true;
562 return (hasNonZeroAVL(LIS) && Other.hasNonZeroAVL(LIS));
563 }
564
565 bool hasSameAVL(const VSETVLIInfo &Other) const {
566 if (hasAVLReg() && Other.hasAVLReg())
567 return getAVLVNInfo()->id == Other.getAVLVNInfo()->id &&
568 getAVLReg() == Other.getAVLReg();
569
570 if (hasAVLImm() && Other.hasAVLImm())
571 return getAVLImm() == Other.getAVLImm();
572
573 if (hasAVLVLMAX())
574 return Other.hasAVLVLMAX() && hasSameVLMAX(Other);
575
576 if (hasAVLIgnored())
577 return Other.hasAVLIgnored();
578
579 return false;
580 }
581
582 void setVTYPE(unsigned VType) {
583 assert(isValid() && !isUnknown() &&
584 "Can't set VTYPE for uninitialized or unknown");
585 VLMul = RISCVVType::getVLMUL(VType);
586 SEW = RISCVVType::getSEW(VType);
587 TailAgnostic = RISCVVType::isTailAgnostic(VType);
588 MaskAgnostic = RISCVVType::isMaskAgnostic(VType);
589 }
590 void setVTYPE(RISCVII::VLMUL L, unsigned S, bool TA, bool MA) {
591 assert(isValid() && !isUnknown() &&
592 "Can't set VTYPE for uninitialized or unknown");
593 VLMul = L;
594 SEW = S;
595 TailAgnostic = TA;
596 MaskAgnostic = MA;
597 }
598
599 void setVLMul(RISCVII::VLMUL VLMul) { this->VLMul = VLMul; }
600
601 unsigned encodeVTYPE() const {
602 assert(isValid() && !isUnknown() && !SEWLMULRatioOnly &&
603 "Can't encode VTYPE for uninitialized or unknown");
604 return RISCVVType::encodeVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
605 }
606
607 bool hasSEWLMULRatioOnly() const { return SEWLMULRatioOnly; }
608
609 bool hasSameVTYPE(const VSETVLIInfo &Other) const {
610 assert(isValid() && Other.isValid() &&
611 "Can't compare invalid VSETVLIInfos");
612 assert(!isUnknown() && !Other.isUnknown() &&
613 "Can't compare VTYPE in unknown state");
614 assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
615 "Can't compare when only LMUL/SEW ratio is valid.");
616 return std::tie(VLMul, SEW, TailAgnostic, MaskAgnostic) ==
617 std::tie(Other.VLMul, Other.SEW, Other.TailAgnostic,
618 Other.MaskAgnostic);
619 }
620
621 unsigned getSEWLMULRatio() const {
622 assert(isValid() && !isUnknown() &&
623 "Can't use VTYPE for uninitialized or unknown");
624 return RISCVVType::getSEWLMULRatio(SEW, VLMul);
625 }
626
627 // Check if the VTYPE for these two VSETVLIInfos produce the same VLMAX.
628 // Note that having the same VLMAX ensures that both share the same
629 // function from AVL to VL; that is, they must produce the same VL value
630 // for any given AVL value.
631 bool hasSameVLMAX(const VSETVLIInfo &Other) const {
632 assert(isValid() && Other.isValid() &&
633 "Can't compare invalid VSETVLIInfos");
634 assert(!isUnknown() && !Other.isUnknown() &&
635 "Can't compare VTYPE in unknown state");
636 return getSEWLMULRatio() == Other.getSEWLMULRatio();
637 }
638
639 bool hasCompatibleVTYPE(const DemandedFields &Used,
640 const VSETVLIInfo &Require) const {
641 return areCompatibleVTYPEs(Require.encodeVTYPE(), encodeVTYPE(), Used);
642 }
643
644 // Determine whether the vector instructions requirements represented by
645 // Require are compatible with the previous vsetvli instruction represented
646 // by this. MI is the instruction whose requirements we're considering.
647 bool isCompatible(const DemandedFields &Used, const VSETVLIInfo &Require,
648 const LiveIntervals *LIS) const {
649 assert(isValid() && Require.isValid() &&
650 "Can't compare invalid VSETVLIInfos");
651 assert(!Require.SEWLMULRatioOnly &&
652 "Expected a valid VTYPE for instruction!");
653 // Nothing is compatible with Unknown.
654 if (isUnknown() || Require.isUnknown())
655 return false;
656
657 // If only our VLMAX ratio is valid, then this isn't compatible.
658 if (SEWLMULRatioOnly)
659 return false;
660
661 if (Used.VLAny && !(hasSameAVL(Require) && hasSameVLMAX(Require)))
662 return false;
663
664 if (Used.VLZeroness && !hasEquallyZeroAVL(Require, LIS))
665 return false;
666
667 return hasCompatibleVTYPE(Used, Require);
668 }
669
670 bool operator==(const VSETVLIInfo &Other) const {
671 // Uninitialized is only equal to another Uninitialized.
672 if (!isValid())
673 return !Other.isValid();
674 if (!Other.isValid())
675 return !isValid();
676
677 // Unknown is only equal to another Unknown.
678 if (isUnknown())
679 return Other.isUnknown();
680 if (Other.isUnknown())
681 return isUnknown();
682
683 if (!hasSameAVL(Other))
684 return false;
685
686 // If the SEWLMULRatioOnly bits are different, then they aren't equal.
687 if (SEWLMULRatioOnly != Other.SEWLMULRatioOnly)
688 return false;
689
690 // If only the VLMAX is valid, check that it is the same.
691 if (SEWLMULRatioOnly)
692 return hasSameVLMAX(Other);
693
694 // If the full VTYPE is valid, check that it is the same.
695 return hasSameVTYPE(Other);
696 }
697
698 bool operator!=(const VSETVLIInfo &Other) const {
699 return !(*this == Other);
700 }
701
702 // Calculate the VSETVLIInfo visible to a block assuming this and Other are
703 // both predecessors.
704 VSETVLIInfo intersect(const VSETVLIInfo &Other) const {
705 // If the new value isn't valid, ignore it.
706 if (!Other.isValid())
707 return *this;
708
709 // If this value isn't valid, this must be the first predecessor, use it.
710 if (!isValid())
711 return Other;
712
713 // If either is unknown, the result is unknown.
714 if (isUnknown() || Other.isUnknown())
715 return VSETVLIInfo::getUnknown();
716
717 // If we have an exact, match return this.
718 if (*this == Other)
719 return *this;
720
721 // Not an exact match, but maybe the AVL and VLMAX are the same. If so,
722 // return an SEW/LMUL ratio only value.
723 if (hasSameAVL(Other) && hasSameVLMAX(Other)) {
724 VSETVLIInfo MergeInfo = *this;
725 MergeInfo.SEWLMULRatioOnly = true;
726 return MergeInfo;
727 }
728
729 // Otherwise the result is unknown.
730 return VSETVLIInfo::getUnknown();
731 }
732
733#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
734 /// Support for debugging, callable in GDB: V->dump()
735 LLVM_DUMP_METHOD void dump() const {
736 print(dbgs());
737 dbgs() << "\n";
738 }
739
740 /// Implement operator<<.
741 /// @{
742 void print(raw_ostream &OS) const {
743 OS << "{";
744 if (!isValid())
745 OS << "Uninitialized";
746 if (isUnknown())
747 OS << "unknown";
748 if (hasAVLReg())
749 OS << "AVLReg=" << (unsigned)getAVLReg();
750 if (hasAVLImm())
751 OS << "AVLImm=" << (unsigned)AVLImm;
752 if (hasAVLVLMAX())
753 OS << "AVLVLMAX";
754 if (hasAVLIgnored())
755 OS << "AVLIgnored";
756 OS << ", "
757 << "VLMul=" << (unsigned)VLMul << ", "
758 << "SEW=" << (unsigned)SEW << ", "
759 << "TailAgnostic=" << (bool)TailAgnostic << ", "
760 << "MaskAgnostic=" << (bool)MaskAgnostic << ", "
761 << "SEWLMULRatioOnly=" << (bool)SEWLMULRatioOnly << "}";
762 }
763#endif
764};
765
766#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
768inline raw_ostream &operator<<(raw_ostream &OS, const VSETVLIInfo &V) {
769 V.print(OS);
770 return OS;
771}
772#endif
773
774struct BlockData {
775 // The VSETVLIInfo that represents the VL/VTYPE settings on exit from this
776 // block. Calculated in Phase 2.
777 VSETVLIInfo Exit;
778
779 // The VSETVLIInfo that represents the VL/VTYPE settings from all predecessor
780 // blocks. Calculated in Phase 2, and used by Phase 3.
781 VSETVLIInfo Pred;
782
783 // Keeps track of whether the block is already in the queue.
784 bool InQueue = false;
785
786 BlockData() = default;
787};
788
789class RISCVInsertVSETVLI : public MachineFunctionPass {
790 const RISCVSubtarget *ST;
791 const TargetInstrInfo *TII;
794
795 std::vector<BlockData> BlockInfo;
796 std::queue<const MachineBasicBlock *> WorkList;
797
798public:
799 static char ID;
800
801 RISCVInsertVSETVLI() : MachineFunctionPass(ID) {}
802 bool runOnMachineFunction(MachineFunction &MF) override;
803
804 void getAnalysisUsage(AnalysisUsage &AU) const override {
805 AU.setPreservesCFG();
806
813
815 }
816
817 StringRef getPassName() const override { return RISCV_INSERT_VSETVLI_NAME; }
818
819private:
820 bool needVSETVLI(const MachineInstr &MI, const VSETVLIInfo &Require,
821 const VSETVLIInfo &CurInfo) const;
822 bool needVSETVLIPHI(const VSETVLIInfo &Require,
823 const MachineBasicBlock &MBB) const;
824 void insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
825 const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
826 void insertVSETVLI(MachineBasicBlock &MBB,
828 const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
829
830 void transferBefore(VSETVLIInfo &Info, const MachineInstr &MI) const;
831 void transferAfter(VSETVLIInfo &Info, const MachineInstr &MI) const;
832 bool computeVLVTYPEChanges(const MachineBasicBlock &MBB,
833 VSETVLIInfo &Info) const;
834 void computeIncomingVLVTYPE(const MachineBasicBlock &MBB);
835 void emitVSETVLIs(MachineBasicBlock &MBB);
836 void doPRE(MachineBasicBlock &MBB);
837 void insertReadVL(MachineBasicBlock &MBB);
838};
839
840class RISCVCoalesceVSETVLI : public MachineFunctionPass {
841public:
842 static char ID;
843 const RISCVSubtarget *ST;
844 const TargetInstrInfo *TII;
847
848 RISCVCoalesceVSETVLI() : MachineFunctionPass(ID) {}
849 bool runOnMachineFunction(MachineFunction &MF) override;
850
851 void getAnalysisUsage(AnalysisUsage &AU) const override {
852 AU.setPreservesCFG();
853
860
862 }
863
864 StringRef getPassName() const override { return RISCV_COALESCE_VSETVLI_NAME; }
865
866private:
867 bool coalesceVSETVLIs(MachineBasicBlock &MBB);
868};
869
870} // end anonymous namespace
871
872char RISCVInsertVSETVLI::ID = 0;
873
875 false, false)
876
877char RISCVCoalesceVSETVLI::ID = 0;
878
879INITIALIZE_PASS(RISCVCoalesceVSETVLI, "riscv-coalesce-vsetvli",
881
882// Return a VSETVLIInfo representing the changes made by this VSETVLI or
883// VSETIVLI instruction.
884static VSETVLIInfo getInfoForVSETVLI(const MachineInstr &MI,
886 VSETVLIInfo NewInfo;
887 if (MI.getOpcode() == RISCV::PseudoVSETIVLI) {
888 NewInfo.setAVLImm(MI.getOperand(1).getImm());
889 } else {
890 assert(MI.getOpcode() == RISCV::PseudoVSETVLI ||
891 MI.getOpcode() == RISCV::PseudoVSETVLIX0);
892 Register AVLReg = MI.getOperand(1).getReg();
893 assert((AVLReg != RISCV::X0 || MI.getOperand(0).getReg() != RISCV::X0) &&
894 "Can't handle X0, X0 vsetvli yet");
895 if (AVLReg == RISCV::X0)
896 NewInfo.setAVLVLMAX();
897 else
898 NewInfo.setAVLRegDef(getVNInfoFromReg(AVLReg, MI, LIS), AVLReg);
899 }
900 NewInfo.setVTYPE(MI.getOperand(2).getImm());
901
902 return NewInfo;
903}
904
905static unsigned computeVLMAX(unsigned VLEN, unsigned SEW,
906 RISCVII::VLMUL VLMul) {
907 auto [LMul, Fractional] = RISCVVType::decodeVLMUL(VLMul);
908 if (Fractional)
909 VLEN = VLEN / LMul;
910 else
911 VLEN = VLEN * LMul;
912 return VLEN/SEW;
913}
914
915static VSETVLIInfo computeInfoForInstr(const MachineInstr &MI, uint64_t TSFlags,
916 const RISCVSubtarget &ST,
917 const LiveIntervals *LIS) {
918 VSETVLIInfo InstrInfo;
919
920 bool TailAgnostic = true;
921 bool MaskAgnostic = true;
922 if (!hasUndefinedMergeOp(MI)) {
923 // Start with undisturbed.
924 TailAgnostic = false;
925 MaskAgnostic = false;
926
927 // If there is a policy operand, use it.
928 if (RISCVII::hasVecPolicyOp(TSFlags)) {
929 const MachineOperand &Op = MI.getOperand(MI.getNumExplicitOperands() - 1);
930 uint64_t Policy = Op.getImm();
932 "Invalid Policy Value");
933 TailAgnostic = Policy & RISCVII::TAIL_AGNOSTIC;
934 MaskAgnostic = Policy & RISCVII::MASK_AGNOSTIC;
935 }
936
937 // Some pseudo instructions force a tail agnostic policy despite having a
938 // tied def.
940 TailAgnostic = true;
941
942 if (!RISCVII::usesMaskPolicy(TSFlags))
943 MaskAgnostic = true;
944 }
945
946 RISCVII::VLMUL VLMul = RISCVII::getLMul(TSFlags);
947
948 unsigned Log2SEW = MI.getOperand(getSEWOpNum(MI)).getImm();
949 // A Log2SEW of 0 is an operation on mask registers only.
950 unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
951 assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
952
953 if (RISCVII::hasVLOp(TSFlags)) {
954 const MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
955 if (VLOp.isImm()) {
956 int64_t Imm = VLOp.getImm();
957 // Conver the VLMax sentintel to X0 register.
958 if (Imm == RISCV::VLMaxSentinel) {
959 // If we know the exact VLEN, see if we can use the constant encoding
960 // for the VLMAX instead. This reduces register pressure slightly.
961 const unsigned VLMAX = computeVLMAX(ST.getRealMaxVLen(), SEW, VLMul);
962 if (ST.getRealMinVLen() == ST.getRealMaxVLen() && VLMAX <= 31)
963 InstrInfo.setAVLImm(VLMAX);
964 else
965 InstrInfo.setAVLVLMAX();
966 }
967 else
968 InstrInfo.setAVLImm(Imm);
969 } else {
970 InstrInfo.setAVLRegDef(getVNInfoFromReg(VLOp.getReg(), MI, LIS),
971 VLOp.getReg());
972 }
973 } else {
974 assert(isScalarExtractInstr(MI));
975 // TODO: If we are more clever about x0,x0 insertion then we should be able
976 // to deduce that the VL is ignored based off of DemandedFields, and remove
977 // the AVLIsIgnored state. Then we can just use an arbitrary immediate AVL.
978 InstrInfo.setAVLIgnored();
979 }
980#ifndef NDEBUG
981 if (std::optional<unsigned> EEW = getEEWForLoadStore(MI)) {
982 assert(SEW == EEW && "Initial SEW doesn't match expected EEW");
983 }
984#endif
985 InstrInfo.setVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
986
987 // If AVL is defined by a vsetvli with the same VLMAX, we can replace the
988 // AVL operand with the AVL of the defining vsetvli. We avoid general
989 // register AVLs to avoid extending live ranges without being sure we can
990 // kill the original source reg entirely.
991 if (InstrInfo.hasAVLReg()) {
992 if (const MachineInstr *DefMI = InstrInfo.getAVLDefMI(LIS);
993 DefMI && isVectorConfigInstr(*DefMI)) {
994 VSETVLIInfo DefInstrInfo = getInfoForVSETVLI(*DefMI, LIS);
995 if (DefInstrInfo.hasSameVLMAX(InstrInfo) &&
996 (DefInstrInfo.hasAVLImm() || DefInstrInfo.hasAVLVLMAX()))
997 InstrInfo.setAVL(DefInstrInfo);
998 }
999 }
1000
1001 return InstrInfo;
1002}
1003
1004void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
1005 const VSETVLIInfo &Info,
1006 const VSETVLIInfo &PrevInfo) {
1007 DebugLoc DL = MI.getDebugLoc();
1008 insertVSETVLI(MBB, MachineBasicBlock::iterator(&MI), DL, Info, PrevInfo);
1009}
1010
1011void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB,
1013 const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo) {
1014
1015 ++NumInsertedVSETVL;
1016 if (PrevInfo.isValid() && !PrevInfo.isUnknown()) {
1017 // Use X0, X0 form if the AVL is the same and the SEW+LMUL gives the same
1018 // VLMAX.
1019 if (Info.hasSameAVL(PrevInfo) && Info.hasSameVLMAX(PrevInfo)) {
1020 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
1022 .addReg(RISCV::X0, RegState::Kill)
1023 .addImm(Info.encodeVTYPE())
1024 .addReg(RISCV::VL, RegState::Implicit);
1025 LIS->InsertMachineInstrInMaps(*MI);
1026 return;
1027 }
1028
1029 // If our AVL is a virtual register, it might be defined by a VSET(I)VLI. If
1030 // it has the same VLMAX we want and the last VL/VTYPE we observed is the
1031 // same, we can use the X0, X0 form.
1032 if (Info.hasSameVLMAX(PrevInfo) && Info.hasAVLReg()) {
1033 if (const MachineInstr *DefMI = Info.getAVLDefMI(LIS);
1034 DefMI && isVectorConfigInstr(*DefMI)) {
1035 VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI, LIS);
1036 if (DefInfo.hasSameAVL(PrevInfo) && DefInfo.hasSameVLMAX(PrevInfo)) {
1037 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
1039 .addReg(RISCV::X0, RegState::Kill)
1040 .addImm(Info.encodeVTYPE())
1041 .addReg(RISCV::VL, RegState::Implicit);
1042 LIS->InsertMachineInstrInMaps(*MI);
1043 return;
1044 }
1045 }
1046 }
1047 }
1048
1049 if (Info.hasAVLImm()) {
1050 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETIVLI))
1052 .addImm(Info.getAVLImm())
1053 .addImm(Info.encodeVTYPE());
1054 LIS->InsertMachineInstrInMaps(*MI);
1055 return;
1056 }
1057
1058 if (Info.hasAVLIgnored()) {
1059 // We can only use x0, x0 if there's no chance of the vtype change causing
1060 // the previous vl to become invalid.
1061 if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
1062 Info.hasSameVLMAX(PrevInfo)) {
1063 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
1065 .addReg(RISCV::X0, RegState::Kill)
1066 .addImm(Info.encodeVTYPE())
1067 .addReg(RISCV::VL, RegState::Implicit);
1068 LIS->InsertMachineInstrInMaps(*MI);
1069 return;
1070 }
1071 // Otherwise use an AVL of 1 to avoid depending on previous vl.
1072 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETIVLI))
1074 .addImm(1)
1075 .addImm(Info.encodeVTYPE());
1076 LIS->InsertMachineInstrInMaps(*MI);
1077 return;
1078 }
1079
1080 if (Info.hasAVLVLMAX()) {
1081 Register DestReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
1082 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
1084 .addReg(RISCV::X0, RegState::Kill)
1085 .addImm(Info.encodeVTYPE());
1086 LIS->InsertMachineInstrInMaps(*MI);
1087 LIS->createAndComputeVirtRegInterval(DestReg);
1088 return;
1089 }
1090
1091 Register AVLReg = Info.getAVLReg();
1092 MRI->constrainRegClass(AVLReg, &RISCV::GPRNoX0RegClass);
1093 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLI))
1095 .addReg(AVLReg)
1096 .addImm(Info.encodeVTYPE());
1097 LIS->InsertMachineInstrInMaps(*MI);
1098 // Normally the AVL's live range will already extend past the inserted vsetvli
1099 // because the pseudos below will already use the AVL. But this isn't always
1100 // the case, e.g. PseudoVMV_X_S doesn't have an AVL operand.
1101 LIS->getInterval(AVLReg).extendInBlock(
1102 LIS->getMBBStartIdx(&MBB), LIS->getInstructionIndex(*MI).getRegSlot());
1103}
1104
1106 auto [LMul, Fractional] = RISCVVType::decodeVLMUL(LMUL);
1107 return Fractional || LMul == 1;
1108}
1109
1110/// Return true if a VSETVLI is required to transition from CurInfo to Require
1111/// before MI.
1112bool RISCVInsertVSETVLI::needVSETVLI(const MachineInstr &MI,
1113 const VSETVLIInfo &Require,
1114 const VSETVLIInfo &CurInfo) const {
1115 assert(Require == computeInfoForInstr(MI, MI.getDesc().TSFlags, *ST, LIS));
1116
1117 if (!CurInfo.isValid() || CurInfo.isUnknown() || CurInfo.hasSEWLMULRatioOnly())
1118 return true;
1119
1120 DemandedFields Used = getDemanded(MI, ST);
1121
1122 // A slidedown/slideup with an *undefined* merge op can freely clobber
1123 // elements not copied from the source vector (e.g. masked off, tail, or
1124 // slideup's prefix). Notes:
1125 // * We can't modify SEW here since the slide amount is in units of SEW.
1126 // * VL=1 is special only because we have existing support for zero vs
1127 // non-zero VL. We could generalize this if we had a VL > C predicate.
1128 // * The LMUL1 restriction is for machines whose latency may depend on VL.
1129 // * As above, this is only legal for tail "undefined" not "agnostic".
1130 if (isVSlideInstr(MI) && Require.hasAVLImm() && Require.getAVLImm() == 1 &&
1131 isLMUL1OrSmaller(CurInfo.getVLMUL()) && hasUndefinedMergeOp(MI)) {
1132 Used.VLAny = false;
1133 Used.VLZeroness = true;
1134 Used.LMUL = false;
1135 Used.TailPolicy = false;
1136 }
1137
1138 // A tail undefined vmv.v.i/x or vfmv.v.f with VL=1 can be treated in the same
1139 // semantically as vmv.s.x. This is particularly useful since we don't have an
1140 // immediate form of vmv.s.x, and thus frequently use vmv.v.i in it's place.
1141 // Since a splat is non-constant time in LMUL, we do need to be careful to not
1142 // increase the number of active vector registers (unlike for vmv.s.x.)
1143 if (isScalarSplatInstr(MI) && Require.hasAVLImm() &&
1144 Require.getAVLImm() == 1 && isLMUL1OrSmaller(CurInfo.getVLMUL()) &&
1145 hasUndefinedMergeOp(MI)) {
1146 Used.LMUL = false;
1147 Used.SEWLMULRatio = false;
1148 Used.VLAny = false;
1149 if (isFloatScalarMoveOrScalarSplatInstr(MI) && !ST->hasVInstructionsF64())
1150 Used.SEW = DemandedFields::SEWGreaterThanOrEqualAndLessThan64;
1151 else
1152 Used.SEW = DemandedFields::SEWGreaterThanOrEqual;
1153 Used.TailPolicy = false;
1154 }
1155
1156 if (CurInfo.isCompatible(Used, Require, LIS))
1157 return false;
1158
1159 // We didn't find a compatible value. If our AVL is a virtual register,
1160 // it might be defined by a VSET(I)VLI. If it has the same VLMAX we need
1161 // and the last VL/VTYPE we observed is the same, we don't need a
1162 // VSETVLI here.
1163 if (Require.hasAVLReg() && CurInfo.hasCompatibleVTYPE(Used, Require)) {
1164 if (const MachineInstr *DefMI = Require.getAVLDefMI(LIS);
1165 DefMI && isVectorConfigInstr(*DefMI)) {
1166 VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI, LIS);
1167 if (DefInfo.hasSameAVL(CurInfo) && DefInfo.hasSameVLMAX(CurInfo))
1168 return false;
1169 }
1170 }
1171
1172 return true;
1173}
1174
1175// If we don't use LMUL or the SEW/LMUL ratio, then adjust LMUL so that we
1176// maintain the SEW/LMUL ratio. This allows us to eliminate VL toggles in more
1177// places.
1178static VSETVLIInfo adjustIncoming(VSETVLIInfo PrevInfo, VSETVLIInfo NewInfo,
1179 DemandedFields &Demanded) {
1180 VSETVLIInfo Info = NewInfo;
1181
1182 if (!Demanded.LMUL && !Demanded.SEWLMULRatio && PrevInfo.isValid() &&
1183 !PrevInfo.isUnknown()) {
1184 if (auto NewVLMul = RISCVVType::getSameRatioLMUL(
1185 PrevInfo.getSEW(), PrevInfo.getVLMUL(), Info.getSEW()))
1186 Info.setVLMul(*NewVLMul);
1187 Demanded.LMUL = true;
1188 }
1189
1190 return Info;
1191}
1192
1193// Given an incoming state reaching MI, minimally modifies that state so that it
1194// is compatible with MI. The resulting state is guaranteed to be semantically
1195// legal for MI, but may not be the state requested by MI.
1196void RISCVInsertVSETVLI::transferBefore(VSETVLIInfo &Info,
1197 const MachineInstr &MI) const {
1198 uint64_t TSFlags = MI.getDesc().TSFlags;
1199 if (!RISCVII::hasSEWOp(TSFlags))
1200 return;
1201
1202 const VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, *ST, LIS);
1203 assert(NewInfo.isValid() && !NewInfo.isUnknown());
1204 if (Info.isValid() && !needVSETVLI(MI, NewInfo, Info))
1205 return;
1206
1207 const VSETVLIInfo PrevInfo = Info;
1208 if (!Info.isValid() || Info.isUnknown())
1209 Info = NewInfo;
1210
1211 DemandedFields Demanded = getDemanded(MI, ST);
1212 const VSETVLIInfo IncomingInfo = adjustIncoming(PrevInfo, NewInfo, Demanded);
1213
1214 // If MI only demands that VL has the same zeroness, we only need to set the
1215 // AVL if the zeroness differs. This removes a vsetvli entirely if the types
1216 // match or allows use of cheaper avl preserving variant if VLMAX doesn't
1217 // change. If VLMAX might change, we couldn't use the 'vsetvli x0, x0, vtype"
1218 // variant, so we avoid the transform to prevent extending live range of an
1219 // avl register operand.
1220 // TODO: We can probably relax this for immediates.
1221 bool EquallyZero = IncomingInfo.hasEquallyZeroAVL(PrevInfo, LIS) &&
1222 IncomingInfo.hasSameVLMAX(PrevInfo);
1223 if (Demanded.VLAny || (Demanded.VLZeroness && !EquallyZero))
1224 Info.setAVL(IncomingInfo);
1225
1226 Info.setVTYPE(
1227 ((Demanded.LMUL || Demanded.SEWLMULRatio) ? IncomingInfo : Info)
1228 .getVLMUL(),
1229 ((Demanded.SEW || Demanded.SEWLMULRatio) ? IncomingInfo : Info).getSEW(),
1230 // Prefer tail/mask agnostic since it can be relaxed to undisturbed later
1231 // if needed.
1232 (Demanded.TailPolicy ? IncomingInfo : Info).getTailAgnostic() ||
1233 IncomingInfo.getTailAgnostic(),
1234 (Demanded.MaskPolicy ? IncomingInfo : Info).getMaskAgnostic() ||
1235 IncomingInfo.getMaskAgnostic());
1236
1237 // If we only knew the sew/lmul ratio previously, replace the VTYPE but keep
1238 // the AVL.
1239 if (Info.hasSEWLMULRatioOnly()) {
1240 VSETVLIInfo RatiolessInfo = IncomingInfo;
1241 RatiolessInfo.setAVL(Info);
1242 Info = RatiolessInfo;
1243 }
1244}
1245
1246// Given a state with which we evaluated MI (see transferBefore above for why
1247// this might be different that the state MI requested), modify the state to
1248// reflect the changes MI might make.
1249void RISCVInsertVSETVLI::transferAfter(VSETVLIInfo &Info,
1250 const MachineInstr &MI) const {
1251 if (isVectorConfigInstr(MI)) {
1252 Info = getInfoForVSETVLI(MI, LIS);
1253 return;
1254 }
1255
1257 // Update AVL to vl-output of the fault first load.
1258 assert(MI.getOperand(1).getReg().isVirtual());
1259 auto &LI = LIS->getInterval(MI.getOperand(1).getReg());
1260 SlotIndex SI = LIS->getSlotIndexes()->getInstructionIndex(MI).getRegSlot();
1261 VNInfo *VNI = LI.getVNInfoAt(SI);
1262 Info.setAVLRegDef(VNI, MI.getOperand(1).getReg());
1263 return;
1264 }
1265
1266 // If this is something that updates VL/VTYPE that we don't know about, set
1267 // the state to unknown.
1268 if (MI.isCall() || MI.isInlineAsm() ||
1269 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
1270 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
1271 Info = VSETVLIInfo::getUnknown();
1272}
1273
1274bool RISCVInsertVSETVLI::computeVLVTYPEChanges(const MachineBasicBlock &MBB,
1275 VSETVLIInfo &Info) const {
1276 bool HadVectorOp = false;
1277
1278 Info = BlockInfo[MBB.getNumber()].Pred;
1279 for (const MachineInstr &MI : MBB) {
1280 transferBefore(Info, MI);
1281
1282 if (isVectorConfigInstr(MI) || RISCVII::hasSEWOp(MI.getDesc().TSFlags))
1283 HadVectorOp = true;
1284
1285 transferAfter(Info, MI);
1286 }
1287
1288 return HadVectorOp;
1289}
1290
1291void RISCVInsertVSETVLI::computeIncomingVLVTYPE(const MachineBasicBlock &MBB) {
1292
1293 BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1294
1295 BBInfo.InQueue = false;
1296
1297 // Start with the previous entry so that we keep the most conservative state
1298 // we have ever found.
1299 VSETVLIInfo InInfo = BBInfo.Pred;
1300 if (MBB.pred_empty()) {
1301 // There are no predecessors, so use the default starting status.
1302 InInfo.setUnknown();
1303 } else {
1305 InInfo = InInfo.intersect(BlockInfo[P->getNumber()].Exit);
1306 }
1307
1308 // If we don't have any valid predecessor value, wait until we do.
1309 if (!InInfo.isValid())
1310 return;
1311
1312 // If no change, no need to rerun block
1313 if (InInfo == BBInfo.Pred)
1314 return;
1315
1316 BBInfo.Pred = InInfo;
1317 LLVM_DEBUG(dbgs() << "Entry state of " << printMBBReference(MBB)
1318 << " changed to " << BBInfo.Pred << "\n");
1319
1320 // Note: It's tempting to cache the state changes here, but due to the
1321 // compatibility checks performed a blocks output state can change based on
1322 // the input state. To cache, we'd have to add logic for finding
1323 // never-compatible state changes.
1324 VSETVLIInfo TmpStatus;
1325 computeVLVTYPEChanges(MBB, TmpStatus);
1326
1327 // If the new exit value matches the old exit value, we don't need to revisit
1328 // any blocks.
1329 if (BBInfo.Exit == TmpStatus)
1330 return;
1331
1332 BBInfo.Exit = TmpStatus;
1333 LLVM_DEBUG(dbgs() << "Exit state of " << printMBBReference(MBB)
1334 << " changed to " << BBInfo.Exit << "\n");
1335
1336 // Add the successors to the work list so we can propagate the changed exit
1337 // status.
1338 for (MachineBasicBlock *S : MBB.successors())
1339 if (!BlockInfo[S->getNumber()].InQueue) {
1340 BlockInfo[S->getNumber()].InQueue = true;
1341 WorkList.push(S);
1342 }
1343}
1344
1345// If we weren't able to prove a vsetvli was directly unneeded, it might still
1346// be unneeded if the AVL was a phi node where all incoming values are VL
1347// outputs from the last VSETVLI in their respective basic blocks.
1348bool RISCVInsertVSETVLI::needVSETVLIPHI(const VSETVLIInfo &Require,
1349 const MachineBasicBlock &MBB) const {
1351 return true;
1352
1353 if (!Require.hasAVLReg())
1354 return true;
1355
1356 // We need the AVL to have been produced by a PHI node in this basic block.
1357 const VNInfo *Valno = Require.getAVLVNInfo();
1358 if (!Valno->isPHIDef() || LIS->getMBBFromIndex(Valno->def) != &MBB)
1359 return true;
1360
1361 const LiveRange &LR = LIS->getInterval(Require.getAVLReg());
1362
1363 for (auto *PBB : MBB.predecessors()) {
1364 const VSETVLIInfo &PBBExit = BlockInfo[PBB->getNumber()].Exit;
1365
1366 // We need the PHI input to the be the output of a VSET(I)VLI.
1367 const VNInfo *Value = LR.getVNInfoBefore(LIS->getMBBEndIdx(PBB));
1368 if (!Value)
1369 return true;
1370 MachineInstr *DefMI = LIS->getInstructionFromIndex(Value->def);
1371 if (!DefMI || !isVectorConfigInstr(*DefMI))
1372 return true;
1373
1374 // We found a VSET(I)VLI make sure it matches the output of the
1375 // predecessor block.
1376 VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI, LIS);
1377 if (DefInfo != PBBExit)
1378 return true;
1379
1380 // Require has the same VL as PBBExit, so if the exit from the
1381 // predecessor has the VTYPE we are looking for we might be able
1382 // to avoid a VSETVLI.
1383 if (PBBExit.isUnknown() || !PBBExit.hasSameVTYPE(Require))
1384 return true;
1385 }
1386
1387 // If all the incoming values to the PHI checked out, we don't need
1388 // to insert a VSETVLI.
1389 return false;
1390}
1391
1392void RISCVInsertVSETVLI::emitVSETVLIs(MachineBasicBlock &MBB) {
1393 VSETVLIInfo CurInfo = BlockInfo[MBB.getNumber()].Pred;
1394 // Track whether the prefix of the block we've scanned is transparent
1395 // (meaning has not yet changed the abstract state).
1396 bool PrefixTransparent = true;
1397 for (MachineInstr &MI : MBB) {
1398 const VSETVLIInfo PrevInfo = CurInfo;
1399 transferBefore(CurInfo, MI);
1400
1401 // If this is an explicit VSETVLI or VSETIVLI, update our state.
1402 if (isVectorConfigInstr(MI)) {
1403 // Conservatively, mark the VL and VTYPE as live.
1404 assert(MI.getOperand(3).getReg() == RISCV::VL &&
1405 MI.getOperand(4).getReg() == RISCV::VTYPE &&
1406 "Unexpected operands where VL and VTYPE should be");
1407 MI.getOperand(3).setIsDead(false);
1408 MI.getOperand(4).setIsDead(false);
1409 PrefixTransparent = false;
1410 }
1411
1412 uint64_t TSFlags = MI.getDesc().TSFlags;
1413 if (RISCVII::hasSEWOp(TSFlags)) {
1414 if (PrevInfo != CurInfo) {
1415 // If this is the first implicit state change, and the state change
1416 // requested can be proven to produce the same register contents, we
1417 // can skip emitting the actual state change and continue as if we
1418 // had since we know the GPR result of the implicit state change
1419 // wouldn't be used and VL/VTYPE registers are correct. Note that
1420 // we *do* need to model the state as if it changed as while the
1421 // register contents are unchanged, the abstract model can change.
1422 if (!PrefixTransparent || needVSETVLIPHI(CurInfo, MBB))
1423 insertVSETVLI(MBB, MI, CurInfo, PrevInfo);
1424 PrefixTransparent = false;
1425 }
1426
1427 if (RISCVII::hasVLOp(TSFlags)) {
1428 MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1429 if (VLOp.isReg()) {
1430 Register Reg = VLOp.getReg();
1431 LiveInterval &LI = LIS->getInterval(Reg);
1432
1433 // Erase the AVL operand from the instruction.
1434 VLOp.setReg(RISCV::NoRegister);
1435 VLOp.setIsKill(false);
1437 LIS->shrinkToUses(&LI, &DeadMIs);
1438 // We might have separate components that need split due to
1439 // needVSETVLIPHI causing us to skip inserting a new VL def.
1441 LIS->splitSeparateComponents(LI, SplitLIs);
1442
1443 // If the AVL was an immediate > 31, then it would have been emitted
1444 // as an ADDI. However, the ADDI might not have been used in the
1445 // vsetvli, or a vsetvli might not have been emitted, so it may be
1446 // dead now.
1447 for (MachineInstr *DeadMI : DeadMIs) {
1448 if (!TII->isAddImmediate(*DeadMI, Reg))
1449 continue;
1450 LIS->RemoveMachineInstrFromMaps(*DeadMI);
1451 DeadMI->eraseFromParent();
1452 }
1453 }
1454 MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ false,
1455 /*isImp*/ true));
1456 }
1457 MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
1458 /*isImp*/ true));
1459 }
1460
1461 if (MI.isCall() || MI.isInlineAsm() ||
1462 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
1463 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
1464 PrefixTransparent = false;
1465
1466 transferAfter(CurInfo, MI);
1467 }
1468
1469 const auto &Info = BlockInfo[MBB.getNumber()];
1470 if (CurInfo != Info.Exit) {
1471 LLVM_DEBUG(dbgs() << "in block " << printMBBReference(MBB) << "\n");
1472 LLVM_DEBUG(dbgs() << " begin state: " << Info.Pred << "\n");
1473 LLVM_DEBUG(dbgs() << " expected end state: " << Info.Exit << "\n");
1474 LLVM_DEBUG(dbgs() << " actual end state: " << CurInfo << "\n");
1475 }
1476 assert(CurInfo == Info.Exit && "InsertVSETVLI dataflow invariant violated");
1477}
1478
1479/// Perform simple partial redundancy elimination of the VSETVLI instructions
1480/// we're about to insert by looking for cases where we can PRE from the
1481/// beginning of one block to the end of one of its predecessors. Specifically,
1482/// this is geared to catch the common case of a fixed length vsetvl in a single
1483/// block loop when it could execute once in the preheader instead.
1484void RISCVInsertVSETVLI::doPRE(MachineBasicBlock &MBB) {
1485 if (!BlockInfo[MBB.getNumber()].Pred.isUnknown())
1486 return;
1487
1488 MachineBasicBlock *UnavailablePred = nullptr;
1489 VSETVLIInfo AvailableInfo;
1490 for (MachineBasicBlock *P : MBB.predecessors()) {
1491 const VSETVLIInfo &PredInfo = BlockInfo[P->getNumber()].Exit;
1492 if (PredInfo.isUnknown()) {
1493 if (UnavailablePred)
1494 return;
1495 UnavailablePred = P;
1496 } else if (!AvailableInfo.isValid()) {
1497 AvailableInfo = PredInfo;
1498 } else if (AvailableInfo != PredInfo) {
1499 return;
1500 }
1501 }
1502
1503 // Unreachable, single pred, or full redundancy. Note that FRE is handled by
1504 // phase 3.
1505 if (!UnavailablePred || !AvailableInfo.isValid())
1506 return;
1507
1508 // If we don't know the exact VTYPE, we can't copy the vsetvli to the exit of
1509 // the unavailable pred.
1510 if (AvailableInfo.hasSEWLMULRatioOnly())
1511 return;
1512
1513 // Critical edge - TODO: consider splitting?
1514 if (UnavailablePred->succ_size() != 1)
1515 return;
1516
1517 // If the AVL value is a register (other than our VLMAX sentinel),
1518 // we need to prove the value is available at the point we're going
1519 // to insert the vsetvli at.
1520 if (AvailableInfo.hasAVLReg()) {
1521 SlotIndex SI = AvailableInfo.getAVLVNInfo()->def;
1522 // This is an inline dominance check which covers the case of
1523 // UnavailablePred being the preheader of a loop.
1524 if (LIS->getMBBFromIndex(SI) != UnavailablePred)
1525 return;
1526 if (!UnavailablePred->terminators().empty() &&
1527 SI >= LIS->getInstructionIndex(*UnavailablePred->getFirstTerminator()))
1528 return;
1529 }
1530
1531 // If the AVL isn't used in its predecessors then bail, since we have no AVL
1532 // to insert a vsetvli with.
1533 if (AvailableInfo.hasAVLIgnored())
1534 return;
1535
1536 // Model the effect of changing the input state of the block MBB to
1537 // AvailableInfo. We're looking for two issues here; one legality,
1538 // one profitability.
1539 // 1) If the block doesn't use some of the fields from VL or VTYPE, we
1540 // may hit the end of the block with a different end state. We can
1541 // not make this change without reflowing later blocks as well.
1542 // 2) If we don't actually remove a transition, inserting a vsetvli
1543 // into the predecessor block would be correct, but unprofitable.
1544 VSETVLIInfo OldInfo = BlockInfo[MBB.getNumber()].Pred;
1545 VSETVLIInfo CurInfo = AvailableInfo;
1546 int TransitionsRemoved = 0;
1547 for (const MachineInstr &MI : MBB) {
1548 const VSETVLIInfo LastInfo = CurInfo;
1549 const VSETVLIInfo LastOldInfo = OldInfo;
1550 transferBefore(CurInfo, MI);
1551 transferBefore(OldInfo, MI);
1552 if (CurInfo == LastInfo)
1553 TransitionsRemoved++;
1554 if (LastOldInfo == OldInfo)
1555 TransitionsRemoved--;
1556 transferAfter(CurInfo, MI);
1557 transferAfter(OldInfo, MI);
1558 if (CurInfo == OldInfo)
1559 // Convergence. All transitions after this must match by construction.
1560 break;
1561 }
1562 if (CurInfo != OldInfo || TransitionsRemoved <= 0)
1563 // Issues 1 and 2 above
1564 return;
1565
1566 // Finally, update both data flow state and insert the actual vsetvli.
1567 // Doing both keeps the code in sync with the dataflow results, which
1568 // is critical for correctness of phase 3.
1569 auto OldExit = BlockInfo[UnavailablePred->getNumber()].Exit;
1570 LLVM_DEBUG(dbgs() << "PRE VSETVLI from " << MBB.getName() << " to "
1571 << UnavailablePred->getName() << " with state "
1572 << AvailableInfo << "\n");
1573 BlockInfo[UnavailablePred->getNumber()].Exit = AvailableInfo;
1574 BlockInfo[MBB.getNumber()].Pred = AvailableInfo;
1575
1576 // Note there's an implicit assumption here that terminators never use
1577 // or modify VL or VTYPE. Also, fallthrough will return end().
1578 auto InsertPt = UnavailablePred->getFirstInstrTerminator();
1579 insertVSETVLI(*UnavailablePred, InsertPt,
1580 UnavailablePred->findDebugLoc(InsertPt),
1581 AvailableInfo, OldExit);
1582}
1583
1584// Return true if we can mutate PrevMI to match MI without changing any the
1585// fields which would be observed.
1586static bool canMutatePriorConfig(const MachineInstr &PrevMI,
1587 const MachineInstr &MI,
1588 const DemandedFields &Used,
1589 const MachineRegisterInfo &MRI,
1590 const LiveIntervals *LIS) {
1591 // If the VL values aren't equal, return false if either a) the former is
1592 // demanded, or b) we can't rewrite the former to be the later for
1593 // implementation reasons.
1594 if (!isVLPreservingConfig(MI)) {
1595 if (Used.VLAny)
1596 return false;
1597
1598 if (Used.VLZeroness) {
1599 if (isVLPreservingConfig(PrevMI))
1600 return false;
1601 if (!getInfoForVSETVLI(PrevMI, LIS)
1602 .hasEquallyZeroAVL(getInfoForVSETVLI(MI, LIS), LIS))
1603 return false;
1604 }
1605
1606 auto &AVL = MI.getOperand(1);
1607 auto &PrevAVL = PrevMI.getOperand(1);
1608
1609 // If the AVL is a register, we need to make sure MI's AVL dominates PrevMI.
1610 // For now just check that PrevMI uses the same virtual register.
1611 if (AVL.isReg() && AVL.getReg() != RISCV::X0 &&
1612 (!MRI.hasOneDef(AVL.getReg()) || !PrevAVL.isReg() ||
1613 PrevAVL.getReg() != AVL.getReg()))
1614 return false;
1615 }
1616
1617 assert(PrevMI.getOperand(2).isImm() && MI.getOperand(2).isImm());
1618 auto PriorVType = PrevMI.getOperand(2).getImm();
1619 auto VType = MI.getOperand(2).getImm();
1620 return areCompatibleVTYPEs(PriorVType, VType, Used);
1621}
1622
1623bool RISCVCoalesceVSETVLI::coalesceVSETVLIs(MachineBasicBlock &MBB) {
1624 MachineInstr *NextMI = nullptr;
1625 // We can have arbitrary code in successors, so VL and VTYPE
1626 // must be considered demanded.
1627 DemandedFields Used;
1628 Used.demandVL();
1629 Used.demandVTYPE();
1631 for (MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend())) {
1632
1633 if (!isVectorConfigInstr(MI)) {
1634 Used.doUnion(getDemanded(MI, ST));
1635 if (MI.isCall() || MI.isInlineAsm() ||
1636 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
1637 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
1638 NextMI = nullptr;
1639 continue;
1640 }
1641
1642 if (!MI.getOperand(0).isDead())
1643 Used.demandVL();
1644
1645 if (NextMI) {
1646 if (!Used.usedVL() && !Used.usedVTYPE()) {
1647 ToDelete.push_back(&MI);
1648 // Leave NextMI unchanged
1649 continue;
1650 }
1651
1652 if (canMutatePriorConfig(MI, *NextMI, Used, *MRI, LIS)) {
1653 if (!isVLPreservingConfig(*NextMI)) {
1654 Register DefReg = NextMI->getOperand(0).getReg();
1655
1656 MI.getOperand(0).setReg(DefReg);
1657 MI.getOperand(0).setIsDead(false);
1658
1659 // The def of DefReg moved to MI, so extend the LiveInterval up to
1660 // it.
1661 if (DefReg.isVirtual()) {
1662 LiveInterval &DefLI = LIS->getInterval(DefReg);
1663 SlotIndex MISlot = LIS->getInstructionIndex(MI).getRegSlot();
1664 VNInfo *DefVNI = DefLI.getVNInfoAt(DefLI.beginIndex());
1665 LiveInterval::Segment S(MISlot, DefLI.beginIndex(), DefVNI);
1666 DefLI.addSegment(S);
1667 DefVNI->def = MISlot;
1668 // Mark DefLI as spillable if it was previously unspillable
1669 DefLI.setWeight(0);
1670
1671 // DefReg may have had no uses, in which case we need to shrink
1672 // the LiveInterval up to MI.
1673 LIS->shrinkToUses(&DefLI);
1674 }
1675
1676 Register OldVLReg;
1677 if (MI.getOperand(1).isReg())
1678 OldVLReg = MI.getOperand(1).getReg();
1679 if (NextMI->getOperand(1).isImm())
1680 MI.getOperand(1).ChangeToImmediate(NextMI->getOperand(1).getImm());
1681 else
1682 MI.getOperand(1).ChangeToRegister(NextMI->getOperand(1).getReg(), false);
1683
1684 // Clear NextMI's AVL early so we're not counting it as a use.
1685 if (NextMI->getOperand(1).isReg())
1686 NextMI->getOperand(1).setReg(RISCV::NoRegister);
1687
1688 if (OldVLReg && OldVLReg.isVirtual()) {
1689 // NextMI no longer uses OldVLReg so shrink its LiveInterval.
1690 LIS->shrinkToUses(&LIS->getInterval(OldVLReg));
1691
1692 MachineInstr *VLOpDef = MRI->getUniqueVRegDef(OldVLReg);
1693 if (VLOpDef && TII->isAddImmediate(*VLOpDef, OldVLReg) &&
1694 MRI->use_nodbg_empty(OldVLReg)) {
1695 VLOpDef->eraseFromParent();
1696 LIS->removeInterval(OldVLReg);
1697 }
1698 }
1699 MI.setDesc(NextMI->getDesc());
1700 }
1701 MI.getOperand(2).setImm(NextMI->getOperand(2).getImm());
1702 ToDelete.push_back(NextMI);
1703 // fallthrough
1704 }
1705 }
1706 NextMI = &MI;
1707 Used = getDemanded(MI, ST);
1708 }
1709
1710 NumCoalescedVSETVL += ToDelete.size();
1711 for (auto *MI : ToDelete) {
1712 LIS->RemoveMachineInstrFromMaps(*MI);
1713 MI->eraseFromParent();
1714 }
1715
1716 return !ToDelete.empty();
1717}
1718
1719void RISCVInsertVSETVLI::insertReadVL(MachineBasicBlock &MBB) {
1720 for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
1721 MachineInstr &MI = *I++;
1723 Register VLOutput = MI.getOperand(1).getReg();
1724 assert(VLOutput.isVirtual());
1725 if (!MI.getOperand(1).isDead()) {
1726 auto ReadVLMI = BuildMI(MBB, I, MI.getDebugLoc(),
1727 TII->get(RISCV::PseudoReadVL), VLOutput);
1728 // Move the LiveInterval's definition down to PseudoReadVL.
1729 SlotIndex NewDefSI =
1730 LIS->InsertMachineInstrInMaps(*ReadVLMI).getRegSlot();
1731 LiveInterval &DefLI = LIS->getInterval(VLOutput);
1732 VNInfo *DefVNI = DefLI.getVNInfoAt(DefLI.beginIndex());
1733 DefLI.removeSegment(DefLI.beginIndex(), NewDefSI);
1734 DefVNI->def = NewDefSI;
1735 }
1736 // We don't use the vl output of the VLEFF/VLSEGFF anymore.
1737 MI.getOperand(1).setReg(RISCV::X0);
1738 }
1739 }
1740}
1741
1742bool RISCVInsertVSETVLI::runOnMachineFunction(MachineFunction &MF) {
1743 // Skip if the vector extension is not enabled.
1745 if (!ST->hasVInstructions())
1746 return false;
1747
1748 LLVM_DEBUG(dbgs() << "Entering InsertVSETVLI for " << MF.getName() << "\n");
1749
1750 TII = ST->getInstrInfo();
1751 MRI = &MF.getRegInfo();
1752 LIS = &getAnalysis<LiveIntervals>();
1753
1754 assert(BlockInfo.empty() && "Expect empty block infos");
1755 BlockInfo.resize(MF.getNumBlockIDs());
1756
1757 bool HaveVectorOp = false;
1758
1759 // Phase 1 - determine how VL/VTYPE are affected by the each block.
1760 for (const MachineBasicBlock &MBB : MF) {
1761 VSETVLIInfo TmpStatus;
1762 HaveVectorOp |= computeVLVTYPEChanges(MBB, TmpStatus);
1763 // Initial exit state is whatever change we found in the block.
1764 BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1765 BBInfo.Exit = TmpStatus;
1766 LLVM_DEBUG(dbgs() << "Initial exit state of " << printMBBReference(MBB)
1767 << " is " << BBInfo.Exit << "\n");
1768
1769 }
1770
1771 // If we didn't find any instructions that need VSETVLI, we're done.
1772 if (!HaveVectorOp) {
1773 BlockInfo.clear();
1774 return false;
1775 }
1776
1777 // Phase 2 - determine the exit VL/VTYPE from each block. We add all
1778 // blocks to the list here, but will also add any that need to be revisited
1779 // during Phase 2 processing.
1780 for (const MachineBasicBlock &MBB : MF) {
1781 WorkList.push(&MBB);
1782 BlockInfo[MBB.getNumber()].InQueue = true;
1783 }
1784 while (!WorkList.empty()) {
1785 const MachineBasicBlock &MBB = *WorkList.front();
1786 WorkList.pop();
1787 computeIncomingVLVTYPE(MBB);
1788 }
1789
1790 // Perform partial redundancy elimination of vsetvli transitions.
1791 for (MachineBasicBlock &MBB : MF)
1792 doPRE(MBB);
1793
1794 // Phase 3 - add any vsetvli instructions needed in the block. Use the
1795 // Phase 2 information to avoid adding vsetvlis before the first vector
1796 // instruction in the block if the VL/VTYPE is satisfied by its
1797 // predecessors.
1798 for (MachineBasicBlock &MBB : MF)
1799 emitVSETVLIs(MBB);
1800
1801 // Insert PseudoReadVL after VLEFF/VLSEGFF and replace it with the vl output
1802 // of VLEFF/VLSEGFF.
1803 for (MachineBasicBlock &MBB : MF)
1804 insertReadVL(MBB);
1805
1806 BlockInfo.clear();
1807 return HaveVectorOp;
1808}
1809
1810/// Returns an instance of the Insert VSETVLI pass.
1812 return new RISCVInsertVSETVLI();
1813}
1814
1815// Now that all vsetvlis are explicit, go through and do block local
1816// DSE and peephole based demanded fields based transforms. Note that
1817// this *must* be done outside the main dataflow so long as we allow
1818// any cross block analysis within the dataflow. We can't have both
1819// demanded fields based mutation and non-local analysis in the
1820// dataflow at the same time without introducing inconsistencies.
1821bool RISCVCoalesceVSETVLI::runOnMachineFunction(MachineFunction &MF) {
1822 // Skip if the vector extension is not enabled.
1823 ST = &MF.getSubtarget<RISCVSubtarget>();
1824 if (!ST->hasVInstructions())
1825 return false;
1826 TII = ST->getInstrInfo();
1827 MRI = &MF.getRegInfo();
1828 LIS = &getAnalysis<LiveIntervals>();
1829
1830 bool Changed = false;
1831 for (MachineBasicBlock &MBB : MF)
1832 Changed |= coalesceVSETVLIs(MBB);
1833
1834 return Changed;
1835}
1836
1838 return new RISCVCoalesceVSETVLI();
1839}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder MachineInstrBuilder & DefMI
aarch64 promote const
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define LLVM_ATTRIBUTE_USED
Definition: Compiler.h:151
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:537
#define LLVM_DEBUG(X)
Definition: Debug.h:101
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1291
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static ValueLatticeElement intersect(const ValueLatticeElement &A, const ValueLatticeElement &B)
Combine two sets of facts about the same value into a single set of facts.
#define I(x, y, z)
Definition: MD5.cpp:58
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
NewInfo setVTYPE(MI.getOperand(2).getImm())
static VSETVLIInfo computeInfoForInstr(const MachineInstr &MI, uint64_t TSFlags, const RISCVSubtarget &ST, const LiveIntervals *LIS)
Register AVLReg
#define RISCV_COALESCE_VSETVLI_NAME
assert((AVLReg !=RISCV::X0||MI.getOperand(0).getReg() !=RISCV::X0) &&"Can't handle X0, X0 vsetvli yet")
static unsigned computeVLMAX(unsigned VLEN, unsigned SEW, RISCVII::VLMUL VLMul)
#define RISCV_INSERT_VSETVLI_NAME
static VSETVLIInfo adjustIncoming(VSETVLIInfo PrevInfo, VSETVLIInfo NewInfo, DemandedFields &Demanded)
else NewInfo setAVLRegDef(getVNInfoFromReg(AVLReg, MI, LIS), AVLReg)
static bool isLMUL1OrSmaller(RISCVII::VLMUL LMUL)
static cl::opt< bool > DisableInsertVSETVLPHIOpt("riscv-disable-insert-vsetvl-phi-opt", cl::init(false), cl::Hidden, cl::desc("Disable looking through phis when inserting vsetvlis."))
#define DEBUG_TYPE
static bool canMutatePriorConfig(const MachineInstr &PrevMI, const MachineInstr &MI, const DemandedFields &Used, const MachineRegisterInfo &MRI, const LiveIntervals *LIS)
return NewInfo
INITIALIZE_PASS(RISCVInsertVSETVLI, DEBUG_TYPE, RISCV_INSERT_VSETVLI_NAME, false, false) char RISCVCoalesceVSETVLI const LiveIntervals * LIS
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
raw_pwrite_stream & OS
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
BlockData()=default
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:269
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:33
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:687
void setWeight(float Value)
Definition: LiveInterval.h:721
This class represents the liveness of a register, stack slot, etc.
Definition: LiveInterval.h:157
iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarilly including Idx,...
Definition: LiveInterval.h:429
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
Definition: LiveInterval.h:385
void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified interval from this live range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Definition: LiveInterval.h:421
reverse_iterator rend()
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
unsigned succ_size() const
DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
iterator_range< iterator > terminators()
iterator_range< succ_iterator > successors()
instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
reverse_iterator rbegin()
iterator_range< pred_iterator > predecessors()
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:555
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:568
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:68
SlotIndexes pass.
Definition: SlotIndexes.h:300
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
TargetInstrInfo - Interface to description of machine instruction set.
VNInfo - Value Number Information.
Definition: LiveInterval.h:53
SlotIndex def
The index of the defining instruction.
Definition: LiveInterval.h:61
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
Definition: LiveInterval.h:78
LLVM Value Representation.
Definition: Value.h:74
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
TargetPassConfig.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
static bool usesMaskPolicy(uint64_t TSFlags)
static unsigned getVLOpNum(const MCInstrDesc &Desc)
static bool doesForceTailAgnostic(uint64_t TSFlags)
static VLMUL getLMul(uint64_t TSFlags)
static bool hasVLOp(uint64_t TSFlags)
static bool hasVecPolicyOp(uint64_t TSFlags)
static unsigned getSEWOpNum(const MCInstrDesc &Desc)
static bool hasSEWOp(uint64_t TSFlags)
static bool isTailAgnostic(unsigned VType)
static RISCVII::VLMUL getVLMUL(unsigned VType)
std::pair< unsigned, bool > decodeVLMUL(RISCVII::VLMUL VLMUL)
unsigned getSEWLMULRatio(unsigned SEW, RISCVII::VLMUL VLMul)
static bool isMaskAgnostic(unsigned VType)
static bool isValidSEW(unsigned SEW)
unsigned encodeVTYPE(RISCVII::VLMUL VLMUL, unsigned SEW, bool TailAgnostic, bool MaskAgnostic)
static unsigned getSEW(unsigned VType)
std::optional< RISCVII::VLMUL > getSameRatioLMUL(unsigned SEW, RISCVII::VLMUL VLMUL, unsigned EEW)
unsigned getRVVMCOpcode(unsigned RVVPseudoOpcode)
bool isFaultFirstLoad(const MachineInstr &MI)
static constexpr int64_t VLMaxSentinel
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Define
Register definition.
@ Kill
The last use of a register.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Uninitialized
Definition: Threading.h:61
bool operator!=(uint64_t V1, const APInt &V2)
Definition: APInt.h:2050
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createRISCVInsertVSETVLIPass()
Returns an instance of the Insert VSETVLI pass.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:293
FunctionPass * createRISCVCoalesceVSETVLIPass()
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
Status intersect(const Status &S) const
This represents a simple continuous liveness interval for a value.
Definition: LiveInterval.h:162