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.
11 //
12 // This pass consists of 3 phases:
13 //
14 // Phase 1 collects how each basic block affects VL/VTYPE.
15 //
16 // Phase 2 uses the information from phase 1 to do a data flow analysis to
17 // propagate the VL/VTYPE changes through the function. This gives us the
18 // VL/VTYPE at the start of each basic block.
19 //
20 // Phase 3 inserts VSETVLI instructions in each basic block. Information from
21 // phase 2 is used to prevent inserting a VSETVLI before the first vector
22 // instruction in the block if possible.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "RISCV.h"
27 #include "RISCVSubtarget.h"
28 #include "llvm/CodeGen/LiveIntervals.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include <queue>
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "riscv-insert-vsetvli"
34 #define RISCV_INSERT_VSETVLI_NAME "RISCV Insert VSETVLI pass"
35 
36 static cl::opt<bool> DisableInsertVSETVLPHIOpt(
37     "riscv-disable-insert-vsetvl-phi-opt", cl::init(false), cl::Hidden,
38     cl::desc("Disable looking through phis when inserting vsetvlis."));
39 
40 namespace {
41 
42 class VSETVLIInfo {
43   union {
44     Register AVLReg;
45     unsigned AVLImm;
46   };
47 
48   enum : uint8_t {
49     Uninitialized,
50     AVLIsReg,
51     AVLIsImm,
52     Unknown,
53   } State = Uninitialized;
54 
55   // Fields from VTYPE.
56   RISCVII::VLMUL VLMul = RISCVII::LMUL_1;
57   uint8_t SEW = 0;
58   uint8_t TailAgnostic : 1;
59   uint8_t MaskAgnostic : 1;
60   uint8_t MaskRegOp : 1;
61   uint8_t StoreOp : 1;
62   uint8_t ScalarMovOp : 1;
63   uint8_t SEWLMULRatioOnly : 1;
64 
65 public:
66   VSETVLIInfo()
67       : AVLImm(0), TailAgnostic(false), MaskAgnostic(false), MaskRegOp(false),
68         StoreOp(false), ScalarMovOp(false), SEWLMULRatioOnly(false) {}
69 
70   static VSETVLIInfo getUnknown() {
71     VSETVLIInfo Info;
72     Info.setUnknown();
73     return Info;
74   }
75 
76   bool isValid() const { return State != Uninitialized; }
77   void setUnknown() { State = Unknown; }
78   bool isUnknown() const { return State == Unknown; }
79 
80   void setAVLReg(Register Reg) {
81     AVLReg = Reg;
82     State = AVLIsReg;
83   }
84 
85   void setAVLImm(unsigned Imm) {
86     AVLImm = Imm;
87     State = AVLIsImm;
88   }
89 
90   bool hasAVLImm() const { return State == AVLIsImm; }
91   bool hasAVLReg() const { return State == AVLIsReg; }
92   Register getAVLReg() const {
93     assert(hasAVLReg());
94     return AVLReg;
95   }
96   unsigned getAVLImm() const {
97     assert(hasAVLImm());
98     return AVLImm;
99   }
100   bool hasZeroAVL() const {
101     if (hasAVLImm())
102       return getAVLImm() == 0;
103     return false;
104   }
105   bool hasNonZeroAVL() const {
106     if (hasAVLImm())
107       return getAVLImm() > 0;
108     if (hasAVLReg())
109       return getAVLReg() == RISCV::X0;
110     return false;
111   }
112 
113   bool hasSameAVL(const VSETVLIInfo &Other) const {
114     assert(isValid() && Other.isValid() &&
115            "Can't compare invalid VSETVLIInfos");
116     assert(!isUnknown() && !Other.isUnknown() &&
117            "Can't compare AVL in unknown state");
118     if (hasAVLReg() && Other.hasAVLReg())
119       return getAVLReg() == Other.getAVLReg();
120 
121     if (hasAVLImm() && Other.hasAVLImm())
122       return getAVLImm() == Other.getAVLImm();
123 
124     return false;
125   }
126 
127   void setVTYPE(unsigned VType) {
128     assert(isValid() && !isUnknown() &&
129            "Can't set VTYPE for uninitialized or unknown");
130     VLMul = RISCVVType::getVLMUL(VType);
131     SEW = RISCVVType::getSEW(VType);
132     TailAgnostic = RISCVVType::isTailAgnostic(VType);
133     MaskAgnostic = RISCVVType::isMaskAgnostic(VType);
134   }
135   void setVTYPE(RISCVII::VLMUL L, unsigned S, bool TA, bool MA, bool MRO,
136                 bool IsStore, bool IsScalarMovOp) {
137     assert(isValid() && !isUnknown() &&
138            "Can't set VTYPE for uninitialized or unknown");
139     VLMul = L;
140     SEW = S;
141     TailAgnostic = TA;
142     MaskAgnostic = MA;
143     MaskRegOp = MRO;
144     StoreOp = IsStore;
145     ScalarMovOp = IsScalarMovOp;
146   }
147 
148   unsigned encodeVTYPE() const {
149     assert(isValid() && !isUnknown() && !SEWLMULRatioOnly &&
150            "Can't encode VTYPE for uninitialized or unknown");
151     return RISCVVType::encodeVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
152   }
153 
154   bool hasSEWLMULRatioOnly() const { return SEWLMULRatioOnly; }
155 
156   bool hasSameSEW(const VSETVLIInfo &Other) const {
157     assert(isValid() && Other.isValid() &&
158            "Can't compare invalid VSETVLIInfos");
159     assert(!isUnknown() && !Other.isUnknown() &&
160            "Can't compare VTYPE in unknown state");
161     assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
162            "Can't compare when only LMUL/SEW ratio is valid.");
163     return SEW == Other.SEW;
164   }
165 
166   bool hasSameVTYPE(const VSETVLIInfo &Other) const {
167     assert(isValid() && Other.isValid() &&
168            "Can't compare invalid VSETVLIInfos");
169     assert(!isUnknown() && !Other.isUnknown() &&
170            "Can't compare VTYPE in unknown state");
171     assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
172            "Can't compare when only LMUL/SEW ratio is valid.");
173     return std::tie(VLMul, SEW, TailAgnostic, MaskAgnostic) ==
174            std::tie(Other.VLMul, Other.SEW, Other.TailAgnostic,
175                     Other.MaskAgnostic);
176   }
177 
178   static unsigned getSEWLMULRatio(unsigned SEW, RISCVII::VLMUL VLMul) {
179     unsigned LMul;
180     bool Fractional;
181     std::tie(LMul, Fractional) = RISCVVType::decodeVLMUL(VLMul);
182 
183     // Convert LMul to a fixed point value with 3 fractional bits.
184     LMul = Fractional ? (8 / LMul) : (LMul * 8);
185 
186     assert(SEW >= 8 && "Unexpected SEW value");
187     return (SEW * 8) / LMul;
188   }
189 
190   unsigned getSEWLMULRatio() const {
191     assert(isValid() && !isUnknown() &&
192            "Can't use VTYPE for uninitialized or unknown");
193     return getSEWLMULRatio(SEW, VLMul);
194   }
195 
196   // Check if the VTYPE for these two VSETVLIInfos produce the same VLMAX.
197   bool hasSameVLMAX(const VSETVLIInfo &Other) const {
198     assert(isValid() && Other.isValid() &&
199            "Can't compare invalid VSETVLIInfos");
200     assert(!isUnknown() && !Other.isUnknown() &&
201            "Can't compare VTYPE in unknown state");
202     return getSEWLMULRatio() == Other.getSEWLMULRatio();
203   }
204 
205   bool hasSamePolicy(const VSETVLIInfo &Other) const {
206     assert(isValid() && Other.isValid() &&
207            "Can't compare invalid VSETVLIInfos");
208     assert(!isUnknown() && !Other.isUnknown() &&
209            "Can't compare VTYPE in unknown state");
210     return TailAgnostic == Other.TailAgnostic &&
211            MaskAgnostic == Other.MaskAgnostic;
212   }
213 
214   bool hasCompatibleVTYPE(const VSETVLIInfo &InstrInfo, bool Strict) const {
215     // Simple case, see if full VTYPE matches.
216     if (hasSameVTYPE(InstrInfo))
217       return true;
218 
219     if (Strict)
220       return false;
221 
222     // If this is a mask reg operation, it only cares about VLMAX.
223     // FIXME: Mask reg operations are probably ok if "this" VLMAX is larger
224     // than "InstrInfo".
225     // FIXME: The policy bits can probably be ignored for mask reg operations.
226     if (InstrInfo.MaskRegOp && hasSameVLMAX(InstrInfo) &&
227         TailAgnostic == InstrInfo.TailAgnostic &&
228         MaskAgnostic == InstrInfo.MaskAgnostic)
229       return true;
230 
231     return false;
232   }
233 
234   // Determine whether the vector instructions requirements represented by
235   // InstrInfo are compatible with the previous vsetvli instruction represented
236   // by this.
237   bool isCompatible(const VSETVLIInfo &InstrInfo, bool Strict) const {
238     assert(isValid() && InstrInfo.isValid() &&
239            "Can't compare invalid VSETVLIInfos");
240     assert(!InstrInfo.SEWLMULRatioOnly &&
241            "Expected a valid VTYPE for instruction!");
242     // Nothing is compatible with Unknown.
243     if (isUnknown() || InstrInfo.isUnknown())
244       return false;
245 
246     // If only our VLMAX ratio is valid, then this isn't compatible.
247     if (SEWLMULRatioOnly)
248       return false;
249 
250     // If the instruction doesn't need an AVLReg and the SEW matches, consider
251     // it compatible.
252     if (!Strict && InstrInfo.hasAVLReg() &&
253         InstrInfo.AVLReg == RISCV::NoRegister) {
254       if (SEW == InstrInfo.SEW)
255         return true;
256     }
257 
258     // For vmv.s.x and vfmv.s.f, there is only two behaviors, VL = 0 and VL > 0.
259     // So it's compatible when we could make sure that both VL be the same
260     // situation.
261     if (!Strict && InstrInfo.ScalarMovOp && InstrInfo.hasAVLImm() &&
262         ((hasNonZeroAVL() && InstrInfo.hasNonZeroAVL()) ||
263          (hasZeroAVL() && InstrInfo.hasZeroAVL())) &&
264         hasSameSEW(InstrInfo) && hasSamePolicy(InstrInfo))
265       return true;
266 
267     // The AVL must match.
268     if (!hasSameAVL(InstrInfo))
269       return false;
270 
271     if (hasCompatibleVTYPE(InstrInfo, Strict))
272       return true;
273 
274     // Strict matches must ensure a full VTYPE match.
275     if (Strict)
276       return false;
277 
278     // Store instructions don't use the policy fields.
279     // TODO: Move into hasCompatibleVTYPE?
280     if (InstrInfo.StoreOp && VLMul == InstrInfo.VLMul && SEW == InstrInfo.SEW)
281       return true;
282 
283     // Anything else is not compatible.
284     return false;
285   }
286 
287   bool isCompatibleWithLoadStoreEEW(unsigned EEW,
288                                     const VSETVLIInfo &InstrInfo) const {
289     assert(isValid() && InstrInfo.isValid() &&
290            "Can't compare invalid VSETVLIInfos");
291     assert(!InstrInfo.SEWLMULRatioOnly &&
292            "Expected a valid VTYPE for instruction!");
293     assert(EEW == InstrInfo.SEW && "Mismatched EEW/SEW for store");
294 
295     if (isUnknown() || hasSEWLMULRatioOnly())
296       return false;
297 
298     if (!hasSameAVL(InstrInfo))
299       return false;
300 
301     // Stores can ignore the tail and mask policies.
302     if (!InstrInfo.StoreOp && (TailAgnostic != InstrInfo.TailAgnostic ||
303                                MaskAgnostic != InstrInfo.MaskAgnostic))
304       return false;
305 
306     return getSEWLMULRatio() == getSEWLMULRatio(EEW, InstrInfo.VLMul);
307   }
308 
309   bool operator==(const VSETVLIInfo &Other) const {
310     // Uninitialized is only equal to another Uninitialized.
311     if (!isValid())
312       return !Other.isValid();
313     if (!Other.isValid())
314       return !isValid();
315 
316     // Unknown is only equal to another Unknown.
317     if (isUnknown())
318       return Other.isUnknown();
319     if (Other.isUnknown())
320       return isUnknown();
321 
322     if (!hasSameAVL(Other))
323       return false;
324 
325     // If only the VLMAX is valid, check that it is the same.
326     if (SEWLMULRatioOnly && Other.SEWLMULRatioOnly)
327       return hasSameVLMAX(Other);
328 
329     // If the full VTYPE is valid, check that it is the same.
330     if (!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly)
331       return hasSameVTYPE(Other);
332 
333     // If the SEWLMULRatioOnly bits are different, then they aren't equal.
334     return false;
335   }
336 
337   bool operator!=(const VSETVLIInfo &Other) const {
338     return !(*this == Other);
339   }
340 
341   // Calculate the VSETVLIInfo visible to a block assuming this and Other are
342   // both predecessors.
343   VSETVLIInfo intersect(const VSETVLIInfo &Other) const {
344     // If the new value isn't valid, ignore it.
345     if (!Other.isValid())
346       return *this;
347 
348     // If this value isn't valid, this must be the first predecessor, use it.
349     if (!isValid())
350       return Other;
351 
352     // If either is unknown, the result is unknown.
353     if (isUnknown() || Other.isUnknown())
354       return VSETVLIInfo::getUnknown();
355 
356     // If we have an exact, match return this.
357     if (*this == Other)
358       return *this;
359 
360     // Not an exact match, but maybe the AVL and VLMAX are the same. If so,
361     // return an SEW/LMUL ratio only value.
362     if (hasSameAVL(Other) && hasSameVLMAX(Other)) {
363       VSETVLIInfo MergeInfo = *this;
364       MergeInfo.SEWLMULRatioOnly = true;
365       return MergeInfo;
366     }
367 
368     // Otherwise the result is unknown.
369     return VSETVLIInfo::getUnknown();
370   }
371 
372   // Calculate the VSETVLIInfo visible at the end of the block assuming this
373   // is the predecessor value, and Other is change for this block.
374   VSETVLIInfo merge(const VSETVLIInfo &Other) const {
375     assert(isValid() && "Can only merge with a valid VSETVLInfo");
376 
377     // Nothing changed from the predecessor, keep it.
378     if (!Other.isValid())
379       return *this;
380 
381     // If the change is compatible with the input, we won't create a VSETVLI
382     // and should keep the predecessor.
383     if (isCompatible(Other, /*Strict*/ true))
384       return *this;
385 
386     // Otherwise just use whatever is in this block.
387     return Other;
388   }
389 };
390 
391 struct BlockData {
392   // The VSETVLIInfo that represents the net changes to the VL/VTYPE registers
393   // made by this block. Calculated in Phase 1.
394   VSETVLIInfo Change;
395 
396   // The VSETVLIInfo that represents the VL/VTYPE settings on exit from this
397   // block. Calculated in Phase 2.
398   VSETVLIInfo Exit;
399 
400   // The VSETVLIInfo that represents the VL/VTYPE settings from all predecessor
401   // blocks. Calculated in Phase 2, and used by Phase 3.
402   VSETVLIInfo Pred;
403 
404   // Keeps track of whether the block is already in the queue.
405   bool InQueue = false;
406 
407   BlockData() = default;
408 };
409 
410 class RISCVInsertVSETVLI : public MachineFunctionPass {
411   const TargetInstrInfo *TII;
412   MachineRegisterInfo *MRI;
413 
414   std::vector<BlockData> BlockInfo;
415   std::queue<const MachineBasicBlock *> WorkList;
416 
417 public:
418   static char ID;
419 
420   RISCVInsertVSETVLI() : MachineFunctionPass(ID) {
421     initializeRISCVInsertVSETVLIPass(*PassRegistry::getPassRegistry());
422   }
423   bool runOnMachineFunction(MachineFunction &MF) override;
424 
425   void getAnalysisUsage(AnalysisUsage &AU) const override {
426     AU.setPreservesCFG();
427     MachineFunctionPass::getAnalysisUsage(AU);
428   }
429 
430   StringRef getPassName() const override { return RISCV_INSERT_VSETVLI_NAME; }
431 
432 private:
433   bool needVSETVLI(const VSETVLIInfo &Require, const VSETVLIInfo &CurInfo);
434   bool needVSETVLIPHI(const VSETVLIInfo &Require, const MachineBasicBlock &MBB);
435   void insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
436                      const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
437 
438   bool computeVLVTYPEChanges(const MachineBasicBlock &MBB);
439   void computeIncomingVLVTYPE(const MachineBasicBlock &MBB);
440   void emitVSETVLIs(MachineBasicBlock &MBB);
441 };
442 
443 } // end anonymous namespace
444 
445 char RISCVInsertVSETVLI::ID = 0;
446 
447 INITIALIZE_PASS(RISCVInsertVSETVLI, DEBUG_TYPE, RISCV_INSERT_VSETVLI_NAME,
448                 false, false)
449 
450 static bool isVectorConfigInstr(const MachineInstr &MI) {
451   return MI.getOpcode() == RISCV::PseudoVSETVLI ||
452          MI.getOpcode() == RISCV::PseudoVSETVLIX0 ||
453          MI.getOpcode() == RISCV::PseudoVSETIVLI;
454 }
455 
456 static MachineInstr *elideCopies(MachineInstr *MI,
457                                  const MachineRegisterInfo *MRI) {
458   while (true) {
459     if (!MI->isFullCopy())
460       return MI;
461     if (!Register::isVirtualRegister(MI->getOperand(1).getReg()))
462       return nullptr;
463     MI = MRI->getVRegDef(MI->getOperand(1).getReg());
464     if (!MI)
465       return nullptr;
466   }
467 }
468 
469 static bool isScalarMoveInstr(const MachineInstr &MI) {
470   switch (MI.getOpcode()) {
471   default:
472     return false;
473   case RISCV::PseudoVMV_S_X_M1:
474   case RISCV::PseudoVMV_S_X_M2:
475   case RISCV::PseudoVMV_S_X_M4:
476   case RISCV::PseudoVMV_S_X_M8:
477   case RISCV::PseudoVMV_S_X_MF2:
478   case RISCV::PseudoVMV_S_X_MF4:
479   case RISCV::PseudoVMV_S_X_MF8:
480   case RISCV::PseudoVFMV_S_F16_M1:
481   case RISCV::PseudoVFMV_S_F16_M2:
482   case RISCV::PseudoVFMV_S_F16_M4:
483   case RISCV::PseudoVFMV_S_F16_M8:
484   case RISCV::PseudoVFMV_S_F16_MF2:
485   case RISCV::PseudoVFMV_S_F16_MF4:
486   case RISCV::PseudoVFMV_S_F32_M1:
487   case RISCV::PseudoVFMV_S_F32_M2:
488   case RISCV::PseudoVFMV_S_F32_M4:
489   case RISCV::PseudoVFMV_S_F32_M8:
490   case RISCV::PseudoVFMV_S_F32_MF2:
491   case RISCV::PseudoVFMV_S_F64_M1:
492   case RISCV::PseudoVFMV_S_F64_M2:
493   case RISCV::PseudoVFMV_S_F64_M4:
494   case RISCV::PseudoVFMV_S_F64_M8:
495     return true;
496   }
497 }
498 
499 static VSETVLIInfo computeInfoForInstr(const MachineInstr &MI, uint64_t TSFlags,
500                                        const MachineRegisterInfo *MRI) {
501   VSETVLIInfo InstrInfo;
502   unsigned NumOperands = MI.getNumExplicitOperands();
503   bool HasPolicy = RISCVII::hasVecPolicyOp(TSFlags);
504 
505   // If the instruction has policy argument, use the argument.
506   // If there is no policy argument, default to tail agnostic unless the
507   // destination is tied to a source. Unless the source is undef. In that case
508   // the user would have some control over the policy values. Some pseudo
509   // instructions force a tail agnostic policy despite having a tied def.
510   bool ForceTailAgnostic = RISCVII::doesForceTailAgnostic(TSFlags);
511   bool TailAgnostic = true;
512   bool UsesMaskPolicy = RISCVII::UsesMaskPolicy(TSFlags);
513   // FIXME: Could we look at the above or below instructions to choose the
514   // matched mask policy to reduce vsetvli instructions? Default mask policy is
515   // agnostic if instructions use mask policy, otherwise is undisturbed. Because
516   // most mask operations are mask undisturbed, so we could possibly reduce the
517   // vsetvli between mask and nomasked instruction sequence.
518   bool MaskAgnostic = UsesMaskPolicy;
519   unsigned UseOpIdx;
520   if (HasPolicy) {
521     const MachineOperand &Op = MI.getOperand(MI.getNumExplicitOperands() - 1);
522     uint64_t Policy = Op.getImm();
523     assert(Policy <= (RISCVII::TAIL_AGNOSTIC | RISCVII::MASK_AGNOSTIC) &&
524            "Invalid Policy Value");
525     // Although in some cases, mismatched passthru/maskedoff with policy value
526     // does not make sense (ex. tied operand is IMPLICIT_DEF with non-TAMA
527     // policy, or tied operand is not IMPLICIT_DEF with TAMA policy), but users
528     // have set the policy value explicitly, so compiler would not fix it.
529     TailAgnostic = Policy & RISCVII::TAIL_AGNOSTIC;
530     MaskAgnostic = Policy & RISCVII::MASK_AGNOSTIC;
531   } else if (!ForceTailAgnostic && MI.isRegTiedToUseOperand(0, &UseOpIdx)) {
532     TailAgnostic = false;
533     if (UsesMaskPolicy)
534       MaskAgnostic = false;
535     // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic.
536     const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
537     MachineInstr *UseMI = MRI->getVRegDef(UseMO.getReg());
538     if (UseMI) {
539       UseMI = elideCopies(UseMI, MRI);
540       if (UseMI && UseMI->isImplicitDef()) {
541         TailAgnostic = true;
542         if (UsesMaskPolicy)
543           MaskAgnostic = true;
544       }
545     }
546   }
547 
548   // Remove the tail policy so we can find the SEW and VL.
549   if (HasPolicy)
550     --NumOperands;
551 
552   RISCVII::VLMUL VLMul = RISCVII::getLMul(TSFlags);
553 
554   unsigned Log2SEW = MI.getOperand(NumOperands - 1).getImm();
555   // A Log2SEW of 0 is an operation on mask registers only.
556   bool MaskRegOp = Log2SEW == 0;
557   unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
558   assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
559 
560   // If there are no explicit defs, this is a store instruction which can
561   // ignore the tail and mask policies.
562   bool StoreOp = MI.getNumExplicitDefs() == 0;
563   bool ScalarMovOp = isScalarMoveInstr(MI);
564 
565   if (RISCVII::hasVLOp(TSFlags)) {
566     const MachineOperand &VLOp = MI.getOperand(NumOperands - 2);
567     if (VLOp.isImm()) {
568       int64_t Imm = VLOp.getImm();
569       // Conver the VLMax sentintel to X0 register.
570       if (Imm == RISCV::VLMaxSentinel)
571         InstrInfo.setAVLReg(RISCV::X0);
572       else
573         InstrInfo.setAVLImm(Imm);
574     } else {
575       InstrInfo.setAVLReg(VLOp.getReg());
576     }
577   } else
578     InstrInfo.setAVLReg(RISCV::NoRegister);
579   InstrInfo.setVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic, MaskRegOp, StoreOp,
580                      ScalarMovOp);
581 
582   return InstrInfo;
583 }
584 
585 void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
586                                        const VSETVLIInfo &Info,
587                                        const VSETVLIInfo &PrevInfo) {
588   DebugLoc DL = MI.getDebugLoc();
589 
590   // Use X0, X0 form if the AVL is the same and the SEW+LMUL gives the same
591   // VLMAX.
592   if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
593       Info.hasSameAVL(PrevInfo) && Info.hasSameVLMAX(PrevInfo)) {
594     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETVLIX0))
595         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
596         .addReg(RISCV::X0, RegState::Kill)
597         .addImm(Info.encodeVTYPE())
598         .addReg(RISCV::VL, RegState::Implicit);
599     return;
600   }
601 
602   if (Info.hasAVLImm()) {
603     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETIVLI))
604         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
605         .addImm(Info.getAVLImm())
606         .addImm(Info.encodeVTYPE());
607     return;
608   }
609 
610   Register AVLReg = Info.getAVLReg();
611   if (AVLReg == RISCV::NoRegister) {
612     // We can only use x0, x0 if there's no chance of the vtype change causing
613     // the previous vl to become invalid.
614     if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
615         Info.hasSameVLMAX(PrevInfo)) {
616       BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETVLIX0))
617           .addReg(RISCV::X0, RegState::Define | RegState::Dead)
618           .addReg(RISCV::X0, RegState::Kill)
619           .addImm(Info.encodeVTYPE())
620           .addReg(RISCV::VL, RegState::Implicit);
621       return;
622     }
623     // Otherwise use an AVL of 0 to avoid depending on previous vl.
624     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETIVLI))
625         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
626         .addImm(0)
627         .addImm(Info.encodeVTYPE());
628     return;
629   }
630 
631   if (AVLReg.isVirtual())
632     MRI->constrainRegClass(AVLReg, &RISCV::GPRNoX0RegClass);
633 
634   // Use X0 as the DestReg unless AVLReg is X0. We also need to change the
635   // opcode if the AVLReg is X0 as they have different register classes for
636   // the AVL operand.
637   Register DestReg = RISCV::X0;
638   unsigned Opcode = RISCV::PseudoVSETVLI;
639   if (AVLReg == RISCV::X0) {
640     DestReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
641     Opcode = RISCV::PseudoVSETVLIX0;
642   }
643   BuildMI(MBB, MI, DL, TII->get(Opcode))
644       .addReg(DestReg, RegState::Define | RegState::Dead)
645       .addReg(AVLReg)
646       .addImm(Info.encodeVTYPE());
647 }
648 
649 // Return a VSETVLIInfo representing the changes made by this VSETVLI or
650 // VSETIVLI instruction.
651 static VSETVLIInfo getInfoForVSETVLI(const MachineInstr &MI) {
652   VSETVLIInfo NewInfo;
653   if (MI.getOpcode() == RISCV::PseudoVSETIVLI) {
654     NewInfo.setAVLImm(MI.getOperand(1).getImm());
655   } else {
656     assert(MI.getOpcode() == RISCV::PseudoVSETVLI ||
657            MI.getOpcode() == RISCV::PseudoVSETVLIX0);
658     Register AVLReg = MI.getOperand(1).getReg();
659     assert((AVLReg != RISCV::X0 || MI.getOperand(0).getReg() != RISCV::X0) &&
660            "Can't handle X0, X0 vsetvli yet");
661     NewInfo.setAVLReg(AVLReg);
662   }
663   NewInfo.setVTYPE(MI.getOperand(2).getImm());
664 
665   return NewInfo;
666 }
667 
668 bool RISCVInsertVSETVLI::needVSETVLI(const VSETVLIInfo &Require,
669                                      const VSETVLIInfo &CurInfo) {
670   if (CurInfo.isCompatible(Require, /*Strict*/ false))
671     return false;
672 
673   // We didn't find a compatible value. If our AVL is a virtual register,
674   // it might be defined by a VSET(I)VLI. If it has the same VTYPE we need
675   // and the last VL/VTYPE we observed is the same, we don't need a
676   // VSETVLI here.
677   if (!CurInfo.isUnknown() && Require.hasAVLReg() &&
678       Require.getAVLReg().isVirtual() && !CurInfo.hasSEWLMULRatioOnly() &&
679       CurInfo.hasCompatibleVTYPE(Require, /*Strict*/ false)) {
680     if (MachineInstr *DefMI = MRI->getVRegDef(Require.getAVLReg())) {
681       if (isVectorConfigInstr(*DefMI)) {
682         VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
683         if (DefInfo.hasSameAVL(CurInfo) && DefInfo.hasSameVTYPE(CurInfo))
684           return false;
685       }
686     }
687   }
688 
689   return true;
690 }
691 
692 bool canSkipVSETVLIForLoadStore(const MachineInstr &MI,
693                                 const VSETVLIInfo &Require,
694                                 const VSETVLIInfo &CurInfo) {
695   unsigned EEW;
696   switch (MI.getOpcode()) {
697   default:
698     return false;
699   case RISCV::PseudoVLE8_V_M1:
700   case RISCV::PseudoVLE8_V_M1_MASK:
701   case RISCV::PseudoVLE8_V_M2:
702   case RISCV::PseudoVLE8_V_M2_MASK:
703   case RISCV::PseudoVLE8_V_M4:
704   case RISCV::PseudoVLE8_V_M4_MASK:
705   case RISCV::PseudoVLE8_V_M8:
706   case RISCV::PseudoVLE8_V_M8_MASK:
707   case RISCV::PseudoVLE8_V_MF2:
708   case RISCV::PseudoVLE8_V_MF2_MASK:
709   case RISCV::PseudoVLE8_V_MF4:
710   case RISCV::PseudoVLE8_V_MF4_MASK:
711   case RISCV::PseudoVLE8_V_MF8:
712   case RISCV::PseudoVLE8_V_MF8_MASK:
713   case RISCV::PseudoVLSE8_V_M1:
714   case RISCV::PseudoVLSE8_V_M1_MASK:
715   case RISCV::PseudoVLSE8_V_M2:
716   case RISCV::PseudoVLSE8_V_M2_MASK:
717   case RISCV::PseudoVLSE8_V_M4:
718   case RISCV::PseudoVLSE8_V_M4_MASK:
719   case RISCV::PseudoVLSE8_V_M8:
720   case RISCV::PseudoVLSE8_V_M8_MASK:
721   case RISCV::PseudoVLSE8_V_MF2:
722   case RISCV::PseudoVLSE8_V_MF2_MASK:
723   case RISCV::PseudoVLSE8_V_MF4:
724   case RISCV::PseudoVLSE8_V_MF4_MASK:
725   case RISCV::PseudoVLSE8_V_MF8:
726   case RISCV::PseudoVLSE8_V_MF8_MASK:
727   case RISCV::PseudoVSE8_V_M1:
728   case RISCV::PseudoVSE8_V_M1_MASK:
729   case RISCV::PseudoVSE8_V_M2:
730   case RISCV::PseudoVSE8_V_M2_MASK:
731   case RISCV::PseudoVSE8_V_M4:
732   case RISCV::PseudoVSE8_V_M4_MASK:
733   case RISCV::PseudoVSE8_V_M8:
734   case RISCV::PseudoVSE8_V_M8_MASK:
735   case RISCV::PseudoVSE8_V_MF2:
736   case RISCV::PseudoVSE8_V_MF2_MASK:
737   case RISCV::PseudoVSE8_V_MF4:
738   case RISCV::PseudoVSE8_V_MF4_MASK:
739   case RISCV::PseudoVSE8_V_MF8:
740   case RISCV::PseudoVSE8_V_MF8_MASK:
741   case RISCV::PseudoVSSE8_V_M1:
742   case RISCV::PseudoVSSE8_V_M1_MASK:
743   case RISCV::PseudoVSSE8_V_M2:
744   case RISCV::PseudoVSSE8_V_M2_MASK:
745   case RISCV::PseudoVSSE8_V_M4:
746   case RISCV::PseudoVSSE8_V_M4_MASK:
747   case RISCV::PseudoVSSE8_V_M8:
748   case RISCV::PseudoVSSE8_V_M8_MASK:
749   case RISCV::PseudoVSSE8_V_MF2:
750   case RISCV::PseudoVSSE8_V_MF2_MASK:
751   case RISCV::PseudoVSSE8_V_MF4:
752   case RISCV::PseudoVSSE8_V_MF4_MASK:
753   case RISCV::PseudoVSSE8_V_MF8:
754   case RISCV::PseudoVSSE8_V_MF8_MASK:
755     EEW = 8;
756     break;
757   case RISCV::PseudoVLE16_V_M1:
758   case RISCV::PseudoVLE16_V_M1_MASK:
759   case RISCV::PseudoVLE16_V_M2:
760   case RISCV::PseudoVLE16_V_M2_MASK:
761   case RISCV::PseudoVLE16_V_M4:
762   case RISCV::PseudoVLE16_V_M4_MASK:
763   case RISCV::PseudoVLE16_V_M8:
764   case RISCV::PseudoVLE16_V_M8_MASK:
765   case RISCV::PseudoVLE16_V_MF2:
766   case RISCV::PseudoVLE16_V_MF2_MASK:
767   case RISCV::PseudoVLE16_V_MF4:
768   case RISCV::PseudoVLE16_V_MF4_MASK:
769   case RISCV::PseudoVLSE16_V_M1:
770   case RISCV::PseudoVLSE16_V_M1_MASK:
771   case RISCV::PseudoVLSE16_V_M2:
772   case RISCV::PseudoVLSE16_V_M2_MASK:
773   case RISCV::PseudoVLSE16_V_M4:
774   case RISCV::PseudoVLSE16_V_M4_MASK:
775   case RISCV::PseudoVLSE16_V_M8:
776   case RISCV::PseudoVLSE16_V_M8_MASK:
777   case RISCV::PseudoVLSE16_V_MF2:
778   case RISCV::PseudoVLSE16_V_MF2_MASK:
779   case RISCV::PseudoVLSE16_V_MF4:
780   case RISCV::PseudoVLSE16_V_MF4_MASK:
781   case RISCV::PseudoVSE16_V_M1:
782   case RISCV::PseudoVSE16_V_M1_MASK:
783   case RISCV::PseudoVSE16_V_M2:
784   case RISCV::PseudoVSE16_V_M2_MASK:
785   case RISCV::PseudoVSE16_V_M4:
786   case RISCV::PseudoVSE16_V_M4_MASK:
787   case RISCV::PseudoVSE16_V_M8:
788   case RISCV::PseudoVSE16_V_M8_MASK:
789   case RISCV::PseudoVSE16_V_MF2:
790   case RISCV::PseudoVSE16_V_MF2_MASK:
791   case RISCV::PseudoVSE16_V_MF4:
792   case RISCV::PseudoVSE16_V_MF4_MASK:
793   case RISCV::PseudoVSSE16_V_M1:
794   case RISCV::PseudoVSSE16_V_M1_MASK:
795   case RISCV::PseudoVSSE16_V_M2:
796   case RISCV::PseudoVSSE16_V_M2_MASK:
797   case RISCV::PseudoVSSE16_V_M4:
798   case RISCV::PseudoVSSE16_V_M4_MASK:
799   case RISCV::PseudoVSSE16_V_M8:
800   case RISCV::PseudoVSSE16_V_M8_MASK:
801   case RISCV::PseudoVSSE16_V_MF2:
802   case RISCV::PseudoVSSE16_V_MF2_MASK:
803   case RISCV::PseudoVSSE16_V_MF4:
804   case RISCV::PseudoVSSE16_V_MF4_MASK:
805     EEW = 16;
806     break;
807   case RISCV::PseudoVLE32_V_M1:
808   case RISCV::PseudoVLE32_V_M1_MASK:
809   case RISCV::PseudoVLE32_V_M2:
810   case RISCV::PseudoVLE32_V_M2_MASK:
811   case RISCV::PseudoVLE32_V_M4:
812   case RISCV::PseudoVLE32_V_M4_MASK:
813   case RISCV::PseudoVLE32_V_M8:
814   case RISCV::PseudoVLE32_V_M8_MASK:
815   case RISCV::PseudoVLE32_V_MF2:
816   case RISCV::PseudoVLE32_V_MF2_MASK:
817   case RISCV::PseudoVLSE32_V_M1:
818   case RISCV::PseudoVLSE32_V_M1_MASK:
819   case RISCV::PseudoVLSE32_V_M2:
820   case RISCV::PseudoVLSE32_V_M2_MASK:
821   case RISCV::PseudoVLSE32_V_M4:
822   case RISCV::PseudoVLSE32_V_M4_MASK:
823   case RISCV::PseudoVLSE32_V_M8:
824   case RISCV::PseudoVLSE32_V_M8_MASK:
825   case RISCV::PseudoVLSE32_V_MF2:
826   case RISCV::PseudoVLSE32_V_MF2_MASK:
827   case RISCV::PseudoVSE32_V_M1:
828   case RISCV::PseudoVSE32_V_M1_MASK:
829   case RISCV::PseudoVSE32_V_M2:
830   case RISCV::PseudoVSE32_V_M2_MASK:
831   case RISCV::PseudoVSE32_V_M4:
832   case RISCV::PseudoVSE32_V_M4_MASK:
833   case RISCV::PseudoVSE32_V_M8:
834   case RISCV::PseudoVSE32_V_M8_MASK:
835   case RISCV::PseudoVSE32_V_MF2:
836   case RISCV::PseudoVSE32_V_MF2_MASK:
837   case RISCV::PseudoVSSE32_V_M1:
838   case RISCV::PseudoVSSE32_V_M1_MASK:
839   case RISCV::PseudoVSSE32_V_M2:
840   case RISCV::PseudoVSSE32_V_M2_MASK:
841   case RISCV::PseudoVSSE32_V_M4:
842   case RISCV::PseudoVSSE32_V_M4_MASK:
843   case RISCV::PseudoVSSE32_V_M8:
844   case RISCV::PseudoVSSE32_V_M8_MASK:
845   case RISCV::PseudoVSSE32_V_MF2:
846   case RISCV::PseudoVSSE32_V_MF2_MASK:
847     EEW = 32;
848     break;
849   case RISCV::PseudoVLE64_V_M1:
850   case RISCV::PseudoVLE64_V_M1_MASK:
851   case RISCV::PseudoVLE64_V_M2:
852   case RISCV::PseudoVLE64_V_M2_MASK:
853   case RISCV::PseudoVLE64_V_M4:
854   case RISCV::PseudoVLE64_V_M4_MASK:
855   case RISCV::PseudoVLE64_V_M8:
856   case RISCV::PseudoVLE64_V_M8_MASK:
857   case RISCV::PseudoVLSE64_V_M1:
858   case RISCV::PseudoVLSE64_V_M1_MASK:
859   case RISCV::PseudoVLSE64_V_M2:
860   case RISCV::PseudoVLSE64_V_M2_MASK:
861   case RISCV::PseudoVLSE64_V_M4:
862   case RISCV::PseudoVLSE64_V_M4_MASK:
863   case RISCV::PseudoVLSE64_V_M8:
864   case RISCV::PseudoVLSE64_V_M8_MASK:
865   case RISCV::PseudoVSE64_V_M1:
866   case RISCV::PseudoVSE64_V_M1_MASK:
867   case RISCV::PseudoVSE64_V_M2:
868   case RISCV::PseudoVSE64_V_M2_MASK:
869   case RISCV::PseudoVSE64_V_M4:
870   case RISCV::PseudoVSE64_V_M4_MASK:
871   case RISCV::PseudoVSE64_V_M8:
872   case RISCV::PseudoVSE64_V_M8_MASK:
873   case RISCV::PseudoVSSE64_V_M1:
874   case RISCV::PseudoVSSE64_V_M1_MASK:
875   case RISCV::PseudoVSSE64_V_M2:
876   case RISCV::PseudoVSSE64_V_M2_MASK:
877   case RISCV::PseudoVSSE64_V_M4:
878   case RISCV::PseudoVSSE64_V_M4_MASK:
879   case RISCV::PseudoVSSE64_V_M8:
880   case RISCV::PseudoVSSE64_V_M8_MASK:
881     EEW = 64;
882     break;
883   }
884 
885   return CurInfo.isCompatibleWithLoadStoreEEW(EEW, Require);
886 }
887 
888 bool RISCVInsertVSETVLI::computeVLVTYPEChanges(const MachineBasicBlock &MBB) {
889   bool HadVectorOp = false;
890 
891   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
892   for (const MachineInstr &MI : MBB) {
893     // If this is an explicit VSETVLI or VSETIVLI, update our state.
894     if (isVectorConfigInstr(MI)) {
895       HadVectorOp = true;
896       BBInfo.Change = getInfoForVSETVLI(MI);
897       continue;
898     }
899 
900     uint64_t TSFlags = MI.getDesc().TSFlags;
901     if (RISCVII::hasSEWOp(TSFlags)) {
902       HadVectorOp = true;
903 
904       VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
905 
906       if (!BBInfo.Change.isValid()) {
907         BBInfo.Change = NewInfo;
908       } else {
909         // If this instruction isn't compatible with the previous VL/VTYPE
910         // we need to insert a VSETVLI.
911         // If this is a unit-stride or strided load/store, we may be able to use
912         // the EMUL=(EEW/SEW)*LMUL relationship to avoid changing vtype.
913         // NOTE: We only do this if the vtype we're comparing against was
914         // created in this block. We need the first and third phase to treat
915         // the store the same way.
916         if (!canSkipVSETVLIForLoadStore(MI, NewInfo, BBInfo.Change) &&
917             needVSETVLI(NewInfo, BBInfo.Change))
918           BBInfo.Change = NewInfo;
919       }
920     }
921 
922     // If this is something that updates VL/VTYPE that we don't know about, set
923     // the state to unknown.
924     if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
925         MI.modifiesRegister(RISCV::VTYPE)) {
926       BBInfo.Change = VSETVLIInfo::getUnknown();
927     }
928   }
929 
930   // Initial exit state is whatever change we found in the block.
931   BBInfo.Exit = BBInfo.Change;
932 
933   return HadVectorOp;
934 }
935 
936 void RISCVInsertVSETVLI::computeIncomingVLVTYPE(const MachineBasicBlock &MBB) {
937   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
938 
939   BBInfo.InQueue = false;
940 
941   VSETVLIInfo InInfo;
942   if (MBB.pred_empty()) {
943     // There are no predecessors, so use the default starting status.
944     InInfo.setUnknown();
945   } else {
946     for (MachineBasicBlock *P : MBB.predecessors())
947       InInfo = InInfo.intersect(BlockInfo[P->getNumber()].Exit);
948   }
949 
950   // If we don't have any valid predecessor value, wait until we do.
951   if (!InInfo.isValid())
952     return;
953 
954   BBInfo.Pred = InInfo;
955 
956   VSETVLIInfo TmpStatus = BBInfo.Pred.merge(BBInfo.Change);
957 
958   // If the new exit value matches the old exit value, we don't need to revisit
959   // any blocks.
960   if (BBInfo.Exit == TmpStatus)
961     return;
962 
963   BBInfo.Exit = TmpStatus;
964 
965   // Add the successors to the work list so we can propagate the changed exit
966   // status.
967   for (MachineBasicBlock *S : MBB.successors())
968     if (!BlockInfo[S->getNumber()].InQueue)
969       WorkList.push(S);
970 }
971 
972 // If we weren't able to prove a vsetvli was directly unneeded, it might still
973 // be/ unneeded if the AVL is a phi node where all incoming values are VL
974 // outputs from the last VSETVLI in their respective basic blocks.
975 bool RISCVInsertVSETVLI::needVSETVLIPHI(const VSETVLIInfo &Require,
976                                         const MachineBasicBlock &MBB) {
977   if (DisableInsertVSETVLPHIOpt)
978     return true;
979 
980   if (!Require.hasAVLReg())
981     return true;
982 
983   Register AVLReg = Require.getAVLReg();
984   if (!AVLReg.isVirtual())
985     return true;
986 
987   // We need the AVL to be produce by a PHI node in this basic block.
988   MachineInstr *PHI = MRI->getVRegDef(AVLReg);
989   if (!PHI || PHI->getOpcode() != RISCV::PHI || PHI->getParent() != &MBB)
990     return true;
991 
992   for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
993        PHIOp += 2) {
994     Register InReg = PHI->getOperand(PHIOp).getReg();
995     MachineBasicBlock *PBB = PHI->getOperand(PHIOp + 1).getMBB();
996     const BlockData &PBBInfo = BlockInfo[PBB->getNumber()];
997     // If the exit from the predecessor has the VTYPE we are looking for
998     // we might be able to avoid a VSETVLI.
999     if (PBBInfo.Exit.isUnknown() ||
1000         !PBBInfo.Exit.hasCompatibleVTYPE(Require, /*Strict*/ false))
1001       return true;
1002 
1003     // We need the PHI input to the be the output of a VSET(I)VLI.
1004     MachineInstr *DefMI = MRI->getVRegDef(InReg);
1005     if (!DefMI || !isVectorConfigInstr(*DefMI))
1006       return true;
1007 
1008     // We found a VSET(I)VLI make sure it matches the output of the
1009     // predecessor block.
1010     VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1011     if (!DefInfo.hasSameAVL(PBBInfo.Exit) ||
1012         !DefInfo.hasSameVTYPE(PBBInfo.Exit))
1013       return true;
1014   }
1015 
1016   // If all the incoming values to the PHI checked out, we don't need
1017   // to insert a VSETVLI.
1018   return false;
1019 }
1020 
1021 void RISCVInsertVSETVLI::emitVSETVLIs(MachineBasicBlock &MBB) {
1022   VSETVLIInfo CurInfo;
1023   // Only be set if current VSETVLIInfo is from an explicit VSET(I)VLI.
1024   MachineInstr *PrevVSETVLIMI = nullptr;
1025 
1026   for (MachineInstr &MI : MBB) {
1027     // If this is an explicit VSETVLI or VSETIVLI, update our state.
1028     if (isVectorConfigInstr(MI)) {
1029       // Conservatively, mark the VL and VTYPE as live.
1030       assert(MI.getOperand(3).getReg() == RISCV::VL &&
1031              MI.getOperand(4).getReg() == RISCV::VTYPE &&
1032              "Unexpected operands where VL and VTYPE should be");
1033       MI.getOperand(3).setIsDead(false);
1034       MI.getOperand(4).setIsDead(false);
1035       CurInfo = getInfoForVSETVLI(MI);
1036       PrevVSETVLIMI = &MI;
1037       continue;
1038     }
1039 
1040     uint64_t TSFlags = MI.getDesc().TSFlags;
1041     if (RISCVII::hasSEWOp(TSFlags)) {
1042       VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
1043       if (RISCVII::hasVLOp(TSFlags)) {
1044         unsigned Offset = 2;
1045         if (RISCVII::hasVecPolicyOp(TSFlags))
1046           Offset = 3;
1047         MachineOperand &VLOp =
1048             MI.getOperand(MI.getNumExplicitOperands() - Offset);
1049         if (VLOp.isReg()) {
1050           // Erase the AVL operand from the instruction.
1051           VLOp.setReg(RISCV::NoRegister);
1052           VLOp.setIsKill(false);
1053         }
1054         MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ false,
1055                                                 /*isImp*/ true));
1056       }
1057       MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
1058                                               /*isImp*/ true));
1059 
1060       if (!CurInfo.isValid()) {
1061         // We haven't found any vector instructions or VL/VTYPE changes yet,
1062         // use the predecessor information.
1063         assert(BlockInfo[MBB.getNumber()].Pred.isValid() &&
1064                "Expected a valid predecessor state.");
1065         if (needVSETVLI(NewInfo, BlockInfo[MBB.getNumber()].Pred) &&
1066             needVSETVLIPHI(NewInfo, MBB)) {
1067           insertVSETVLI(MBB, MI, NewInfo, BlockInfo[MBB.getNumber()].Pred);
1068           CurInfo = NewInfo;
1069         }
1070       } else {
1071         // If this instruction isn't compatible with the previous VL/VTYPE
1072         // we need to insert a VSETVLI.
1073         // If this is a unit-stride or strided load/store, we may be able to use
1074         // the EMUL=(EEW/SEW)*LMUL relationship to avoid changing vtype.
1075         // NOTE: We can't use predecessor information for the store. We must
1076         // treat it the same as the first phase so that we produce the correct
1077         // vl/vtype for succesor blocks.
1078         if (!canSkipVSETVLIForLoadStore(MI, NewInfo, CurInfo) &&
1079             needVSETVLI(NewInfo, CurInfo)) {
1080           // If the previous VL/VTYPE is set by VSETVLI and do not use, Merge it
1081           // with current VL/VTYPE.
1082           bool NeedInsertVSETVLI = true;
1083           if (PrevVSETVLIMI) {
1084             bool HasSameAVL =
1085                 CurInfo.hasSameAVL(NewInfo) ||
1086                 (NewInfo.hasAVLReg() && NewInfo.getAVLReg().isVirtual() &&
1087                  NewInfo.getAVLReg() == PrevVSETVLIMI->getOperand(0).getReg());
1088             // If these two VSETVLI have the same AVL and the same VLMAX,
1089             // we could merge these two VSETVLI.
1090             if (HasSameAVL &&
1091                 CurInfo.getSEWLMULRatio() == NewInfo.getSEWLMULRatio()) {
1092               PrevVSETVLIMI->getOperand(2).setImm(NewInfo.encodeVTYPE());
1093               NeedInsertVSETVLI = false;
1094             }
1095             if (isScalarMoveInstr(MI) &&
1096                 ((CurInfo.hasNonZeroAVL() && NewInfo.hasNonZeroAVL()) ||
1097                  (CurInfo.hasZeroAVL() && NewInfo.hasZeroAVL())) &&
1098                 NewInfo.hasSameVLMAX(CurInfo)) {
1099               PrevVSETVLIMI->getOperand(2).setImm(NewInfo.encodeVTYPE());
1100               NeedInsertVSETVLI = false;
1101             }
1102           }
1103           if (NeedInsertVSETVLI)
1104             insertVSETVLI(MBB, MI, NewInfo, CurInfo);
1105           CurInfo = NewInfo;
1106         }
1107       }
1108       PrevVSETVLIMI = nullptr;
1109     }
1110 
1111     // If this is something updates VL/VTYPE that we don't know about, set
1112     // the state to unknown.
1113     if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
1114         MI.modifiesRegister(RISCV::VTYPE)) {
1115       CurInfo = VSETVLIInfo::getUnknown();
1116       PrevVSETVLIMI = nullptr;
1117     }
1118 
1119     // If we reach the end of the block and our current info doesn't match the
1120     // expected info, insert a vsetvli to correct.
1121     if (MI.isTerminator()) {
1122       const VSETVLIInfo &ExitInfo = BlockInfo[MBB.getNumber()].Exit;
1123       if (CurInfo.isValid() && ExitInfo.isValid() && !ExitInfo.isUnknown() &&
1124           CurInfo != ExitInfo) {
1125         insertVSETVLI(MBB, MI, ExitInfo, CurInfo);
1126         CurInfo = ExitInfo;
1127       }
1128     }
1129   }
1130 }
1131 
1132 bool RISCVInsertVSETVLI::runOnMachineFunction(MachineFunction &MF) {
1133   // Skip if the vector extension is not enabled.
1134   const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
1135   if (!ST.hasVInstructions())
1136     return false;
1137 
1138   TII = ST.getInstrInfo();
1139   MRI = &MF.getRegInfo();
1140 
1141   assert(BlockInfo.empty() && "Expect empty block infos");
1142   BlockInfo.resize(MF.getNumBlockIDs());
1143 
1144   bool HaveVectorOp = false;
1145 
1146   // Phase 1 - determine how VL/VTYPE are affected by the each block.
1147   for (const MachineBasicBlock &MBB : MF)
1148     HaveVectorOp |= computeVLVTYPEChanges(MBB);
1149 
1150   // If we didn't find any instructions that need VSETVLI, we're done.
1151   if (HaveVectorOp) {
1152     // Phase 2 - determine the exit VL/VTYPE from each block. We add all
1153     // blocks to the list here, but will also add any that need to be revisited
1154     // during Phase 2 processing.
1155     for (const MachineBasicBlock &MBB : MF) {
1156       WorkList.push(&MBB);
1157       BlockInfo[MBB.getNumber()].InQueue = true;
1158     }
1159     while (!WorkList.empty()) {
1160       const MachineBasicBlock &MBB = *WorkList.front();
1161       WorkList.pop();
1162       computeIncomingVLVTYPE(MBB);
1163     }
1164 
1165     // Phase 3 - add any vsetvli instructions needed in the block. Use the
1166     // Phase 2 information to avoid adding vsetvlis before the first vector
1167     // instruction in the block if the VL/VTYPE is satisfied by its
1168     // predecessors.
1169     for (MachineBasicBlock &MBB : MF)
1170       emitVSETVLIs(MBB);
1171   }
1172 
1173   BlockInfo.clear();
1174 
1175   return HaveVectorOp;
1176 }
1177 
1178 /// Returns an instance of the Insert VSETVLI pass.
1179 FunctionPass *llvm::createRISCVInsertVSETVLIPass() {
1180   return new RISCVInsertVSETVLI();
1181 }
1182