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