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