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.
509   bool TailAgnostic = true;
510   bool UsesMaskPolicy = RISCVII::UsesMaskPolicy(TSFlags);
511   // FIXME: Could we look at the above or below instructions to choose the
512   // matched mask policy to reduce vsetvli instructions? Default mask policy is
513   // agnostic if instructions use mask policy, otherwise is undisturbed. Because
514   // most mask operations are mask undisturbed, so we could possibly reduce the
515   // vsetvli between mask and nomasked instruction sequence.
516   bool MaskAgnostic = UsesMaskPolicy;
517   unsigned UseOpIdx;
518   if (HasPolicy) {
519     const MachineOperand &Op = MI.getOperand(MI.getNumExplicitOperands() - 1);
520     uint64_t Policy = Op.getImm();
521     assert(Policy <= (RISCVII::TAIL_AGNOSTIC | RISCVII::MASK_AGNOSTIC) &&
522            "Invalid Policy Value");
523     // Although in some cases, mismatched passthru/maskedoff with policy value
524     // does not make sense (ex. tied operand is IMPLICIT_DEF with non-TAMA
525     // policy, or tied operand is not IMPLICIT_DEF with TAMA policy), but users
526     // have set the policy value explicitly, so compiler would not fix it.
527     TailAgnostic = Policy & RISCVII::TAIL_AGNOSTIC;
528     MaskAgnostic = Policy & RISCVII::MASK_AGNOSTIC;
529   } else if (MI.isRegTiedToUseOperand(0, &UseOpIdx)) {
530     TailAgnostic = false;
531     if (UsesMaskPolicy)
532       MaskAgnostic = false;
533     // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic.
534     const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
535     MachineInstr *UseMI = MRI->getVRegDef(UseMO.getReg());
536     if (UseMI) {
537       UseMI = elideCopies(UseMI, MRI);
538       if (UseMI && UseMI->isImplicitDef()) {
539         TailAgnostic = true;
540         if (UsesMaskPolicy)
541           MaskAgnostic = true;
542       }
543     }
544     // Some pseudo instructions force a tail agnostic policy despite having a
545     // tied def.
546     if (RISCVII::doesForceTailAgnostic(TSFlags))
547       TailAgnostic = true;
548   }
549 
550   // Remove the tail policy so we can find the SEW and VL.
551   if (HasPolicy)
552     --NumOperands;
553 
554   RISCVII::VLMUL VLMul = RISCVII::getLMul(TSFlags);
555 
556   unsigned Log2SEW = MI.getOperand(NumOperands - 1).getImm();
557   // A Log2SEW of 0 is an operation on mask registers only.
558   bool MaskRegOp = Log2SEW == 0;
559   unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
560   assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
561 
562   // If there are no explicit defs, this is a store instruction which can
563   // ignore the tail and mask policies.
564   bool StoreOp = MI.getNumExplicitDefs() == 0;
565   bool ScalarMovOp = isScalarMoveInstr(MI);
566 
567   if (RISCVII::hasVLOp(TSFlags)) {
568     const MachineOperand &VLOp = MI.getOperand(NumOperands - 2);
569     if (VLOp.isImm()) {
570       int64_t Imm = VLOp.getImm();
571       // Conver the VLMax sentintel to X0 register.
572       if (Imm == RISCV::VLMaxSentinel)
573         InstrInfo.setAVLReg(RISCV::X0);
574       else
575         InstrInfo.setAVLImm(Imm);
576     } else {
577       InstrInfo.setAVLReg(VLOp.getReg());
578     }
579   } else
580     InstrInfo.setAVLReg(RISCV::NoRegister);
581   InstrInfo.setVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic, MaskRegOp, StoreOp,
582                      ScalarMovOp);
583 
584   return InstrInfo;
585 }
586 
587 void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
588                                        const VSETVLIInfo &Info,
589                                        const VSETVLIInfo &PrevInfo) {
590   DebugLoc DL = MI.getDebugLoc();
591 
592   // Use X0, X0 form if the AVL is the same and the SEW+LMUL gives the same
593   // VLMAX.
594   if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
595       Info.hasSameAVL(PrevInfo) && Info.hasSameVLMAX(PrevInfo)) {
596     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETVLIX0))
597         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
598         .addReg(RISCV::X0, RegState::Kill)
599         .addImm(Info.encodeVTYPE())
600         .addReg(RISCV::VL, RegState::Implicit);
601     return;
602   }
603 
604   if (Info.hasAVLImm()) {
605     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETIVLI))
606         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
607         .addImm(Info.getAVLImm())
608         .addImm(Info.encodeVTYPE());
609     return;
610   }
611 
612   Register AVLReg = Info.getAVLReg();
613   if (AVLReg == RISCV::NoRegister) {
614     // We can only use x0, x0 if there's no chance of the vtype change causing
615     // the previous vl to become invalid.
616     if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
617         Info.hasSameVLMAX(PrevInfo)) {
618       BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETVLIX0))
619           .addReg(RISCV::X0, RegState::Define | RegState::Dead)
620           .addReg(RISCV::X0, RegState::Kill)
621           .addImm(Info.encodeVTYPE())
622           .addReg(RISCV::VL, RegState::Implicit);
623       return;
624     }
625     // Otherwise use an AVL of 0 to avoid depending on previous vl.
626     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETIVLI))
627         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
628         .addImm(0)
629         .addImm(Info.encodeVTYPE());
630     return;
631   }
632 
633   if (AVLReg.isVirtual())
634     MRI->constrainRegClass(AVLReg, &RISCV::GPRNoX0RegClass);
635 
636   // Use X0 as the DestReg unless AVLReg is X0. We also need to change the
637   // opcode if the AVLReg is X0 as they have different register classes for
638   // the AVL operand.
639   Register DestReg = RISCV::X0;
640   unsigned Opcode = RISCV::PseudoVSETVLI;
641   if (AVLReg == RISCV::X0) {
642     DestReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
643     Opcode = RISCV::PseudoVSETVLIX0;
644   }
645   BuildMI(MBB, MI, DL, TII->get(Opcode))
646       .addReg(DestReg, RegState::Define | RegState::Dead)
647       .addReg(AVLReg)
648       .addImm(Info.encodeVTYPE());
649 }
650 
651 // Return a VSETVLIInfo representing the changes made by this VSETVLI or
652 // VSETIVLI instruction.
653 static VSETVLIInfo getInfoForVSETVLI(const MachineInstr &MI) {
654   VSETVLIInfo NewInfo;
655   if (MI.getOpcode() == RISCV::PseudoVSETIVLI) {
656     NewInfo.setAVLImm(MI.getOperand(1).getImm());
657   } else {
658     assert(MI.getOpcode() == RISCV::PseudoVSETVLI ||
659            MI.getOpcode() == RISCV::PseudoVSETVLIX0);
660     Register AVLReg = MI.getOperand(1).getReg();
661     assert((AVLReg != RISCV::X0 || MI.getOperand(0).getReg() != RISCV::X0) &&
662            "Can't handle X0, X0 vsetvli yet");
663     NewInfo.setAVLReg(AVLReg);
664   }
665   NewInfo.setVTYPE(MI.getOperand(2).getImm());
666 
667   return NewInfo;
668 }
669 
670 bool RISCVInsertVSETVLI::needVSETVLI(const VSETVLIInfo &Require,
671                                      const VSETVLIInfo &CurInfo) {
672   if (CurInfo.isCompatible(Require, /*Strict*/ false))
673     return false;
674 
675   // We didn't find a compatible value. If our AVL is a virtual register,
676   // it might be defined by a VSET(I)VLI. If it has the same VTYPE we need
677   // and the last VL/VTYPE we observed is the same, we don't need a
678   // VSETVLI here.
679   if (!CurInfo.isUnknown() && Require.hasAVLReg() &&
680       Require.getAVLReg().isVirtual() && !CurInfo.hasSEWLMULRatioOnly() &&
681       CurInfo.hasCompatibleVTYPE(Require, /*Strict*/ false)) {
682     if (MachineInstr *DefMI = MRI->getVRegDef(Require.getAVLReg())) {
683       if (isVectorConfigInstr(*DefMI)) {
684         VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
685         if (DefInfo.hasSameAVL(CurInfo) && DefInfo.hasSameVTYPE(CurInfo))
686           return false;
687       }
688     }
689   }
690 
691   return true;
692 }
693 
694 bool canSkipVSETVLIForLoadStore(const MachineInstr &MI,
695                                 const VSETVLIInfo &Require,
696                                 const VSETVLIInfo &CurInfo) {
697   unsigned EEW;
698   switch (MI.getOpcode()) {
699   default:
700     return false;
701   case RISCV::PseudoVLE8_V_M1:
702   case RISCV::PseudoVLE8_V_M1_MASK:
703   case RISCV::PseudoVLE8_V_M2:
704   case RISCV::PseudoVLE8_V_M2_MASK:
705   case RISCV::PseudoVLE8_V_M4:
706   case RISCV::PseudoVLE8_V_M4_MASK:
707   case RISCV::PseudoVLE8_V_M8:
708   case RISCV::PseudoVLE8_V_M8_MASK:
709   case RISCV::PseudoVLE8_V_MF2:
710   case RISCV::PseudoVLE8_V_MF2_MASK:
711   case RISCV::PseudoVLE8_V_MF4:
712   case RISCV::PseudoVLE8_V_MF4_MASK:
713   case RISCV::PseudoVLE8_V_MF8:
714   case RISCV::PseudoVLE8_V_MF8_MASK:
715   case RISCV::PseudoVLSE8_V_M1:
716   case RISCV::PseudoVLSE8_V_M1_MASK:
717   case RISCV::PseudoVLSE8_V_M2:
718   case RISCV::PseudoVLSE8_V_M2_MASK:
719   case RISCV::PseudoVLSE8_V_M4:
720   case RISCV::PseudoVLSE8_V_M4_MASK:
721   case RISCV::PseudoVLSE8_V_M8:
722   case RISCV::PseudoVLSE8_V_M8_MASK:
723   case RISCV::PseudoVLSE8_V_MF2:
724   case RISCV::PseudoVLSE8_V_MF2_MASK:
725   case RISCV::PseudoVLSE8_V_MF4:
726   case RISCV::PseudoVLSE8_V_MF4_MASK:
727   case RISCV::PseudoVLSE8_V_MF8:
728   case RISCV::PseudoVLSE8_V_MF8_MASK:
729   case RISCV::PseudoVSE8_V_M1:
730   case RISCV::PseudoVSE8_V_M1_MASK:
731   case RISCV::PseudoVSE8_V_M2:
732   case RISCV::PseudoVSE8_V_M2_MASK:
733   case RISCV::PseudoVSE8_V_M4:
734   case RISCV::PseudoVSE8_V_M4_MASK:
735   case RISCV::PseudoVSE8_V_M8:
736   case RISCV::PseudoVSE8_V_M8_MASK:
737   case RISCV::PseudoVSE8_V_MF2:
738   case RISCV::PseudoVSE8_V_MF2_MASK:
739   case RISCV::PseudoVSE8_V_MF4:
740   case RISCV::PseudoVSE8_V_MF4_MASK:
741   case RISCV::PseudoVSE8_V_MF8:
742   case RISCV::PseudoVSE8_V_MF8_MASK:
743   case RISCV::PseudoVSSE8_V_M1:
744   case RISCV::PseudoVSSE8_V_M1_MASK:
745   case RISCV::PseudoVSSE8_V_M2:
746   case RISCV::PseudoVSSE8_V_M2_MASK:
747   case RISCV::PseudoVSSE8_V_M4:
748   case RISCV::PseudoVSSE8_V_M4_MASK:
749   case RISCV::PseudoVSSE8_V_M8:
750   case RISCV::PseudoVSSE8_V_M8_MASK:
751   case RISCV::PseudoVSSE8_V_MF2:
752   case RISCV::PseudoVSSE8_V_MF2_MASK:
753   case RISCV::PseudoVSSE8_V_MF4:
754   case RISCV::PseudoVSSE8_V_MF4_MASK:
755   case RISCV::PseudoVSSE8_V_MF8:
756   case RISCV::PseudoVSSE8_V_MF8_MASK:
757     EEW = 8;
758     break;
759   case RISCV::PseudoVLE16_V_M1:
760   case RISCV::PseudoVLE16_V_M1_MASK:
761   case RISCV::PseudoVLE16_V_M2:
762   case RISCV::PseudoVLE16_V_M2_MASK:
763   case RISCV::PseudoVLE16_V_M4:
764   case RISCV::PseudoVLE16_V_M4_MASK:
765   case RISCV::PseudoVLE16_V_M8:
766   case RISCV::PseudoVLE16_V_M8_MASK:
767   case RISCV::PseudoVLE16_V_MF2:
768   case RISCV::PseudoVLE16_V_MF2_MASK:
769   case RISCV::PseudoVLE16_V_MF4:
770   case RISCV::PseudoVLE16_V_MF4_MASK:
771   case RISCV::PseudoVLSE16_V_M1:
772   case RISCV::PseudoVLSE16_V_M1_MASK:
773   case RISCV::PseudoVLSE16_V_M2:
774   case RISCV::PseudoVLSE16_V_M2_MASK:
775   case RISCV::PseudoVLSE16_V_M4:
776   case RISCV::PseudoVLSE16_V_M4_MASK:
777   case RISCV::PseudoVLSE16_V_M8:
778   case RISCV::PseudoVLSE16_V_M8_MASK:
779   case RISCV::PseudoVLSE16_V_MF2:
780   case RISCV::PseudoVLSE16_V_MF2_MASK:
781   case RISCV::PseudoVLSE16_V_MF4:
782   case RISCV::PseudoVLSE16_V_MF4_MASK:
783   case RISCV::PseudoVSE16_V_M1:
784   case RISCV::PseudoVSE16_V_M1_MASK:
785   case RISCV::PseudoVSE16_V_M2:
786   case RISCV::PseudoVSE16_V_M2_MASK:
787   case RISCV::PseudoVSE16_V_M4:
788   case RISCV::PseudoVSE16_V_M4_MASK:
789   case RISCV::PseudoVSE16_V_M8:
790   case RISCV::PseudoVSE16_V_M8_MASK:
791   case RISCV::PseudoVSE16_V_MF2:
792   case RISCV::PseudoVSE16_V_MF2_MASK:
793   case RISCV::PseudoVSE16_V_MF4:
794   case RISCV::PseudoVSE16_V_MF4_MASK:
795   case RISCV::PseudoVSSE16_V_M1:
796   case RISCV::PseudoVSSE16_V_M1_MASK:
797   case RISCV::PseudoVSSE16_V_M2:
798   case RISCV::PseudoVSSE16_V_M2_MASK:
799   case RISCV::PseudoVSSE16_V_M4:
800   case RISCV::PseudoVSSE16_V_M4_MASK:
801   case RISCV::PseudoVSSE16_V_M8:
802   case RISCV::PseudoVSSE16_V_M8_MASK:
803   case RISCV::PseudoVSSE16_V_MF2:
804   case RISCV::PseudoVSSE16_V_MF2_MASK:
805   case RISCV::PseudoVSSE16_V_MF4:
806   case RISCV::PseudoVSSE16_V_MF4_MASK:
807     EEW = 16;
808     break;
809   case RISCV::PseudoVLE32_V_M1:
810   case RISCV::PseudoVLE32_V_M1_MASK:
811   case RISCV::PseudoVLE32_V_M2:
812   case RISCV::PseudoVLE32_V_M2_MASK:
813   case RISCV::PseudoVLE32_V_M4:
814   case RISCV::PseudoVLE32_V_M4_MASK:
815   case RISCV::PseudoVLE32_V_M8:
816   case RISCV::PseudoVLE32_V_M8_MASK:
817   case RISCV::PseudoVLE32_V_MF2:
818   case RISCV::PseudoVLE32_V_MF2_MASK:
819   case RISCV::PseudoVLSE32_V_M1:
820   case RISCV::PseudoVLSE32_V_M1_MASK:
821   case RISCV::PseudoVLSE32_V_M2:
822   case RISCV::PseudoVLSE32_V_M2_MASK:
823   case RISCV::PseudoVLSE32_V_M4:
824   case RISCV::PseudoVLSE32_V_M4_MASK:
825   case RISCV::PseudoVLSE32_V_M8:
826   case RISCV::PseudoVLSE32_V_M8_MASK:
827   case RISCV::PseudoVLSE32_V_MF2:
828   case RISCV::PseudoVLSE32_V_MF2_MASK:
829   case RISCV::PseudoVSE32_V_M1:
830   case RISCV::PseudoVSE32_V_M1_MASK:
831   case RISCV::PseudoVSE32_V_M2:
832   case RISCV::PseudoVSE32_V_M2_MASK:
833   case RISCV::PseudoVSE32_V_M4:
834   case RISCV::PseudoVSE32_V_M4_MASK:
835   case RISCV::PseudoVSE32_V_M8:
836   case RISCV::PseudoVSE32_V_M8_MASK:
837   case RISCV::PseudoVSE32_V_MF2:
838   case RISCV::PseudoVSE32_V_MF2_MASK:
839   case RISCV::PseudoVSSE32_V_M1:
840   case RISCV::PseudoVSSE32_V_M1_MASK:
841   case RISCV::PseudoVSSE32_V_M2:
842   case RISCV::PseudoVSSE32_V_M2_MASK:
843   case RISCV::PseudoVSSE32_V_M4:
844   case RISCV::PseudoVSSE32_V_M4_MASK:
845   case RISCV::PseudoVSSE32_V_M8:
846   case RISCV::PseudoVSSE32_V_M8_MASK:
847   case RISCV::PseudoVSSE32_V_MF2:
848   case RISCV::PseudoVSSE32_V_MF2_MASK:
849     EEW = 32;
850     break;
851   case RISCV::PseudoVLE64_V_M1:
852   case RISCV::PseudoVLE64_V_M1_MASK:
853   case RISCV::PseudoVLE64_V_M2:
854   case RISCV::PseudoVLE64_V_M2_MASK:
855   case RISCV::PseudoVLE64_V_M4:
856   case RISCV::PseudoVLE64_V_M4_MASK:
857   case RISCV::PseudoVLE64_V_M8:
858   case RISCV::PseudoVLE64_V_M8_MASK:
859   case RISCV::PseudoVLSE64_V_M1:
860   case RISCV::PseudoVLSE64_V_M1_MASK:
861   case RISCV::PseudoVLSE64_V_M2:
862   case RISCV::PseudoVLSE64_V_M2_MASK:
863   case RISCV::PseudoVLSE64_V_M4:
864   case RISCV::PseudoVLSE64_V_M4_MASK:
865   case RISCV::PseudoVLSE64_V_M8:
866   case RISCV::PseudoVLSE64_V_M8_MASK:
867   case RISCV::PseudoVSE64_V_M1:
868   case RISCV::PseudoVSE64_V_M1_MASK:
869   case RISCV::PseudoVSE64_V_M2:
870   case RISCV::PseudoVSE64_V_M2_MASK:
871   case RISCV::PseudoVSE64_V_M4:
872   case RISCV::PseudoVSE64_V_M4_MASK:
873   case RISCV::PseudoVSE64_V_M8:
874   case RISCV::PseudoVSE64_V_M8_MASK:
875   case RISCV::PseudoVSSE64_V_M1:
876   case RISCV::PseudoVSSE64_V_M1_MASK:
877   case RISCV::PseudoVSSE64_V_M2:
878   case RISCV::PseudoVSSE64_V_M2_MASK:
879   case RISCV::PseudoVSSE64_V_M4:
880   case RISCV::PseudoVSSE64_V_M4_MASK:
881   case RISCV::PseudoVSSE64_V_M8:
882   case RISCV::PseudoVSSE64_V_M8_MASK:
883     EEW = 64;
884     break;
885   }
886 
887   return CurInfo.isCompatibleWithLoadStoreEEW(EEW, Require);
888 }
889 
890 bool RISCVInsertVSETVLI::computeVLVTYPEChanges(const MachineBasicBlock &MBB) {
891   bool HadVectorOp = false;
892 
893   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
894   for (const MachineInstr &MI : MBB) {
895     // If this is an explicit VSETVLI or VSETIVLI, update our state.
896     if (isVectorConfigInstr(MI)) {
897       HadVectorOp = true;
898       BBInfo.Change = getInfoForVSETVLI(MI);
899       continue;
900     }
901 
902     uint64_t TSFlags = MI.getDesc().TSFlags;
903     if (RISCVII::hasSEWOp(TSFlags)) {
904       HadVectorOp = true;
905 
906       VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
907 
908       if (!BBInfo.Change.isValid()) {
909         BBInfo.Change = NewInfo;
910       } else {
911         // If this instruction isn't compatible with the previous VL/VTYPE
912         // we need to insert a VSETVLI.
913         // If this is a unit-stride or strided load/store, we may be able to use
914         // the EMUL=(EEW/SEW)*LMUL relationship to avoid changing vtype.
915         // NOTE: We only do this if the vtype we're comparing against was
916         // created in this block. We need the first and third phase to treat
917         // the store the same way.
918         if (!canSkipVSETVLIForLoadStore(MI, NewInfo, BBInfo.Change) &&
919             needVSETVLI(NewInfo, BBInfo.Change))
920           BBInfo.Change = NewInfo;
921       }
922     }
923 
924     // If this is something that updates VL/VTYPE that we don't know about, set
925     // the state to unknown.
926     if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
927         MI.modifiesRegister(RISCV::VTYPE)) {
928       BBInfo.Change = VSETVLIInfo::getUnknown();
929     }
930   }
931 
932   // Initial exit state is whatever change we found in the block.
933   BBInfo.Exit = BBInfo.Change;
934 
935   return HadVectorOp;
936 }
937 
938 void RISCVInsertVSETVLI::computeIncomingVLVTYPE(const MachineBasicBlock &MBB) {
939   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
940 
941   BBInfo.InQueue = false;
942 
943   VSETVLIInfo InInfo;
944   if (MBB.pred_empty()) {
945     // There are no predecessors, so use the default starting status.
946     InInfo.setUnknown();
947   } else {
948     for (MachineBasicBlock *P : MBB.predecessors())
949       InInfo = InInfo.intersect(BlockInfo[P->getNumber()].Exit);
950   }
951 
952   // If we don't have any valid predecessor value, wait until we do.
953   if (!InInfo.isValid())
954     return;
955 
956   BBInfo.Pred = InInfo;
957 
958   VSETVLIInfo TmpStatus = BBInfo.Pred.merge(BBInfo.Change);
959 
960   // If the new exit value matches the old exit value, we don't need to revisit
961   // any blocks.
962   if (BBInfo.Exit == TmpStatus)
963     return;
964 
965   BBInfo.Exit = TmpStatus;
966 
967   // Add the successors to the work list so we can propagate the changed exit
968   // status.
969   for (MachineBasicBlock *S : MBB.successors())
970     if (!BlockInfo[S->getNumber()].InQueue)
971       WorkList.push(S);
972 }
973 
974 // If we weren't able to prove a vsetvli was directly unneeded, it might still
975 // be/ unneeded if the AVL is a phi node where all incoming values are VL
976 // outputs from the last VSETVLI in their respective basic blocks.
977 bool RISCVInsertVSETVLI::needVSETVLIPHI(const VSETVLIInfo &Require,
978                                         const MachineBasicBlock &MBB) {
979   if (DisableInsertVSETVLPHIOpt)
980     return true;
981 
982   if (!Require.hasAVLReg())
983     return true;
984 
985   Register AVLReg = Require.getAVLReg();
986   if (!AVLReg.isVirtual())
987     return true;
988 
989   // We need the AVL to be produce by a PHI node in this basic block.
990   MachineInstr *PHI = MRI->getVRegDef(AVLReg);
991   if (!PHI || PHI->getOpcode() != RISCV::PHI || PHI->getParent() != &MBB)
992     return true;
993 
994   for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
995        PHIOp += 2) {
996     Register InReg = PHI->getOperand(PHIOp).getReg();
997     MachineBasicBlock *PBB = PHI->getOperand(PHIOp + 1).getMBB();
998     const BlockData &PBBInfo = BlockInfo[PBB->getNumber()];
999     // If the exit from the predecessor has the VTYPE we are looking for
1000     // we might be able to avoid a VSETVLI.
1001     if (PBBInfo.Exit.isUnknown() ||
1002         !PBBInfo.Exit.hasCompatibleVTYPE(Require, /*Strict*/ false))
1003       return true;
1004 
1005     // We need the PHI input to the be the output of a VSET(I)VLI.
1006     MachineInstr *DefMI = MRI->getVRegDef(InReg);
1007     if (!DefMI || !isVectorConfigInstr(*DefMI))
1008       return true;
1009 
1010     // We found a VSET(I)VLI make sure it matches the output of the
1011     // predecessor block.
1012     VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1013     if (!DefInfo.hasSameAVL(PBBInfo.Exit) ||
1014         !DefInfo.hasSameVTYPE(PBBInfo.Exit))
1015       return true;
1016   }
1017 
1018   // If all the incoming values to the PHI checked out, we don't need
1019   // to insert a VSETVLI.
1020   return false;
1021 }
1022 
1023 void RISCVInsertVSETVLI::emitVSETVLIs(MachineBasicBlock &MBB) {
1024   VSETVLIInfo CurInfo;
1025   // Only be set if current VSETVLIInfo is from an explicit VSET(I)VLI.
1026   MachineInstr *PrevVSETVLIMI = nullptr;
1027 
1028   for (MachineInstr &MI : MBB) {
1029     // If this is an explicit VSETVLI or VSETIVLI, update our state.
1030     if (isVectorConfigInstr(MI)) {
1031       // Conservatively, mark the VL and VTYPE as live.
1032       assert(MI.getOperand(3).getReg() == RISCV::VL &&
1033              MI.getOperand(4).getReg() == RISCV::VTYPE &&
1034              "Unexpected operands where VL and VTYPE should be");
1035       MI.getOperand(3).setIsDead(false);
1036       MI.getOperand(4).setIsDead(false);
1037       CurInfo = getInfoForVSETVLI(MI);
1038       PrevVSETVLIMI = &MI;
1039       continue;
1040     }
1041 
1042     uint64_t TSFlags = MI.getDesc().TSFlags;
1043     if (RISCVII::hasSEWOp(TSFlags)) {
1044       VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
1045       if (RISCVII::hasVLOp(TSFlags)) {
1046         unsigned Offset = 2;
1047         if (RISCVII::hasVecPolicyOp(TSFlags))
1048           Offset = 3;
1049         MachineOperand &VLOp =
1050             MI.getOperand(MI.getNumExplicitOperands() - Offset);
1051         if (VLOp.isReg()) {
1052           // Erase the AVL operand from the instruction.
1053           VLOp.setReg(RISCV::NoRegister);
1054           VLOp.setIsKill(false);
1055         }
1056         MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ false,
1057                                                 /*isImp*/ true));
1058       }
1059       MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
1060                                               /*isImp*/ true));
1061 
1062       if (!CurInfo.isValid()) {
1063         // We haven't found any vector instructions or VL/VTYPE changes yet,
1064         // use the predecessor information.
1065         assert(BlockInfo[MBB.getNumber()].Pred.isValid() &&
1066                "Expected a valid predecessor state.");
1067         if (needVSETVLI(NewInfo, BlockInfo[MBB.getNumber()].Pred) &&
1068             needVSETVLIPHI(NewInfo, MBB)) {
1069           insertVSETVLI(MBB, MI, NewInfo, BlockInfo[MBB.getNumber()].Pred);
1070           CurInfo = NewInfo;
1071         }
1072       } else {
1073         // If this instruction isn't compatible with the previous VL/VTYPE
1074         // we need to insert a VSETVLI.
1075         // If this is a unit-stride or strided load/store, we may be able to use
1076         // the EMUL=(EEW/SEW)*LMUL relationship to avoid changing vtype.
1077         // NOTE: We can't use predecessor information for the store. We must
1078         // treat it the same as the first phase so that we produce the correct
1079         // vl/vtype for succesor blocks.
1080         if (!canSkipVSETVLIForLoadStore(MI, NewInfo, CurInfo) &&
1081             needVSETVLI(NewInfo, CurInfo)) {
1082           // If the previous VL/VTYPE is set by VSETVLI and do not use, Merge it
1083           // with current VL/VTYPE.
1084           bool NeedInsertVSETVLI = true;
1085           if (PrevVSETVLIMI) {
1086             bool HasSameAVL =
1087                 CurInfo.hasSameAVL(NewInfo) ||
1088                 (NewInfo.hasAVLReg() && NewInfo.getAVLReg().isVirtual() &&
1089                  NewInfo.getAVLReg() == PrevVSETVLIMI->getOperand(0).getReg());
1090             // If these two VSETVLI have the same AVL and the same VLMAX,
1091             // we could merge these two VSETVLI.
1092             if (HasSameAVL &&
1093                 CurInfo.getSEWLMULRatio() == NewInfo.getSEWLMULRatio()) {
1094               PrevVSETVLIMI->getOperand(2).setImm(NewInfo.encodeVTYPE());
1095               NeedInsertVSETVLI = false;
1096             }
1097             if (isScalarMoveInstr(MI) &&
1098                 ((CurInfo.hasNonZeroAVL() && NewInfo.hasNonZeroAVL()) ||
1099                  (CurInfo.hasZeroAVL() && NewInfo.hasZeroAVL())) &&
1100                 NewInfo.hasSameVLMAX(CurInfo)) {
1101               PrevVSETVLIMI->getOperand(2).setImm(NewInfo.encodeVTYPE());
1102               NeedInsertVSETVLI = false;
1103             }
1104           }
1105           if (NeedInsertVSETVLI)
1106             insertVSETVLI(MBB, MI, NewInfo, CurInfo);
1107           CurInfo = NewInfo;
1108         }
1109       }
1110       PrevVSETVLIMI = nullptr;
1111     }
1112 
1113     // If this is something updates VL/VTYPE that we don't know about, set
1114     // the state to unknown.
1115     if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
1116         MI.modifiesRegister(RISCV::VTYPE)) {
1117       CurInfo = VSETVLIInfo::getUnknown();
1118       PrevVSETVLIMI = nullptr;
1119     }
1120 
1121     // If we reach the end of the block and our current info doesn't match the
1122     // expected info, insert a vsetvli to correct.
1123     if (MI.isTerminator()) {
1124       const VSETVLIInfo &ExitInfo = BlockInfo[MBB.getNumber()].Exit;
1125       if (CurInfo.isValid() && ExitInfo.isValid() && !ExitInfo.isUnknown() &&
1126           CurInfo != ExitInfo) {
1127         insertVSETVLI(MBB, MI, ExitInfo, CurInfo);
1128         CurInfo = ExitInfo;
1129       }
1130     }
1131   }
1132 }
1133 
1134 bool RISCVInsertVSETVLI::runOnMachineFunction(MachineFunction &MF) {
1135   // Skip if the vector extension is not enabled.
1136   const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
1137   if (!ST.hasVInstructions())
1138     return false;
1139 
1140   TII = ST.getInstrInfo();
1141   MRI = &MF.getRegInfo();
1142 
1143   assert(BlockInfo.empty() && "Expect empty block infos");
1144   BlockInfo.resize(MF.getNumBlockIDs());
1145 
1146   bool HaveVectorOp = false;
1147 
1148   // Phase 1 - determine how VL/VTYPE are affected by the each block.
1149   for (const MachineBasicBlock &MBB : MF)
1150     HaveVectorOp |= computeVLVTYPEChanges(MBB);
1151 
1152   // If we didn't find any instructions that need VSETVLI, we're done.
1153   if (HaveVectorOp) {
1154     // Phase 2 - determine the exit VL/VTYPE from each block. We add all
1155     // blocks to the list here, but will also add any that need to be revisited
1156     // during Phase 2 processing.
1157     for (const MachineBasicBlock &MBB : MF) {
1158       WorkList.push(&MBB);
1159       BlockInfo[MBB.getNumber()].InQueue = true;
1160     }
1161     while (!WorkList.empty()) {
1162       const MachineBasicBlock &MBB = *WorkList.front();
1163       WorkList.pop();
1164       computeIncomingVLVTYPE(MBB);
1165     }
1166 
1167     // Phase 3 - add any vsetvli instructions needed in the block. Use the
1168     // Phase 2 information to avoid adding vsetvlis before the first vector
1169     // instruction in the block if the VL/VTYPE is satisfied by its
1170     // predecessors.
1171     for (MachineBasicBlock &MBB : MF)
1172       emitVSETVLIs(MBB);
1173   }
1174 
1175   BlockInfo.clear();
1176 
1177   return HaveVectorOp;
1178 }
1179 
1180 /// Returns an instance of the Insert VSETVLI pass.
1181 FunctionPass *llvm::createRISCVInsertVSETVLIPass() {
1182   return new RISCVInsertVSETVLI();
1183 }
1184