1 //===- RISCVInsertVSETVLI.cpp - Insert VSETVLI instructions ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a function pass that inserts VSETVLI instructions where
10 // needed.
11 //
12 // This pass consists of 3 phases:
13 //
14 // Phase 1 collects how each basic block affects VL/VTYPE.
15 //
16 // Phase 2 uses the information from phase 1 to do a data flow analysis to
17 // propagate the VL/VTYPE changes through the function. This gives us the
18 // VL/VTYPE at the start of each basic block.
19 //
20 // Phase 3 inserts VSETVLI instructions in each basic block. Information from
21 // phase 2 is used to prevent inserting a VSETVLI before the first vector
22 // instruction in the block if possible.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "RISCV.h"
27 #include "RISCVSubtarget.h"
28 #include "llvm/CodeGen/LiveIntervals.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include <queue>
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "riscv-insert-vsetvli"
34 #define RISCV_INSERT_VSETVLI_NAME "RISCV Insert VSETVLI pass"
35 
36 static cl::opt<bool> DisableInsertVSETVLPHIOpt(
37     "riscv-disable-insert-vsetvl-phi-opt", cl::init(false), cl::Hidden,
38     cl::desc("Disable looking through phis when inserting vsetvlis."));
39 
40 namespace {
41 
42 class VSETVLIInfo {
43   union {
44     Register AVLReg;
45     unsigned AVLImm;
46   };
47 
48   enum : uint8_t {
49     Uninitialized,
50     AVLIsReg,
51     AVLIsImm,
52     Unknown,
53   } State = Uninitialized;
54 
55   // Fields from VTYPE.
56   RISCVII::VLMUL VLMul = RISCVII::LMUL_1;
57   uint8_t SEW = 0;
58   uint8_t TailAgnostic : 1;
59   uint8_t MaskAgnostic : 1;
60   uint8_t MaskRegOp : 1;
61   uint8_t SEWLMULRatioOnly : 1;
62 
63 public:
64   VSETVLIInfo()
65       : AVLImm(0), TailAgnostic(false), MaskAgnostic(false), MaskRegOp(false),
66         SEWLMULRatioOnly(false) {}
67 
68   static VSETVLIInfo getUnknown() {
69     VSETVLIInfo Info;
70     Info.setUnknown();
71     return Info;
72   }
73 
74   bool isValid() const { return State != Uninitialized; }
75   void setUnknown() { State = Unknown; }
76   bool isUnknown() const { return State == Unknown; }
77 
78   void setAVLReg(Register Reg) {
79     AVLReg = Reg;
80     State = AVLIsReg;
81   }
82 
83   void setAVLImm(unsigned Imm) {
84     AVLImm = Imm;
85     State = AVLIsImm;
86   }
87 
88   bool hasAVLImm() const { return State == AVLIsImm; }
89   bool hasAVLReg() const { return State == AVLIsReg; }
90   Register getAVLReg() const {
91     assert(hasAVLReg());
92     return AVLReg;
93   }
94   unsigned getAVLImm() const {
95     assert(hasAVLImm());
96     return AVLImm;
97   }
98 
99   bool hasSameAVL(const VSETVLIInfo &Other) const {
100     assert(isValid() && Other.isValid() &&
101            "Can't compare invalid VSETVLIInfos");
102     assert(!isUnknown() && !Other.isUnknown() &&
103            "Can't compare AVL in unknown state");
104     if (hasAVLReg() && Other.hasAVLReg())
105       return getAVLReg() == Other.getAVLReg();
106 
107     if (hasAVLImm() && Other.hasAVLImm())
108       return getAVLImm() == Other.getAVLImm();
109 
110     return false;
111   }
112 
113   void setVTYPE(unsigned VType) {
114     assert(isValid() && !isUnknown() &&
115            "Can't set VTYPE for uninitialized or unknown");
116     VLMul = RISCVVType::getVLMUL(VType);
117     SEW = RISCVVType::getSEW(VType);
118     TailAgnostic = RISCVVType::isTailAgnostic(VType);
119     MaskAgnostic = RISCVVType::isMaskAgnostic(VType);
120   }
121   void setVTYPE(RISCVII::VLMUL L, unsigned S, bool TA, bool MA, bool MRO) {
122     assert(isValid() && !isUnknown() &&
123            "Can't set VTYPE for uninitialized or unknown");
124     VLMul = L;
125     SEW = S;
126     TailAgnostic = TA;
127     MaskAgnostic = MA;
128     MaskRegOp = MRO;
129   }
130 
131   unsigned encodeVTYPE() const {
132     assert(isValid() && !isUnknown() && !SEWLMULRatioOnly &&
133            "Can't encode VTYPE for uninitialized or unknown");
134     return RISCVVType::encodeVTYPE(VLMul, SEW, TailAgnostic, MaskAgnostic);
135   }
136 
137   bool hasSEWLMULRatioOnly() const { return SEWLMULRatioOnly; }
138 
139   bool hasSameVTYPE(const VSETVLIInfo &Other) const {
140     assert(isValid() && Other.isValid() &&
141            "Can't compare invalid VSETVLIInfos");
142     assert(!isUnknown() && !Other.isUnknown() &&
143            "Can't compare VTYPE in unknown state");
144     assert(!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly &&
145            "Can't compare when only LMUL/SEW ratio is valid.");
146     return std::tie(VLMul, SEW, TailAgnostic, MaskAgnostic) ==
147            std::tie(Other.VLMul, Other.SEW, Other.TailAgnostic,
148                     Other.MaskAgnostic);
149   }
150 
151   // Convert VLMUL to a fixed point value with 3 bits of fraction.
152   unsigned getSEWLMULRatio() const {
153     assert(isValid() && !isUnknown() &&
154            "Can't use VTYPE for uninitialized or unknown");
155     unsigned LMul;
156     bool Fractional;
157     std::tie(LMul, Fractional) = RISCVVType::decodeVLMUL(VLMul);
158 
159     // Convert LMul to a fixed point value with 3 fractional bits.
160     LMul = Fractional ? (8 / LMul) : (LMul * 8);
161 
162     assert(SEW >= 8 && "Unexpected SEW value");
163     return (SEW * 8) / LMul;
164   }
165 
166   // Check if the VTYPE for these two VSETVLIInfos produce the same VLMAX.
167   bool hasSameVLMAX(const VSETVLIInfo &Other) const {
168     assert(isValid() && Other.isValid() &&
169            "Can't compare invalid VSETVLIInfos");
170     assert(!isUnknown() && !Other.isUnknown() &&
171            "Can't compare VTYPE in unknown state");
172     return getSEWLMULRatio() == Other.getSEWLMULRatio();
173   }
174 
175   // Determine whether the vector instructions requirements represented by
176   // InstrInfo are compatible with the previous vsetvli instruction represented
177   // by this.
178   bool isCompatible(const VSETVLIInfo &InstrInfo) const {
179     assert(isValid() && InstrInfo.isValid() &&
180            "Can't compare invalid VSETVLIInfos");
181     assert(!InstrInfo.SEWLMULRatioOnly &&
182            "Expected a valid VTYPE for instruction!");
183     // Nothing is compatible with Unknown.
184     if (isUnknown() || InstrInfo.isUnknown())
185       return false;
186 
187     // If only our VLMAX ratio is valid, then this isn't compatible.
188     if (SEWLMULRatioOnly)
189       return false;
190 
191     // If the instruction doesn't need an AVLReg and the SEW matches, consider
192     // it compatible.
193     if (InstrInfo.hasAVLReg() && InstrInfo.AVLReg == RISCV::NoRegister) {
194       if (SEW == InstrInfo.SEW)
195         return true;
196     }
197 
198     // VTypes must match unless the instruction is a mask reg operation, then it
199     // only care about VLMAX.
200     // FIXME: Mask reg operations are probably ok if "this" VLMAX is larger
201     // than "InstrInfo".
202     if (!hasSameVTYPE(InstrInfo) &&
203         !(InstrInfo.MaskRegOp && hasSameVLMAX(InstrInfo) &&
204           TailAgnostic == InstrInfo.TailAgnostic &&
205           MaskAgnostic == InstrInfo.MaskAgnostic))
206       return false;
207 
208     return hasSameAVL(InstrInfo);
209   }
210 
211   bool operator==(const VSETVLIInfo &Other) const {
212     // Uninitialized is only equal to another Uninitialized.
213     if (!isValid())
214       return !Other.isValid();
215     if (!Other.isValid())
216       return !isValid();
217 
218     // Unknown is only equal to another Unknown.
219     if (isUnknown())
220       return Other.isUnknown();
221     if (Other.isUnknown())
222       return isUnknown();
223 
224     if (!hasSameAVL(Other))
225       return false;
226 
227     // If only the VLMAX is valid, check that it is the same.
228     if (SEWLMULRatioOnly && Other.SEWLMULRatioOnly)
229       return hasSameVLMAX(Other);
230 
231     // If the full VTYPE is valid, check that it is the same.
232     if (!SEWLMULRatioOnly && !Other.SEWLMULRatioOnly)
233       return hasSameVTYPE(Other);
234 
235     // If the SEWLMULRatioOnly bits are different, then they aren't equal.
236     return false;
237   }
238 
239   // Calculate the VSETVLIInfo visible to a block assuming this and Other are
240   // both predecessors.
241   VSETVLIInfo intersect(const VSETVLIInfo &Other) const {
242     // If the new value isn't valid, ignore it.
243     if (!Other.isValid())
244       return *this;
245 
246     // If this value isn't valid, this must be the first predecessor, use it.
247     if (!isValid())
248       return Other;
249 
250     // If either is unknown, the result is unknown.
251     if (isUnknown() || Other.isUnknown())
252       return VSETVLIInfo::getUnknown();
253 
254     // If we have an exact, match return this.
255     if (*this == Other)
256       return *this;
257 
258     // Not an exact match, but maybe the AVL and VLMAX are the same. If so,
259     // return an SEW/LMUL ratio only value.
260     if (hasSameAVL(Other) && hasSameVLMAX(Other)) {
261       VSETVLIInfo MergeInfo = *this;
262       MergeInfo.SEWLMULRatioOnly = true;
263       return MergeInfo;
264     }
265 
266     // Otherwise the result is unknown.
267     return VSETVLIInfo::getUnknown();
268   }
269 
270   // Calculate the VSETVLIInfo visible at the end of the block assuming this
271   // is the predecessor value, and Other is change for this block.
272   VSETVLIInfo merge(const VSETVLIInfo &Other) const {
273     assert(isValid() && "Can only merge with a valid VSETVLInfo");
274 
275     // Nothing changed from the predecessor, keep it.
276     if (!Other.isValid())
277       return *this;
278 
279     // If the change is compatible with the input, we won't create a VSETVLI
280     // and should keep the predecessor.
281     if (isCompatible(Other))
282       return *this;
283 
284     // Otherwise just use whatever is in this block.
285     return Other;
286   }
287 };
288 
289 struct BlockData {
290   // The VSETVLIInfo that represents the net changes to the VL/VTYPE registers
291   // made by this block. Calculated in Phase 1.
292   VSETVLIInfo Change;
293 
294   // The VSETVLIInfo that represents the VL/VTYPE settings on exit from this
295   // block. Calculated in Phase 2.
296   VSETVLIInfo Exit;
297 
298   // The VSETVLIInfo that represents the VL/VTYPE settings from all predecessor
299   // blocks. Calculated in Phase 2, and used by Phase 3.
300   VSETVLIInfo Pred;
301 
302   // Keeps track of whether the block is already in the queue.
303   bool InQueue = false;
304 
305   BlockData() {}
306 };
307 
308 class RISCVInsertVSETVLI : public MachineFunctionPass {
309   const TargetInstrInfo *TII;
310   MachineRegisterInfo *MRI;
311 
312   std::vector<BlockData> BlockInfo;
313   std::queue<const MachineBasicBlock *> WorkList;
314 
315 public:
316   static char ID;
317 
318   RISCVInsertVSETVLI() : MachineFunctionPass(ID) {
319     initializeRISCVInsertVSETVLIPass(*PassRegistry::getPassRegistry());
320   }
321   bool runOnMachineFunction(MachineFunction &MF) override;
322 
323   void getAnalysisUsage(AnalysisUsage &AU) const override {
324     AU.setPreservesCFG();
325     MachineFunctionPass::getAnalysisUsage(AU);
326   }
327 
328   StringRef getPassName() const override { return RISCV_INSERT_VSETVLI_NAME; }
329 
330 private:
331   bool needVSETVLI(const VSETVLIInfo &Require, const VSETVLIInfo &CurInfo);
332   bool needVSETVLIPHI(const VSETVLIInfo &Require, const MachineBasicBlock &MBB);
333   void insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
334                      const VSETVLIInfo &Info, const VSETVLIInfo &PrevInfo);
335 
336   bool computeVLVTYPEChanges(const MachineBasicBlock &MBB);
337   void computeIncomingVLVTYPE(const MachineBasicBlock &MBB);
338   void emitVSETVLIs(MachineBasicBlock &MBB);
339 };
340 
341 } // end anonymous namespace
342 
343 char RISCVInsertVSETVLI::ID = 0;
344 
345 INITIALIZE_PASS(RISCVInsertVSETVLI, DEBUG_TYPE, RISCV_INSERT_VSETVLI_NAME,
346                 false, false)
347 
348 static MachineInstr *elideCopies(MachineInstr *MI,
349                                  const MachineRegisterInfo *MRI) {
350   while (true) {
351     if (!MI->isFullCopy())
352       return MI;
353     if (!Register::isVirtualRegister(MI->getOperand(1).getReg()))
354       return nullptr;
355     MI = MRI->getVRegDef(MI->getOperand(1).getReg());
356     if (!MI)
357       return nullptr;
358   }
359 }
360 
361 static VSETVLIInfo computeInfoForInstr(const MachineInstr &MI, uint64_t TSFlags,
362                                        const MachineRegisterInfo *MRI) {
363   VSETVLIInfo InstrInfo;
364   unsigned NumOperands = MI.getNumExplicitOperands();
365 
366   RISCVII::VLMUL VLMul = RISCVII::getLMul(TSFlags);
367 
368   unsigned Log2SEW = MI.getOperand(NumOperands - 1).getImm();
369   // A Log2SEW of 0 is an operation on mask registers only.
370   bool MaskRegOp = Log2SEW == 0;
371   unsigned SEW = Log2SEW ? 1 << Log2SEW : 8;
372   assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
373 
374   // Default to tail agnostic unless the destination is tied to a source.
375   // Unless the source is undef. In that case the user would have some control
376   // over the tail values. The tail policy is also ignored on instructions
377   // that only update element 0 like vmv.s.x or reductions so use agnostic
378   // there to match the common case.
379   // FIXME: This is conservatively correct, but we might want to detect that
380   // the input is undefined.
381   bool ForceTailAgnostic = RISCVII::doesForceTailAgnostic(TSFlags);
382   bool TailAgnostic = true;
383   unsigned UseOpIdx;
384   if (!ForceTailAgnostic && MI.isRegTiedToUseOperand(0, &UseOpIdx)) {
385     TailAgnostic = false;
386     // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic.
387     const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
388     MachineInstr *UseMI = MRI->getVRegDef(UseMO.getReg());
389     if (UseMI) {
390       UseMI = elideCopies(UseMI, MRI);
391       if (UseMI && UseMI->isImplicitDef())
392         TailAgnostic = true;
393     }
394   }
395 
396   if (RISCVII::hasVLOp(TSFlags)) {
397     const MachineOperand &VLOp = MI.getOperand(MI.getNumExplicitOperands() - 2);
398     if (VLOp.isImm())
399       InstrInfo.setAVLImm(VLOp.getImm());
400     else
401       InstrInfo.setAVLReg(VLOp.getReg());
402   } else
403     InstrInfo.setAVLReg(RISCV::NoRegister);
404   InstrInfo.setVTYPE(VLMul, SEW, /*TailAgnostic*/ TailAgnostic,
405                      /*MaskAgnostic*/ false, MaskRegOp);
406 
407   return InstrInfo;
408 }
409 
410 void RISCVInsertVSETVLI::insertVSETVLI(MachineBasicBlock &MBB, MachineInstr &MI,
411                                        const VSETVLIInfo &Info,
412                                        const VSETVLIInfo &PrevInfo) {
413   DebugLoc DL = MI.getDebugLoc();
414 
415   // Use X0, X0 form if the AVL is the same and the SEW+LMUL gives the same
416   // VLMAX.
417   if (PrevInfo.isValid() && !PrevInfo.isUnknown() &&
418       Info.hasSameAVL(PrevInfo) && Info.hasSameVLMAX(PrevInfo)) {
419     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETVLI))
420         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
421         .addReg(RISCV::X0, RegState::Kill)
422         .addImm(Info.encodeVTYPE())
423         .addReg(RISCV::VL, RegState::Implicit);
424     return;
425   }
426 
427   if (Info.hasAVLImm()) {
428     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETIVLI))
429         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
430         .addImm(Info.getAVLImm())
431         .addImm(Info.encodeVTYPE());
432     return;
433   }
434 
435   Register AVLReg = Info.getAVLReg();
436   if (AVLReg == RISCV::NoRegister) {
437     BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETVLI))
438         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
439         .addReg(RISCV::X0, RegState::Kill)
440         .addImm(Info.encodeVTYPE())
441         .addReg(RISCV::VL, RegState::Implicit);
442     return;
443   }
444 
445   // Use X0 as the DestReg unless AVLReg is X0.
446   Register DestReg = RISCV::X0;
447   if (AVLReg == RISCV::X0)
448     DestReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
449   BuildMI(MBB, MI, DL, TII->get(RISCV::PseudoVSETVLI))
450       .addReg(DestReg, RegState::Define | RegState::Dead)
451       .addReg(AVLReg)
452       .addImm(Info.encodeVTYPE());
453 }
454 
455 // Return a VSETVLIInfo representing the changes made by this VSETVLI or
456 // VSETIVLI instruction.
457 static VSETVLIInfo getInfoForVSETVLI(const MachineInstr &MI) {
458   VSETVLIInfo NewInfo;
459   if (MI.getOpcode() == RISCV::PseudoVSETVLI) {
460     Register AVLReg = MI.getOperand(1).getReg();
461     assert((AVLReg != RISCV::X0 || MI.getOperand(0).getReg() != RISCV::X0) &&
462            "Can't handle X0, X0 vsetvli yet");
463     NewInfo.setAVLReg(AVLReg);
464   } else {
465     assert(MI.getOpcode() == RISCV::PseudoVSETIVLI);
466     NewInfo.setAVLImm(MI.getOperand(1).getImm());
467   }
468   NewInfo.setVTYPE(MI.getOperand(2).getImm());
469 
470   return NewInfo;
471 }
472 
473 bool RISCVInsertVSETVLI::needVSETVLI(const VSETVLIInfo &Require,
474                                      const VSETVLIInfo &CurInfo) {
475   if (CurInfo.isCompatible(Require))
476     return false;
477 
478   // We didn't find a compatible value. If our AVL is a virtual register,
479   // it might be defined by a VSET(I)VLI. If it has the same VTYPE we need
480   // and the last VL/VTYPE we observed is the same, we don't need a
481   // VSETVLI here.
482   if (!CurInfo.isUnknown() && Require.hasAVLReg() &&
483       Require.getAVLReg().isVirtual() && !CurInfo.hasSEWLMULRatioOnly() &&
484       Require.hasSameVTYPE(CurInfo)) {
485     if (MachineInstr *DefMI = MRI->getVRegDef(Require.getAVLReg())) {
486       if (DefMI->getOpcode() == RISCV::PseudoVSETVLI ||
487           DefMI->getOpcode() == RISCV::PseudoVSETIVLI) {
488         VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
489         if (DefInfo.hasSameAVL(CurInfo) && DefInfo.hasSameVTYPE(CurInfo))
490           return false;
491       }
492     }
493   }
494 
495   return true;
496 }
497 
498 bool RISCVInsertVSETVLI::computeVLVTYPEChanges(const MachineBasicBlock &MBB) {
499   bool HadVectorOp = false;
500 
501   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
502   for (const MachineInstr &MI : MBB) {
503     // If this is an explicit VSETVLI or VSETIVLI, update our state.
504     if (MI.getOpcode() == RISCV::PseudoVSETVLI ||
505         MI.getOpcode() == RISCV::PseudoVSETIVLI) {
506       HadVectorOp = true;
507       BBInfo.Change = getInfoForVSETVLI(MI);
508       continue;
509     }
510 
511     uint64_t TSFlags = MI.getDesc().TSFlags;
512     if (RISCVII::hasSEWOp(TSFlags)) {
513       HadVectorOp = true;
514 
515       VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
516 
517       if (!BBInfo.Change.isValid()) {
518         BBInfo.Change = NewInfo;
519       } else {
520         // If this instruction isn't compatible with the previous VL/VTYPE
521         // we need to insert a VSETVLI.
522         if (needVSETVLI(NewInfo, BBInfo.Change))
523           BBInfo.Change = NewInfo;
524       }
525     }
526 
527     // If this is something that updates VL/VTYPE that we don't know about, set
528     // the state to unknown.
529     if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
530         MI.modifiesRegister(RISCV::VTYPE)) {
531       BBInfo.Change = VSETVLIInfo::getUnknown();
532     }
533   }
534 
535   // Initial exit state is whatever change we found in the block.
536   BBInfo.Exit = BBInfo.Change;
537 
538   return HadVectorOp;
539 }
540 
541 void RISCVInsertVSETVLI::computeIncomingVLVTYPE(const MachineBasicBlock &MBB) {
542   BlockData &BBInfo = BlockInfo[MBB.getNumber()];
543 
544   BBInfo.InQueue = false;
545 
546   VSETVLIInfo InInfo;
547   if (MBB.pred_empty()) {
548     // There are no predecessors, so use the default starting status.
549     InInfo.setUnknown();
550   } else {
551     for (MachineBasicBlock *P : MBB.predecessors())
552       InInfo = InInfo.intersect(BlockInfo[P->getNumber()].Exit);
553   }
554 
555   // If we don't have any valid predecessor value, wait until we do.
556   if (!InInfo.isValid())
557     return;
558 
559   BBInfo.Pred = InInfo;
560 
561   VSETVLIInfo TmpStatus = BBInfo.Pred.merge(BBInfo.Change);
562 
563   // If the new exit value matches the old exit value, we don't need to revisit
564   // any blocks.
565   if (BBInfo.Exit == TmpStatus)
566     return;
567 
568   BBInfo.Exit = TmpStatus;
569 
570   // Add the successors to the work list so we can propagate the changed exit
571   // status.
572   for (MachineBasicBlock *S : MBB.successors())
573     if (!BlockInfo[S->getNumber()].InQueue)
574       WorkList.push(S);
575 }
576 
577 // If we weren't able to prove a vsetvli was directly unneeded, it might still
578 // be/ unneeded if the AVL is a phi node where all incoming values are VL
579 // outputs from the last VSETVLI in their respective basic blocks.
580 bool RISCVInsertVSETVLI::needVSETVLIPHI(const VSETVLIInfo &Require,
581                                         const MachineBasicBlock &MBB) {
582   if (DisableInsertVSETVLPHIOpt)
583     return true;
584 
585   if (!Require.hasAVLReg())
586     return true;
587 
588   Register AVLReg = Require.getAVLReg();
589   if (!AVLReg.isVirtual())
590     return true;
591 
592   // We need the AVL to be produce by a PHI node in this basic block.
593   MachineInstr *PHI = MRI->getVRegDef(AVLReg);
594   if (!PHI || PHI->getOpcode() != RISCV::PHI || PHI->getParent() != &MBB)
595     return true;
596 
597   for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
598        PHIOp += 2) {
599     Register InReg = PHI->getOperand(PHIOp).getReg();
600     MachineBasicBlock *PBB = PHI->getOperand(PHIOp + 1).getMBB();
601     const BlockData &PBBInfo = BlockInfo[PBB->getNumber()];
602     // If the exit from the predecessor has the VTYPE we are looking for
603     // we might be able to avoid a VSETVLI.
604     if (PBBInfo.Exit.isUnknown() || !PBBInfo.Exit.hasSameVTYPE(Require))
605       return true;
606 
607     // We need the PHI input to the be the output of a VSET(I)VLI.
608     MachineInstr *DefMI = MRI->getVRegDef(InReg);
609     if (!DefMI || (DefMI->getOpcode() != RISCV::PseudoVSETVLI &&
610                    DefMI->getOpcode() != RISCV::PseudoVSETIVLI))
611       return true;
612 
613     // We found a VSET(I)VLI make sure it matches the output of the
614     // predecessor block.
615     VSETVLIInfo DefInfo = getInfoForVSETVLI(*DefMI);
616     if (!DefInfo.hasSameAVL(PBBInfo.Exit) ||
617         !DefInfo.hasSameVTYPE(PBBInfo.Exit))
618       return true;
619   }
620 
621   // If all the incoming values to the PHI checked out, we don't need
622   // to insert a VSETVLI.
623   return false;
624 }
625 
626 void RISCVInsertVSETVLI::emitVSETVLIs(MachineBasicBlock &MBB) {
627   VSETVLIInfo CurInfo;
628 
629   for (MachineInstr &MI : MBB) {
630     // If this is an explicit VSETVLI or VSETIVLI, update our state.
631     if (MI.getOpcode() == RISCV::PseudoVSETVLI ||
632         MI.getOpcode() == RISCV::PseudoVSETIVLI) {
633       // Conservatively, mark the VL and VTYPE as live.
634       assert(MI.getOperand(3).getReg() == RISCV::VL &&
635              MI.getOperand(4).getReg() == RISCV::VTYPE &&
636              "Unexpected operands where VL and VTYPE should be");
637       MI.getOperand(3).setIsDead(false);
638       MI.getOperand(4).setIsDead(false);
639       CurInfo = getInfoForVSETVLI(MI);
640       continue;
641     }
642 
643     uint64_t TSFlags = MI.getDesc().TSFlags;
644     if (RISCVII::hasSEWOp(TSFlags)) {
645       VSETVLIInfo NewInfo = computeInfoForInstr(MI, TSFlags, MRI);
646       if (RISCVII::hasVLOp(TSFlags)) {
647         MachineOperand &VLOp = MI.getOperand(MI.getNumExplicitOperands() - 2);
648         if (VLOp.isReg()) {
649           // Erase the AVL operand from the instruction.
650           VLOp.setReg(RISCV::NoRegister);
651           VLOp.setIsKill(false);
652         }
653         MI.addOperand(MachineOperand::CreateReg(RISCV::VL, /*isDef*/ false,
654                                                 /*isImp*/ true));
655       }
656       MI.addOperand(MachineOperand::CreateReg(RISCV::VTYPE, /*isDef*/ false,
657                                               /*isImp*/ true));
658 
659       if (!CurInfo.isValid()) {
660         // We haven't found any vector instructions or VL/VTYPE changes yet,
661         // use the predecessor information.
662         assert(BlockInfo[MBB.getNumber()].Pred.isValid() &&
663                "Expected a valid predecessor state.");
664         if (needVSETVLI(NewInfo, BlockInfo[MBB.getNumber()].Pred) &&
665             needVSETVLIPHI(NewInfo, MBB)) {
666           insertVSETVLI(MBB, MI, NewInfo, BlockInfo[MBB.getNumber()].Pred);
667           CurInfo = NewInfo;
668         }
669       } else {
670         // If this instruction isn't compatible with the previous VL/VTYPE
671         // we need to insert a VSETVLI.
672         if (needVSETVLI(NewInfo, CurInfo)) {
673           insertVSETVLI(MBB, MI, NewInfo, CurInfo);
674           CurInfo = NewInfo;
675         }
676       }
677     }
678 
679     // If this is something updates VL/VTYPE that we don't know about, set
680     // the state to unknown.
681     if (MI.isCall() || MI.isInlineAsm() || MI.modifiesRegister(RISCV::VL) ||
682         MI.modifiesRegister(RISCV::VTYPE)) {
683       CurInfo = VSETVLIInfo::getUnknown();
684     }
685   }
686 }
687 
688 bool RISCVInsertVSETVLI::runOnMachineFunction(MachineFunction &MF) {
689   // Skip if the vector extension is not enabled.
690   const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
691   if (!ST.hasStdExtV())
692     return false;
693 
694   TII = ST.getInstrInfo();
695   MRI = &MF.getRegInfo();
696 
697   assert(BlockInfo.empty() && "Expect empty block infos");
698   BlockInfo.resize(MF.getNumBlockIDs());
699 
700   bool HaveVectorOp = false;
701 
702   // Phase 1 - determine how VL/VTYPE are affected by the each block.
703   for (const MachineBasicBlock &MBB : MF)
704     HaveVectorOp |= computeVLVTYPEChanges(MBB);
705 
706   // If we didn't find any instructions that need VSETVLI, we're done.
707   if (HaveVectorOp) {
708     // Phase 2 - determine the exit VL/VTYPE from each block. We add all
709     // blocks to the list here, but will also add any that need to be revisited
710     // during Phase 2 processing.
711     for (const MachineBasicBlock &MBB : MF) {
712       WorkList.push(&MBB);
713       BlockInfo[MBB.getNumber()].InQueue = true;
714     }
715     while (!WorkList.empty()) {
716       const MachineBasicBlock &MBB = *WorkList.front();
717       WorkList.pop();
718       computeIncomingVLVTYPE(MBB);
719     }
720 
721     // Phase 3 - add any vsetvli instructions needed in the block. Use the
722     // Phase 2 information to avoid adding vsetvlis before the first vector
723     // instruction in the block if the VL/VTYPE is satisfied by its
724     // predecessors.
725     for (MachineBasicBlock &MBB : MF)
726       emitVSETVLIs(MBB);
727   }
728 
729   BlockInfo.clear();
730 
731   return HaveVectorOp;
732 }
733 
734 /// Returns an instance of the Insert VSETVLI pass.
735 FunctionPass *llvm::createRISCVInsertVSETVLIPass() {
736   return new RISCVInsertVSETVLI();
737 }
738