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