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