LLVM 22.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"
30#include "llvm/ADT/Statistic.h"
35#include <queue>
36using namespace llvm;
37
38#define DEBUG_TYPE "riscv-insert-vsetvli"
39#define RISCV_INSERT_VSETVLI_NAME "RISC-V Insert VSETVLI pass"
40
41STATISTIC(NumInsertedVSETVL, "Number of VSETVL inst inserted");
42STATISTIC(NumCoalescedVSETVL, "Number of VSETVL inst coalesced");
43
45 DEBUG_TYPE "-whole-vector-register-move-valid-vtype", cl::Hidden,
46 cl::desc("Insert vsetvlis before vmvNr.vs to ensure vtype is valid and "
47 "vill is cleared"),
48 cl::init(true));
49
50namespace {
51
52/// Given a virtual register \p Reg, return the corresponding VNInfo for it.
53/// This will return nullptr if the virtual register is an implicit_def or
54/// if LiveIntervals is not available.
55static VNInfo *getVNInfoFromReg(Register Reg, const MachineInstr &MI,
56 const LiveIntervals *LIS) {
57 assert(Reg.isVirtual());
58 if (!LIS)
59 return nullptr;
60 auto &LI = LIS->getInterval(Reg);
62 return LI.getVNInfoBefore(SI);
63}
64
65static unsigned getVLOpNum(const MachineInstr &MI) {
66 return RISCVII::getVLOpNum(MI.getDesc());
67}
68
69static unsigned getSEWOpNum(const MachineInstr &MI) {
70 return RISCVII::getSEWOpNum(MI.getDesc());
71}
72
73static unsigned getVecPolicyOpNum(const MachineInstr &MI) {
74 return RISCVII::getVecPolicyOpNum(MI.getDesc());
75}
76
77/// Get the EEW for a load or store instruction. Return std::nullopt if MI is
78/// not a load or store which ignores SEW.
79static std::optional<unsigned> getEEWForLoadStore(const MachineInstr &MI) {
80 switch (RISCV::getRVVMCOpcode(MI.getOpcode())) {
81 default:
82 return std::nullopt;
83 case RISCV::VLE8_V:
84 case RISCV::VLSE8_V:
85 case RISCV::VSE8_V:
86 case RISCV::VSSE8_V:
87 return 8;
88 case RISCV::VLE16_V:
89 case RISCV::VLSE16_V:
90 case RISCV::VSE16_V:
91 case RISCV::VSSE16_V:
92 return 16;
93 case RISCV::VLE32_V:
94 case RISCV::VLSE32_V:
95 case RISCV::VSE32_V:
96 case RISCV::VSSE32_V:
97 return 32;
98 case RISCV::VLE64_V:
99 case RISCV::VLSE64_V:
100 case RISCV::VSE64_V:
101 case RISCV::VSSE64_V:
102 return 64;
103 }
104}
105
106/// Return true if this is an operation on mask registers. Note that
107/// this includes both arithmetic/logical ops and load/store (vlm/vsm).
108static bool isMaskRegOp(const MachineInstr &MI) {
109 if (!RISCVII::hasSEWOp(MI.getDesc().TSFlags))
110 return false;
111 const unsigned Log2SEW = MI.getOperand(getSEWOpNum(MI)).getImm();
112 // A Log2SEW of 0 is an operation on mask registers only.
113 return Log2SEW == 0;
114}
115
116/// Return true if the inactive elements in the result are entirely undefined.
117/// Note that this is different from "agnostic" as defined by the vector
118/// specification. Agnostic requires each lane to either be undisturbed, or
119/// take the value -1; no other value is allowed.
120static bool hasUndefinedPassthru(const MachineInstr &MI) {
121
122 unsigned UseOpIdx;
123 if (!MI.isRegTiedToUseOperand(0, &UseOpIdx))
124 // If there is no passthrough operand, then the pass through
125 // lanes are undefined.
126 return true;
127
128 // All undefined passthrus should be $noreg: see
129 // RISCVDAGToDAGISel::doPeepholeNoRegPassThru
130 const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
131 return !UseMO.getReg().isValid() || UseMO.isUndef();
132}
133
134/// Return true if \p MI is a copy that will be lowered to one or more vmvNr.vs.
135static bool isVectorCopy(const TargetRegisterInfo *TRI,
136 const MachineInstr &MI) {
137 return MI.isCopy() && MI.getOperand(0).getReg().isPhysical() &&
139 TRI->getMinimalPhysRegClass(MI.getOperand(0).getReg()));
140}
141
142/// Which subfields of VL or VTYPE have values we need to preserve?
143struct DemandedFields {
144 // Some unknown property of VL is used. If demanded, must preserve entire
145 // value.
146 bool VLAny = false;
147 // Only zero vs non-zero is used. If demanded, can change non-zero values.
148 bool VLZeroness = false;
149 // What properties of SEW we need to preserve.
150 enum : uint8_t {
151 SEWEqual = 3, // The exact value of SEW needs to be preserved.
152 SEWGreaterThanOrEqualAndLessThan64 =
153 2, // SEW can be changed as long as it's greater
154 // than or equal to the original value, but must be less
155 // than 64.
156 SEWGreaterThanOrEqual = 1, // SEW can be changed as long as it's greater
157 // than or equal to the original value.
158 SEWNone = 0 // We don't need to preserve SEW at all.
159 } SEW = SEWNone;
160 enum : uint8_t {
161 LMULEqual = 2, // The exact value of LMUL needs to be preserved.
162 LMULLessThanOrEqualToM1 = 1, // We can use any LMUL <= M1.
163 LMULNone = 0 // We don't need to preserve LMUL at all.
164 } LMUL = LMULNone;
165 bool SEWLMULRatio = false;
166 bool TailPolicy = false;
167 bool MaskPolicy = false;
168 // If this is true, we demand that VTYPE is set to some legal state, i.e. that
169 // vill is unset.
170 bool VILL = false;
171 bool TWiden = false;
172 bool AltFmt = false;
173
174 // Return true if any part of VTYPE was used
175 bool usedVTYPE() const {
176 return SEW || LMUL || SEWLMULRatio || TailPolicy || MaskPolicy || VILL ||
177 TWiden || AltFmt;
178 }
179
180 // Return true if any property of VL was used
181 bool usedVL() {
182 return VLAny || VLZeroness;
183 }
184
185 // Mark all VTYPE subfields and properties as demanded
186 void demandVTYPE() {
187 SEW = SEWEqual;
188 LMUL = LMULEqual;
189 SEWLMULRatio = true;
190 TailPolicy = true;
191 MaskPolicy = true;
192 VILL = true;
193 TWiden = true;
194 AltFmt = true;
195 }
196
197 // Mark all VL properties as demanded
198 void demandVL() {
199 VLAny = true;
200 VLZeroness = true;
201 }
202
203 static DemandedFields all() {
204 DemandedFields DF;
205 DF.demandVTYPE();
206 DF.demandVL();
207 return DF;
208 }
209
210 // Make this the result of demanding both the fields in this and B.
211 void doUnion(const DemandedFields &B) {
212 VLAny |= B.VLAny;
213 VLZeroness |= B.VLZeroness;
214 SEW = std::max(SEW, B.SEW);
215 LMUL = std::max(LMUL, B.LMUL);
216 SEWLMULRatio |= B.SEWLMULRatio;
217 TailPolicy |= B.TailPolicy;
218 MaskPolicy |= B.MaskPolicy;
219 VILL |= B.VILL;
220 AltFmt |= B.AltFmt;
221 TWiden |= B.TWiden;
222 }
223
224#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
225 /// Support for debugging, callable in GDB: V->dump()
226 LLVM_DUMP_METHOD void dump() const {
227 print(dbgs());
228 dbgs() << "\n";
229 }
230
231 /// Implement operator<<.
232 void print(raw_ostream &OS) const {
233 OS << "{";
234 OS << "VLAny=" << VLAny << ", ";
235 OS << "VLZeroness=" << VLZeroness << ", ";
236 OS << "SEW=";
237 switch (SEW) {
238 case SEWEqual:
239 OS << "SEWEqual";
240 break;
241 case SEWGreaterThanOrEqual:
242 OS << "SEWGreaterThanOrEqual";
243 break;
244 case SEWGreaterThanOrEqualAndLessThan64:
245 OS << "SEWGreaterThanOrEqualAndLessThan64";
246 break;
247 case SEWNone:
248 OS << "SEWNone";
249 break;
250 };
251 OS << ", ";
252 OS << "LMUL=";
253 switch (LMUL) {
254 case LMULEqual:
255 OS << "LMULEqual";
256 break;
257 case LMULLessThanOrEqualToM1:
258 OS << "LMULLessThanOrEqualToM1";
259 break;
260 case LMULNone:
261 OS << "LMULNone";
262 break;
263 };
264 OS << ", ";
265 OS << "SEWLMULRatio=" << SEWLMULRatio << ", ";
266 OS << "TailPolicy=" << TailPolicy << ", ";
267 OS << "MaskPolicy=" << MaskPolicy << ", ";
268 OS << "VILL=" << VILL << ", ";
269 OS << "AltFmt=" << AltFmt << ", ";
270 OS << "TWiden=" << TWiden;
271 OS << "}";
272 }
273#endif
274};
275
276#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
278inline raw_ostream &operator<<(raw_ostream &OS, const DemandedFields &DF) {
279 DF.print(OS);
280 return OS;
281}
282#endif
283
284static bool isLMUL1OrSmaller(RISCVVType::VLMUL LMUL) {
285 auto [LMul, Fractional] = RISCVVType::decodeVLMUL(LMUL);
286 return Fractional || LMul == 1;
287}
288
289/// Return true if moving from CurVType to NewVType is
290/// indistinguishable from the perspective of an instruction (or set
291/// of instructions) which use only the Used subfields and properties.
292static bool areCompatibleVTYPEs(uint64_t CurVType, uint64_t NewVType,
293 const DemandedFields &Used) {
294 switch (Used.SEW) {
295 case DemandedFields::SEWNone:
296 break;
297 case DemandedFields::SEWEqual:
298 if (RISCVVType::getSEW(CurVType) != RISCVVType::getSEW(NewVType))
299 return false;
300 break;
301 case DemandedFields::SEWGreaterThanOrEqual:
302 if (RISCVVType::getSEW(NewVType) < RISCVVType::getSEW(CurVType))
303 return false;
304 break;
305 case DemandedFields::SEWGreaterThanOrEqualAndLessThan64:
306 if (RISCVVType::getSEW(NewVType) < RISCVVType::getSEW(CurVType) ||
307 RISCVVType::getSEW(NewVType) >= 64)
308 return false;
309 break;
310 }
311
312 switch (Used.LMUL) {
313 case DemandedFields::LMULNone:
314 break;
315 case DemandedFields::LMULEqual:
316 if (RISCVVType::getVLMUL(CurVType) != RISCVVType::getVLMUL(NewVType))
317 return false;
318 break;
319 case DemandedFields::LMULLessThanOrEqualToM1:
320 if (!isLMUL1OrSmaller(RISCVVType::getVLMUL(NewVType)))
321 return false;
322 break;
323 }
324
325 if (Used.SEWLMULRatio) {
326 auto Ratio1 = RISCVVType::getSEWLMULRatio(RISCVVType::getSEW(CurVType),
327 RISCVVType::getVLMUL(CurVType));
328 auto Ratio2 = RISCVVType::getSEWLMULRatio(RISCVVType::getSEW(NewVType),
329 RISCVVType::getVLMUL(NewVType));
330 if (Ratio1 != Ratio2)
331 return false;
332 }
333
334 if (Used.TailPolicy && RISCVVType::isTailAgnostic(CurVType) !=
336 return false;
337 if (Used.MaskPolicy && RISCVVType::isMaskAgnostic(CurVType) !=
339 return false;
340 if (Used.TWiden && (RISCVVType::hasXSfmmWiden(CurVType) !=
341 RISCVVType::hasXSfmmWiden(NewVType) ||
342 (RISCVVType::hasXSfmmWiden(CurVType) &&
343 RISCVVType::getXSfmmWiden(CurVType) !=
344 RISCVVType::getXSfmmWiden(NewVType))))
345 return false;
346 if (Used.AltFmt &&
347 RISCVVType::isAltFmt(CurVType) != RISCVVType::isAltFmt(NewVType))
348 return false;
349 return true;
350}
351
352/// Return the fields and properties demanded by the provided instruction.
353DemandedFields getDemanded(const MachineInstr &MI, const RISCVSubtarget *ST) {
354 // This function works in coalesceVSETVLI too. We can still use the value of a
355 // SEW, VL, or Policy operand even though it might not be the exact value in
356 // the VL or VTYPE, since we only care about what the instruction originally
357 // demanded.
358
359 // Most instructions don't use any of these subfeilds.
360 DemandedFields Res;
361 // Start conservative if registers are used
362 if (MI.isCall() || MI.isInlineAsm() ||
363 MI.readsRegister(RISCV::VL, /*TRI=*/nullptr))
364 Res.demandVL();
365 if (MI.isCall() || MI.isInlineAsm() ||
366 MI.readsRegister(RISCV::VTYPE, /*TRI=*/nullptr))
367 Res.demandVTYPE();
368 // Start conservative on the unlowered form too
369 uint64_t TSFlags = MI.getDesc().TSFlags;
370 if (RISCVII::hasSEWOp(TSFlags)) {
371 Res.demandVTYPE();
372 if (RISCVII::hasVLOp(TSFlags))
373 if (const MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
374 !VLOp.isReg() || !VLOp.isUndef())
375 Res.demandVL();
376
377 // Behavior is independent of mask policy.
378 if (!RISCVII::usesMaskPolicy(TSFlags))
379 Res.MaskPolicy = false;
380 }
381
382 // Loads and stores with implicit EEW do not demand SEW or LMUL directly.
383 // They instead demand the ratio of the two which is used in computing
384 // EMUL, but which allows us the flexibility to change SEW and LMUL
385 // provided we don't change the ratio.
386 // Note: We assume that the instructions initial SEW is the EEW encoded
387 // in the opcode. This is asserted when constructing the VSETVLIInfo.
388 if (getEEWForLoadStore(MI)) {
389 Res.SEW = DemandedFields::SEWNone;
390 Res.LMUL = DemandedFields::LMULNone;
391 }
392
393 // Store instructions don't use the policy fields.
394 if (RISCVII::hasSEWOp(TSFlags) && MI.getNumExplicitDefs() == 0) {
395 Res.TailPolicy = false;
396 Res.MaskPolicy = false;
397 }
398
399 // If this is a mask reg operation, it only cares about VLMAX.
400 // TODO: Possible extensions to this logic
401 // * Probably ok if available VLMax is larger than demanded
402 // * The policy bits can probably be ignored..
403 if (isMaskRegOp(MI)) {
404 Res.SEW = DemandedFields::SEWNone;
405 Res.LMUL = DemandedFields::LMULNone;
406 }
407
408 // For vmv.s.x and vfmv.s.f, there are only two behaviors, VL = 0 and VL > 0.
409 if (RISCVInstrInfo::isScalarInsertInstr(MI)) {
410 Res.LMUL = DemandedFields::LMULNone;
411 Res.SEWLMULRatio = false;
412 Res.VLAny = false;
413 // For vmv.s.x and vfmv.s.f, if the passthru is *undefined*, we don't
414 // need to preserve any other bits and are thus compatible with any larger,
415 // etype and can disregard policy bits. Warning: It's tempting to try doing
416 // this for any tail agnostic operation, but we can't as TA requires
417 // tail lanes to either be the original value or -1. We are writing
418 // unknown bits to the lanes here.
419 if (hasUndefinedPassthru(MI)) {
420 if (RISCVInstrInfo::isFloatScalarMoveOrScalarSplatInstr(MI) &&
421 !ST->hasVInstructionsF64())
422 Res.SEW = DemandedFields::SEWGreaterThanOrEqualAndLessThan64;
423 else
424 Res.SEW = DemandedFields::SEWGreaterThanOrEqual;
425 Res.TailPolicy = false;
426 }
427 }
428
429 // vmv.x.s, and vfmv.f.s are unconditional and ignore everything except SEW.
430 if (RISCVInstrInfo::isScalarExtractInstr(MI)) {
431 assert(!RISCVII::hasVLOp(TSFlags));
432 Res.LMUL = DemandedFields::LMULNone;
433 Res.SEWLMULRatio = false;
434 Res.TailPolicy = false;
435 Res.MaskPolicy = false;
436 }
437
438 if (RISCVII::hasVLOp(MI.getDesc().TSFlags)) {
439 const MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
440 // A slidedown/slideup with an *undefined* passthru can freely clobber
441 // elements not copied from the source vector (e.g. masked off, tail, or
442 // slideup's prefix). Notes:
443 // * We can't modify SEW here since the slide amount is in units of SEW.
444 // * VL=1 is special only because we have existing support for zero vs
445 // non-zero VL. We could generalize this if we had a VL > C predicate.
446 // * The LMUL1 restriction is for machines whose latency may depend on LMUL.
447 // * As above, this is only legal for tail "undefined" not "agnostic".
448 // * We avoid increasing vl if the subtarget has +vl-dependent-latency
449 if (RISCVInstrInfo::isVSlideInstr(MI) && VLOp.isImm() &&
450 VLOp.getImm() == 1 && hasUndefinedPassthru(MI) &&
451 !ST->hasVLDependentLatency()) {
452 Res.VLAny = false;
453 Res.VLZeroness = true;
454 Res.LMUL = DemandedFields::LMULLessThanOrEqualToM1;
455 Res.TailPolicy = false;
456 }
457
458 // A tail undefined vmv.v.i/x or vfmv.v.f with VL=1 can be treated in the
459 // same semantically as vmv.s.x. This is particularly useful since we don't
460 // have an immediate form of vmv.s.x, and thus frequently use vmv.v.i in
461 // it's place. Since a splat is non-constant time in LMUL, we do need to be
462 // careful to not increase the number of active vector registers (unlike for
463 // vmv.s.x.)
464 if (RISCVInstrInfo::isScalarSplatInstr(MI) && VLOp.isImm() &&
465 VLOp.getImm() == 1 && hasUndefinedPassthru(MI) &&
466 !ST->hasVLDependentLatency()) {
467 Res.LMUL = DemandedFields::LMULLessThanOrEqualToM1;
468 Res.SEWLMULRatio = false;
469 Res.VLAny = false;
470 if (RISCVInstrInfo::isFloatScalarMoveOrScalarSplatInstr(MI) &&
471 !ST->hasVInstructionsF64())
472 Res.SEW = DemandedFields::SEWGreaterThanOrEqualAndLessThan64;
473 else
474 Res.SEW = DemandedFields::SEWGreaterThanOrEqual;
475 Res.TailPolicy = false;
476 }
477 }
478
479 // In §32.16.6, whole vector register moves have a dependency on SEW. At the
480 // MIR level though we don't encode the element type, and it gives the same
481 // result whatever the SEW may be.
482 //
483 // However it does need valid SEW, i.e. vill must be cleared. The entry to a
484 // function, calls and inline assembly may all set it, so make sure we clear
485 // it for whole register copies. Do this by leaving VILL demanded.
486 if (isVectorCopy(ST->getRegisterInfo(), MI)) {
487 Res.LMUL = DemandedFields::LMULNone;
488 Res.SEW = DemandedFields::SEWNone;
489 Res.SEWLMULRatio = false;
490 Res.TailPolicy = false;
491 Res.MaskPolicy = false;
492 }
493
494 if (RISCVInstrInfo::isVExtractInstr(MI)) {
495 assert(!RISCVII::hasVLOp(TSFlags));
496 // TODO: LMUL can be any larger value (without cost)
497 Res.TailPolicy = false;
498 }
499
500 Res.AltFmt = RISCVII::getAltFmtType(MI.getDesc().TSFlags) !=
502 Res.TWiden = RISCVII::hasTWidenOp(MI.getDesc().TSFlags) ||
503 RISCVInstrInfo::isXSfmmVectorConfigInstr(MI);
504
505 return Res;
506}
507
508/// Defines the abstract state with which the forward dataflow models the
509/// values of the VL and VTYPE registers after insertion.
510class VSETVLIInfo {
511 struct AVLDef {
512 // Every AVLDef should have a VNInfo, unless we're running without
513 // LiveIntervals in which case this will be nullptr.
514 const VNInfo *ValNo;
515 Register DefReg;
516 };
517 union {
518 AVLDef AVLRegDef;
519 unsigned AVLImm;
520 };
521
522 enum : uint8_t {
523 Uninitialized,
524 AVLIsReg,
525 AVLIsImm,
526 AVLIsVLMAX,
527 Unknown, // AVL and VTYPE are fully unknown
528 } State = Uninitialized;
529
530 // Fields from VTYPE.
532 uint8_t SEW = 0;
533 uint8_t TailAgnostic : 1;
534 uint8_t MaskAgnostic : 1;
535 uint8_t SEWLMULRatioOnly : 1;
536 uint8_t AltFmt : 1;
537 uint8_t TWiden : 3;
538
539public:
540 VSETVLIInfo()
541 : AVLImm(0), TailAgnostic(false), MaskAgnostic(false),
542 SEWLMULRatioOnly(false) {}
543
544 static VSETVLIInfo getUnknown() {
545 VSETVLIInfo Info;
546 Info.setUnknown();
547 return Info;
548 }
549
550 bool isValid() const { return State != Uninitialized; }
551 void setUnknown() { State = Unknown; }
552 bool isUnknown() const { return State == Unknown; }
553
554 void setAVLRegDef(const VNInfo *VNInfo, Register AVLReg) {
555 assert(AVLReg.isVirtual());
556 AVLRegDef.ValNo = VNInfo;
557 AVLRegDef.DefReg = AVLReg;
558 State = AVLIsReg;
559 }
560
561 void setAVLImm(unsigned Imm) {
562 AVLImm = Imm;
563 State = AVLIsImm;
564 }
565
566 void setAVLVLMAX() { State = AVLIsVLMAX; }
567
568 bool hasAVLImm() const { return State == AVLIsImm; }
569 bool hasAVLReg() const { return State == AVLIsReg; }
570 bool hasAVLVLMAX() const { return State == AVLIsVLMAX; }
571 Register getAVLReg() const {
572 assert(hasAVLReg() && AVLRegDef.DefReg.isVirtual());
573 return AVLRegDef.DefReg;
574 }
575 unsigned getAVLImm() const {
576 assert(hasAVLImm());
577 return AVLImm;
578 }
579 const VNInfo *getAVLVNInfo() const {
580 assert(hasAVLReg());
581 return AVLRegDef.ValNo;
582 }
583 // Most AVLIsReg infos will have a single defining MachineInstr, unless it was
584 // a PHI node. In that case getAVLVNInfo()->def will point to the block
585 // boundary slot and this will return nullptr. If LiveIntervals isn't
586 // available, nullptr is also returned.
587 const MachineInstr *getAVLDefMI(const LiveIntervals *LIS) const {
588 assert(hasAVLReg());
589 if (!LIS || getAVLVNInfo()->isPHIDef())
590 return nullptr;
591 auto *MI = LIS->getInstructionFromIndex(getAVLVNInfo()->def);
592 assert(MI);
593 return MI;
594 }
595
596 void setAVL(const VSETVLIInfo &Info) {
597 assert(Info.isValid());
598 if (Info.isUnknown())
599 setUnknown();
600 else if (Info.hasAVLReg())
601 setAVLRegDef(Info.getAVLVNInfo(), Info.getAVLReg());
602 else if (Info.hasAVLVLMAX())
603 setAVLVLMAX();
604 else {
605 assert(Info.hasAVLImm());
606 setAVLImm(Info.getAVLImm());
607 }
608 }
609
610 unsigned getSEW() const { return SEW; }
611 RISCVVType::VLMUL getVLMUL() const { return VLMul; }
612 bool getTailAgnostic() const { return TailAgnostic; }
613 bool getMaskAgnostic() const { return MaskAgnostic; }
614 bool getAltFmt() const { return AltFmt; }
615 unsigned getTWiden() const { return TWiden; }
616
617 bool hasNonZeroAVL(const LiveIntervals *LIS) const {
618 if (hasAVLImm())
619 return getAVLImm() > 0;
620 if (hasAVLReg()) {
621 if (auto *DefMI = getAVLDefMI(LIS))
622 return RISCVInstrInfo::isNonZeroLoadImmediate(*DefMI);
623 }
624 if (hasAVLVLMAX())
625 return true;
626 return false;
627 }
628
629 bool hasEquallyZeroAVL(const VSETVLIInfo &Other,
630 const LiveIntervals *LIS) const {
631 if (hasSameAVL(Other))
632 return true;
633 return (hasNonZeroAVL(LIS) && Other.hasNonZeroAVL(LIS));
634 }
635
636 bool hasSameAVLLatticeValue(const VSETVLIInfo &Other) const {
637 if (hasAVLReg() && Other.hasAVLReg()) {
638 assert(!getAVLVNInfo() == !Other.getAVLVNInfo() &&
639 "we either have intervals or we don't");
640 if (!getAVLVNInfo())
641 return getAVLReg() == Other.getAVLReg();
642 return getAVLVNInfo()->id == Other.getAVLVNInfo()->id &&
643 getAVLReg() == Other.getAVLReg();
644 }
645
646 if (hasAVLImm() && Other.hasAVLImm())
647 return getAVLImm() == Other.getAVLImm();
648
649 if (hasAVLVLMAX())
650 return Other.hasAVLVLMAX() && hasSameVLMAX(Other);
651
652 return false;
653 }
654
655 // Return true if the two lattice values are guaranteed to have
656 // the same AVL value at runtime.
657 bool hasSameAVL(const VSETVLIInfo &Other) const {
658 // Without LiveIntervals, we don't know which instruction defines a
659 // register. Since a register may be redefined, this means all AVLIsReg
660 // states must be treated as possibly distinct.
661 if (hasAVLReg() && Other.hasAVLReg()) {
662 assert(!getAVLVNInfo() == !Other.getAVLVNInfo() &&
663 "we either have intervals or we don't");
664 if (!getAVLVNInfo())
665 return false;
666 }
667 return hasSameAVLLatticeValue(Other);
668 }
669
670 void setVTYPE(unsigned VType) {
671 assert(isValid() && !isUnknown() &&
672 "Can't set VTYPE for uninitialized or unknown");
673 VLMul = RISCVVType::getVLMUL(VType);
674 SEW = RISCVVType::getSEW(VType);
675 TailAgnostic = RISCVVType::isTailAgnostic(VType);
676 MaskAgnostic = RISCVVType::isMaskAgnostic(VType);
677 AltFmt = RISCVVType::isAltFmt(VType);
678 TWiden =
680 }
681 void setVTYPE(RISCVVType::VLMUL L, unsigned S, bool TA, bool MA, bool Altfmt,
682 unsigned W) {
683 assert(isValid() && !isUnknown() &&
684 "Can't set VTYPE for uninitialized or unknown");
685 VLMul = L;
686 SEW = S;
687 TailAgnostic = TA;
688 MaskAgnostic = MA;
689 AltFmt = Altfmt;
690 TWiden = W;
691 }
692
693 void setAltFmt(bool AF) { AltFmt = AF; }
694
695 void setVLMul(RISCVVType::VLMUL VLMul) { this->VLMul = VLMul; }
696
697 unsigned encodeVTYPE() const {
698 assert(isValid() && !isUnknown() && !SEWLMULRatioOnly &&
699 "Can't encode VTYPE for uninitialized or unknown");
700 if (TWiden != 0)
701 return RISCVVType::encodeXSfmmVType(SEW, TWiden, AltFmt);
702 return RISCVVType::encodeVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic,
703 AltFmt);
704 }
705
706 bool hasSEWLMULRatioOnly() const { return SEWLMULRatioOnly; }
707
708 bool hasSameVTYPE(const VSETVLIInfo &Other) const {
709 assert(isValid() && Other.isValid() &&
710 "Can't compare invalid VSETVLIInfos");
711 assert(!isUnknown() && !Other.isUnknown() &&
712 "Can't compare VTYPE in unknown state");
713 assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
714 "Can't compare when only LMUL/SEW ratio is valid.");
715 return std::tie(VLMul, SEW, TailAgnostic, MaskAgnostic, AltFmt, TWiden) ==
716 std::tie(Other.VLMul, Other.SEW, Other.TailAgnostic,
717 Other.MaskAgnostic, Other.AltFmt, Other.TWiden);
718 }
719
720 unsigned getSEWLMULRatio() const {
721 assert(isValid() && !isUnknown() &&
722 "Can't use VTYPE for uninitialized or unknown");
723 return RISCVVType::getSEWLMULRatio(SEW, VLMul);
724 }
725
726 // Check if the VTYPE for these two VSETVLIInfos produce the same VLMAX.
727 // Note that having the same VLMAX ensures that both share the same
728 // function from AVL to VL; that is, they must produce the same VL value
729 // for any given AVL value.
730 bool hasSameVLMAX(const VSETVLIInfo &Other) const {
731 assert(isValid() && Other.isValid() &&
732 "Can't compare invalid VSETVLIInfos");
733 assert(!isUnknown() && !Other.isUnknown() &&
734 "Can't compare VTYPE in unknown state");
735 return getSEWLMULRatio() == Other.getSEWLMULRatio();
736 }
737
738 bool hasCompatibleVTYPE(const DemandedFields &Used,
739 const VSETVLIInfo &Require) const {
740 return areCompatibleVTYPEs(Require.encodeVTYPE(), encodeVTYPE(), Used);
741 }
742
743 // Determine whether the vector instructions requirements represented by
744 // Require are compatible with the previous vsetvli instruction represented
745 // by this. MI is the instruction whose requirements we're considering.
746 bool isCompatible(const DemandedFields &Used, const VSETVLIInfo &Require,
747 const LiveIntervals *LIS) const {
748 assert(isValid() && Require.isValid() &&
749 "Can't compare invalid VSETVLIInfos");
750 // Nothing is compatible with Unknown.
751 if (isUnknown() || Require.isUnknown())
752 return false;
753
754 // If only our VLMAX ratio is valid, then this isn't compatible.
755 if (SEWLMULRatioOnly || Require.SEWLMULRatioOnly)
756 return false;
757
758 if (Used.VLAny && !(hasSameAVL(Require) && hasSameVLMAX(Require)))
759 return false;
760
761 if (Used.VLZeroness && !hasEquallyZeroAVL(Require, LIS))
762 return false;
763
764 return hasCompatibleVTYPE(Used, Require);
765 }
766
767 bool operator==(const VSETVLIInfo &Other) const {
768 // Uninitialized is only equal to another Uninitialized.
769 if (!isValid())
770 return !Other.isValid();
771 if (!Other.isValid())
772 return !isValid();
773
774 // Unknown is only equal to another Unknown.
775 if (isUnknown())
776 return Other.isUnknown();
777 if (Other.isUnknown())
778 return isUnknown();
779
780 if (!hasSameAVLLatticeValue(Other))
781 return false;
782
783 // If the SEWLMULRatioOnly bits are different, then they aren't equal.
784 if (SEWLMULRatioOnly != Other.SEWLMULRatioOnly)
785 return false;
786
787 // If only the VLMAX is valid, check that it is the same.
788 if (SEWLMULRatioOnly)
789 return hasSameVLMAX(Other);
790
791 // If the full VTYPE is valid, check that it is the same.
792 return hasSameVTYPE(Other);
793 }
794
795 bool operator!=(const VSETVLIInfo &Other) const {
796 return !(*this == Other);
797 }
798
799 // Calculate the VSETVLIInfo visible to a block assuming this and Other are
800 // both predecessors.
801 VSETVLIInfo intersect(const VSETVLIInfo &Other) const {
802 // If the new value isn't valid, ignore it.
803 if (!Other.isValid())
804 return *this;
805
806 // If this value isn't valid, this must be the first predecessor, use it.
807 if (!isValid())
808 return Other;
809
810 // If either is unknown, the result is unknown.
811 if (isUnknown() || Other.isUnknown())
812 return VSETVLIInfo::getUnknown();
813
814 // If we have an exact, match return this.
815 if (*this == Other)
816 return *this;
817
818 // Not an exact match, but maybe the AVL and VLMAX are the same. If so,
819 // return an SEW/LMUL ratio only value.
820 if (hasSameAVL(Other) && hasSameVLMAX(Other)) {
821 VSETVLIInfo MergeInfo = *this;
822 MergeInfo.SEWLMULRatioOnly = true;
823 return MergeInfo;
824 }
825
826 // Otherwise the result is unknown.
827 return VSETVLIInfo::getUnknown();
828 }
829
830#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
831 /// Support for debugging, callable in GDB: V->dump()
832 LLVM_DUMP_METHOD void dump() const {
833 print(dbgs());
834 dbgs() << "\n";
835 }
836
837 /// Implement operator<<.
838 /// @{
839 void print(raw_ostream &OS) const {
840 OS << "{";
841 if (!isValid())
842 OS << "Uninitialized";
843 if (isUnknown())
844 OS << "unknown";
845 if (hasAVLReg())
846 OS << "AVLReg=" << llvm::printReg(getAVLReg());
847 if (hasAVLImm())
848 OS << "AVLImm=" << (unsigned)AVLImm;
849 if (hasAVLVLMAX())
850 OS << "AVLVLMAX";
851 OS << ", ";
852
853 unsigned LMul;
854 bool Fractional;
855 std::tie(LMul, Fractional) = decodeVLMUL(VLMul);
856
857 OS << "VLMul=";
858 if (Fractional)
859 OS << "mf";
860 else
861 OS << "m";
862 OS << LMul << ", "
863 << "SEW=e" << (unsigned)SEW << ", "
864 << "TailAgnostic=" << (bool)TailAgnostic << ", "
865 << "MaskAgnostic=" << (bool)MaskAgnostic << ", "
866 << "SEWLMULRatioOnly=" << (bool)SEWLMULRatioOnly << ", "
867 << "TWiden=" << (unsigned)TWiden << ", "
868 << "AltFmt=" << (bool)AltFmt << "}";
869 }
870#endif
871};
872
873#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
875inline raw_ostream &operator<<(raw_ostream &OS, const VSETVLIInfo &V) {
876 V.print(OS);
877 return OS;
878}
879#endif
880
881struct BlockData {
882 // The VSETVLIInfo that represents the VL/VTYPE settings on exit from this
883 // block. Calculated in Phase 2.
884 VSETVLIInfo Exit;
885
886 // The VSETVLIInfo that represents the VL/VTYPE settings from all predecessor
887 // blocks. Calculated in Phase 2, and used by Phase 3.
888 VSETVLIInfo Pred;
889
890 // Keeps track of whether the block is already in the queue.
891 bool InQueue = false;
892
893 BlockData() = default;
894};
895
896enum TKTMMode {
897 VSETTK = 0,
898 VSETTM = 1,
899};
900
901class RISCVInsertVSETVLI : public MachineFunctionPass {
902 const RISCVSubtarget *ST;
903 const TargetInstrInfo *TII;
904 MachineRegisterInfo *MRI;
905 // Possibly null!
906 LiveIntervals *LIS;
907
908 std::vector<BlockData> BlockInfo;
909 std::queue<const MachineBasicBlock *> WorkList;
910
911public:
912 static char ID;
913
914 RISCVInsertVSETVLI() : MachineFunctionPass(ID) {}
915 bool runOnMachineFunction(MachineFunction &MF) override;
916
917 void getAnalysisUsage(AnalysisUsage &AU) const override {
918 AU.setPreservesCFG();
919
920 AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
921 AU.addPreserved<LiveIntervalsWrapperPass>();
922 AU.addPreserved<SlotIndexesWrapperPass>();
923 AU.addPreserved<LiveDebugVariablesWrapperLegacy>();
924 AU.addPreserved<LiveStacksWrapperLegacy>();
925
927 }
928
929 StringRef getPassName() const override { return RISCV_INSERT_VSETVLI_NAME; }
930
931private:
932 bool needVSETVLI(const DemandedFields &Used, const VSETVLIInfo &Require,
933 const VSETVLIInfo &CurInfo) const;
934 bool needVSETVLIPHI(const VSETVLIInfo &Require,
935 const MachineBasicBlock &MBB) const;
936 void insertVSETVLI(MachineBasicBlock &MBB,
938 const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
939
940 void transferBefore(VSETVLIInfo &Info, const MachineInstr &MI) const;
941 void transferAfter(VSETVLIInfo &Info, const MachineInstr &MI) const;
942 bool computeVLVTYPEChanges(const MachineBasicBlock &MBB,
943 VSETVLIInfo &Info) const;
944 void computeIncomingVLVTYPE(const MachineBasicBlock &MBB);
945 void emitVSETVLIs(MachineBasicBlock &MBB);
946 void doPRE(MachineBasicBlock &MBB);
947 void insertReadVL(MachineBasicBlock &MBB);
948
949 bool canMutatePriorConfig(const MachineInstr &PrevMI, const MachineInstr &MI,
950 const DemandedFields &Used) const;
951 void coalesceVSETVLIs(MachineBasicBlock &MBB) const;
952
953 VSETVLIInfo getInfoForVSETVLI(const MachineInstr &MI) const;
954 VSETVLIInfo computeInfoForInstr(const MachineInstr &MI) const;
955 void forwardVSETVLIAVL(VSETVLIInfo &Info) const;
956 bool insertVSETMTK(MachineBasicBlock &MBB, TKTMMode Mode) const;
957};
958
959} // end anonymous namespace
960
961char RISCVInsertVSETVLI::ID = 0;
962char &llvm::RISCVInsertVSETVLIID = RISCVInsertVSETVLI::ID;
963
965 false, false)
966
967// If the AVL is defined by a vsetvli's output vl with the same VLMAX, we can
968// replace the AVL operand with the AVL of the defining vsetvli. E.g.
969//
970// %vl = PseudoVSETVLI %avl:gpr, SEW=32, LMUL=M1
971// $x0 = PseudoVSETVLI %vl:gpr, SEW=32, LMUL=M1
972// ->
973// %vl = PseudoVSETVLI %avl:gpr, SEW=32, LMUL=M1
974// $x0 = PseudoVSETVLI %avl:gpr, SEW=32, LMUL=M1
975void RISCVInsertVSETVLI::forwardVSETVLIAVL(VSETVLIInfo &Info) const {
976 if (!Info.hasAVLReg())
977 return;
978 const MachineInstr *DefMI = Info.getAVLDefMI(LIS);
979 if (!DefMI || !RISCVInstrInfo::isVectorConfigInstr(*DefMI))
980 return;
981 VSETVLIInfo DefInstrInfo = getInfoForVSETVLI(*DefMI);
982 if (!DefInstrInfo.hasSameVLMAX(Info))
983 return;
984 Info.setAVL(DefInstrInfo);
985}
986
987// Return a VSETVLIInfo representing the changes made by this VSETVLI or
988// VSETIVLI instruction.
989VSETVLIInfo
990RISCVInsertVSETVLI::getInfoForVSETVLI(const MachineInstr &MI) const {
991 VSETVLIInfo NewInfo;
992 if (MI.getOpcode() == RISCV::PseudoVSETIVLI) {
993 NewInfo.setAVLImm(MI.getOperand(1).getImm());
994 } else if (RISCVInstrInfo::isXSfmmVectorConfigTNInstr(MI)) {
995 assert(MI.getOpcode() == RISCV::PseudoSF_VSETTNT ||
996 MI.getOpcode() == RISCV::PseudoSF_VSETTNTX0);
997 switch (MI.getOpcode()) {
998 case RISCV::PseudoSF_VSETTNTX0:
999 NewInfo.setAVLVLMAX();
1000 break;
1001 case RISCV::PseudoSF_VSETTNT:
1002 Register ATNReg = MI.getOperand(1).getReg();
1003 NewInfo.setAVLRegDef(getVNInfoFromReg(ATNReg, MI, LIS), ATNReg);
1004 break;
1005 }
1006 } else {
1007 assert(MI.getOpcode() == RISCV::PseudoVSETVLI ||
1008 MI.getOpcode() == RISCV::PseudoVSETVLIX0);
1009 if (MI.getOpcode() == RISCV::PseudoVSETVLIX0)
1010 NewInfo.setAVLVLMAX();
1011 else if (MI.getOperand(1).isUndef())
1012 // Otherwise use an AVL of 1 to avoid depending on previous vl.
1013 NewInfo.setAVLImm(1);
1014 else {
1015 Register AVLReg = MI.getOperand(1).getReg();
1016 VNInfo *VNI = getVNInfoFromReg(AVLReg, MI, LIS);
1017 NewInfo.setAVLRegDef(VNI, AVLReg);
1018 }
1019 }
1020 NewInfo.setVTYPE(MI.getOperand(2).getImm());
1021
1022 forwardVSETVLIAVL(NewInfo);
1023
1024 return NewInfo;
1025}
1026
1027static unsigned computeVLMAX(unsigned VLEN, unsigned SEW,
1028 RISCVVType::VLMUL VLMul) {
1029 auto [LMul, Fractional] = RISCVVType::decodeVLMUL(VLMul);
1030 if (Fractional)
1031 VLEN = VLEN / LMul;
1032 else
1033 VLEN = VLEN * LMul;
1034 return VLEN/SEW;
1035}
1036
1037VSETVLIInfo
1038RISCVInsertVSETVLI::computeInfoForInstr(const MachineInstr &MI) const {
1039 VSETVLIInfo InstrInfo;
1040 const uint64_t TSFlags = MI.getDesc().TSFlags;
1041
1042 bool TailAgnostic = true;
1043 bool MaskAgnostic = true;
1044 if (!hasUndefinedPassthru(MI)) {
1045 // Start with undisturbed.
1046 TailAgnostic = false;
1047 MaskAgnostic = false;
1048
1049 // If there is a policy operand, use it.
1050 if (RISCVII::hasVecPolicyOp(TSFlags)) {
1051 const MachineOperand &Op = MI.getOperand(getVecPolicyOpNum(MI));
1052 uint64_t Policy = Op.getImm();
1053 assert(Policy <=
1055 "Invalid Policy Value");
1056 TailAgnostic = Policy & RISCVVType::TAIL_AGNOSTIC;
1057 MaskAgnostic = Policy & RISCVVType::MASK_AGNOSTIC;
1058 }
1059
1060 if (!RISCVII::usesMaskPolicy(TSFlags))
1061 MaskAgnostic = true;
1062 }
1063
1064 RISCVVType::VLMUL VLMul = RISCVII::getLMul(TSFlags);
1065
1066 bool AltFmt = RISCVII::getAltFmtType(TSFlags) == RISCVII::AltFmtType::AltFmt;
1067 InstrInfo.setAltFmt(AltFmt);
1068
1069 unsigned Log2SEW = MI.getOperand(getSEWOpNum(MI)).getImm();
1070 // A Log2SEW of 0 is an operation on mask registers only.
1071 unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
1072 assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
1073
1074 if (RISCVII::hasTWidenOp(TSFlags)) {
1075 const MachineOperand &TWidenOp =
1076 MI.getOperand(MI.getNumExplicitOperands() - 1);
1077 unsigned TWiden = TWidenOp.getImm();
1078
1079 InstrInfo.setAVLVLMAX();
1080 if (RISCVII::hasVLOp(TSFlags)) {
1081 const MachineOperand &TNOp =
1082 MI.getOperand(RISCVII::getTNOpNum(MI.getDesc()));
1083
1084 if (TNOp.getReg().isVirtual())
1085 InstrInfo.setAVLRegDef(getVNInfoFromReg(TNOp.getReg(), MI, LIS),
1086 TNOp.getReg());
1087 }
1088
1089 InstrInfo.setVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic, AltFmt, TWiden);
1090
1091 return InstrInfo;
1092 }
1093
1094 if (RISCVII::hasVLOp(TSFlags)) {
1095 const MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1096 if (VLOp.isImm()) {
1097 int64_t Imm = VLOp.getImm();
1098 // Convert the VLMax sentintel to X0 register.
1099 if (Imm == RISCV::VLMaxSentinel) {
1100 // If we know the exact VLEN, see if we can use the constant encoding
1101 // for the VLMAX instead. This reduces register pressure slightly.
1102 const unsigned VLMAX = computeVLMAX(ST->getRealMaxVLen(), SEW, VLMul);
1103 if (ST->getRealMinVLen() == ST->getRealMaxVLen() && VLMAX <= 31)
1104 InstrInfo.setAVLImm(VLMAX);
1105 else
1106 InstrInfo.setAVLVLMAX();
1107 }
1108 else
1109 InstrInfo.setAVLImm(Imm);
1110 } else if (VLOp.isUndef()) {
1111 // Otherwise use an AVL of 1 to avoid depending on previous vl.
1112 InstrInfo.setAVLImm(1);
1113 } else {
1114 VNInfo *VNI = getVNInfoFromReg(VLOp.getReg(), MI, LIS);
1115 InstrInfo.setAVLRegDef(VNI, VLOp.getReg());
1116 }
1117 } else {
1118 assert(RISCVInstrInfo::isScalarExtractInstr(MI) ||
1119 RISCVInstrInfo::isVExtractInstr(MI));
1120 // Pick a random value for state tracking purposes, will be ignored via
1121 // the demanded fields mechanism
1122 InstrInfo.setAVLImm(1);
1123 }
1124#ifndef NDEBUG
1125 if (std::optional<unsigned> EEW = getEEWForLoadStore(MI)) {
1126 assert(SEW == EEW && "Initial SEW doesn't match expected EEW");
1127 }
1128#endif
1129 // TODO: Propagate the twiden from previous vtype for potential reuse.
1130 InstrInfo.setVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic, AltFmt,
1131 /*TWiden*/ 0);
1132
1133 forwardVSETVLIAVL(InstrInfo);
1134
1135 return InstrInfo;
1136}
1137
1138void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB,
1140 DebugLoc DL, const VSETVLIInfo &Info,
1141 const VSETVLIInfo &PrevInfo) {
1142 ++NumInsertedVSETVL;
1143
1144 if (Info.getTWiden()) {
1145 if (Info.hasAVLVLMAX()) {
1146 Register DestReg = MRI->createVirtualRegister(&RISCV::GPRNoX0RegClass);
1147 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoSF_VSETTNTX0))
1149 .addReg(RISCV::X0, RegState::Kill)
1150 .addImm(Info.encodeVTYPE());
1151 if (LIS) {
1153 LIS->createAndComputeVirtRegInterval(DestReg);
1154 }
1155 } else {
1156 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoSF_VSETTNT))
1158 .addReg(Info.getAVLReg())
1159 .addImm(Info.encodeVTYPE());
1160 if (LIS)
1162 }
1163 return;
1164 }
1165
1166 if (PrevInfo.isValid() && !PrevInfo.isUnknown()) {
1167 // Use X0, X0 form if the AVL is the same and the SEW+LMUL gives the same
1168 // VLMAX.
1169 if (Info.hasSameAVL(PrevInfo) && Info.hasSameVLMAX(PrevInfo)) {
1170 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0X0))
1172 .addReg(RISCV::X0, RegState::Kill)
1173 .addImm(Info.encodeVTYPE())
1174 .addReg(RISCV::VL, RegState::Implicit);
1175 if (LIS)
1177 return;
1178 }
1179
1180 // If our AVL is a virtual register, it might be defined by a VSET(I)VLI. If
1181 // it has the same VLMAX we want and the last VL/VTYPE we observed is the
1182 // same, we can use the X0, X0 form.
1183 if (Info.hasSameVLMAX(PrevInfo) && Info.hasAVLReg()) {
1184 if (const MachineInstr *DefMI = Info.getAVLDefMI(LIS);
1185 DefMI && RISCVInstrInfo::isVectorConfigInstr(*DefMI)) {
1186 VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1187 if (DefInfo.hasSameAVL(PrevInfo) && DefInfo.hasSameVLMAX(PrevInfo)) {
1188 auto MI =
1189 BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0X0))
1191 .addReg(RISCV::X0, RegState::Kill)
1192 .addImm(Info.encodeVTYPE())
1193 .addReg(RISCV::VL, RegState::Implicit);
1194 if (LIS)
1196 return;
1197 }
1198 }
1199 }
1200 }
1201
1202 if (Info.hasAVLImm()) {
1203 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETIVLI))
1205 .addImm(Info.getAVLImm())
1206 .addImm(Info.encodeVTYPE());
1207 if (LIS)
1209 return;
1210 }
1211
1212 if (Info.hasAVLVLMAX()) {
1213 Register DestReg = MRI->createVirtualRegister(&RISCV::GPRNoX0RegClass);
1214 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
1216 .addReg(RISCV::X0, RegState::Kill)
1217 .addImm(Info.encodeVTYPE());
1218 if (LIS) {
1220 LIS->createAndComputeVirtRegInterval(DestReg);
1221 }
1222 return;
1223 }
1224
1225 Register AVLReg = Info.getAVLReg();
1226 MRI->constrainRegClass(AVLReg, &RISCV::GPRNoX0RegClass);
1227 auto MI = BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLI))
1229 .addReg(AVLReg)
1230 .addImm(Info.encodeVTYPE());
1231 if (LIS) {
1233 LiveInterval &LI = LIS->getInterval(AVLReg);
1234 SlotIndex SI = LIS->getInstructionIndex(*MI).getRegSlot();
1235 const VNInfo *CurVNI = Info.getAVLVNInfo();
1236 // If the AVL value isn't live at MI, do a quick check to see if it's easily
1237 // extendable. Otherwise, we need to copy it.
1238 if (LI.getVNInfoBefore(SI) != CurVNI) {
1239 if (!LI.liveAt(SI) && LI.containsOneValue())
1240 LIS->extendToIndices(LI, SI);
1241 else {
1242 Register AVLCopyReg =
1243 MRI->createVirtualRegister(&RISCV::GPRNoX0RegClass);
1244 MachineBasicBlock *MBB = LIS->getMBBFromIndex(CurVNI->def);
1246 if (CurVNI->isPHIDef())
1247 II = MBB->getFirstNonPHI();
1248 else {
1249 II = LIS->getInstructionFromIndex(CurVNI->def);
1250 II = std::next(II);
1251 }
1252 assert(II.isValid());
1253 auto AVLCopy = BuildMI(*MBB, II, DL, TII->get(RISCV::COPY), AVLCopyReg)
1254 .addReg(AVLReg);
1255 LIS->InsertMachineInstrInMaps(*AVLCopy);
1256 MI->getOperand(1).setReg(AVLCopyReg);
1257 LIS->createAndComputeVirtRegInterval(AVLCopyReg);
1258 }
1259 }
1260 }
1261}
1262
1263/// Return true if a VSETVLI is required to transition from CurInfo to Require
1264/// given a set of DemandedFields \p Used.
1265bool RISCVInsertVSETVLI::needVSETVLI(const DemandedFields &Used,
1266 const VSETVLIInfo &Require,
1267 const VSETVLIInfo &CurInfo) const {
1268 if (!CurInfo.isValid() || CurInfo.isUnknown() || CurInfo.hasSEWLMULRatioOnly())
1269 return true;
1270
1271 if (CurInfo.isCompatible(Used, Require, LIS))
1272 return false;
1273
1274 return true;
1275}
1276
1277// If we don't use LMUL or the SEW/LMUL ratio, then adjust LMUL so that we
1278// maintain the SEW/LMUL ratio. This allows us to eliminate VL toggles in more
1279// places.
1280static VSETVLIInfo adjustIncoming(const VSETVLIInfo &PrevInfo,
1281 const VSETVLIInfo &NewInfo,
1282 DemandedFields &Demanded) {
1283 VSETVLIInfo Info = NewInfo;
1284
1285 if (!Demanded.LMUL && !Demanded.SEWLMULRatio && PrevInfo.isValid() &&
1286 !PrevInfo.isUnknown()) {
1287 if (auto NewVLMul = RISCVVType::getSameRatioLMUL(
1288 PrevInfo.getSEW(), PrevInfo.getVLMUL(), Info.getSEW()))
1289 Info.setVLMul(*NewVLMul);
1290 Demanded.LMUL = DemandedFields::LMULEqual;
1291 }
1292
1293 return Info;
1294}
1295
1296// Given an incoming state reaching MI, minimally modifies that state so that it
1297// is compatible with MI. The resulting state is guaranteed to be semantically
1298// legal for MI, but may not be the state requested by MI.
1299void RISCVInsertVSETVLI::transferBefore(VSETVLIInfo &Info,
1300 const MachineInstr &MI) const {
1301 if (isVectorCopy(ST->getRegisterInfo(), MI) &&
1302 (Info.isUnknown() || !Info.isValid() || Info.hasSEWLMULRatioOnly())) {
1303 // Use an arbitrary but valid AVL and VTYPE so vill will be cleared. It may
1304 // be coalesced into another vsetvli since we won't demand any fields.
1305 VSETVLIInfo NewInfo; // Need a new VSETVLIInfo to clear SEWLMULRatioOnly
1306 NewInfo.setAVLImm(1);
1307 NewInfo.setVTYPE(RISCVVType::LMUL_1, /*sew*/ 8, /*ta*/ true, /*ma*/ true,
1308 /*AltFmt*/ false, /*W*/ 0);
1309 Info = NewInfo;
1310 return;
1311 }
1312
1313 if (!RISCVII::hasSEWOp(MI.getDesc().TSFlags))
1314 return;
1315
1316 DemandedFields Demanded = getDemanded(MI, ST);
1317
1318 const VSETVLIInfo NewInfo = computeInfoForInstr(MI);
1319 assert(NewInfo.isValid() && !NewInfo.isUnknown());
1320 if (Info.isValid() && !needVSETVLI(Demanded, NewInfo, Info))
1321 return;
1322
1323 const VSETVLIInfo PrevInfo = Info;
1324 if (!Info.isValid() || Info.isUnknown())
1325 Info = NewInfo;
1326
1327 const VSETVLIInfo IncomingInfo = adjustIncoming(PrevInfo, NewInfo, Demanded);
1328
1329 // If MI only demands that VL has the same zeroness, we only need to set the
1330 // AVL if the zeroness differs. This removes a vsetvli entirely if the types
1331 // match or allows use of cheaper avl preserving variant if VLMAX doesn't
1332 // change. If VLMAX might change, we couldn't use the 'vsetvli x0, x0, vtype"
1333 // variant, so we avoid the transform to prevent extending live range of an
1334 // avl register operand.
1335 // TODO: We can probably relax this for immediates.
1336 bool EquallyZero = IncomingInfo.hasEquallyZeroAVL(PrevInfo, LIS) &&
1337 IncomingInfo.hasSameVLMAX(PrevInfo);
1338 if (Demanded.VLAny || (Demanded.VLZeroness && !EquallyZero))
1339 Info.setAVL(IncomingInfo);
1340
1341 Info.setVTYPE(
1342 ((Demanded.LMUL || Demanded.SEWLMULRatio) ? IncomingInfo : Info)
1343 .getVLMUL(),
1344 ((Demanded.SEW || Demanded.SEWLMULRatio) ? IncomingInfo : Info).getSEW(),
1345 // Prefer tail/mask agnostic since it can be relaxed to undisturbed later
1346 // if needed.
1347 (Demanded.TailPolicy ? IncomingInfo : Info).getTailAgnostic() ||
1348 IncomingInfo.getTailAgnostic(),
1349 (Demanded.MaskPolicy ? IncomingInfo : Info).getMaskAgnostic() ||
1350 IncomingInfo.getMaskAgnostic(),
1351 (Demanded.AltFmt ? IncomingInfo : Info).getAltFmt(),
1352 Demanded.TWiden ? IncomingInfo.getTWiden() : 0);
1353
1354 // If we only knew the sew/lmul ratio previously, replace the VTYPE but keep
1355 // the AVL.
1356 if (Info.hasSEWLMULRatioOnly()) {
1357 VSETVLIInfo RatiolessInfo = IncomingInfo;
1358 RatiolessInfo.setAVL(Info);
1359 Info = RatiolessInfo;
1360 }
1361}
1362
1363// Given a state with which we evaluated MI (see transferBefore above for why
1364// this might be different that the state MI requested), modify the state to
1365// reflect the changes MI might make.
1366void RISCVInsertVSETVLI::transferAfter(VSETVLIInfo &Info,
1367 const MachineInstr &MI) const {
1368 if (RISCVInstrInfo::isVectorConfigInstr(MI)) {
1369 Info = getInfoForVSETVLI(MI);
1370 return;
1371 }
1372
1373 if (RISCVInstrInfo::isFaultOnlyFirstLoad(MI)) {
1374 // Update AVL to vl-output of the fault first load.
1375 assert(MI.getOperand(1).getReg().isVirtual());
1376 if (LIS) {
1377 auto &LI = LIS->getInterval(MI.getOperand(1).getReg());
1378 SlotIndex SI =
1380 VNInfo *VNI = LI.getVNInfoAt(SI);
1381 Info.setAVLRegDef(VNI, MI.getOperand(1).getReg());
1382 } else
1383 Info.setAVLRegDef(nullptr, MI.getOperand(1).getReg());
1384 return;
1385 }
1386
1387 // If this is something that updates VL/VTYPE that we don't know about, set
1388 // the state to unknown.
1389 if (MI.isCall() || MI.isInlineAsm() ||
1390 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
1391 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
1392 Info = VSETVLIInfo::getUnknown();
1393}
1394
1395bool RISCVInsertVSETVLI::computeVLVTYPEChanges(const MachineBasicBlock &MBB,
1396 VSETVLIInfo &Info) const {
1397 bool HadVectorOp = false;
1398
1399 Info = BlockInfo[MBB.getNumber()].Pred;
1400 for (const MachineInstr &MI : MBB) {
1401 transferBefore(Info, MI);
1402
1403 if (RISCVInstrInfo::isVectorConfigInstr(MI) ||
1404 RISCVII::hasSEWOp(MI.getDesc().TSFlags) ||
1405 isVectorCopy(ST->getRegisterInfo(), MI) ||
1406 RISCVInstrInfo::isXSfmmVectorConfigInstr(MI))
1407 HadVectorOp = true;
1408
1409 transferAfter(Info, MI);
1410 }
1411
1412 return HadVectorOp;
1413}
1414
1415void RISCVInsertVSETVLI::computeIncomingVLVTYPE(const MachineBasicBlock &MBB) {
1416
1417 BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1418
1419 BBInfo.InQueue = false;
1420
1421 // Start with the previous entry so that we keep the most conservative state
1422 // we have ever found.
1423 VSETVLIInfo InInfo = BBInfo.Pred;
1424 if (MBB.pred_empty()) {
1425 // There are no predecessors, so use the default starting status.
1426 InInfo.setUnknown();
1427 } else {
1428 for (MachineBasicBlock *P : MBB.predecessors())
1429 InInfo = InInfo.intersect(BlockInfo[P->getNumber()].Exit);
1430 }
1431
1432 // If we don't have any valid predecessor value, wait until we do.
1433 if (!InInfo.isValid())
1434 return;
1435
1436 // If no change, no need to rerun block
1437 if (InInfo == BBInfo.Pred)
1438 return;
1439
1440 BBInfo.Pred = InInfo;
1441 LLVM_DEBUG(dbgs() << "Entry state of " << printMBBReference(MBB)
1442 << " changed to " << BBInfo.Pred << "\n");
1443
1444 // Note: It's tempting to cache the state changes here, but due to the
1445 // compatibility checks performed a blocks output state can change based on
1446 // the input state. To cache, we'd have to add logic for finding
1447 // never-compatible state changes.
1448 VSETVLIInfo TmpStatus;
1449 computeVLVTYPEChanges(MBB, TmpStatus);
1450
1451 // If the new exit value matches the old exit value, we don't need to revisit
1452 // any blocks.
1453 if (BBInfo.Exit == TmpStatus)
1454 return;
1455
1456 BBInfo.Exit = TmpStatus;
1457 LLVM_DEBUG(dbgs() << "Exit state of " << printMBBReference(MBB)
1458 << " changed to " << BBInfo.Exit << "\n");
1459
1460 // Add the successors to the work list so we can propagate the changed exit
1461 // status.
1462 for (MachineBasicBlock *S : MBB.successors())
1463 if (!BlockInfo[S->getNumber()].InQueue) {
1464 BlockInfo[S->getNumber()].InQueue = true;
1465 WorkList.push(S);
1466 }
1467}
1468
1469// If we weren't able to prove a vsetvli was directly unneeded, it might still
1470// be unneeded if the AVL was a phi node where all incoming values are VL
1471// outputs from the last VSETVLI in their respective basic blocks.
1472bool RISCVInsertVSETVLI::needVSETVLIPHI(const VSETVLIInfo &Require,
1473 const MachineBasicBlock &MBB) const {
1474 if (!Require.hasAVLReg())
1475 return true;
1476
1477 if (!LIS)
1478 return true;
1479
1480 // We need the AVL to have been produced by a PHI node in this basic block.
1481 const VNInfo *Valno = Require.getAVLVNInfo();
1482 if (!Valno->isPHIDef() || LIS->getMBBFromIndex(Valno->def) != &MBB)
1483 return true;
1484
1485 const LiveRange &LR = LIS->getInterval(Require.getAVLReg());
1486
1487 for (auto *PBB : MBB.predecessors()) {
1488 const VSETVLIInfo &PBBExit = BlockInfo[PBB->getNumber()].Exit;
1489
1490 // We need the PHI input to the be the output of a VSET(I)VLI.
1491 const VNInfo *Value = LR.getVNInfoBefore(LIS->getMBBEndIdx(PBB));
1492 if (!Value)
1493 return true;
1494 MachineInstr *DefMI = LIS->getInstructionFromIndex(Value->def);
1495 if (!DefMI || !RISCVInstrInfo::isVectorConfigInstr(*DefMI))
1496 return true;
1497
1498 // We found a VSET(I)VLI make sure it matches the output of the
1499 // predecessor block.
1500 VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1501 if (DefInfo != PBBExit)
1502 return true;
1503
1504 // Require has the same VL as PBBExit, so if the exit from the
1505 // predecessor has the VTYPE we are looking for we might be able
1506 // to avoid a VSETVLI.
1507 if (PBBExit.isUnknown() || !PBBExit.hasSameVTYPE(Require))
1508 return true;
1509 }
1510
1511 // If all the incoming values to the PHI checked out, we don't need
1512 // to insert a VSETVLI.
1513 return false;
1514}
1515
1516void RISCVInsertVSETVLI::emitVSETVLIs(MachineBasicBlock &MBB) {
1517 VSETVLIInfo CurInfo = BlockInfo[MBB.getNumber()].Pred;
1518 // Track whether the prefix of the block we've scanned is transparent
1519 // (meaning has not yet changed the abstract state).
1520 bool PrefixTransparent = true;
1521 for (MachineInstr &MI : MBB) {
1522 const VSETVLIInfo PrevInfo = CurInfo;
1523 transferBefore(CurInfo, MI);
1524
1525 // If this is an explicit VSETVLI or VSETIVLI, update our state.
1526 if (RISCVInstrInfo::isVectorConfigInstr(MI)) {
1527 // Conservatively, mark the VL and VTYPE as live.
1528 assert(MI.getOperand(3).getReg() == RISCV::VL &&
1529 MI.getOperand(4).getReg() == RISCV::VTYPE &&
1530 "Unexpected operands where VL and VTYPE should be");
1531 MI.getOperand(3).setIsDead(false);
1532 MI.getOperand(4).setIsDead(false);
1533 PrefixTransparent = false;
1534 }
1535
1537 isVectorCopy(ST->getRegisterInfo(), MI)) {
1538 if (!PrevInfo.isCompatible(DemandedFields::all(), CurInfo, LIS)) {
1539 insertVSETVLI(MBB, MI, MI.getDebugLoc(), CurInfo, PrevInfo);
1540 PrefixTransparent = false;
1541 }
1542 MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
1543 /*isImp*/ true));
1544 }
1545
1546 uint64_t TSFlags = MI.getDesc().TSFlags;
1547 if (RISCVII::hasSEWOp(TSFlags)) {
1548 if (!PrevInfo.isCompatible(DemandedFields::all(), CurInfo, LIS)) {
1549 // If this is the first implicit state change, and the state change
1550 // requested can be proven to produce the same register contents, we
1551 // can skip emitting the actual state change and continue as if we
1552 // had since we know the GPR result of the implicit state change
1553 // wouldn't be used and VL/VTYPE registers are correct. Note that
1554 // we *do* need to model the state as if it changed as while the
1555 // register contents are unchanged, the abstract model can change.
1556 if (!PrefixTransparent || needVSETVLIPHI(CurInfo, MBB))
1557 insertVSETVLI(MBB, MI, MI.getDebugLoc(), CurInfo, PrevInfo);
1558 PrefixTransparent = false;
1559 }
1560
1561 if (RISCVII::hasVLOp(TSFlags)) {
1562 MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1563 if (VLOp.isReg()) {
1564 Register Reg = VLOp.getReg();
1565
1566 // Erase the AVL operand from the instruction.
1567 VLOp.setReg(Register());
1568 VLOp.setIsKill(false);
1569 if (LIS) {
1570 LiveInterval &LI = LIS->getInterval(Reg);
1572 LIS->shrinkToUses(&LI, &DeadMIs);
1573 // We might have separate components that need split due to
1574 // needVSETVLIPHI causing us to skip inserting a new VL def.
1576 LIS->splitSeparateComponents(LI, SplitLIs);
1577
1578 // If the AVL was an immediate > 31, then it would have been emitted
1579 // as an ADDI. However, the ADDI might not have been used in the
1580 // vsetvli, or a vsetvli might not have been emitted, so it may be
1581 // dead now.
1582 for (MachineInstr *DeadMI : DeadMIs) {
1583 if (!TII->isAddImmediate(*DeadMI, Reg))
1584 continue;
1585 LIS->RemoveMachineInstrFromMaps(*DeadMI);
1586 DeadMI->eraseFromParent();
1587 }
1588 }
1589 }
1590 MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ false,
1591 /*isImp*/ true));
1592 }
1593 MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
1594 /*isImp*/ true));
1595 }
1596
1597 if (MI.isInlineAsm()) {
1598 MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ true,
1599 /*isImp*/ true));
1600 MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ true,
1601 /*isImp*/ true));
1602 }
1603
1604 if (MI.isCall() || MI.isInlineAsm() ||
1605 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
1606 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
1607 PrefixTransparent = false;
1608
1609 transferAfter(CurInfo, MI);
1610 }
1611
1612 const auto &Info = BlockInfo[MBB.getNumber()];
1613 if (CurInfo != Info.Exit) {
1614 LLVM_DEBUG(dbgs() << "in block " << printMBBReference(MBB) << "\n");
1615 LLVM_DEBUG(dbgs() << " begin state: " << Info.Pred << "\n");
1616 LLVM_DEBUG(dbgs() << " expected end state: " << Info.Exit << "\n");
1617 LLVM_DEBUG(dbgs() << " actual end state: " << CurInfo << "\n");
1618 }
1619 assert(CurInfo == Info.Exit && "InsertVSETVLI dataflow invariant violated");
1620}
1621
1622/// Perform simple partial redundancy elimination of the VSETVLI instructions
1623/// we're about to insert by looking for cases where we can PRE from the
1624/// beginning of one block to the end of one of its predecessors. Specifically,
1625/// this is geared to catch the common case of a fixed length vsetvl in a single
1626/// block loop when it could execute once in the preheader instead.
1627void RISCVInsertVSETVLI::doPRE(MachineBasicBlock &MBB) {
1628 if (!BlockInfo[MBB.getNumber()].Pred.isUnknown())
1629 return;
1630
1631 MachineBasicBlock *UnavailablePred = nullptr;
1632 VSETVLIInfo AvailableInfo;
1633 for (MachineBasicBlock *P : MBB.predecessors()) {
1634 const VSETVLIInfo &PredInfo = BlockInfo[P->getNumber()].Exit;
1635 if (PredInfo.isUnknown()) {
1636 if (UnavailablePred)
1637 return;
1638 UnavailablePred = P;
1639 } else if (!AvailableInfo.isValid()) {
1640 AvailableInfo = PredInfo;
1641 } else if (AvailableInfo != PredInfo) {
1642 return;
1643 }
1644 }
1645
1646 // Unreachable, single pred, or full redundancy. Note that FRE is handled by
1647 // phase 3.
1648 if (!UnavailablePred || !AvailableInfo.isValid())
1649 return;
1650
1651 if (!LIS)
1652 return;
1653
1654 // If we don't know the exact VTYPE, we can't copy the vsetvli to the exit of
1655 // the unavailable pred.
1656 if (AvailableInfo.hasSEWLMULRatioOnly())
1657 return;
1658
1659 // Critical edge - TODO: consider splitting?
1660 if (UnavailablePred->succ_size() != 1)
1661 return;
1662
1663 // If the AVL value is a register (other than our VLMAX sentinel),
1664 // we need to prove the value is available at the point we're going
1665 // to insert the vsetvli at.
1666 if (AvailableInfo.hasAVLReg()) {
1667 SlotIndex SI = AvailableInfo.getAVLVNInfo()->def;
1668 // This is an inline dominance check which covers the case of
1669 // UnavailablePred being the preheader of a loop.
1670 if (LIS->getMBBFromIndex(SI) != UnavailablePred)
1671 return;
1672 if (!UnavailablePred->terminators().empty() &&
1673 SI >= LIS->getInstructionIndex(*UnavailablePred->getFirstTerminator()))
1674 return;
1675 }
1676
1677 // Model the effect of changing the input state of the block MBB to
1678 // AvailableInfo. We're looking for two issues here; one legality,
1679 // one profitability.
1680 // 1) If the block doesn't use some of the fields from VL or VTYPE, we
1681 // may hit the end of the block with a different end state. We can
1682 // not make this change without reflowing later blocks as well.
1683 // 2) If we don't actually remove a transition, inserting a vsetvli
1684 // into the predecessor block would be correct, but unprofitable.
1685 VSETVLIInfo OldInfo = BlockInfo[MBB.getNumber()].Pred;
1686 VSETVLIInfo CurInfo = AvailableInfo;
1687 int TransitionsRemoved = 0;
1688 for (const MachineInstr &MI : MBB) {
1689 const VSETVLIInfo LastInfo = CurInfo;
1690 const VSETVLIInfo LastOldInfo = OldInfo;
1691 transferBefore(CurInfo, MI);
1692 transferBefore(OldInfo, MI);
1693 if (CurInfo == LastInfo)
1694 TransitionsRemoved++;
1695 if (LastOldInfo == OldInfo)
1696 TransitionsRemoved--;
1697 transferAfter(CurInfo, MI);
1698 transferAfter(OldInfo, MI);
1699 if (CurInfo == OldInfo)
1700 // Convergence. All transitions after this must match by construction.
1701 break;
1702 }
1703 if (CurInfo != OldInfo || TransitionsRemoved <= 0)
1704 // Issues 1 and 2 above
1705 return;
1706
1707 // Finally, update both data flow state and insert the actual vsetvli.
1708 // Doing both keeps the code in sync with the dataflow results, which
1709 // is critical for correctness of phase 3.
1710 auto OldExit = BlockInfo[UnavailablePred->getNumber()].Exit;
1711 LLVM_DEBUG(dbgs() << "PRE VSETVLI from " << MBB.getName() << " to "
1712 << UnavailablePred->getName() << " with state "
1713 << AvailableInfo << "\n");
1714 BlockInfo[UnavailablePred->getNumber()].Exit = AvailableInfo;
1715 BlockInfo[MBB.getNumber()].Pred = AvailableInfo;
1716
1717 // Note there's an implicit assumption here that terminators never use
1718 // or modify VL or VTYPE. Also, fallthrough will return end().
1719 auto InsertPt = UnavailablePred->getFirstInstrTerminator();
1720 insertVSETVLI(*UnavailablePred, InsertPt,
1721 UnavailablePred->findDebugLoc(InsertPt),
1722 AvailableInfo, OldExit);
1723}
1724
1725// Return true if we can mutate PrevMI to match MI without changing any the
1726// fields which would be observed.
1727bool RISCVInsertVSETVLI::canMutatePriorConfig(
1728 const MachineInstr &PrevMI, const MachineInstr &MI,
1729 const DemandedFields &Used) const {
1730 // If the VL values aren't equal, return false if either a) the former is
1731 // demanded, or b) we can't rewrite the former to be the later for
1732 // implementation reasons.
1733 if (!RISCVInstrInfo::isVLPreservingConfig(MI)) {
1734 if (Used.VLAny)
1735 return false;
1736
1737 if (Used.VLZeroness) {
1738 if (RISCVInstrInfo::isVLPreservingConfig(PrevMI))
1739 return false;
1740 if (!getInfoForVSETVLI(PrevMI).hasEquallyZeroAVL(getInfoForVSETVLI(MI),
1741 LIS))
1742 return false;
1743 }
1744
1745 auto &AVL = MI.getOperand(1);
1746
1747 // If the AVL is a register, we need to make sure its definition is the same
1748 // at PrevMI as it was at MI.
1749 if (AVL.isReg() && AVL.getReg() != RISCV::X0) {
1750 VNInfo *VNI = getVNInfoFromReg(AVL.getReg(), MI, LIS);
1751 VNInfo *PrevVNI = getVNInfoFromReg(AVL.getReg(), PrevMI, LIS);
1752 if (!VNI || !PrevVNI || VNI != PrevVNI)
1753 return false;
1754 }
1755 }
1756
1757 assert(PrevMI.getOperand(2).isImm() && MI.getOperand(2).isImm());
1758 auto PriorVType = PrevMI.getOperand(2).getImm();
1759 auto VType = MI.getOperand(2).getImm();
1760 return areCompatibleVTYPEs(PriorVType, VType, Used);
1761}
1762
1763void RISCVInsertVSETVLI::coalesceVSETVLIs(MachineBasicBlock &MBB) const {
1764 MachineInstr *NextMI = nullptr;
1765 // We can have arbitrary code in successors, so VL and VTYPE
1766 // must be considered demanded.
1767 DemandedFields Used;
1768 Used.demandVL();
1769 Used.demandVTYPE();
1771
1772 auto dropAVLUse = [&](MachineOperand &MO) {
1773 if (!MO.isReg() || !MO.getReg().isVirtual())
1774 return;
1775 Register OldVLReg = MO.getReg();
1776 MO.setReg(Register());
1777
1778 if (LIS)
1779 LIS->shrinkToUses(&LIS->getInterval(OldVLReg));
1780
1781 MachineInstr *VLOpDef = MRI->getUniqueVRegDef(OldVLReg);
1782 if (VLOpDef && TII->isAddImmediate(*VLOpDef, OldVLReg) &&
1783 MRI->use_nodbg_empty(OldVLReg))
1784 ToDelete.push_back(VLOpDef);
1785 };
1786
1787 for (MachineInstr &MI : make_early_inc_range(reverse(MBB))) {
1788 // TODO: Support XSfmm.
1789 if (RISCVII::hasTWidenOp(MI.getDesc().TSFlags) ||
1790 RISCVInstrInfo::isXSfmmVectorConfigInstr(MI)) {
1791 NextMI = nullptr;
1792 continue;
1793 }
1794
1795 if (!RISCVInstrInfo::isVectorConfigInstr(MI)) {
1796 Used.doUnion(getDemanded(MI, ST));
1797 if (MI.isCall() || MI.isInlineAsm() ||
1798 MI.modifiesRegister(RISCV::VL, /*TRI=*/nullptr) ||
1799 MI.modifiesRegister(RISCV::VTYPE, /*TRI=*/nullptr))
1800 NextMI = nullptr;
1801 continue;
1802 }
1803
1804 if (!MI.getOperand(0).isDead())
1805 Used.demandVL();
1806
1807 if (NextMI) {
1808 if (!Used.usedVL() && !Used.usedVTYPE()) {
1809 dropAVLUse(MI.getOperand(1));
1810 if (LIS)
1812 MI.eraseFromParent();
1813 NumCoalescedVSETVL++;
1814 // Leave NextMI unchanged
1815 continue;
1816 }
1817
1818 if (canMutatePriorConfig(MI, *NextMI, Used)) {
1819 if (!RISCVInstrInfo::isVLPreservingConfig(*NextMI)) {
1820 Register DefReg = NextMI->getOperand(0).getReg();
1821
1822 MI.getOperand(0).setReg(DefReg);
1823 MI.getOperand(0).setIsDead(false);
1824
1825 // Move the AVL from NextMI to MI
1826 dropAVLUse(MI.getOperand(1));
1827 if (NextMI->getOperand(1).isImm())
1828 MI.getOperand(1).ChangeToImmediate(NextMI->getOperand(1).getImm());
1829 else
1830 MI.getOperand(1).ChangeToRegister(NextMI->getOperand(1).getReg(),
1831 false);
1832 dropAVLUse(NextMI->getOperand(1));
1833
1834 // The def of DefReg moved to MI, so extend the LiveInterval up to
1835 // it.
1836 if (DefReg.isVirtual() && LIS) {
1837 LiveInterval &DefLI = LIS->getInterval(DefReg);
1838 SlotIndex MISlot = LIS->getInstructionIndex(MI).getRegSlot();
1839 SlotIndex NextMISlot =
1840 LIS->getInstructionIndex(*NextMI).getRegSlot();
1841 VNInfo *DefVNI = DefLI.getVNInfoAt(NextMISlot);
1842 LiveInterval::Segment S(MISlot, NextMISlot, DefVNI);
1843 DefLI.addSegment(S);
1844 DefVNI->def = MISlot;
1845 // Mark DefLI as spillable if it was previously unspillable
1846 DefLI.setWeight(0);
1847
1848 // DefReg may have had no uses, in which case we need to shrink
1849 // the LiveInterval up to MI.
1850 LIS->shrinkToUses(&DefLI);
1851 }
1852
1853 MI.setDesc(NextMI->getDesc());
1854 }
1855 MI.getOperand(2).setImm(NextMI->getOperand(2).getImm());
1856
1857 dropAVLUse(NextMI->getOperand(1));
1858 if (LIS)
1859 LIS->RemoveMachineInstrFromMaps(*NextMI);
1860 NextMI->eraseFromParent();
1861 NumCoalescedVSETVL++;
1862 // fallthrough
1863 }
1864 }
1865 NextMI = &MI;
1866 Used = getDemanded(MI, ST);
1867 }
1868
1869 // Loop over the dead AVL values, and delete them now. This has
1870 // to be outside the above loop to avoid invalidating iterators.
1871 for (auto *MI : ToDelete) {
1872 if (LIS) {
1873 LIS->removeInterval(MI->getOperand(0).getReg());
1875 }
1876 MI->eraseFromParent();
1877 }
1878}
1879
1880void RISCVInsertVSETVLI::insertReadVL(MachineBasicBlock &MBB) {
1881 for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
1882 MachineInstr &MI = *I++;
1883 if (RISCVInstrInfo::isFaultOnlyFirstLoad(MI)) {
1884 Register VLOutput = MI.getOperand(1).getReg();
1885 assert(VLOutput.isVirtual());
1886 if (!MI.getOperand(1).isDead()) {
1887 auto ReadVLMI = BuildMI(MBB, I, MI.getDebugLoc(),
1888 TII->get(RISCV::PseudoReadVL), VLOutput);
1889 // Move the LiveInterval's definition down to PseudoReadVL.
1890 if (LIS) {
1891 SlotIndex NewDefSI =
1892 LIS->InsertMachineInstrInMaps(*ReadVLMI).getRegSlot();
1893 LiveInterval &DefLI = LIS->getInterval(VLOutput);
1894 LiveRange::Segment *DefSeg = DefLI.getSegmentContaining(NewDefSI);
1895 VNInfo *DefVNI = DefLI.getVNInfoAt(DefSeg->start);
1896 DefLI.removeSegment(DefSeg->start, NewDefSI);
1897 DefVNI->def = NewDefSI;
1898 }
1899 }
1900 // We don't use the vl output of the VLEFF/VLSEGFF anymore.
1901 MI.getOperand(1).setReg(RISCV::X0);
1902 MI.addRegisterDefined(RISCV::VL, MRI->getTargetRegisterInfo());
1903 }
1904 }
1905}
1906
1907bool RISCVInsertVSETVLI::insertVSETMTK(MachineBasicBlock &MBB,
1908 TKTMMode Mode) const {
1909
1910 bool Changed = false;
1911 for (auto &MI : MBB) {
1912 uint64_t TSFlags = MI.getDesc().TSFlags;
1913 if (RISCVInstrInfo::isXSfmmVectorConfigTMTKInstr(MI) ||
1914 !RISCVII::hasSEWOp(TSFlags) || !RISCVII::hasTWidenOp(TSFlags))
1915 continue;
1916
1917 VSETVLIInfo CurrInfo = computeInfoForInstr(MI);
1918
1919 if (Mode == VSETTK && !RISCVII::hasTKOp(TSFlags))
1920 continue;
1921
1922 if (Mode == VSETTM && !RISCVII::hasTMOp(TSFlags))
1923 continue;
1924
1925 unsigned OpNum = 0;
1926 unsigned Opcode = 0;
1927 switch (Mode) {
1928 case VSETTK:
1929 OpNum = RISCVII::getTKOpNum(MI.getDesc());
1930 Opcode = RISCV::PseudoSF_VSETTK;
1931 break;
1932 case VSETTM:
1933 OpNum = RISCVII::getTMOpNum(MI.getDesc());
1934 Opcode = RISCV::PseudoSF_VSETTM;
1935 break;
1936 }
1937
1938 assert(OpNum && Opcode && "Invalid OpNum or Opcode");
1939
1940 MachineOperand &Op = MI.getOperand(OpNum);
1941
1942 auto TmpMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(Opcode))
1944 .addReg(Op.getReg())
1945 .addImm(Log2_32(CurrInfo.getSEW()))
1946 .addImm(Log2_32(CurrInfo.getTWiden()) + 1);
1947
1948 Changed = true;
1949 Register Reg = Op.getReg();
1950 Op.setReg(Register());
1951 Op.setIsKill(false);
1952 if (LIS) {
1953 LIS->InsertMachineInstrInMaps(*TmpMI);
1954 LiveInterval &LI = LIS->getInterval(Reg);
1955
1956 // Erase the AVL operand from the instruction.
1957 LIS->shrinkToUses(&LI);
1958 // TODO: Enable this once needVSETVLIPHI is supported.
1959 // SmallVector<LiveInterval *> SplitLIs;
1960 // LIS->splitSeparateComponents(LI, SplitLIs);
1961 }
1962 }
1963 return Changed;
1964}
1965
1966bool RISCVInsertVSETVLI::runOnMachineFunction(MachineFunction &MF) {
1967 // Skip if the vector extension is not enabled.
1968 ST = &MF.getSubtarget<RISCVSubtarget>();
1969 if (!ST->hasVInstructions())
1970 return false;
1971
1972 LLVM_DEBUG(dbgs() << "Entering InsertVSETVLI for " << MF.getName() << "\n");
1973
1974 TII = ST->getInstrInfo();
1975 MRI = &MF.getRegInfo();
1976 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
1977 LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
1978
1979 assert(BlockInfo.empty() && "Expect empty block infos");
1980 BlockInfo.resize(MF.getNumBlockIDs());
1981
1982 bool HaveVectorOp = false;
1983
1984 // Phase 1 - determine how VL/VTYPE are affected by the each block.
1985 for (const MachineBasicBlock &MBB : MF) {
1986 VSETVLIInfo TmpStatus;
1987 HaveVectorOp |= computeVLVTYPEChanges(MBB, TmpStatus);
1988 // Initial exit state is whatever change we found in the block.
1989 BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1990 BBInfo.Exit = TmpStatus;
1991 LLVM_DEBUG(dbgs() << "Initial exit state of " << printMBBReference(MBB)
1992 << " is " << BBInfo.Exit << "\n");
1993
1994 }
1995
1996 // If we didn't find any instructions that need VSETVLI, we're done.
1997 if (!HaveVectorOp) {
1998 BlockInfo.clear();
1999 return false;
2000 }
2001
2002 // Phase 2 - determine the exit VL/VTYPE from each block. We add all
2003 // blocks to the list here, but will also add any that need to be revisited
2004 // during Phase 2 processing.
2005 for (const MachineBasicBlock &MBB : MF) {
2006 WorkList.push(&MBB);
2007 BlockInfo[MBB.getNumber()].InQueue = true;
2008 }
2009 while (!WorkList.empty()) {
2010 const MachineBasicBlock &MBB = *WorkList.front();
2011 WorkList.pop();
2012 computeIncomingVLVTYPE(MBB);
2013 }
2014
2015 // Perform partial redundancy elimination of vsetvli transitions.
2016 for (MachineBasicBlock &MBB : MF)
2017 doPRE(MBB);
2018
2019 // Phase 3 - add any vsetvli instructions needed in the block. Use the
2020 // Phase 2 information to avoid adding vsetvlis before the first vector
2021 // instruction in the block if the VL/VTYPE is satisfied by its
2022 // predecessors.
2023 for (MachineBasicBlock &MBB : MF)
2024 emitVSETVLIs(MBB);
2025
2026 // Now that all vsetvlis are explicit, go through and do block local
2027 // DSE and peephole based demanded fields based transforms. Note that
2028 // this *must* be done outside the main dataflow so long as we allow
2029 // any cross block analysis within the dataflow. We can't have both
2030 // demanded fields based mutation and non-local analysis in the
2031 // dataflow at the same time without introducing inconsistencies.
2032 // We're visiting blocks from the bottom up because a VSETVLI in the
2033 // earlier block might become dead when its uses in later blocks are
2034 // optimized away.
2035 for (MachineBasicBlock *MBB : post_order(&MF))
2036 coalesceVSETVLIs(*MBB);
2037
2038 // Insert PseudoReadVL after VLEFF/VLSEGFF and replace it with the vl output
2039 // of VLEFF/VLSEGFF.
2040 for (MachineBasicBlock &MBB : MF)
2041 insertReadVL(MBB);
2042
2043 for (MachineBasicBlock &MBB : MF) {
2044 insertVSETMTK(MBB, VSETTM);
2045 insertVSETMTK(MBB, VSETTK);
2046 }
2047
2048 BlockInfo.clear();
2049 return HaveVectorOp;
2050}
2051
2052/// Returns an instance of the Insert VSETVLI pass.
2054 return new RISCVInsertVSETVLI();
2055}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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:236
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:638
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:58
Register Reg
Register const TargetRegisterInfo * TRI
static Interval intersect(const Interval &I1, const Interval &I2)
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static cl::opt< bool > EnsureWholeVectorRegisterMoveValidVTYPE(DEBUG_TYPE "-whole-vector-register-move-valid-vtype", cl::Hidden, cl::desc("Insert vsetvlis before vmvNr.vs to ensure vtype is valid and " "vill is cleared"), cl::init(true))
static VSETVLIInfo adjustIncoming(const VSETVLIInfo &PrevInfo, const VSETVLIInfo &NewInfo, DemandedFields &Demanded)
#define RISCV_INSERT_VSETVLI_NAME
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI Optimize VGPR LiveRange
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
BlockData()=default
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
void setWeight(float Value)
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
SlotIndexes * getSlotIndexes() const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
LLVM_ABI void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
LLVM_ABI void splitSeparateComponents(LiveInterval &LI, SmallVectorImpl< LiveInterval * > &SplitLIs)
Split separate components in LiveInterval LI into separate intervals.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
bool liveAt(SlotIndex index) const
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
bool containsOneValue() const
LLVM_ABI 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.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI 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()
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI 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.
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.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI 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)
Wrapper class representing virtual and physical registers.
Definition Register.h:19
constexpr bool isValid() const
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:74
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
void push_back(const T &Elt)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
VNInfo - Value Number Information.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
Predicate all(Predicate P0, Predicate P1)
True iff P0 and P1 are true.
static unsigned getVecPolicyOpNum(const MCInstrDesc &Desc)
static unsigned getTMOpNum(const MCInstrDesc &Desc)
static bool usesMaskPolicy(uint64_t TSFlags)
static bool hasTWidenOp(uint64_t TSFlags)
static RISCVVType::VLMUL getLMul(uint64_t TSFlags)
static unsigned getTKOpNum(const MCInstrDesc &Desc)
static unsigned getVLOpNum(const MCInstrDesc &Desc)
static AltFmtType getAltFmtType(uint64_t TSFlags)
static bool hasTKOp(uint64_t TSFlags)
static bool hasVLOp(uint64_t TSFlags)
static bool hasTMOp(uint64_t TSFlags)
static unsigned getTNOpNum(const MCInstrDesc &Desc)
static bool hasVecPolicyOp(uint64_t TSFlags)
static unsigned getSEWOpNum(const MCInstrDesc &Desc)
static bool hasSEWOp(uint64_t TSFlags)
static bool isTailAgnostic(unsigned VType)
LLVM_ABI std::optional< VLMUL > getSameRatioLMUL(unsigned SEW, VLMUL VLMUL, unsigned EEW)
LLVM_ABI unsigned encodeXSfmmVType(unsigned SEW, unsigned Widen, bool AltFmt)
static unsigned getXSfmmWiden(unsigned VType)
static bool isMaskAgnostic(unsigned VType)
LLVM_ABI std::pair< unsigned, bool > decodeVLMUL(VLMUL VLMul)
static bool hasXSfmmWiden(unsigned VType)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static bool isValidSEW(unsigned SEW)
static bool isAltFmt(unsigned VType)
LLVM_ABI unsigned encodeVTYPE(VLMUL VLMUL, unsigned SEW, bool TailAgnostic, bool MaskAgnostic, bool AltFmt=false)
static unsigned getSEW(unsigned VType)
static VLMUL getVLMUL(unsigned VType)
unsigned getRVVMCOpcode(unsigned RVVPseudoOpcode)
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.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2113
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
iterator_range< po_iterator< T > > post_order(const T &G)
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:331
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionPass * createRISCVInsertVSETVLIPass()
Returns an instance of the Insert VSETVLI pass.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
char & RISCVInsertVSETVLIID
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
static bool isRVVRegClass(const TargetRegisterClass *RC)