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 and expands the vl outputs of VLEFF/VLSEGFF to PseudoReadVL
11 // instructions.
12 //
13 // This pass consists of 3 phases:
14 //
15 // Phase 1 collects how each basic block affects VL/VTYPE.
16 //
17 // Phase 2 uses the information from phase 1 to do a data flow analysis to
18 // propagate the VL/VTYPE changes through the function. This gives us the
19 // VL/VTYPE at the start of each basic block.
20 //
21 // Phase 3 inserts VSETVLI instructions in each basic block. Information from
22 // phase 2 is used to prevent inserting a VSETVLI before the first vector
23 // instruction in the block if possible.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "RISCV.h"
28 #include "RISCVSubtarget.h"
29 #include "llvm/CodeGen/LiveIntervals.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include <queue>
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "riscv-insert-vsetvli"
35 #define RISCV_INSERT_VSETVLI_NAME "RISCV Insert VSETVLI pass"
36 
37 static cl::opt<bool> DisableInsertVSETVLPHIOpt(
38     "riscv-disable-insert-vsetvl-phi-opt", cl::init(false), cl::Hidden,
39     cl::desc("Disable looking through phis when inserting vsetvlis."));
40 
41 static cl::opt<bool> UseStrictAsserts(
42     "riscv-insert-vsetvl-strict-asserts", cl::init(true), cl::Hidden,
43     cl::desc("Enable strict assertion checking for the dataflow algorithm"));
44 
45 namespace {
46 
47 static unsigned getVLOpNum(const MachineInstr &MI) {
48   return RISCVII::getVLOpNum(MI.getDesc());
49 }
50 
51 static unsigned getSEWOpNum(const MachineInstr &MI) {
52   return RISCVII::getSEWOpNum(MI.getDesc());
53 }
54 
55 static bool isScalarMoveInstr(const MachineInstr &MI) {
56   switch (MI.getOpcode()) {
57   default:
58     return false;
59   case RISCV::PseudoVMV_S_X_M1:
60   case RISCV::PseudoVMV_S_X_M2:
61   case RISCV::PseudoVMV_S_X_M4:
62   case RISCV::PseudoVMV_S_X_M8:
63   case RISCV::PseudoVMV_S_X_MF2:
64   case RISCV::PseudoVMV_S_X_MF4:
65   case RISCV::PseudoVMV_S_X_MF8:
66   case RISCV::PseudoVFMV_S_F16_M1:
67   case RISCV::PseudoVFMV_S_F16_M2:
68   case RISCV::PseudoVFMV_S_F16_M4:
69   case RISCV::PseudoVFMV_S_F16_M8:
70   case RISCV::PseudoVFMV_S_F16_MF2:
71   case RISCV::PseudoVFMV_S_F16_MF4:
72   case RISCV::PseudoVFMV_S_F32_M1:
73   case RISCV::PseudoVFMV_S_F32_M2:
74   case RISCV::PseudoVFMV_S_F32_M4:
75   case RISCV::PseudoVFMV_S_F32_M8:
76   case RISCV::PseudoVFMV_S_F32_MF2:
77   case RISCV::PseudoVFMV_S_F64_M1:
78   case RISCV::PseudoVFMV_S_F64_M2:
79   case RISCV::PseudoVFMV_S_F64_M4:
80   case RISCV::PseudoVFMV_S_F64_M8:
81     return true;
82   }
83 }
84 
85 
86 class VSETVLIInfo {
87   union {
88     Register AVLReg;
89     unsigned AVLImm;
90   };
91 
92   enum : uint8_t {
93     Uninitialized,
94     AVLIsReg,
95     AVLIsImm,
96     Unknown,
97   } State = Uninitialized;
98 
99   // Fields from VTYPE.
100   RISCVII::VLMUL VLMul = RISCVII::LMUL_1;
101   uint8_t SEW = 0;
102   uint8_t TailAgnostic : 1;
103   uint8_t MaskAgnostic : 1;
104   uint8_t SEWLMULRatioOnly : 1;
105 
106 public:
107   VSETVLIInfo()
108       : AVLImm(0), TailAgnostic(false), MaskAgnostic(false),
109         SEWLMULRatioOnly(false) {}
110 
111   static VSETVLIInfo getUnknown() {
112     VSETVLIInfo Info;
113     Info.setUnknown();
114     return Info;
115   }
116 
117   bool isValid() const { return State != Uninitialized; }
118   void setUnknown() { State = Unknown; }
119   bool isUnknown() const { return State == Unknown; }
120 
121   void setAVLReg(Register Reg) {
122     AVLReg = Reg;
123     State = AVLIsReg;
124   }
125 
126   void setAVLImm(unsigned Imm) {
127     AVLImm = Imm;
128     State = AVLIsImm;
129   }
130 
131   bool hasAVLImm() const { return State == AVLIsImm; }
132   bool hasAVLReg() const { return State == AVLIsReg; }
133   Register getAVLReg() const {
134     assert(hasAVLReg());
135     return AVLReg;
136   }
137   unsigned getAVLImm() const {
138     assert(hasAVLImm());
139     return AVLImm;
140   }
141 
142   unsigned getSEW() const { return SEW; }
143   RISCVII::VLMUL getVLMUL() const { return VLMul; }
144 
145   bool hasZeroAVL() const {
146     if (hasAVLImm())
147       return getAVLImm() == 0;
148     return false;
149   }
150   bool hasNonZeroAVL() const {
151     if (hasAVLImm())
152       return getAVLImm() > 0;
153     if (hasAVLReg())
154       return getAVLReg() == RISCV::X0;
155     return false;
156   }
157 
158   bool hasSameAVL(const VSETVLIInfo &Other) const {
159     assert(isValid() && Other.isValid() &&
160            "Can't compare invalid VSETVLIInfos");
161     assert(!isUnknown() && !Other.isUnknown() &&
162            "Can't compare AVL in unknown state");
163     if (hasAVLReg() && Other.hasAVLReg())
164       return getAVLReg() == Other.getAVLReg();
165 
166     if (hasAVLImm() && Other.hasAVLImm())
167       return getAVLImm() == Other.getAVLImm();
168 
169     return false;
170   }
171 
172   void setVTYPE(unsigned VType) {
173     assert(isValid() && !isUnknown() &&
174            "Can't set VTYPE for uninitialized or unknown");
175     VLMul = RISCVVType::getVLMUL(VType);
176     SEW = RISCVVType::getSEW(VType);
177     TailAgnostic = RISCVVType::isTailAgnostic(VType);
178     MaskAgnostic = RISCVVType::isMaskAgnostic(VType);
179   }
180   void setVTYPE(RISCVII::VLMUL L, unsigned S, bool TA, bool MA) {
181     assert(isValid() && !isUnknown() &&
182            "Can't set VTYPE for uninitialized or unknown");
183     VLMul = L;
184     SEW = S;
185     TailAgnostic = TA;
186     MaskAgnostic = MA;
187   }
188 
189   unsigned encodeVTYPE() const {
190     assert(isValid() && !isUnknown() && !SEWLMULRatioOnly &&
191            "Can't encode VTYPE for uninitialized or unknown");
192     return RISCVVType::encodeVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
193   }
194 
195   bool hasSEWLMULRatioOnly() const { return SEWLMULRatioOnly; }
196 
197   bool hasSameSEW(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     assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
203            "Can't compare when only LMUL/SEW ratio is valid.");
204     return SEW == Other.SEW;
205   }
206 
207   bool hasSameVTYPE(const VSETVLIInfo &Other) const {
208     assert(isValid() && Other.isValid() &&
209            "Can't compare invalid VSETVLIInfos");
210     assert(!isUnknown() && !Other.isUnknown() &&
211            "Can't compare VTYPE in unknown state");
212     assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
213            "Can't compare when only LMUL/SEW ratio is valid.");
214     return std::tie(VLMul, SEW, TailAgnostic, MaskAgnostic) ==
215            std::tie(Other.VLMul, Other.SEW, Other.TailAgnostic,
216                     Other.MaskAgnostic);
217   }
218 
219   static unsigned getSEWLMULRatio(unsigned SEW, RISCVII::VLMUL VLMul) {
220     unsigned LMul;
221     bool Fractional;
222     std::tie(LMul, Fractional) = RISCVVType::decodeVLMUL(VLMul);
223 
224     // Convert LMul to a fixed point value with 3 fractional bits.
225     LMul = Fractional ? (8 / LMul) : (LMul * 8);
226 
227     assert(SEW >= 8 && "Unexpected SEW value");
228     return (SEW * 8) / LMul;
229   }
230 
231   unsigned getSEWLMULRatio() const {
232     assert(isValid() && !isUnknown() &&
233            "Can't use VTYPE for uninitialized or unknown");
234     return getSEWLMULRatio(SEW, VLMul);
235   }
236 
237   // Check if the VTYPE for these two VSETVLIInfos produce the same VLMAX.
238   // Note that having the same VLMAX ensures that both share the same
239   // function from AVL to VL; that is, they must produce the same VL value
240   // for any given AVL value.
241   bool hasSameVLMAX(const VSETVLIInfo &Other) const {
242     assert(isValid() && Other.isValid() &&
243            "Can't compare invalid VSETVLIInfos");
244     assert(!isUnknown() && !Other.isUnknown() &&
245            "Can't compare VTYPE in unknown state");
246     return getSEWLMULRatio() == Other.getSEWLMULRatio();
247   }
248 
249   bool hasSamePolicy(const VSETVLIInfo &Other) const {
250     assert(isValid() && Other.isValid() &&
251            "Can't compare invalid VSETVLIInfos");
252     assert(!isUnknown() && !Other.isUnknown() &&
253            "Can't compare VTYPE in unknown state");
254     return TailAgnostic == Other.TailAgnostic &&
255            MaskAgnostic == Other.MaskAgnostic;
256   }
257 
258   bool hasCompatibleVTYPE(const MachineInstr &MI,
259                           const VSETVLIInfo &Require) const {
260     // Simple case, see if full VTYPE matches.
261     if (hasSameVTYPE(Require))
262       return true;
263 
264     // If this is a mask reg operation, it only cares about VLMAX.
265     // FIXME: Mask reg operations are probably ok if "this" VLMAX is larger
266     // than "Require".
267     // FIXME: The policy bits can probably be ignored for mask reg operations.
268     const unsigned Log2SEW = MI.getOperand(getSEWOpNum(MI)).getImm();
269     // A Log2SEW of 0 is an operation on mask registers only.
270     const bool MaskRegOp = Log2SEW == 0;
271     if (MaskRegOp && hasSameVLMAX(Require) &&
272         TailAgnostic == Require.TailAgnostic &&
273         MaskAgnostic == Require.MaskAgnostic)
274       return true;
275 
276     return false;
277   }
278 
279   // Determine whether the vector instructions requirements represented by
280   // Require are compatible with the previous vsetvli instruction represented
281   // by this.  MI is the instruction whose requirements we're considering.
282   bool isCompatible(const MachineInstr &MI, const VSETVLIInfo &Require) const {
283     assert(isValid() && Require.isValid() &&
284            "Can't compare invalid VSETVLIInfos");
285     assert(!Require.SEWLMULRatioOnly &&
286            "Expected a valid VTYPE for instruction!");
287     // Nothing is compatible with Unknown.
288     if (isUnknown() || Require.isUnknown())
289       return false;
290 
291     // If only our VLMAX ratio is valid, then this isn't compatible.
292     if (SEWLMULRatioOnly)
293       return false;
294 
295     // If the instruction doesn't need an AVLReg and the SEW matches, consider
296     // it compatible.
297     if (Require.hasAVLReg() && Require.AVLReg == RISCV::NoRegister)
298       if (SEW == Require.SEW)
299         return true;
300 
301     // For vmv.s.x and vfmv.s.f, there is only two behaviors, VL = 0 and VL > 0.
302     // So it's compatible when we could make sure that both VL be the same
303     // situation.
304     if (isScalarMoveInstr(MI) && Require.hasAVLImm() &&
305         ((hasNonZeroAVL() && Require.hasNonZeroAVL()) ||
306          (hasZeroAVL() && Require.hasZeroAVL())) &&
307         hasSameSEW(Require) && hasSamePolicy(Require))
308       return true;
309 
310     // The AVL must match.
311     if (!hasSameAVL(Require))
312       return false;
313 
314     if (hasCompatibleVTYPE(MI, Require))
315       return true;
316 
317     // Store instructions don't use the policy fields.
318     const bool StoreOp = MI.getNumExplicitDefs() == 0;
319     if (StoreOp && VLMul == Require.VLMul && SEW == Require.SEW)
320       return true;
321 
322     // Anything else is not compatible.
323     return false;
324   }
325 
326   bool isCompatibleWithLoadStoreEEW(unsigned EEW,
327                                     const VSETVLIInfo &Require) const {
328     assert(isValid() && Require.isValid() &&
329            "Can't compare invalid VSETVLIInfos");
330     assert(!Require.SEWLMULRatioOnly &&
331            "Expected a valid VTYPE for instruction!");
332     assert(EEW == Require.SEW && "Mismatched EEW/SEW for store");
333 
334     if (isUnknown() || hasSEWLMULRatioOnly())
335       return false;
336 
337     if (!hasSameAVL(Require))
338       return false;
339 
340     return getSEWLMULRatio() == getSEWLMULRatio(EEW, Require.VLMul);
341   }
342 
343   bool operator==(const VSETVLIInfo &Other) const {
344     // Uninitialized is only equal to another Uninitialized.
345     if (!isValid())
346       return !Other.isValid();
347     if (!Other.isValid())
348       return !isValid();
349 
350     // Unknown is only equal to another Unknown.
351     if (isUnknown())
352       return Other.isUnknown();
353     if (Other.isUnknown())
354       return isUnknown();
355 
356     if (!hasSameAVL(Other))
357       return false;
358 
359     // If the SEWLMULRatioOnly bits are different, then they aren't equal.
360     if (SEWLMULRatioOnly != Other.SEWLMULRatioOnly)
361       return false;
362 
363     // If only the VLMAX is valid, check that it is the same.
364     if (SEWLMULRatioOnly)
365       return hasSameVLMAX(Other);
366 
367     // If the full VTYPE is valid, check that it is the same.
368     return hasSameVTYPE(Other);
369   }
370 
371   bool operator!=(const VSETVLIInfo &Other) const {
372     return !(*this == Other);
373   }
374 
375   // Calculate the VSETVLIInfo visible to a block assuming this and Other are
376   // both predecessors.
377   VSETVLIInfo intersect(const VSETVLIInfo &Other) const {
378     // If the new value isn't valid, ignore it.
379     if (!Other.isValid())
380       return *this;
381 
382     // If this value isn't valid, this must be the first predecessor, use it.
383     if (!isValid())
384       return Other;
385 
386     // If either is unknown, the result is unknown.
387     if (isUnknown() || Other.isUnknown())
388       return VSETVLIInfo::getUnknown();
389 
390     // If we have an exact, match return this.
391     if (*this == Other)
392       return *this;
393 
394     // Not an exact match, but maybe the AVL and VLMAX are the same. If so,
395     // return an SEW/LMUL ratio only value.
396     if (hasSameAVL(Other) && hasSameVLMAX(Other)) {
397       VSETVLIInfo MergeInfo = *this;
398       MergeInfo.SEWLMULRatioOnly = true;
399       return MergeInfo;
400     }
401 
402     // Otherwise the result is unknown.
403     return VSETVLIInfo::getUnknown();
404   }
405 
406 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
407   /// Support for debugging, callable in GDB: V->dump()
408   LLVM_DUMP_METHOD void dump() const {
409     print(dbgs());
410     dbgs() << "\n";
411   }
412 
413   /// Implement operator<<.
414   /// @{
415   void print(raw_ostream &OS) const {
416     OS << "{";
417     if (!isValid())
418       OS << "Uninitialized";
419     if (isUnknown())
420       OS << "unknown";;
421     if (hasAVLReg())
422       OS << "AVLReg=" << (unsigned)AVLReg;
423     if (hasAVLImm())
424       OS << "AVLImm=" << (unsigned)AVLImm;
425     OS << ", "
426        << "VLMul=" << (unsigned)VLMul << ", "
427        << "SEW=" << (unsigned)SEW << ", "
428        << "TailAgnostic=" << (bool)TailAgnostic << ", "
429        << "MaskAgnostic=" << (bool)MaskAgnostic << ", "
430        << "SEWLMULRatioOnly=" << (bool)SEWLMULRatioOnly << "}";
431   }
432 #endif
433 };
434 
435 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
436 LLVM_ATTRIBUTE_USED
437 inline raw_ostream &operator<<(raw_ostream &OS, const VSETVLIInfo &V) {
438   V.print(OS);
439   return OS;
440 }
441 #endif
442 
443 struct BlockData {
444   // The VSETVLIInfo that represents the net changes to the VL/VTYPE registers
445   // made by this block. Calculated in Phase 1.
446   VSETVLIInfo Change;
447 
448   // The VSETVLIInfo that represents the VL/VTYPE settings on exit from this
449   // block. Calculated in Phase 2.
450   VSETVLIInfo Exit;
451 
452   // The VSETVLIInfo that represents the VL/VTYPE settings from all predecessor
453   // blocks. Calculated in Phase 2, and used by Phase 3.
454   VSETVLIInfo Pred;
455 
456   // Keeps track of whether the block is already in the queue.
457   bool InQueue = false;
458 
459   BlockData() = default;
460 };
461 
462 class RISCVInsertVSETVLI : public MachineFunctionPass {
463   const TargetInstrInfo *TII;
464   MachineRegisterInfo *MRI;
465 
466   std::vector<BlockData> BlockInfo;
467   std::queue<const MachineBasicBlock *> WorkList;
468 
469 public:
470   static char ID;
471 
472   RISCVInsertVSETVLI() : MachineFunctionPass(ID) {
473     initializeRISCVInsertVSETVLIPass(*PassRegistry::getPassRegistry());
474   }
475   bool runOnMachineFunction(MachineFunction &MF) override;
476 
477   void getAnalysisUsage(AnalysisUsage &AU) const override {
478     AU.setPreservesCFG();
479     MachineFunctionPass::getAnalysisUsage(AU);
480   }
481 
482   StringRef getPassName() const override { return RISCV_INSERT_VSETVLI_NAME; }
483 
484 private:
485   bool needVSETVLI(const MachineInstr &MI, const VSETVLIInfo &Require,
486                    const VSETVLIInfo &CurInfo) const;
487   bool needVSETVLIPHI(const VSETVLIInfo &Require,
488                       const MachineBasicBlock &MBB) const;
489   void insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
490                      const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
491   void insertVSETVLI(MachineBasicBlock &MBB,
492                      MachineBasicBlock::iterator InsertPt, DebugLoc DL,
493                      const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
494 
495   void transferBefore(VSETVLIInfo &Info, const MachineInstr &MI);
496   void transferAfter(VSETVLIInfo &Info, const MachineInstr &MI);
497   bool computeVLVTYPEChanges(const MachineBasicBlock &MBB);
498   void computeIncomingVLVTYPE(const MachineBasicBlock &MBB);
499   void emitVSETVLIs(MachineBasicBlock &MBB);
500   void doLocalPrepass(MachineBasicBlock &MBB);
501   void doLocalPostpass(MachineBasicBlock &MBB);
502   void doPRE(MachineBasicBlock &MBB);
503   void insertReadVL(MachineBasicBlock &MBB);
504 };
505 
506 } // end anonymous namespace
507 
508 char RISCVInsertVSETVLI::ID = 0;
509 
510 INITIALIZE_PASS(RISCVInsertVSETVLI, DEBUG_TYPE, RISCV_INSERT_VSETVLI_NAME,
511                 false, false)
512 
513 static bool isVectorConfigInstr(const MachineInstr &MI) {
514   return MI.getOpcode() == RISCV::PseudoVSETVLI ||
515          MI.getOpcode() == RISCV::PseudoVSETVLIX0 ||
516          MI.getOpcode() == RISCV::PseudoVSETIVLI;
517 }
518 
519 /// Return true if this is 'vsetvli x0, x0, vtype' which preserves
520 /// VL and only sets VTYPE.
521 static bool isVLPreservingConfig(const MachineInstr &MI) {
522   if (MI.getOpcode() != RISCV::PseudoVSETVLIX0)
523     return false;
524   assert(RISCV::X0 == MI.getOperand(1).getReg());
525   return RISCV::X0 == MI.getOperand(0).getReg();
526 }
527 
528 static MachineInstr *elideCopies(MachineInstr *MI,
529                                  const MachineRegisterInfo *MRI) {
530   while (true) {
531     if (!MI->isFullCopy())
532       return MI;
533     if (!Register::isVirtualRegister(MI->getOperand(1).getReg()))
534       return nullptr;
535     MI = MRI->getVRegDef(MI->getOperand(1).getReg());
536     if (!MI)
537       return nullptr;
538   }
539 }
540 
541 static VSETVLIInfo computeInfoForInstr(const MachineInstr &MI, uint64_t TSFlags,
542                                        const MachineRegisterInfo *MRI) {
543   VSETVLIInfo InstrInfo;
544 
545   // If the instruction has policy argument, use the argument.
546   // If there is no policy argument, default to tail agnostic unless the
547   // destination is tied to a source. Unless the source is undef. In that case
548   // the user would have some control over the policy values.
549   bool TailAgnostic = true;
550   bool UsesMaskPolicy = RISCVII::usesMaskPolicy(TSFlags);
551   // FIXME: Could we look at the above or below instructions to choose the
552   // matched mask policy to reduce vsetvli instructions? Default mask policy is
553   // agnostic if instructions use mask policy, otherwise is undisturbed. Because
554   // most mask operations are mask undisturbed, so we could possibly reduce the
555   // vsetvli between mask and nomasked instruction sequence.
556   bool MaskAgnostic = UsesMaskPolicy;
557   unsigned UseOpIdx;
558   if (RISCVII::hasVecPolicyOp(TSFlags)) {
559     const MachineOperand &Op = MI.getOperand(MI.getNumExplicitOperands() - 1);
560     uint64_t Policy = Op.getImm();
561     assert(Policy <= (RISCVII::TAIL_AGNOSTIC | RISCVII::MASK_AGNOSTIC) &&
562            "Invalid Policy Value");
563     // Although in some cases, mismatched passthru/maskedoff with policy value
564     // does not make sense (ex. tied operand is IMPLICIT_DEF with non-TAMA
565     // policy, or tied operand is not IMPLICIT_DEF with TAMA policy), but users
566     // have set the policy value explicitly, so compiler would not fix it.
567     TailAgnostic = Policy & RISCVII::TAIL_AGNOSTIC;
568     MaskAgnostic = Policy & RISCVII::MASK_AGNOSTIC;
569   } else if (MI.isRegTiedToUseOperand(0, &UseOpIdx)) {
570     TailAgnostic = false;
571     if (UsesMaskPolicy)
572       MaskAgnostic = false;
573     // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic.
574     const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
575     MachineInstr *UseMI = MRI->getVRegDef(UseMO.getReg());
576     if (UseMI) {
577       UseMI = elideCopies(UseMI, MRI);
578       if (UseMI && UseMI->isImplicitDef()) {
579         TailAgnostic = true;
580         if (UsesMaskPolicy)
581           MaskAgnostic = true;
582       }
583     }
584     // Some pseudo instructions force a tail agnostic policy despite having a
585     // tied def.
586     if (RISCVII::doesForceTailAgnostic(TSFlags))
587       TailAgnostic = true;
588   }
589 
590   RISCVII::VLMUL VLMul = RISCVII::getLMul(TSFlags);
591 
592   unsigned Log2SEW = MI.getOperand(getSEWOpNum(MI)).getImm();
593   // A Log2SEW of 0 is an operation on mask registers only.
594   unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
595   assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
596 
597   if (RISCVII::hasVLOp(TSFlags)) {
598     const MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
599     if (VLOp.isImm()) {
600       int64_t Imm = VLOp.getImm();
601       // Conver the VLMax sentintel to X0 register.
602       if (Imm == RISCV::VLMaxSentinel)
603         InstrInfo.setAVLReg(RISCV::X0);
604       else
605         InstrInfo.setAVLImm(Imm);
606     } else {
607       InstrInfo.setAVLReg(VLOp.getReg());
608     }
609   } else {
610     InstrInfo.setAVLReg(RISCV::NoRegister);
611   }
612   InstrInfo.setVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
613 
614   return InstrInfo;
615 }
616 
617 void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
618                                        const VSETVLIInfo &Info,
619                                        const VSETVLIInfo &PrevInfo) {
620   DebugLoc DL = MI.getDebugLoc();
621   insertVSETVLI(MBB, MachineBasicBlock::iterator(&MI), DL, Info, PrevInfo);
622 }
623 
624 void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB,
625                      MachineBasicBlock::iterator InsertPt, DebugLoc DL,
626                      const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo) {
627 
628   // Use X0, X0 form if the AVL is the same and the SEW+LMUL gives the same
629   // VLMAX.
630   if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
631       Info.hasSameAVL(PrevInfo) && Info.hasSameVLMAX(PrevInfo)) {
632     BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
633         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
634         .addReg(RISCV::X0, RegState::Kill)
635         .addImm(Info.encodeVTYPE())
636         .addReg(RISCV::VL, RegState::Implicit);
637     return;
638   }
639 
640   if (Info.hasAVLImm()) {
641     BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETIVLI))
642         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
643         .addImm(Info.getAVLImm())
644         .addImm(Info.encodeVTYPE());
645     return;
646   }
647 
648   Register AVLReg = Info.getAVLReg();
649   if (AVLReg == RISCV::NoRegister) {
650     // We can only use x0, x0 if there's no chance of the vtype change causing
651     // the previous vl to become invalid.
652     if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
653         Info.hasSameVLMAX(PrevInfo)) {
654       BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETVLIX0))
655           .addReg(RISCV::X0, RegState::Define | RegState::Dead)
656           .addReg(RISCV::X0, RegState::Kill)
657           .addImm(Info.encodeVTYPE())
658           .addReg(RISCV::VL, RegState::Implicit);
659       return;
660     }
661     // Otherwise use an AVL of 0 to avoid depending on previous vl.
662     BuildMI(MBB, InsertPt, DL, TII->get(RISCV::PseudoVSETIVLI))
663         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
664         .addImm(0)
665         .addImm(Info.encodeVTYPE());
666     return;
667   }
668 
669   if (AVLReg.isVirtual())
670     MRI->constrainRegClass(AVLReg, &RISCV::GPRNoX0RegClass);
671 
672   // Use X0 as the DestReg unless AVLReg is X0. We also need to change the
673   // opcode if the AVLReg is X0 as they have different register classes for
674   // the AVL operand.
675   Register DestReg = RISCV::X0;
676   unsigned Opcode = RISCV::PseudoVSETVLI;
677   if (AVLReg == RISCV::X0) {
678     DestReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
679     Opcode = RISCV::PseudoVSETVLIX0;
680   }
681   BuildMI(MBB, InsertPt, DL, TII->get(Opcode))
682       .addReg(DestReg, RegState::Define | RegState::Dead)
683       .addReg(AVLReg)
684       .addImm(Info.encodeVTYPE());
685 }
686 
687 // Return a VSETVLIInfo representing the changes made by this VSETVLI or
688 // VSETIVLI instruction.
689 static VSETVLIInfo getInfoForVSETVLI(const MachineInstr &MI) {
690   VSETVLIInfo NewInfo;
691   if (MI.getOpcode() == RISCV::PseudoVSETIVLI) {
692     NewInfo.setAVLImm(MI.getOperand(1).getImm());
693   } else {
694     assert(MI.getOpcode() == RISCV::PseudoVSETVLI ||
695            MI.getOpcode() == RISCV::PseudoVSETVLIX0);
696     Register AVLReg = MI.getOperand(1).getReg();
697     assert((AVLReg != RISCV::X0 || MI.getOperand(0).getReg() != RISCV::X0) &&
698            "Can't handle X0, X0 vsetvli yet");
699     NewInfo.setAVLReg(AVLReg);
700   }
701   NewInfo.setVTYPE(MI.getOperand(2).getImm());
702 
703   return NewInfo;
704 }
705 
706 /// Get the EEW for a load or store instruction.  Return None if MI is not
707 /// a load or store which ignores SEW.
708 static Optional<unsigned> getEEWForLoadStore(const MachineInstr &MI) {
709   switch (MI.getOpcode()) {
710   default:
711     return None;
712   case RISCV::PseudoVLE8_V_M1:
713   case RISCV::PseudoVLE8_V_M1_MASK:
714   case RISCV::PseudoVLE8_V_M2:
715   case RISCV::PseudoVLE8_V_M2_MASK:
716   case RISCV::PseudoVLE8_V_M4:
717   case RISCV::PseudoVLE8_V_M4_MASK:
718   case RISCV::PseudoVLE8_V_M8:
719   case RISCV::PseudoVLE8_V_M8_MASK:
720   case RISCV::PseudoVLE8_V_MF2:
721   case RISCV::PseudoVLE8_V_MF2_MASK:
722   case RISCV::PseudoVLE8_V_MF4:
723   case RISCV::PseudoVLE8_V_MF4_MASK:
724   case RISCV::PseudoVLE8_V_MF8:
725   case RISCV::PseudoVLE8_V_MF8_MASK:
726   case RISCV::PseudoVLSE8_V_M1:
727   case RISCV::PseudoVLSE8_V_M1_MASK:
728   case RISCV::PseudoVLSE8_V_M2:
729   case RISCV::PseudoVLSE8_V_M2_MASK:
730   case RISCV::PseudoVLSE8_V_M4:
731   case RISCV::PseudoVLSE8_V_M4_MASK:
732   case RISCV::PseudoVLSE8_V_M8:
733   case RISCV::PseudoVLSE8_V_M8_MASK:
734   case RISCV::PseudoVLSE8_V_MF2:
735   case RISCV::PseudoVLSE8_V_MF2_MASK:
736   case RISCV::PseudoVLSE8_V_MF4:
737   case RISCV::PseudoVLSE8_V_MF4_MASK:
738   case RISCV::PseudoVLSE8_V_MF8:
739   case RISCV::PseudoVLSE8_V_MF8_MASK:
740   case RISCV::PseudoVSE8_V_M1:
741   case RISCV::PseudoVSE8_V_M1_MASK:
742   case RISCV::PseudoVSE8_V_M2:
743   case RISCV::PseudoVSE8_V_M2_MASK:
744   case RISCV::PseudoVSE8_V_M4:
745   case RISCV::PseudoVSE8_V_M4_MASK:
746   case RISCV::PseudoVSE8_V_M8:
747   case RISCV::PseudoVSE8_V_M8_MASK:
748   case RISCV::PseudoVSE8_V_MF2:
749   case RISCV::PseudoVSE8_V_MF2_MASK:
750   case RISCV::PseudoVSE8_V_MF4:
751   case RISCV::PseudoVSE8_V_MF4_MASK:
752   case RISCV::PseudoVSE8_V_MF8:
753   case RISCV::PseudoVSE8_V_MF8_MASK:
754   case RISCV::PseudoVSSE8_V_M1:
755   case RISCV::PseudoVSSE8_V_M1_MASK:
756   case RISCV::PseudoVSSE8_V_M2:
757   case RISCV::PseudoVSSE8_V_M2_MASK:
758   case RISCV::PseudoVSSE8_V_M4:
759   case RISCV::PseudoVSSE8_V_M4_MASK:
760   case RISCV::PseudoVSSE8_V_M8:
761   case RISCV::PseudoVSSE8_V_M8_MASK:
762   case RISCV::PseudoVSSE8_V_MF2:
763   case RISCV::PseudoVSSE8_V_MF2_MASK:
764   case RISCV::PseudoVSSE8_V_MF4:
765   case RISCV::PseudoVSSE8_V_MF4_MASK:
766   case RISCV::PseudoVSSE8_V_MF8:
767   case RISCV::PseudoVSSE8_V_MF8_MASK:
768     return 8;
769   case RISCV::PseudoVLE16_V_M1:
770   case RISCV::PseudoVLE16_V_M1_MASK:
771   case RISCV::PseudoVLE16_V_M2:
772   case RISCV::PseudoVLE16_V_M2_MASK:
773   case RISCV::PseudoVLE16_V_M4:
774   case RISCV::PseudoVLE16_V_M4_MASK:
775   case RISCV::PseudoVLE16_V_M8:
776   case RISCV::PseudoVLE16_V_M8_MASK:
777   case RISCV::PseudoVLE16_V_MF2:
778   case RISCV::PseudoVLE16_V_MF2_MASK:
779   case RISCV::PseudoVLE16_V_MF4:
780   case RISCV::PseudoVLE16_V_MF4_MASK:
781   case RISCV::PseudoVLSE16_V_M1:
782   case RISCV::PseudoVLSE16_V_M1_MASK:
783   case RISCV::PseudoVLSE16_V_M2:
784   case RISCV::PseudoVLSE16_V_M2_MASK:
785   case RISCV::PseudoVLSE16_V_M4:
786   case RISCV::PseudoVLSE16_V_M4_MASK:
787   case RISCV::PseudoVLSE16_V_M8:
788   case RISCV::PseudoVLSE16_V_M8_MASK:
789   case RISCV::PseudoVLSE16_V_MF2:
790   case RISCV::PseudoVLSE16_V_MF2_MASK:
791   case RISCV::PseudoVLSE16_V_MF4:
792   case RISCV::PseudoVLSE16_V_MF4_MASK:
793   case RISCV::PseudoVSE16_V_M1:
794   case RISCV::PseudoVSE16_V_M1_MASK:
795   case RISCV::PseudoVSE16_V_M2:
796   case RISCV::PseudoVSE16_V_M2_MASK:
797   case RISCV::PseudoVSE16_V_M4:
798   case RISCV::PseudoVSE16_V_M4_MASK:
799   case RISCV::PseudoVSE16_V_M8:
800   case RISCV::PseudoVSE16_V_M8_MASK:
801   case RISCV::PseudoVSE16_V_MF2:
802   case RISCV::PseudoVSE16_V_MF2_MASK:
803   case RISCV::PseudoVSE16_V_MF4:
804   case RISCV::PseudoVSE16_V_MF4_MASK:
805   case RISCV::PseudoVSSE16_V_M1:
806   case RISCV::PseudoVSSE16_V_M1_MASK:
807   case RISCV::PseudoVSSE16_V_M2:
808   case RISCV::PseudoVSSE16_V_M2_MASK:
809   case RISCV::PseudoVSSE16_V_M4:
810   case RISCV::PseudoVSSE16_V_M4_MASK:
811   case RISCV::PseudoVSSE16_V_M8:
812   case RISCV::PseudoVSSE16_V_M8_MASK:
813   case RISCV::PseudoVSSE16_V_MF2:
814   case RISCV::PseudoVSSE16_V_MF2_MASK:
815   case RISCV::PseudoVSSE16_V_MF4:
816   case RISCV::PseudoVSSE16_V_MF4_MASK:
817     return 16;
818   case RISCV::PseudoVLE32_V_M1:
819   case RISCV::PseudoVLE32_V_M1_MASK:
820   case RISCV::PseudoVLE32_V_M2:
821   case RISCV::PseudoVLE32_V_M2_MASK:
822   case RISCV::PseudoVLE32_V_M4:
823   case RISCV::PseudoVLE32_V_M4_MASK:
824   case RISCV::PseudoVLE32_V_M8:
825   case RISCV::PseudoVLE32_V_M8_MASK:
826   case RISCV::PseudoVLE32_V_MF2:
827   case RISCV::PseudoVLE32_V_MF2_MASK:
828   case RISCV::PseudoVLSE32_V_M1:
829   case RISCV::PseudoVLSE32_V_M1_MASK:
830   case RISCV::PseudoVLSE32_V_M2:
831   case RISCV::PseudoVLSE32_V_M2_MASK:
832   case RISCV::PseudoVLSE32_V_M4:
833   case RISCV::PseudoVLSE32_V_M4_MASK:
834   case RISCV::PseudoVLSE32_V_M8:
835   case RISCV::PseudoVLSE32_V_M8_MASK:
836   case RISCV::PseudoVLSE32_V_MF2:
837   case RISCV::PseudoVLSE32_V_MF2_MASK:
838   case RISCV::PseudoVSE32_V_M1:
839   case RISCV::PseudoVSE32_V_M1_MASK:
840   case RISCV::PseudoVSE32_V_M2:
841   case RISCV::PseudoVSE32_V_M2_MASK:
842   case RISCV::PseudoVSE32_V_M4:
843   case RISCV::PseudoVSE32_V_M4_MASK:
844   case RISCV::PseudoVSE32_V_M8:
845   case RISCV::PseudoVSE32_V_M8_MASK:
846   case RISCV::PseudoVSE32_V_MF2:
847   case RISCV::PseudoVSE32_V_MF2_MASK:
848   case RISCV::PseudoVSSE32_V_M1:
849   case RISCV::PseudoVSSE32_V_M1_MASK:
850   case RISCV::PseudoVSSE32_V_M2:
851   case RISCV::PseudoVSSE32_V_M2_MASK:
852   case RISCV::PseudoVSSE32_V_M4:
853   case RISCV::PseudoVSSE32_V_M4_MASK:
854   case RISCV::PseudoVSSE32_V_M8:
855   case RISCV::PseudoVSSE32_V_M8_MASK:
856   case RISCV::PseudoVSSE32_V_MF2:
857   case RISCV::PseudoVSSE32_V_MF2_MASK:
858     return 32;
859   case RISCV::PseudoVLE64_V_M1:
860   case RISCV::PseudoVLE64_V_M1_MASK:
861   case RISCV::PseudoVLE64_V_M2:
862   case RISCV::PseudoVLE64_V_M2_MASK:
863   case RISCV::PseudoVLE64_V_M4:
864   case RISCV::PseudoVLE64_V_M4_MASK:
865   case RISCV::PseudoVLE64_V_M8:
866   case RISCV::PseudoVLE64_V_M8_MASK:
867   case RISCV::PseudoVLSE64_V_M1:
868   case RISCV::PseudoVLSE64_V_M1_MASK:
869   case RISCV::PseudoVLSE64_V_M2:
870   case RISCV::PseudoVLSE64_V_M2_MASK:
871   case RISCV::PseudoVLSE64_V_M4:
872   case RISCV::PseudoVLSE64_V_M4_MASK:
873   case RISCV::PseudoVLSE64_V_M8:
874   case RISCV::PseudoVLSE64_V_M8_MASK:
875   case RISCV::PseudoVSE64_V_M1:
876   case RISCV::PseudoVSE64_V_M1_MASK:
877   case RISCV::PseudoVSE64_V_M2:
878   case RISCV::PseudoVSE64_V_M2_MASK:
879   case RISCV::PseudoVSE64_V_M4:
880   case RISCV::PseudoVSE64_V_M4_MASK:
881   case RISCV::PseudoVSE64_V_M8:
882   case RISCV::PseudoVSE64_V_M8_MASK:
883   case RISCV::PseudoVSSE64_V_M1:
884   case RISCV::PseudoVSSE64_V_M1_MASK:
885   case RISCV::PseudoVSSE64_V_M2:
886   case RISCV::PseudoVSSE64_V_M2_MASK:
887   case RISCV::PseudoVSSE64_V_M4:
888   case RISCV::PseudoVSSE64_V_M4_MASK:
889   case RISCV::PseudoVSSE64_V_M8:
890   case RISCV::PseudoVSSE64_V_M8_MASK:
891     return 64;
892   }
893 }
894 
895 static bool canSkipVSETVLIForLoadStore(const MachineInstr &MI,
896                                        const VSETVLIInfo &Require,
897                                        const VSETVLIInfo &CurInfo) {
898   Optional<unsigned> EEW = getEEWForLoadStore(MI);
899   if (!EEW)
900     return false;
901 
902   // Stores can ignore the tail and mask policies.
903   const bool StoreOp = MI.getNumExplicitDefs() == 0;
904   if (!StoreOp && !CurInfo.hasSamePolicy(Require))
905     return false;
906 
907   return CurInfo.isCompatibleWithLoadStoreEEW(*EEW, Require);
908 }
909 
910 /// Return true if a VSETVLI is required to transition from CurInfo to Require
911 /// before MI.
912 bool RISCVInsertVSETVLI::needVSETVLI(const MachineInstr &MI,
913                                      const VSETVLIInfo &Require,
914                                      const VSETVLIInfo &CurInfo) const {
915   assert(Require == computeInfoForInstr(MI, MI.getDesc().TSFlags, MRI));
916 
917   if (CurInfo.isCompatible(MI, Require))
918     return false;
919 
920   // We didn't find a compatible value. If our AVL is a virtual register,
921   // it might be defined by a VSET(I)VLI. If it has the same VLMAX we need
922   // and the last VL/VTYPE we observed is the same, we don't need a
923   // VSETVLI here.
924   if (!CurInfo.isUnknown() && Require.hasAVLReg() &&
925       Require.getAVLReg().isVirtual() && !CurInfo.hasSEWLMULRatioOnly() &&
926       CurInfo.hasCompatibleVTYPE(MI, Require)) {
927     if (MachineInstr *DefMI = MRI->getVRegDef(Require.getAVLReg())) {
928       if (isVectorConfigInstr(*DefMI)) {
929         VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
930         if (DefInfo.hasSameAVL(CurInfo) && DefInfo.hasSameVLMAX(CurInfo))
931           return false;
932       }
933     }
934   }
935 
936   // If this is a unit-stride or strided load/store, we may be able to use the
937   // EMUL=(EEW/SEW)*LMUL relationship to avoid changing VTYPE.
938   return CurInfo.isUnknown() || !canSkipVSETVLIForLoadStore(MI, Require, CurInfo);
939 }
940 
941 // Given an incoming state reaching MI, modifies that state so that it is minimally
942 // compatible with MI.  The resulting state is guaranteed to be semantically legal
943 // for MI, but may not be the state requested by MI.
944 void RISCVInsertVSETVLI::transferBefore(VSETVLIInfo &Info, const MachineInstr &MI) {
945   uint64_t TSFlags = MI.getDesc().TSFlags;
946   if (!RISCVII::hasSEWOp(TSFlags))
947     return;
948   VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
949 
950   if (!Info.isValid()) {
951     Info = NewInfo;
952   } else {
953     // If this instruction isn't compatible with the previous VL/VTYPE
954     // we need to insert a VSETVLI.
955     // NOTE: We only do this if the vtype we're comparing against was
956     // created in this block. We need the first and third phase to treat
957     // the store the same way.
958     if (needVSETVLI(MI, NewInfo, Info))
959       Info = NewInfo;
960   }
961 }
962 
963 // Given a state with which we evaluated MI (see transferBefore above for why
964 // this might be different that the state MI requested), modify the state to
965 // reflect the changes MI might make.
966 void RISCVInsertVSETVLI::transferAfter(VSETVLIInfo &Info, const MachineInstr &MI) {
967   if (isVectorConfigInstr(MI)) {
968     Info = getInfoForVSETVLI(MI);
969     return;
970   }
971 
972   if (RISCV::isFaultFirstLoad(MI)) {
973     // Update AVL to vl-output of the fault first load.
974     Info.setAVLReg(MI.getOperand(1).getReg());
975     return;
976   }
977 
978   // If this is something that updates VL/VTYPE that we don't know about, set
979   // the state to unknown.
980   if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
981       MI.modifiesRegister(RISCV::VTYPE))
982     Info = VSETVLIInfo::getUnknown();
983 }
984 
985 bool RISCVInsertVSETVLI::computeVLVTYPEChanges(const MachineBasicBlock &MBB) {
986   bool HadVectorOp = false;
987 
988   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
989   BBInfo.Change = BBInfo.Pred;
990   for (const MachineInstr &MI : MBB) {
991     transferBefore(BBInfo.Change, MI);
992 
993     if (isVectorConfigInstr(MI) || RISCVII::hasSEWOp(MI.getDesc().TSFlags))
994       HadVectorOp = true;
995 
996     transferAfter(BBInfo.Change, MI);
997   }
998 
999   return HadVectorOp;
1000 }
1001 
1002 void RISCVInsertVSETVLI::computeIncomingVLVTYPE(const MachineBasicBlock &MBB) {
1003 
1004   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1005 
1006   BBInfo.InQueue = false;
1007 
1008   VSETVLIInfo InInfo;
1009   if (MBB.pred_empty()) {
1010     // There are no predecessors, so use the default starting status.
1011     InInfo.setUnknown();
1012   } else {
1013     for (MachineBasicBlock *P : MBB.predecessors())
1014       InInfo = InInfo.intersect(BlockInfo[P->getNumber()].Exit);
1015   }
1016 
1017   // If we don't have any valid predecessor value, wait until we do.
1018   if (!InInfo.isValid())
1019     return;
1020 
1021   // If no change, no need to rerun block
1022   if (InInfo == BBInfo.Pred)
1023     return;
1024 
1025   BBInfo.Pred = InInfo;
1026   LLVM_DEBUG(dbgs() << "Entry state of " << printMBBReference(MBB)
1027                     << " changed to " << BBInfo.Pred << "\n");
1028 
1029   // Note: It's tempting to cache the state changes here, but due to the
1030   // compatibility checks performed a blocks output state can change based on
1031   // the input state.  To cache, we'd have to add logic for finding
1032   // never-compatible state changes.
1033   computeVLVTYPEChanges(MBB);
1034   VSETVLIInfo TmpStatus = BBInfo.Change;
1035 
1036   // If the new exit value matches the old exit value, we don't need to revisit
1037   // any blocks.
1038   if (BBInfo.Exit == TmpStatus)
1039     return;
1040 
1041   BBInfo.Exit = TmpStatus;
1042   LLVM_DEBUG(dbgs() << "Exit state of " << printMBBReference(MBB)
1043                     << " changed to " << BBInfo.Exit << "\n");
1044 
1045   // Add the successors to the work list so we can propagate the changed exit
1046   // status.
1047   for (MachineBasicBlock *S : MBB.successors())
1048     if (!BlockInfo[S->getNumber()].InQueue)
1049       WorkList.push(S);
1050 }
1051 
1052 // If we weren't able to prove a vsetvli was directly unneeded, it might still
1053 // be unneeded if the AVL is a phi node where all incoming values are VL
1054 // outputs from the last VSETVLI in their respective basic blocks.
1055 bool RISCVInsertVSETVLI::needVSETVLIPHI(const VSETVLIInfo &Require,
1056                                         const MachineBasicBlock &MBB) const {
1057   if (DisableInsertVSETVLPHIOpt)
1058     return true;
1059 
1060   if (!Require.hasAVLReg())
1061     return true;
1062 
1063   Register AVLReg = Require.getAVLReg();
1064   if (!AVLReg.isVirtual())
1065     return true;
1066 
1067   // We need the AVL to be produce by a PHI node in this basic block.
1068   MachineInstr *PHI = MRI->getVRegDef(AVLReg);
1069   if (!PHI || PHI->getOpcode() != RISCV::PHI || PHI->getParent() != &MBB)
1070     return true;
1071 
1072   for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
1073        PHIOp += 2) {
1074     Register InReg = PHI->getOperand(PHIOp).getReg();
1075     MachineBasicBlock *PBB = PHI->getOperand(PHIOp + 1).getMBB();
1076     const BlockData &PBBInfo = BlockInfo[PBB->getNumber()];
1077     // If the exit from the predecessor has the VTYPE we are looking for
1078     // we might be able to avoid a VSETVLI.
1079     if (PBBInfo.Exit.isUnknown() || !PBBInfo.Exit.hasSameVTYPE(Require))
1080       return true;
1081 
1082     // We need the PHI input to the be the output of a VSET(I)VLI.
1083     MachineInstr *DefMI = MRI->getVRegDef(InReg);
1084     if (!DefMI || !isVectorConfigInstr(*DefMI))
1085       return true;
1086 
1087     // We found a VSET(I)VLI make sure it matches the output of the
1088     // predecessor block.
1089     VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1090     if (!DefInfo.hasSameAVL(PBBInfo.Exit) ||
1091         !DefInfo.hasSameVTYPE(PBBInfo.Exit))
1092       return true;
1093   }
1094 
1095   // If all the incoming values to the PHI checked out, we don't need
1096   // to insert a VSETVLI.
1097   return false;
1098 }
1099 
1100 void RISCVInsertVSETVLI::emitVSETVLIs(MachineBasicBlock &MBB) {
1101   VSETVLIInfo CurInfo = BlockInfo[MBB.getNumber()].Pred;
1102   // Track whether the prefix of the block we've scanned is transparent
1103   // (meaning has not yet changed the abstract state).
1104   bool PrefixTransparent = true;
1105   for (MachineInstr &MI : MBB) {
1106     const VSETVLIInfo PrevInfo = CurInfo;
1107     transferBefore(CurInfo, MI);
1108 
1109     // If this is an explicit VSETVLI or VSETIVLI, update our state.
1110     if (isVectorConfigInstr(MI)) {
1111       // Conservatively, mark the VL and VTYPE as live.
1112       assert(MI.getOperand(3).getReg() == RISCV::VL &&
1113              MI.getOperand(4).getReg() == RISCV::VTYPE &&
1114              "Unexpected operands where VL and VTYPE should be");
1115       MI.getOperand(3).setIsDead(false);
1116       MI.getOperand(4).setIsDead(false);
1117       PrefixTransparent = false;
1118     }
1119 
1120     uint64_t TSFlags = MI.getDesc().TSFlags;
1121     if (RISCVII::hasSEWOp(TSFlags)) {
1122       if (PrevInfo != CurInfo) {
1123         // If this is the first implicit state change, and the state change
1124         // requested can be proven to produce the same register contents, we
1125         // can skip emitting the actual state change and continue as if we
1126         // had since we know the GPR result of the implicit state change
1127         // wouldn't be used and VL/VTYPE registers are correct.  Note that
1128         // we *do* need to model the state as if it changed as while the
1129         // register contents are unchanged, the abstract model can change.
1130         if (!PrefixTransparent || needVSETVLIPHI(CurInfo, MBB))
1131           insertVSETVLI(MBB, MI, CurInfo, PrevInfo);
1132         PrefixTransparent = false;
1133       }
1134 
1135       if (RISCVII::hasVLOp(TSFlags)) {
1136         MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1137         if (VLOp.isReg()) {
1138           // Erase the AVL operand from the instruction.
1139           VLOp.setReg(RISCV::NoRegister);
1140           VLOp.setIsKill(false);
1141         }
1142         MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ false,
1143                                                 /*isImp*/ true));
1144       }
1145       MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
1146                                               /*isImp*/ true));
1147     }
1148 
1149     if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
1150         MI.modifiesRegister(RISCV::VTYPE))
1151       PrefixTransparent = false;
1152 
1153     transferAfter(CurInfo, MI);
1154   }
1155 
1156   // If we reach the end of the block and our current info doesn't match the
1157   // expected info, insert a vsetvli to correct.
1158   if (!UseStrictAsserts) {
1159     const VSETVLIInfo &ExitInfo = BlockInfo[MBB.getNumber()].Exit;
1160     if (CurInfo.isValid() && ExitInfo.isValid() && !ExitInfo.isUnknown() &&
1161         CurInfo != ExitInfo) {
1162       // Note there's an implicit assumption here that terminators never use
1163       // or modify VL or VTYPE.  Also, fallthrough will return end().
1164       auto InsertPt = MBB.getFirstInstrTerminator();
1165       insertVSETVLI(MBB, InsertPt, MBB.findDebugLoc(InsertPt), ExitInfo,
1166                     CurInfo);
1167       CurInfo = ExitInfo;
1168     }
1169   }
1170 
1171   if (UseStrictAsserts && CurInfo.isValid()) {
1172     const auto &Info = BlockInfo[MBB.getNumber()];
1173     if (CurInfo != Info.Exit) {
1174       LLVM_DEBUG(dbgs() << "in block " << printMBBReference(MBB) << "\n");
1175       LLVM_DEBUG(dbgs() << "  begin        state: " << Info.Pred << "\n");
1176       LLVM_DEBUG(dbgs() << "  expected end state: " << Info.Exit << "\n");
1177       LLVM_DEBUG(dbgs() << "  actual   end state: " << CurInfo << "\n");
1178     }
1179     assert(CurInfo == Info.Exit &&
1180            "InsertVSETVLI dataflow invariant violated");
1181   }
1182 }
1183 
1184 void RISCVInsertVSETVLI::doLocalPrepass(MachineBasicBlock &MBB) {
1185   VSETVLIInfo CurInfo = VSETVLIInfo::getUnknown();
1186   for (MachineInstr &MI : MBB) {
1187     // If this is an explicit VSETVLI or VSETIVLI, update our state.
1188     if (isVectorConfigInstr(MI)) {
1189       CurInfo = getInfoForVSETVLI(MI);
1190       continue;
1191     }
1192 
1193     const uint64_t TSFlags = MI.getDesc().TSFlags;
1194     if (isScalarMoveInstr(MI)) {
1195       assert(RISCVII::hasSEWOp(TSFlags) && RISCVII::hasVLOp(TSFlags));
1196       const VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
1197 
1198       // For vmv.s.x and vfmv.s.f, there are only two behaviors, VL = 0 and
1199       // VL > 0. We can discard the user requested AVL and just use the last
1200       // one if we can prove it equally zero.  This removes a vsetvli entirely
1201       // if the types match or allows use of cheaper avl preserving variant
1202       // if VLMAX doesn't change.  If VLMAX might change, we couldn't use
1203       // the 'vsetvli x0, x0, vtype" variant, so we avoid the transform to
1204       // prevent extending live range of an avl register operand.
1205       // TODO: We can probably relax this for immediates.
1206       if (((CurInfo.hasNonZeroAVL() && NewInfo.hasNonZeroAVL()) ||
1207            (CurInfo.hasZeroAVL() && NewInfo.hasZeroAVL())) &&
1208           NewInfo.hasSameVLMAX(CurInfo)) {
1209         MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1210         if (CurInfo.hasAVLImm())
1211           VLOp.ChangeToImmediate(CurInfo.getAVLImm());
1212         else
1213           VLOp.ChangeToRegister(CurInfo.getAVLReg(), /*IsDef*/ false);
1214         CurInfo = computeInfoForInstr(MI, TSFlags, MRI);
1215         continue;
1216       }
1217     }
1218 
1219     if (RISCVII::hasSEWOp(TSFlags)) {
1220       if (RISCVII::hasVLOp(TSFlags)) {
1221         const auto Require = computeInfoForInstr(MI, TSFlags, MRI);
1222         // Two cases involving an AVL resulting from a previous vsetvli.
1223         // 1) If the AVL is the result of a previous vsetvli which has the
1224         //    same AVL and VLMAX as our current state, we can reuse the AVL
1225         //    from the current state for the new one.  This allows us to
1226         //    generate 'vsetvli x0, x0, vtype" or possible skip the transition
1227         //    entirely.
1228         // 2) If AVL is defined by a vsetvli with the same VLMAX, we can
1229         //    replace the AVL operand with the AVL of the defining vsetvli.
1230         //    We avoid general register AVLs to avoid extending live ranges
1231         //    without being sure we can kill the original source reg entirely.
1232         if (Require.hasAVLReg() && Require.getAVLReg().isVirtual()) {
1233           if (MachineInstr *DefMI = MRI->getVRegDef(Require.getAVLReg())) {
1234             if (isVectorConfigInstr(*DefMI)) {
1235               VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
1236               // case 1
1237               if (!CurInfo.isUnknown() && DefInfo.hasSameAVL(CurInfo) &&
1238                   DefInfo.hasSameVLMAX(CurInfo)) {
1239                 MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1240                 if (CurInfo.hasAVLImm())
1241                   VLOp.ChangeToImmediate(CurInfo.getAVLImm());
1242                 else {
1243                   MRI->clearKillFlags(CurInfo.getAVLReg());
1244                   VLOp.ChangeToRegister(CurInfo.getAVLReg(), /*IsDef*/ false);
1245                 }
1246                 CurInfo = computeInfoForInstr(MI, TSFlags, MRI);
1247                 continue;
1248               }
1249               // case 2
1250               if (DefInfo.hasSameVLMAX(Require) &&
1251                   (DefInfo.hasAVLImm() || DefInfo.getAVLReg() == RISCV::X0)) {
1252                 MachineOperand &VLOp = MI.getOperand(getVLOpNum(MI));
1253                 if (DefInfo.hasAVLImm())
1254                   VLOp.ChangeToImmediate(DefInfo.getAVLImm());
1255                 else
1256                   VLOp.ChangeToRegister(DefInfo.getAVLReg(), /*IsDef*/ false);
1257                 CurInfo = computeInfoForInstr(MI, TSFlags, MRI);
1258                 continue;
1259               }
1260             }
1261           }
1262         }
1263       }
1264       CurInfo = computeInfoForInstr(MI, TSFlags, MRI);
1265       continue;
1266     }
1267 
1268     transferAfter(CurInfo, MI);
1269   }
1270 }
1271 
1272 /// Return true if the VL value configured must be equal to the requested one.
1273 static bool hasFixedResult(const VSETVLIInfo &Info, const RISCVSubtarget &ST) {
1274   if (!Info.hasAVLImm())
1275     // VLMAX is always the same value.
1276     // TODO: Could extend to other registers by looking at the associated vreg
1277     // def placement.
1278     return RISCV::X0 == Info.getAVLReg();
1279 
1280   unsigned AVL = Info.getAVLImm();
1281   unsigned SEW = Info.getSEW();
1282   unsigned AVLInBits = AVL * SEW;
1283 
1284   unsigned LMul;
1285   bool Fractional;
1286   std::tie(LMul, Fractional) = RISCVVType::decodeVLMUL(Info.getVLMUL());
1287 
1288   if (Fractional)
1289     return ST.getRealMinVLen() / LMul >= AVLInBits;
1290   return ST.getRealMinVLen() * LMul >= AVLInBits;
1291 }
1292 
1293 /// Perform simple partial redundancy elimination of the VSETVLI instructions
1294 /// we're about to insert by looking for cases where we can PRE from the
1295 /// beginning of one block to the end of one of its predecessors.  Specifically,
1296 /// this is geared to catch the common case of a fixed length vsetvl in a single
1297 /// block loop when it could execute once in the preheader instead.
1298 void RISCVInsertVSETVLI::doPRE(MachineBasicBlock &MBB) {
1299   const MachineFunction &MF = *MBB.getParent();
1300   const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
1301 
1302   if (!BlockInfo[MBB.getNumber()].Pred.isUnknown())
1303     return;
1304 
1305   MachineBasicBlock *UnavailablePred = nullptr;
1306   VSETVLIInfo AvailableInfo;
1307   for (MachineBasicBlock *P : MBB.predecessors()) {
1308     const VSETVLIInfo &PredInfo = BlockInfo[P->getNumber()].Exit;
1309     if (PredInfo.isUnknown()) {
1310       if (UnavailablePred)
1311         return;
1312       UnavailablePred = P;
1313     } else if (!AvailableInfo.isValid()) {
1314       AvailableInfo = PredInfo;
1315     } else if (AvailableInfo != PredInfo) {
1316       return;
1317     }
1318   }
1319 
1320   // Unreachable, single pred, or full redundancy. Note that FRE is handled by
1321   // phase 3.
1322   if (!UnavailablePred || !AvailableInfo.isValid())
1323     return;
1324 
1325   // Critical edge - TODO: consider splitting?
1326   if (UnavailablePred->succ_size() != 1)
1327     return;
1328 
1329   // If VL can be less than AVL, then we can't reduce the frequency of exec.
1330   if (!hasFixedResult(AvailableInfo, ST))
1331     return;
1332 
1333   // Does it actually let us remove an implicit transition in MBB?
1334   bool Found = false;
1335   for (auto &MI : MBB) {
1336     if (isVectorConfigInstr(MI))
1337       return;
1338 
1339     const uint64_t TSFlags = MI.getDesc().TSFlags;
1340     if (RISCVII::hasSEWOp(TSFlags)) {
1341       if (AvailableInfo != computeInfoForInstr(MI, TSFlags, MRI))
1342         return;
1343       Found = true;
1344       break;
1345     }
1346   }
1347   if (!Found)
1348     return;
1349 
1350   // Finally, update both data flow state and insert the actual vsetvli.
1351   // Doing both keeps the code in sync with the dataflow results, which
1352   // is critical for correctness of phase 3.
1353   auto OldInfo = BlockInfo[UnavailablePred->getNumber()].Exit;
1354   LLVM_DEBUG(dbgs() << "PRE VSETVLI from " << MBB.getName() << " to "
1355                     << UnavailablePred->getName() << " with state "
1356                     << AvailableInfo << "\n");
1357   BlockInfo[UnavailablePred->getNumber()].Exit = AvailableInfo;
1358   BlockInfo[MBB.getNumber()].Pred = AvailableInfo;
1359 
1360   // Note there's an implicit assumption here that terminators never use
1361   // or modify VL or VTYPE.  Also, fallthrough will return end().
1362   auto InsertPt = UnavailablePred->getFirstInstrTerminator();
1363   insertVSETVLI(*UnavailablePred, InsertPt,
1364                 UnavailablePred->findDebugLoc(InsertPt),
1365                 AvailableInfo, OldInfo);
1366 }
1367 
1368 /// Which subfields of VL or VTYPE have values we need to preserve?
1369 struct DemandedFields {
1370   bool VL = false;
1371   bool SEW = false;
1372   bool LMUL = false;
1373   bool SEWLMULRatio = false;
1374   bool TailPolicy = false;
1375   bool MaskPolicy = false;
1376 
1377   // Return true if any part of VTYPE was used
1378   bool usedVTYPE() {
1379     return SEW || LMUL || SEWLMULRatio || TailPolicy || MaskPolicy;
1380   }
1381 };
1382 
1383 static void doUnion(DemandedFields &A, DemandedFields B) {
1384   A.VL |= B.VL;
1385   A.SEW |= B.SEW;
1386   A.LMUL |= B.LMUL;
1387   A.SEWLMULRatio |= B.SEWLMULRatio;
1388   A.TailPolicy |= B.TailPolicy;
1389   A.MaskPolicy |= B.MaskPolicy;
1390 }
1391 
1392 // Return which fields are demanded by the given instruction.
1393 static DemandedFields getDemanded(const MachineInstr &MI) {
1394   // Most instructions don't use any of these subfeilds.
1395   DemandedFields Res;
1396   // Start conservative if registers are used
1397   if (MI.isCall() || MI.isInlineAsm() || MI.readsRegister(RISCV::VL))
1398     Res.VL = true;
1399   if (MI.isCall() || MI.isInlineAsm() || MI.readsRegister(RISCV::VTYPE)) {
1400     Res.SEW = true;
1401     Res.LMUL = true;
1402     Res.SEWLMULRatio = true;
1403     Res.TailPolicy = true;
1404     Res.MaskPolicy = true;
1405   }
1406 
1407   return Res;
1408 }
1409 
1410 void RISCVInsertVSETVLI::doLocalPostpass(MachineBasicBlock &MBB) {
1411   MachineInstr *PrevMI = nullptr;
1412   DemandedFields Used;
1413   SmallVector<MachineInstr*> ToDelete;
1414   for (MachineInstr &MI : MBB) {
1415     // Note: Must be *before* vsetvli handling to account for config cases
1416     // which only change some subfields.
1417     doUnion(Used, getDemanded(MI));
1418 
1419     if (!isVectorConfigInstr(MI))
1420       continue;
1421 
1422     if (PrevMI) {
1423       if (!Used.VL && !Used.usedVTYPE()) {
1424         ToDelete.push_back(PrevMI);
1425         // fallthrough
1426       } else if (!Used.usedVTYPE() && isVLPreservingConfig(MI)) {
1427         // Note: `vsetvli x0, x0, vtype' is the canonical instruction
1428         // for this case.  If you find yourself wanting to add other forms
1429         // to this "unused VTYPE" case, we're probably missing a
1430         // canonicalization earlier.
1431         // Note: We don't need to explicitly check vtype compatibility
1432         // here because this form is only legal (per ISA) when not
1433         // changing VL.
1434         PrevMI->getOperand(2).setImm(MI.getOperand(2).getImm());
1435         ToDelete.push_back(&MI);
1436         // Leave PrevMI unchanged
1437         continue;
1438       }
1439     }
1440     PrevMI = &MI;
1441     Used = getDemanded(MI);
1442     Register VRegDef = MI.getOperand(0).getReg();
1443     if (VRegDef != RISCV::X0 &&
1444         !(VRegDef.isVirtual() && MRI->use_nodbg_empty(VRegDef)))
1445       Used.VL = true;
1446   }
1447 
1448   for (auto *MI : ToDelete)
1449     MI->eraseFromParent();
1450 }
1451 
1452 void RISCVInsertVSETVLI::insertReadVL(MachineBasicBlock &MBB) {
1453   for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
1454     MachineInstr &MI = *I++;
1455     if (RISCV::isFaultFirstLoad(MI)) {
1456       Register VLOutput = MI.getOperand(1).getReg();
1457       if (!MRI->use_nodbg_empty(VLOutput))
1458         BuildMI(MBB, I, MI.getDebugLoc(), TII->get(RISCV::PseudoReadVL),
1459                 VLOutput);
1460       // We don't use the vl output of the VLEFF/VLSEGFF anymore.
1461       MI.getOperand(1).setReg(RISCV::X0);
1462     }
1463   }
1464 }
1465 
1466 bool RISCVInsertVSETVLI::runOnMachineFunction(MachineFunction &MF) {
1467   // Skip if the vector extension is not enabled.
1468   const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
1469   if (!ST.hasVInstructions())
1470     return false;
1471 
1472   LLVM_DEBUG(dbgs() << "Entering InsertVSETVLI for " << MF.getName() << "\n");
1473 
1474   TII = ST.getInstrInfo();
1475   MRI = &MF.getRegInfo();
1476 
1477   assert(BlockInfo.empty() && "Expect empty block infos");
1478   BlockInfo.resize(MF.getNumBlockIDs());
1479 
1480   // Scan the block locally for cases where we can mutate the operands
1481   // of the instructions to reduce state transitions.  Critically, this
1482   // must be done before we start propagating data flow states as these
1483   // transforms are allowed to change the contents of VTYPE and VL so
1484   // long as the semantics of the program stays the same.
1485   for (MachineBasicBlock &MBB : MF)
1486     doLocalPrepass(MBB);
1487 
1488   bool HaveVectorOp = false;
1489 
1490   // Phase 1 - determine how VL/VTYPE are affected by the each block.
1491   for (const MachineBasicBlock &MBB : MF) {
1492     HaveVectorOp |= computeVLVTYPEChanges(MBB);
1493     // Initial exit state is whatever change we found in the block.
1494     BlockData &BBInfo = BlockInfo[MBB.getNumber()];
1495     BBInfo.Exit = BBInfo.Change;
1496     LLVM_DEBUG(dbgs() << "Initial exit state of " << printMBBReference(MBB)
1497                       << " is " << BBInfo.Exit << "\n");
1498 
1499   }
1500 
1501   // If we didn't find any instructions that need VSETVLI, we're done.
1502   if (!HaveVectorOp) {
1503     BlockInfo.clear();
1504     return false;
1505   }
1506 
1507   // Phase 2 - determine the exit VL/VTYPE from each block. We add all
1508   // blocks to the list here, but will also add any that need to be revisited
1509   // during Phase 2 processing.
1510   for (const MachineBasicBlock &MBB : MF) {
1511     WorkList.push(&MBB);
1512     BlockInfo[MBB.getNumber()].InQueue = true;
1513   }
1514   while (!WorkList.empty()) {
1515     const MachineBasicBlock &MBB = *WorkList.front();
1516     WorkList.pop();
1517     computeIncomingVLVTYPE(MBB);
1518   }
1519 
1520   // Perform partial redundancy elimination of vsetvli transitions.
1521   for (MachineBasicBlock &MBB : MF)
1522     doPRE(MBB);
1523 
1524   // Phase 3 - add any vsetvli instructions needed in the block. Use the
1525   // Phase 2 information to avoid adding vsetvlis before the first vector
1526   // instruction in the block if the VL/VTYPE is satisfied by its
1527   // predecessors.
1528   for (MachineBasicBlock &MBB : MF)
1529     emitVSETVLIs(MBB);
1530 
1531   // Now that all vsetvlis are explicit, go through and do block local
1532   // DSE and peephole based demanded fields based transforms.  Note that
1533   // this *must* be done outside the main dataflow so long as we allow
1534   // any cross block analysis within the dataflow.  We can't have both
1535   // demanded fields based mutation and non-local analysis in the
1536   // dataflow at the same time without introducing inconsistencies.
1537   for (MachineBasicBlock &MBB : MF)
1538     doLocalPostpass(MBB);
1539 
1540   // Once we're fully done rewriting all the instructions, do a final pass
1541   // through to check for VSETVLIs which write to an unused destination.
1542   // For the non X0, X0 variant, we can replace the destination register
1543   // with X0 to reduce register pressure.  This is really a generic
1544   // optimization which can be applied to any dead def (TODO: generalize).
1545   for (MachineBasicBlock &MBB : MF) {
1546     for (MachineInstr &MI : MBB) {
1547       if (MI.getOpcode() == RISCV::PseudoVSETVLI ||
1548           MI.getOpcode() == RISCV::PseudoVSETIVLI) {
1549         Register VRegDef = MI.getOperand(0).getReg();
1550         if (VRegDef != RISCV::X0 && MRI->use_nodbg_empty(VRegDef))
1551           MI.getOperand(0).setReg(RISCV::X0);
1552       }
1553     }
1554   }
1555 
1556   // Insert PseudoReadVL after VLEFF/VLSEGFF and replace it with the vl output
1557   // of VLEFF/VLSEGFF.
1558   for (MachineBasicBlock &MBB : MF)
1559     insertReadVL(MBB);
1560 
1561   BlockInfo.clear();
1562   return HaveVectorOp;
1563 }
1564 
1565 /// Returns an instance of the Insert VSETVLI pass.
1566 FunctionPass *llvm::createRISCVInsertVSETVLIPass() {
1567   return new RISCVInsertVSETVLI();
1568 }
1569