1 //===-- RISCVISelDAGToDAG.cpp - A dag to dag inst selector for RISCV ------===//
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 defines an instruction selector for the RISCV target.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RISCVISelDAGToDAG.h"
14 #include "MCTargetDesc/RISCVMCTargetDesc.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCVISelLowering.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/IR/IntrinsicsRISCV.h"
20 #include "llvm/Support/Alignment.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/KnownBits.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/raw_ostream.h"
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "riscv-isel"
29 
30 namespace llvm {
31 namespace RISCV {
32 #define GET_RISCVVSSEGTable_IMPL
33 #define GET_RISCVVLSEGTable_IMPL
34 #define GET_RISCVVLXSEGTable_IMPL
35 #define GET_RISCVVSXSEGTable_IMPL
36 #define GET_RISCVVLETable_IMPL
37 #define GET_RISCVVSETable_IMPL
38 #define GET_RISCVVLXTable_IMPL
39 #define GET_RISCVVSXTable_IMPL
40 #define GET_RISCVMaskedPseudosTable_IMPL
41 #include "RISCVGenSearchableTables.inc"
42 } // namespace RISCV
43 } // namespace llvm
44 
45 void RISCVDAGToDAGISel::PreprocessISelDAG() {
46   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
47                                        E = CurDAG->allnodes_end();
48        I != E;) {
49     SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
50 
51     // Convert integer SPLAT_VECTOR to VMV_V_X_VL and floating-point
52     // SPLAT_VECTOR to VFMV_V_F_VL to reduce isel burden.
53     if (N->getOpcode() == ISD::SPLAT_VECTOR) {
54       MVT VT = N->getSimpleValueType(0);
55       unsigned Opc =
56           VT.isInteger() ? RISCVISD::VMV_V_X_VL : RISCVISD::VFMV_V_F_VL;
57       SDLoc DL(N);
58       SDValue VL = CurDAG->getRegister(RISCV::X0, Subtarget->getXLenVT());
59       SDValue Result = CurDAG->getNode(Opc, DL, VT, CurDAG->getUNDEF(VT),
60                                        N->getOperand(0), VL);
61 
62       --I;
63       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
64       ++I;
65       CurDAG->DeleteNode(N);
66       continue;
67     }
68 
69     // Lower SPLAT_VECTOR_SPLIT_I64 to two scalar stores and a stride 0 vector
70     // load. Done after lowering and combining so that we have a chance to
71     // optimize this to VMV_V_X_VL when the upper bits aren't needed.
72     if (N->getOpcode() != RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL)
73       continue;
74 
75     assert(N->getNumOperands() == 4 && "Unexpected number of operands");
76     MVT VT = N->getSimpleValueType(0);
77     SDValue Passthru = N->getOperand(0);
78     SDValue Lo = N->getOperand(1);
79     SDValue Hi = N->getOperand(2);
80     SDValue VL = N->getOperand(3);
81     assert(VT.getVectorElementType() == MVT::i64 && VT.isScalableVector() &&
82            Lo.getValueType() == MVT::i32 && Hi.getValueType() == MVT::i32 &&
83            "Unexpected VTs!");
84     MachineFunction &MF = CurDAG->getMachineFunction();
85     RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
86     SDLoc DL(N);
87 
88     // We use the same frame index we use for moving two i32s into 64-bit FPR.
89     // This is an analogous operation.
90     int FI = FuncInfo->getMoveF64FrameIndex(MF);
91     MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
92     const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
93     SDValue StackSlot =
94         CurDAG->getFrameIndex(FI, TLI.getPointerTy(CurDAG->getDataLayout()));
95 
96     SDValue Chain = CurDAG->getEntryNode();
97     Lo = CurDAG->getStore(Chain, DL, Lo, StackSlot, MPI, Align(8));
98 
99     SDValue OffsetSlot =
100         CurDAG->getMemBasePlusOffset(StackSlot, TypeSize::Fixed(4), DL);
101     Hi = CurDAG->getStore(Chain, DL, Hi, OffsetSlot, MPI.getWithOffset(4),
102                           Align(8));
103 
104     Chain = CurDAG->getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
105 
106     SDVTList VTs = CurDAG->getVTList({VT, MVT::Other});
107     SDValue IntID =
108         CurDAG->getTargetConstant(Intrinsic::riscv_vlse, DL, MVT::i64);
109     SDValue Ops[] = {Chain,
110                      IntID,
111                      Passthru,
112                      StackSlot,
113                      CurDAG->getRegister(RISCV::X0, MVT::i64),
114                      VL};
115 
116     SDValue Result = CurDAG->getMemIntrinsicNode(
117         ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MVT::i64, MPI, Align(8),
118         MachineMemOperand::MOLoad);
119 
120     // We're about to replace all uses of the SPLAT_VECTOR_SPLIT_I64 with the
121     // vlse we created.  This will cause general havok on the dag because
122     // anything below the conversion could be folded into other existing nodes.
123     // To avoid invalidating 'I', back it up to the convert node.
124     --I;
125     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
126 
127     // Now that we did that, the node is dead.  Increment the iterator to the
128     // next node to process, then delete N.
129     ++I;
130     CurDAG->DeleteNode(N);
131   }
132 }
133 
134 void RISCVDAGToDAGISel::PostprocessISelDAG() {
135   HandleSDNode Dummy(CurDAG->getRoot());
136   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
137 
138   bool MadeChange = false;
139   while (Position != CurDAG->allnodes_begin()) {
140     SDNode *N = &*--Position;
141     // Skip dead nodes and any non-machine opcodes.
142     if (N->use_empty() || !N->isMachineOpcode())
143       continue;
144 
145     MadeChange |= doPeepholeSExtW(N);
146     MadeChange |= doPeepholeLoadStoreADDI(N);
147     MadeChange |= doPeepholeMaskedRVV(N);
148   }
149 
150   CurDAG->setRoot(Dummy.getValue());
151 
152   if (MadeChange)
153     CurDAG->RemoveDeadNodes();
154 }
155 
156 static SDNode *selectImmWithConstantPool(SelectionDAG *CurDAG, const SDLoc &DL,
157                                          const MVT VT, int64_t Imm,
158                                          const RISCVSubtarget &Subtarget) {
159   assert(VT == MVT::i64 && "Expecting MVT::i64");
160   const RISCVTargetLowering *TLI = Subtarget.getTargetLowering();
161   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(CurDAG->getConstantPool(
162       ConstantInt::get(EVT(VT).getTypeForEVT(*CurDAG->getContext()), Imm), VT));
163   SDValue Addr = TLI->getAddr(CP, *CurDAG);
164   SDValue Offset = CurDAG->getTargetConstant(0, DL, VT);
165   // Since there is no data race, the chain can be the entry node.
166   SDNode *Load = CurDAG->getMachineNode(RISCV::LD, DL, VT, Addr, Offset,
167                                         CurDAG->getEntryNode());
168   MachineFunction &MF = CurDAG->getMachineFunction();
169   MachineMemOperand *MemOp = MF.getMachineMemOperand(
170       MachinePointerInfo::getConstantPool(MF), MachineMemOperand::MOLoad,
171       LLT(VT), CP->getAlign());
172   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Load), {MemOp});
173   return Load;
174 }
175 
176 static SDNode *selectImm(SelectionDAG *CurDAG, const SDLoc &DL, const MVT VT,
177                          int64_t Imm, const RISCVSubtarget &Subtarget) {
178   MVT XLenVT = Subtarget.getXLenVT();
179   RISCVMatInt::InstSeq Seq =
180       RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits());
181 
182   // If Imm is expensive to build, then we put it into constant pool.
183   if (Subtarget.useConstantPoolForLargeInts() &&
184       Seq.size() > Subtarget.getMaxBuildIntsCost())
185     return selectImmWithConstantPool(CurDAG, DL, VT, Imm, Subtarget);
186 
187   SDNode *Result = nullptr;
188   SDValue SrcReg = CurDAG->getRegister(RISCV::X0, XLenVT);
189   for (RISCVMatInt::Inst &Inst : Seq) {
190     SDValue SDImm = CurDAG->getTargetConstant(Inst.Imm, DL, XLenVT);
191     if (Inst.Opc == RISCV::LUI)
192       Result = CurDAG->getMachineNode(RISCV::LUI, DL, XLenVT, SDImm);
193     else if (Inst.Opc == RISCV::ADD_UW)
194       Result = CurDAG->getMachineNode(RISCV::ADD_UW, DL, XLenVT, SrcReg,
195                                       CurDAG->getRegister(RISCV::X0, XLenVT));
196     else if (Inst.Opc == RISCV::SH1ADD || Inst.Opc == RISCV::SH2ADD ||
197              Inst.Opc == RISCV::SH3ADD)
198       Result = CurDAG->getMachineNode(Inst.Opc, DL, XLenVT, SrcReg, SrcReg);
199     else
200       Result = CurDAG->getMachineNode(Inst.Opc, DL, XLenVT, SrcReg, SDImm);
201 
202     // Only the first instruction has X0 as its source.
203     SrcReg = SDValue(Result, 0);
204   }
205 
206   return Result;
207 }
208 
209 static SDValue createTupleImpl(SelectionDAG &CurDAG, ArrayRef<SDValue> Regs,
210                                unsigned RegClassID, unsigned SubReg0) {
211   assert(Regs.size() >= 2 && Regs.size() <= 8);
212 
213   SDLoc DL(Regs[0]);
214   SmallVector<SDValue, 8> Ops;
215 
216   Ops.push_back(CurDAG.getTargetConstant(RegClassID, DL, MVT::i32));
217 
218   for (unsigned I = 0; I < Regs.size(); ++I) {
219     Ops.push_back(Regs[I]);
220     Ops.push_back(CurDAG.getTargetConstant(SubReg0 + I, DL, MVT::i32));
221   }
222   SDNode *N =
223       CurDAG.getMachineNode(TargetOpcode::REG_SEQUENCE, DL, MVT::Untyped, Ops);
224   return SDValue(N, 0);
225 }
226 
227 static SDValue createM1Tuple(SelectionDAG &CurDAG, ArrayRef<SDValue> Regs,
228                              unsigned NF) {
229   static const unsigned RegClassIDs[] = {
230       RISCV::VRN2M1RegClassID, RISCV::VRN3M1RegClassID, RISCV::VRN4M1RegClassID,
231       RISCV::VRN5M1RegClassID, RISCV::VRN6M1RegClassID, RISCV::VRN7M1RegClassID,
232       RISCV::VRN8M1RegClassID};
233 
234   return createTupleImpl(CurDAG, Regs, RegClassIDs[NF - 2], RISCV::sub_vrm1_0);
235 }
236 
237 static SDValue createM2Tuple(SelectionDAG &CurDAG, ArrayRef<SDValue> Regs,
238                              unsigned NF) {
239   static const unsigned RegClassIDs[] = {RISCV::VRN2M2RegClassID,
240                                          RISCV::VRN3M2RegClassID,
241                                          RISCV::VRN4M2RegClassID};
242 
243   return createTupleImpl(CurDAG, Regs, RegClassIDs[NF - 2], RISCV::sub_vrm2_0);
244 }
245 
246 static SDValue createM4Tuple(SelectionDAG &CurDAG, ArrayRef<SDValue> Regs,
247                              unsigned NF) {
248   return createTupleImpl(CurDAG, Regs, RISCV::VRN2M4RegClassID,
249                          RISCV::sub_vrm4_0);
250 }
251 
252 static SDValue createTuple(SelectionDAG &CurDAG, ArrayRef<SDValue> Regs,
253                            unsigned NF, RISCVII::VLMUL LMUL) {
254   switch (LMUL) {
255   default:
256     llvm_unreachable("Invalid LMUL.");
257   case RISCVII::VLMUL::LMUL_F8:
258   case RISCVII::VLMUL::LMUL_F4:
259   case RISCVII::VLMUL::LMUL_F2:
260   case RISCVII::VLMUL::LMUL_1:
261     return createM1Tuple(CurDAG, Regs, NF);
262   case RISCVII::VLMUL::LMUL_2:
263     return createM2Tuple(CurDAG, Regs, NF);
264   case RISCVII::VLMUL::LMUL_4:
265     return createM4Tuple(CurDAG, Regs, NF);
266   }
267 }
268 
269 void RISCVDAGToDAGISel::addVectorLoadStoreOperands(
270     SDNode *Node, unsigned Log2SEW, const SDLoc &DL, unsigned CurOp,
271     bool IsMasked, bool IsStridedOrIndexed, SmallVectorImpl<SDValue> &Operands,
272     bool IsLoad, MVT *IndexVT) {
273   SDValue Chain = Node->getOperand(0);
274   SDValue Glue;
275 
276   SDValue Base;
277   SelectBaseAddr(Node->getOperand(CurOp++), Base);
278   Operands.push_back(Base); // Base pointer.
279 
280   if (IsStridedOrIndexed) {
281     Operands.push_back(Node->getOperand(CurOp++)); // Index.
282     if (IndexVT)
283       *IndexVT = Operands.back()->getSimpleValueType(0);
284   }
285 
286   if (IsMasked) {
287     // Mask needs to be copied to V0.
288     SDValue Mask = Node->getOperand(CurOp++);
289     Chain = CurDAG->getCopyToReg(Chain, DL, RISCV::V0, Mask, SDValue());
290     Glue = Chain.getValue(1);
291     Operands.push_back(CurDAG->getRegister(RISCV::V0, Mask.getValueType()));
292   }
293   SDValue VL;
294   selectVLOp(Node->getOperand(CurOp++), VL);
295   Operands.push_back(VL);
296 
297   MVT XLenVT = Subtarget->getXLenVT();
298   SDValue SEWOp = CurDAG->getTargetConstant(Log2SEW, DL, XLenVT);
299   Operands.push_back(SEWOp);
300 
301   // Masked load has the tail policy argument.
302   if (IsMasked && IsLoad) {
303     // Policy must be a constant.
304     uint64_t Policy = Node->getConstantOperandVal(CurOp++);
305     SDValue PolicyOp = CurDAG->getTargetConstant(Policy, DL, XLenVT);
306     Operands.push_back(PolicyOp);
307   }
308 
309   Operands.push_back(Chain); // Chain.
310   if (Glue)
311     Operands.push_back(Glue);
312 }
313 
314 void RISCVDAGToDAGISel::selectVLSEG(SDNode *Node, bool IsMasked,
315                                     bool IsStrided) {
316   SDLoc DL(Node);
317   unsigned NF = Node->getNumValues() - 1;
318   MVT VT = Node->getSimpleValueType(0);
319   unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
320   RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
321 
322   unsigned CurOp = 2;
323   SmallVector<SDValue, 8> Operands;
324   if (IsMasked) {
325     SmallVector<SDValue, 8> Regs(Node->op_begin() + CurOp,
326                                  Node->op_begin() + CurOp + NF);
327     SDValue MaskedOff = createTuple(*CurDAG, Regs, NF, LMUL);
328     Operands.push_back(MaskedOff);
329     CurOp += NF;
330   }
331 
332   addVectorLoadStoreOperands(Node, Log2SEW, DL, CurOp, IsMasked, IsStrided,
333                              Operands, /*IsLoad=*/true);
334 
335   const RISCV::VLSEGPseudo *P =
336       RISCV::getVLSEGPseudo(NF, IsMasked, IsStrided, /*FF*/ false, Log2SEW,
337                             static_cast<unsigned>(LMUL));
338   MachineSDNode *Load =
339       CurDAG->getMachineNode(P->Pseudo, DL, MVT::Untyped, MVT::Other, Operands);
340 
341   if (auto *MemOp = dyn_cast<MemSDNode>(Node))
342     CurDAG->setNodeMemRefs(Load, {MemOp->getMemOperand()});
343 
344   SDValue SuperReg = SDValue(Load, 0);
345   for (unsigned I = 0; I < NF; ++I) {
346     unsigned SubRegIdx = RISCVTargetLowering::getSubregIndexByMVT(VT, I);
347     ReplaceUses(SDValue(Node, I),
348                 CurDAG->getTargetExtractSubreg(SubRegIdx, DL, VT, SuperReg));
349   }
350 
351   ReplaceUses(SDValue(Node, NF), SDValue(Load, 1));
352   CurDAG->RemoveDeadNode(Node);
353 }
354 
355 void RISCVDAGToDAGISel::selectVLSEGFF(SDNode *Node, bool IsMasked) {
356   SDLoc DL(Node);
357   unsigned NF = Node->getNumValues() - 2; // Do not count VL and Chain.
358   MVT VT = Node->getSimpleValueType(0);
359   MVT XLenVT = Subtarget->getXLenVT();
360   unsigned SEW = VT.getScalarSizeInBits();
361   unsigned Log2SEW = Log2_32(SEW);
362   RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
363 
364   unsigned CurOp = 2;
365   SmallVector<SDValue, 7> Operands;
366   if (IsMasked) {
367     SmallVector<SDValue, 8> Regs(Node->op_begin() + CurOp,
368                                  Node->op_begin() + CurOp + NF);
369     SDValue MaskedOff = createTuple(*CurDAG, Regs, NF, LMUL);
370     Operands.push_back(MaskedOff);
371     CurOp += NF;
372   }
373 
374   addVectorLoadStoreOperands(Node, Log2SEW, DL, CurOp, IsMasked,
375                              /*IsStridedOrIndexed*/ false, Operands,
376                              /*IsLoad=*/true);
377 
378   const RISCV::VLSEGPseudo *P =
379       RISCV::getVLSEGPseudo(NF, IsMasked, /*Strided*/ false, /*FF*/ true,
380                             Log2SEW, static_cast<unsigned>(LMUL));
381   MachineSDNode *Load = CurDAG->getMachineNode(P->Pseudo, DL, MVT::Untyped,
382                                                MVT::Other, MVT::Glue, Operands);
383   bool TailAgnostic = true;
384   bool MaskAgnostic = false;
385   if (IsMasked) {
386     uint64_t Policy = Node->getConstantOperandVal(Node->getNumOperands() - 1);
387     TailAgnostic = Policy & RISCVII::TAIL_AGNOSTIC;
388     MaskAgnostic = Policy & RISCVII::MASK_AGNOSTIC;
389   }
390   unsigned VType =
391       RISCVVType::encodeVTYPE(LMUL, SEW, TailAgnostic, MaskAgnostic);
392   SDValue VTypeOp = CurDAG->getTargetConstant(VType, DL, XLenVT);
393   SDNode *ReadVL = CurDAG->getMachineNode(RISCV::PseudoReadVL, DL, XLenVT,
394                                           VTypeOp, /*Glue*/ SDValue(Load, 2));
395 
396   if (auto *MemOp = dyn_cast<MemSDNode>(Node))
397     CurDAG->setNodeMemRefs(Load, {MemOp->getMemOperand()});
398 
399   SDValue SuperReg = SDValue(Load, 0);
400   for (unsigned I = 0; I < NF; ++I) {
401     unsigned SubRegIdx = RISCVTargetLowering::getSubregIndexByMVT(VT, I);
402     ReplaceUses(SDValue(Node, I),
403                 CurDAG->getTargetExtractSubreg(SubRegIdx, DL, VT, SuperReg));
404   }
405 
406   ReplaceUses(SDValue(Node, NF), SDValue(ReadVL, 0));   // VL
407   ReplaceUses(SDValue(Node, NF + 1), SDValue(Load, 1)); // Chain
408   CurDAG->RemoveDeadNode(Node);
409 }
410 
411 void RISCVDAGToDAGISel::selectVLXSEG(SDNode *Node, bool IsMasked,
412                                      bool IsOrdered) {
413   SDLoc DL(Node);
414   unsigned NF = Node->getNumValues() - 1;
415   MVT VT = Node->getSimpleValueType(0);
416   unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
417   RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
418 
419   unsigned CurOp = 2;
420   SmallVector<SDValue, 8> Operands;
421   if (IsMasked) {
422     SmallVector<SDValue, 8> Regs(Node->op_begin() + CurOp,
423                                  Node->op_begin() + CurOp + NF);
424     SDValue MaskedOff = createTuple(*CurDAG, Regs, NF, LMUL);
425     Operands.push_back(MaskedOff);
426     CurOp += NF;
427   }
428 
429   MVT IndexVT;
430   addVectorLoadStoreOperands(Node, Log2SEW, DL, CurOp, IsMasked,
431                              /*IsStridedOrIndexed*/ true, Operands,
432                              /*IsLoad=*/true, &IndexVT);
433 
434   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
435          "Element count mismatch");
436 
437   RISCVII::VLMUL IndexLMUL = RISCVTargetLowering::getLMUL(IndexVT);
438   unsigned IndexLog2EEW = Log2_32(IndexVT.getScalarSizeInBits());
439   if (IndexLog2EEW == 6 && !Subtarget->is64Bit()) {
440     report_fatal_error("The V extension does not support EEW=64 for index "
441                        "values when XLEN=32");
442   }
443   const RISCV::VLXSEGPseudo *P = RISCV::getVLXSEGPseudo(
444       NF, IsMasked, IsOrdered, IndexLog2EEW, static_cast<unsigned>(LMUL),
445       static_cast<unsigned>(IndexLMUL));
446   MachineSDNode *Load =
447       CurDAG->getMachineNode(P->Pseudo, DL, MVT::Untyped, MVT::Other, Operands);
448 
449   if (auto *MemOp = dyn_cast<MemSDNode>(Node))
450     CurDAG->setNodeMemRefs(Load, {MemOp->getMemOperand()});
451 
452   SDValue SuperReg = SDValue(Load, 0);
453   for (unsigned I = 0; I < NF; ++I) {
454     unsigned SubRegIdx = RISCVTargetLowering::getSubregIndexByMVT(VT, I);
455     ReplaceUses(SDValue(Node, I),
456                 CurDAG->getTargetExtractSubreg(SubRegIdx, DL, VT, SuperReg));
457   }
458 
459   ReplaceUses(SDValue(Node, NF), SDValue(Load, 1));
460   CurDAG->RemoveDeadNode(Node);
461 }
462 
463 void RISCVDAGToDAGISel::selectVSSEG(SDNode *Node, bool IsMasked,
464                                     bool IsStrided) {
465   SDLoc DL(Node);
466   unsigned NF = Node->getNumOperands() - 4;
467   if (IsStrided)
468     NF--;
469   if (IsMasked)
470     NF--;
471   MVT VT = Node->getOperand(2)->getSimpleValueType(0);
472   unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
473   RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
474   SmallVector<SDValue, 8> Regs(Node->op_begin() + 2, Node->op_begin() + 2 + NF);
475   SDValue StoreVal = createTuple(*CurDAG, Regs, NF, LMUL);
476 
477   SmallVector<SDValue, 8> Operands;
478   Operands.push_back(StoreVal);
479   unsigned CurOp = 2 + NF;
480 
481   addVectorLoadStoreOperands(Node, Log2SEW, DL, CurOp, IsMasked, IsStrided,
482                              Operands);
483 
484   const RISCV::VSSEGPseudo *P = RISCV::getVSSEGPseudo(
485       NF, IsMasked, IsStrided, Log2SEW, static_cast<unsigned>(LMUL));
486   MachineSDNode *Store =
487       CurDAG->getMachineNode(P->Pseudo, DL, Node->getValueType(0), Operands);
488 
489   if (auto *MemOp = dyn_cast<MemSDNode>(Node))
490     CurDAG->setNodeMemRefs(Store, {MemOp->getMemOperand()});
491 
492   ReplaceNode(Node, Store);
493 }
494 
495 void RISCVDAGToDAGISel::selectVSXSEG(SDNode *Node, bool IsMasked,
496                                      bool IsOrdered) {
497   SDLoc DL(Node);
498   unsigned NF = Node->getNumOperands() - 5;
499   if (IsMasked)
500     --NF;
501   MVT VT = Node->getOperand(2)->getSimpleValueType(0);
502   unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
503   RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
504   SmallVector<SDValue, 8> Regs(Node->op_begin() + 2, Node->op_begin() + 2 + NF);
505   SDValue StoreVal = createTuple(*CurDAG, Regs, NF, LMUL);
506 
507   SmallVector<SDValue, 8> Operands;
508   Operands.push_back(StoreVal);
509   unsigned CurOp = 2 + NF;
510 
511   MVT IndexVT;
512   addVectorLoadStoreOperands(Node, Log2SEW, DL, CurOp, IsMasked,
513                              /*IsStridedOrIndexed*/ true, Operands,
514                              /*IsLoad=*/false, &IndexVT);
515 
516   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
517          "Element count mismatch");
518 
519   RISCVII::VLMUL IndexLMUL = RISCVTargetLowering::getLMUL(IndexVT);
520   unsigned IndexLog2EEW = Log2_32(IndexVT.getScalarSizeInBits());
521   if (IndexLog2EEW == 6 && !Subtarget->is64Bit()) {
522     report_fatal_error("The V extension does not support EEW=64 for index "
523                        "values when XLEN=32");
524   }
525   const RISCV::VSXSEGPseudo *P = RISCV::getVSXSEGPseudo(
526       NF, IsMasked, IsOrdered, IndexLog2EEW, static_cast<unsigned>(LMUL),
527       static_cast<unsigned>(IndexLMUL));
528   MachineSDNode *Store =
529       CurDAG->getMachineNode(P->Pseudo, DL, Node->getValueType(0), Operands);
530 
531   if (auto *MemOp = dyn_cast<MemSDNode>(Node))
532     CurDAG->setNodeMemRefs(Store, {MemOp->getMemOperand()});
533 
534   ReplaceNode(Node, Store);
535 }
536 
537 void RISCVDAGToDAGISel::selectVSETVLI(SDNode *Node) {
538   if (!Subtarget->hasVInstructions())
539     return;
540 
541   assert((Node->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
542           Node->getOpcode() == ISD::INTRINSIC_WO_CHAIN) &&
543          "Unexpected opcode");
544 
545   SDLoc DL(Node);
546   MVT XLenVT = Subtarget->getXLenVT();
547 
548   bool HasChain = Node->getOpcode() == ISD::INTRINSIC_W_CHAIN;
549   unsigned IntNoOffset = HasChain ? 1 : 0;
550   unsigned IntNo = Node->getConstantOperandVal(IntNoOffset);
551 
552   assert((IntNo == Intrinsic::riscv_vsetvli ||
553           IntNo == Intrinsic::riscv_vsetvlimax ||
554           IntNo == Intrinsic::riscv_vsetvli_opt ||
555           IntNo == Intrinsic::riscv_vsetvlimax_opt) &&
556          "Unexpected vsetvli intrinsic");
557 
558   bool VLMax = IntNo == Intrinsic::riscv_vsetvlimax ||
559                IntNo == Intrinsic::riscv_vsetvlimax_opt;
560   unsigned Offset = IntNoOffset + (VLMax ? 1 : 2);
561 
562   assert(Node->getNumOperands() == Offset + 2 &&
563          "Unexpected number of operands");
564 
565   unsigned SEW =
566       RISCVVType::decodeVSEW(Node->getConstantOperandVal(Offset) & 0x7);
567   RISCVII::VLMUL VLMul = static_cast<RISCVII::VLMUL>(
568       Node->getConstantOperandVal(Offset + 1) & 0x7);
569 
570   unsigned VTypeI = RISCVVType::encodeVTYPE(VLMul, SEW, /*TailAgnostic*/ true,
571                                             /*MaskAgnostic*/ false);
572   SDValue VTypeIOp = CurDAG->getTargetConstant(VTypeI, DL, XLenVT);
573 
574   SmallVector<EVT, 2> VTs = {XLenVT};
575   if (HasChain)
576     VTs.push_back(MVT::Other);
577 
578   SDValue VLOperand;
579   unsigned Opcode = RISCV::PseudoVSETVLI;
580   if (VLMax) {
581     VLOperand = CurDAG->getRegister(RISCV::X0, XLenVT);
582     Opcode = RISCV::PseudoVSETVLIX0;
583   } else {
584     VLOperand = Node->getOperand(IntNoOffset + 1);
585 
586     if (auto *C = dyn_cast<ConstantSDNode>(VLOperand)) {
587       uint64_t AVL = C->getZExtValue();
588       if (isUInt<5>(AVL)) {
589         SDValue VLImm = CurDAG->getTargetConstant(AVL, DL, XLenVT);
590         SmallVector<SDValue, 3> Ops = {VLImm, VTypeIOp};
591         if (HasChain)
592           Ops.push_back(Node->getOperand(0));
593         ReplaceNode(
594             Node, CurDAG->getMachineNode(RISCV::PseudoVSETIVLI, DL, VTs, Ops));
595         return;
596       }
597     }
598   }
599 
600   SmallVector<SDValue, 3> Ops = {VLOperand, VTypeIOp};
601   if (HasChain)
602     Ops.push_back(Node->getOperand(0));
603 
604   ReplaceNode(Node, CurDAG->getMachineNode(Opcode, DL, VTs, Ops));
605 }
606 
607 void RISCVDAGToDAGISel::Select(SDNode *Node) {
608   // If we have a custom node, we have already selected.
609   if (Node->isMachineOpcode()) {
610     LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << "\n");
611     Node->setNodeId(-1);
612     return;
613   }
614 
615   // Instruction Selection not handled by the auto-generated tablegen selection
616   // should be handled here.
617   unsigned Opcode = Node->getOpcode();
618   MVT XLenVT = Subtarget->getXLenVT();
619   SDLoc DL(Node);
620   MVT VT = Node->getSimpleValueType(0);
621 
622   switch (Opcode) {
623   case ISD::Constant: {
624     auto *ConstNode = cast<ConstantSDNode>(Node);
625     if (VT == XLenVT && ConstNode->isZero()) {
626       SDValue New =
627           CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL, RISCV::X0, XLenVT);
628       ReplaceNode(Node, New.getNode());
629       return;
630     }
631     int64_t Imm = ConstNode->getSExtValue();
632     // If the upper XLen-16 bits are not used, try to convert this to a simm12
633     // by sign extending bit 15.
634     if (isUInt<16>(Imm) && isInt<12>(SignExtend64(Imm, 16)) &&
635         hasAllHUsers(Node))
636       Imm = SignExtend64(Imm, 16);
637     // If the upper 32-bits are not used try to convert this into a simm32 by
638     // sign extending bit 32.
639     if (!isInt<32>(Imm) && isUInt<32>(Imm) && hasAllWUsers(Node))
640       Imm = SignExtend64(Imm, 32);
641 
642     ReplaceNode(Node, selectImm(CurDAG, DL, VT, Imm, *Subtarget));
643     return;
644   }
645   case ISD::FrameIndex: {
646     SDValue Imm = CurDAG->getTargetConstant(0, DL, XLenVT);
647     int FI = cast<FrameIndexSDNode>(Node)->getIndex();
648     SDValue TFI = CurDAG->getTargetFrameIndex(FI, VT);
649     ReplaceNode(Node, CurDAG->getMachineNode(RISCV::ADDI, DL, VT, TFI, Imm));
650     return;
651   }
652   case ISD::SRL: {
653     // Optimize (srl (and X, C2), C) ->
654     //          (srli (slli X, (XLen-C3), (XLen-C3) + C)
655     // Where C2 is a mask with C3 trailing ones.
656     // Taking into account that the C2 may have had lower bits unset by
657     // SimplifyDemandedBits. This avoids materializing the C2 immediate.
658     // This pattern occurs when type legalizing right shifts for types with
659     // less than XLen bits.
660     auto *N1C = dyn_cast<ConstantSDNode>(Node->getOperand(1));
661     if (!N1C)
662       break;
663     SDValue N0 = Node->getOperand(0);
664     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse() ||
665         !isa<ConstantSDNode>(N0.getOperand(1)))
666       break;
667     unsigned ShAmt = N1C->getZExtValue();
668     uint64_t Mask = N0.getConstantOperandVal(1);
669     Mask |= maskTrailingOnes<uint64_t>(ShAmt);
670     if (!isMask_64(Mask))
671       break;
672     unsigned TrailingOnes = countTrailingOnes(Mask);
673     // 32 trailing ones should use srliw via tablegen pattern.
674     if (TrailingOnes == 32 || ShAmt >= TrailingOnes)
675       break;
676     unsigned LShAmt = Subtarget->getXLen() - TrailingOnes;
677     SDNode *SLLI =
678         CurDAG->getMachineNode(RISCV::SLLI, DL, VT, N0->getOperand(0),
679                                CurDAG->getTargetConstant(LShAmt, DL, VT));
680     SDNode *SRLI = CurDAG->getMachineNode(
681         RISCV::SRLI, DL, VT, SDValue(SLLI, 0),
682         CurDAG->getTargetConstant(LShAmt + ShAmt, DL, VT));
683     ReplaceNode(Node, SRLI);
684     return;
685   }
686   case ISD::SRA: {
687     // Optimize (sra (sext_inreg X, i16), C) ->
688     //          (srai (slli X, (XLen-16), (XLen-16) + C)
689     // And      (sra (sext_inreg X, i8), C) ->
690     //          (srai (slli X, (XLen-8), (XLen-8) + C)
691     // This can occur when Zbb is enabled, which makes sext_inreg i16/i8 legal.
692     // This transform matches the code we get without Zbb. The shifts are more
693     // compressible, and this can help expose CSE opportunities in the sdiv by
694     // constant optimization.
695     auto *N1C = dyn_cast<ConstantSDNode>(Node->getOperand(1));
696     if (!N1C)
697       break;
698     SDValue N0 = Node->getOperand(0);
699     if (N0.getOpcode() != ISD::SIGN_EXTEND_INREG || !N0.hasOneUse())
700       break;
701     unsigned ShAmt = N1C->getZExtValue();
702     unsigned ExtSize =
703         cast<VTSDNode>(N0.getOperand(1))->getVT().getSizeInBits();
704     // ExtSize of 32 should use sraiw via tablegen pattern.
705     if (ExtSize >= 32 || ShAmt >= ExtSize)
706       break;
707     unsigned LShAmt = Subtarget->getXLen() - ExtSize;
708     SDNode *SLLI =
709         CurDAG->getMachineNode(RISCV::SLLI, DL, VT, N0->getOperand(0),
710                                CurDAG->getTargetConstant(LShAmt, DL, VT));
711     SDNode *SRAI = CurDAG->getMachineNode(
712         RISCV::SRAI, DL, VT, SDValue(SLLI, 0),
713         CurDAG->getTargetConstant(LShAmt + ShAmt, DL, VT));
714     ReplaceNode(Node, SRAI);
715     return;
716   }
717   case ISD::AND: {
718     auto *N1C = dyn_cast<ConstantSDNode>(Node->getOperand(1));
719     if (!N1C)
720       break;
721 
722     SDValue N0 = Node->getOperand(0);
723 
724     bool LeftShift = N0.getOpcode() == ISD::SHL;
725     if (!LeftShift && N0.getOpcode() != ISD::SRL)
726       break;
727 
728     auto *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
729     if (!C)
730       break;
731     uint64_t C2 = C->getZExtValue();
732     unsigned XLen = Subtarget->getXLen();
733     if (!C2 || C2 >= XLen)
734       break;
735 
736     uint64_t C1 = N1C->getZExtValue();
737 
738     // Keep track of whether this is a c.andi. If we can't use c.andi, the
739     // shift pair might offer more compression opportunities.
740     // TODO: We could check for C extension here, but we don't have many lit
741     // tests with the C extension enabled so not checking gets better coverage.
742     // TODO: What if ANDI faster than shift?
743     bool IsCANDI = isInt<6>(N1C->getSExtValue());
744 
745     // Clear irrelevant bits in the mask.
746     if (LeftShift)
747       C1 &= maskTrailingZeros<uint64_t>(C2);
748     else
749       C1 &= maskTrailingOnes<uint64_t>(XLen - C2);
750 
751     // Some transforms should only be done if the shift has a single use or
752     // the AND would become (srli (slli X, 32), 32)
753     bool OneUseOrZExtW = N0.hasOneUse() || C1 == UINT64_C(0xFFFFFFFF);
754 
755     SDValue X = N0.getOperand(0);
756 
757     // Turn (and (srl x, c2) c1) -> (srli (slli x, c3-c2), c3) if c1 is a mask
758     // with c3 leading zeros.
759     if (!LeftShift && isMask_64(C1)) {
760       uint64_t C3 = XLen - (64 - countLeadingZeros(C1));
761       if (C2 < C3) {
762         // If the number of leading zeros is C2+32 this can be SRLIW.
763         if (C2 + 32 == C3) {
764           SDNode *SRLIW =
765               CurDAG->getMachineNode(RISCV::SRLIW, DL, XLenVT, X,
766                                      CurDAG->getTargetConstant(C2, DL, XLenVT));
767           ReplaceNode(Node, SRLIW);
768           return;
769         }
770 
771         // (and (srl (sexti32 Y), c2), c1) -> (srliw (sraiw Y, 31), c3 - 32) if
772         // c1 is a mask with c3 leading zeros and c2 >= 32 and c3-c2==1.
773         //
774         // This pattern occurs when (i32 (srl (sra 31), c3 - 32)) is type
775         // legalized and goes through DAG combine.
776         if (C2 >= 32 && (C3 - C2) == 1 && N0.hasOneUse() &&
777             X.getOpcode() == ISD::SIGN_EXTEND_INREG &&
778             cast<VTSDNode>(X.getOperand(1))->getVT() == MVT::i32) {
779           SDNode *SRAIW =
780               CurDAG->getMachineNode(RISCV::SRAIW, DL, XLenVT, X.getOperand(0),
781                                      CurDAG->getTargetConstant(31, DL, XLenVT));
782           SDNode *SRLIW = CurDAG->getMachineNode(
783               RISCV::SRLIW, DL, XLenVT, SDValue(SRAIW, 0),
784               CurDAG->getTargetConstant(C3 - 32, DL, XLenVT));
785           ReplaceNode(Node, SRLIW);
786           return;
787         }
788 
789         // (srli (slli x, c3-c2), c3).
790         // Skip if we could use (zext.w (sraiw X, C2)).
791         bool Skip = Subtarget->hasStdExtZba() && C3 == 32 &&
792                     X.getOpcode() == ISD::SIGN_EXTEND_INREG &&
793                     cast<VTSDNode>(X.getOperand(1))->getVT() == MVT::i32;
794         // Also Skip if we can use bexti.
795         Skip |= Subtarget->hasStdExtZbs() && C3 == XLen - 1;
796         if (OneUseOrZExtW && !Skip) {
797           SDNode *SLLI = CurDAG->getMachineNode(
798               RISCV::SLLI, DL, XLenVT, X,
799               CurDAG->getTargetConstant(C3 - C2, DL, XLenVT));
800           SDNode *SRLI =
801               CurDAG->getMachineNode(RISCV::SRLI, DL, XLenVT, SDValue(SLLI, 0),
802                                      CurDAG->getTargetConstant(C3, DL, XLenVT));
803           ReplaceNode(Node, SRLI);
804           return;
805         }
806       }
807     }
808 
809     // Turn (and (shl x, c2), c1) -> (srli (slli c2+c3), c3) if c1 is a mask
810     // shifted by c2 bits with c3 leading zeros.
811     if (LeftShift && isShiftedMask_64(C1)) {
812       uint64_t C3 = XLen - (64 - countLeadingZeros(C1));
813 
814       if (C2 + C3 < XLen &&
815           C1 == (maskTrailingOnes<uint64_t>(XLen - (C2 + C3)) << C2)) {
816         // Use slli.uw when possible.
817         if ((XLen - (C2 + C3)) == 32 && Subtarget->hasStdExtZba()) {
818           SDNode *SLLI_UW =
819               CurDAG->getMachineNode(RISCV::SLLI_UW, DL, XLenVT, X,
820                                      CurDAG->getTargetConstant(C2, DL, XLenVT));
821           ReplaceNode(Node, SLLI_UW);
822           return;
823         }
824 
825         // (srli (slli c2+c3), c3)
826         if (OneUseOrZExtW && !IsCANDI) {
827           SDNode *SLLI = CurDAG->getMachineNode(
828               RISCV::SLLI, DL, XLenVT, X,
829               CurDAG->getTargetConstant(C2 + C3, DL, XLenVT));
830           SDNode *SRLI =
831               CurDAG->getMachineNode(RISCV::SRLI, DL, XLenVT, SDValue(SLLI, 0),
832                                      CurDAG->getTargetConstant(C3, DL, XLenVT));
833           ReplaceNode(Node, SRLI);
834           return;
835         }
836       }
837     }
838 
839     // Turn (and (shr x, c2), c1) -> (slli (srli x, c2+c3), c3) if c1 is a
840     // shifted mask with c2 leading zeros and c3 trailing zeros.
841     if (!LeftShift && isShiftedMask_64(C1)) {
842       uint64_t Leading = XLen - (64 - countLeadingZeros(C1));
843       uint64_t C3 = countTrailingZeros(C1);
844       if (Leading == C2 && C2 + C3 < XLen && OneUseOrZExtW && !IsCANDI) {
845         unsigned SrliOpc = RISCV::SRLI;
846         // If the input is zexti32 we should use SRLIW.
847         if (X.getOpcode() == ISD::AND && isa<ConstantSDNode>(X.getOperand(1)) &&
848             X.getConstantOperandVal(1) == UINT64_C(0xFFFFFFFF)) {
849           SrliOpc = RISCV::SRLIW;
850           X = X.getOperand(0);
851         }
852         SDNode *SRLI = CurDAG->getMachineNode(
853             SrliOpc, DL, XLenVT, X,
854             CurDAG->getTargetConstant(C2 + C3, DL, XLenVT));
855         SDNode *SLLI =
856             CurDAG->getMachineNode(RISCV::SLLI, DL, XLenVT, SDValue(SRLI, 0),
857                                    CurDAG->getTargetConstant(C3, DL, XLenVT));
858         ReplaceNode(Node, SLLI);
859         return;
860       }
861       // If the leading zero count is C2+32, we can use SRLIW instead of SRLI.
862       if (Leading > 32 && (Leading - 32) == C2 && C2 + C3 < 32 &&
863           OneUseOrZExtW && !IsCANDI) {
864         SDNode *SRLIW = CurDAG->getMachineNode(
865             RISCV::SRLIW, DL, XLenVT, X,
866             CurDAG->getTargetConstant(C2 + C3, DL, XLenVT));
867         SDNode *SLLI =
868             CurDAG->getMachineNode(RISCV::SLLI, DL, XLenVT, SDValue(SRLIW, 0),
869                                    CurDAG->getTargetConstant(C3, DL, XLenVT));
870         ReplaceNode(Node, SLLI);
871         return;
872       }
873     }
874 
875     // Turn (and (shl x, c2), c1) -> (slli (srli x, c3-c2), c3) if c1 is a
876     // shifted mask with no leading zeros and c3 trailing zeros.
877     if (LeftShift && isShiftedMask_64(C1)) {
878       uint64_t Leading = XLen - (64 - countLeadingZeros(C1));
879       uint64_t C3 = countTrailingZeros(C1);
880       if (Leading == 0 && C2 < C3 && OneUseOrZExtW && !IsCANDI) {
881         SDNode *SRLI = CurDAG->getMachineNode(
882             RISCV::SRLI, DL, XLenVT, X,
883             CurDAG->getTargetConstant(C3 - C2, DL, XLenVT));
884         SDNode *SLLI =
885             CurDAG->getMachineNode(RISCV::SLLI, DL, XLenVT, SDValue(SRLI, 0),
886                                    CurDAG->getTargetConstant(C3, DL, XLenVT));
887         ReplaceNode(Node, SLLI);
888         return;
889       }
890       // If we have (32-C2) leading zeros, we can use SRLIW instead of SRLI.
891       if (C2 < C3 && Leading + C2 == 32 && OneUseOrZExtW && !IsCANDI) {
892         SDNode *SRLIW = CurDAG->getMachineNode(
893             RISCV::SRLIW, DL, XLenVT, X,
894             CurDAG->getTargetConstant(C3 - C2, DL, XLenVT));
895         SDNode *SLLI =
896             CurDAG->getMachineNode(RISCV::SLLI, DL, XLenVT, SDValue(SRLIW, 0),
897                                    CurDAG->getTargetConstant(C3, DL, XLenVT));
898         ReplaceNode(Node, SLLI);
899         return;
900       }
901     }
902 
903     break;
904   }
905   case ISD::MUL: {
906     // Special case for calculating (mul (and X, C2), C1) where the full product
907     // fits in XLen bits. We can shift X left by the number of leading zeros in
908     // C2 and shift C1 left by XLen-lzcnt(C2). This will ensure the final
909     // product has XLen trailing zeros, putting it in the output of MULHU. This
910     // can avoid materializing a constant in a register for C2.
911 
912     // RHS should be a constant.
913     auto *N1C = dyn_cast<ConstantSDNode>(Node->getOperand(1));
914     if (!N1C || !N1C->hasOneUse())
915       break;
916 
917     // LHS should be an AND with constant.
918     SDValue N0 = Node->getOperand(0);
919     if (N0.getOpcode() != ISD::AND || !isa<ConstantSDNode>(N0.getOperand(1)))
920       break;
921 
922     uint64_t C2 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
923 
924     // Constant should be a mask.
925     if (!isMask_64(C2))
926       break;
927 
928     // This should be the only use of the AND unless we will use
929     // (SRLI (SLLI X, 32), 32). We don't use a shift pair for other AND
930     // constants.
931     if (!N0.hasOneUse() && C2 != UINT64_C(0xFFFFFFFF))
932       break;
933 
934     // If this can be an ANDI, ZEXT.H or ZEXT.W we don't need to do this
935     // optimization.
936     if (isInt<12>(C2) ||
937         (C2 == UINT64_C(0xFFFF) &&
938          (Subtarget->hasStdExtZbb() || Subtarget->hasStdExtZbp())) ||
939         (C2 == UINT64_C(0xFFFFFFFF) && Subtarget->hasStdExtZba()))
940       break;
941 
942     // We need to shift left the AND input and C1 by a total of XLen bits.
943 
944     // How far left do we need to shift the AND input?
945     unsigned XLen = Subtarget->getXLen();
946     unsigned LeadingZeros = XLen - (64 - countLeadingZeros(C2));
947 
948     // The constant gets shifted by the remaining amount unless that would
949     // shift bits out.
950     uint64_t C1 = N1C->getZExtValue();
951     unsigned ConstantShift = XLen - LeadingZeros;
952     if (ConstantShift > (XLen - (64 - countLeadingZeros(C1))))
953       break;
954 
955     uint64_t ShiftedC1 = C1 << ConstantShift;
956     // If this RV32, we need to sign extend the constant.
957     if (XLen == 32)
958       ShiftedC1 = SignExtend64(ShiftedC1, 32);
959 
960     // Create (mulhu (slli X, lzcnt(C2)), C1 << (XLen - lzcnt(C2))).
961     SDNode *Imm = selectImm(CurDAG, DL, VT, ShiftedC1, *Subtarget);
962     SDNode *SLLI =
963         CurDAG->getMachineNode(RISCV::SLLI, DL, VT, N0.getOperand(0),
964                                CurDAG->getTargetConstant(LeadingZeros, DL, VT));
965     SDNode *MULHU = CurDAG->getMachineNode(RISCV::MULHU, DL, VT,
966                                            SDValue(SLLI, 0), SDValue(Imm, 0));
967     ReplaceNode(Node, MULHU);
968     return;
969   }
970   case ISD::INTRINSIC_WO_CHAIN: {
971     unsigned IntNo = Node->getConstantOperandVal(0);
972     switch (IntNo) {
973       // By default we do not custom select any intrinsic.
974     default:
975       break;
976     case Intrinsic::riscv_vmsgeu:
977     case Intrinsic::riscv_vmsge: {
978       SDValue Src1 = Node->getOperand(1);
979       SDValue Src2 = Node->getOperand(2);
980       bool IsUnsigned = IntNo == Intrinsic::riscv_vmsgeu;
981       bool IsCmpUnsignedZero = false;
982       // Only custom select scalar second operand.
983       if (Src2.getValueType() != XLenVT)
984         break;
985       // Small constants are handled with patterns.
986       if (auto *C = dyn_cast<ConstantSDNode>(Src2)) {
987         int64_t CVal = C->getSExtValue();
988         if (CVal >= -15 && CVal <= 16) {
989           if (!IsUnsigned || CVal != 0)
990             break;
991           IsCmpUnsignedZero = true;
992         }
993       }
994       MVT Src1VT = Src1.getSimpleValueType();
995       unsigned VMSLTOpcode, VMNANDOpcode, VMSetOpcode;
996       switch (RISCVTargetLowering::getLMUL(Src1VT)) {
997       default:
998         llvm_unreachable("Unexpected LMUL!");
999 #define CASE_VMSLT_VMNAND_VMSET_OPCODES(lmulenum, suffix, suffix_b)            \
1000   case RISCVII::VLMUL::lmulenum:                                               \
1001     VMSLTOpcode = IsUnsigned ? RISCV::PseudoVMSLTU_VX_##suffix                 \
1002                              : RISCV::PseudoVMSLT_VX_##suffix;                 \
1003     VMNANDOpcode = RISCV::PseudoVMNAND_MM_##suffix;                            \
1004     VMSetOpcode = RISCV::PseudoVMSET_M_##suffix_b;                             \
1005     break;
1006         CASE_VMSLT_VMNAND_VMSET_OPCODES(LMUL_F8, MF8, B1)
1007         CASE_VMSLT_VMNAND_VMSET_OPCODES(LMUL_F4, MF4, B2)
1008         CASE_VMSLT_VMNAND_VMSET_OPCODES(LMUL_F2, MF2, B4)
1009         CASE_VMSLT_VMNAND_VMSET_OPCODES(LMUL_1, M1, B8)
1010         CASE_VMSLT_VMNAND_VMSET_OPCODES(LMUL_2, M2, B16)
1011         CASE_VMSLT_VMNAND_VMSET_OPCODES(LMUL_4, M4, B32)
1012         CASE_VMSLT_VMNAND_VMSET_OPCODES(LMUL_8, M8, B64)
1013 #undef CASE_VMSLT_VMNAND_VMSET_OPCODES
1014       }
1015       SDValue SEW = CurDAG->getTargetConstant(
1016           Log2_32(Src1VT.getScalarSizeInBits()), DL, XLenVT);
1017       SDValue VL;
1018       selectVLOp(Node->getOperand(3), VL);
1019 
1020       // If vmsgeu with 0 immediate, expand it to vmset.
1021       if (IsCmpUnsignedZero) {
1022         ReplaceNode(Node, CurDAG->getMachineNode(VMSetOpcode, DL, VT, VL, SEW));
1023         return;
1024       }
1025 
1026       // Expand to
1027       // vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
1028       SDValue Cmp = SDValue(
1029           CurDAG->getMachineNode(VMSLTOpcode, DL, VT, {Src1, Src2, VL, SEW}),
1030           0);
1031       ReplaceNode(Node, CurDAG->getMachineNode(VMNANDOpcode, DL, VT,
1032                                                {Cmp, Cmp, VL, SEW}));
1033       return;
1034     }
1035     case Intrinsic::riscv_vmsgeu_mask:
1036     case Intrinsic::riscv_vmsge_mask: {
1037       SDValue Src1 = Node->getOperand(2);
1038       SDValue Src2 = Node->getOperand(3);
1039       bool IsUnsigned = IntNo == Intrinsic::riscv_vmsgeu_mask;
1040       bool IsCmpUnsignedZero = false;
1041       // Only custom select scalar second operand.
1042       if (Src2.getValueType() != XLenVT)
1043         break;
1044       // Small constants are handled with patterns.
1045       if (auto *C = dyn_cast<ConstantSDNode>(Src2)) {
1046         int64_t CVal = C->getSExtValue();
1047         if (CVal >= -15 && CVal <= 16) {
1048           if (!IsUnsigned || CVal != 0)
1049             break;
1050           IsCmpUnsignedZero = true;
1051         }
1052       }
1053       MVT Src1VT = Src1.getSimpleValueType();
1054       unsigned VMSLTOpcode, VMSLTMaskOpcode, VMXOROpcode, VMANDNOpcode,
1055           VMOROpcode;
1056       switch (RISCVTargetLowering::getLMUL(Src1VT)) {
1057       default:
1058         llvm_unreachable("Unexpected LMUL!");
1059 #define CASE_VMSLT_OPCODES(lmulenum, suffix, suffix_b)                         \
1060   case RISCVII::VLMUL::lmulenum:                                               \
1061     VMSLTOpcode = IsUnsigned ? RISCV::PseudoVMSLTU_VX_##suffix                 \
1062                              : RISCV::PseudoVMSLT_VX_##suffix;                 \
1063     VMSLTMaskOpcode = IsUnsigned ? RISCV::PseudoVMSLTU_VX_##suffix##_MASK      \
1064                                  : RISCV::PseudoVMSLT_VX_##suffix##_MASK;      \
1065     break;
1066         CASE_VMSLT_OPCODES(LMUL_F8, MF8, B1)
1067         CASE_VMSLT_OPCODES(LMUL_F4, MF4, B2)
1068         CASE_VMSLT_OPCODES(LMUL_F2, MF2, B4)
1069         CASE_VMSLT_OPCODES(LMUL_1, M1, B8)
1070         CASE_VMSLT_OPCODES(LMUL_2, M2, B16)
1071         CASE_VMSLT_OPCODES(LMUL_4, M4, B32)
1072         CASE_VMSLT_OPCODES(LMUL_8, M8, B64)
1073 #undef CASE_VMSLT_OPCODES
1074       }
1075       // Mask operations use the LMUL from the mask type.
1076       switch (RISCVTargetLowering::getLMUL(VT)) {
1077       default:
1078         llvm_unreachable("Unexpected LMUL!");
1079 #define CASE_VMXOR_VMANDN_VMOR_OPCODES(lmulenum, suffix)                       \
1080   case RISCVII::VLMUL::lmulenum:                                               \
1081     VMXOROpcode = RISCV::PseudoVMXOR_MM_##suffix;                              \
1082     VMANDNOpcode = RISCV::PseudoVMANDN_MM_##suffix;                            \
1083     VMOROpcode = RISCV::PseudoVMOR_MM_##suffix;                                \
1084     break;
1085         CASE_VMXOR_VMANDN_VMOR_OPCODES(LMUL_F8, MF8)
1086         CASE_VMXOR_VMANDN_VMOR_OPCODES(LMUL_F4, MF4)
1087         CASE_VMXOR_VMANDN_VMOR_OPCODES(LMUL_F2, MF2)
1088         CASE_VMXOR_VMANDN_VMOR_OPCODES(LMUL_1, M1)
1089         CASE_VMXOR_VMANDN_VMOR_OPCODES(LMUL_2, M2)
1090         CASE_VMXOR_VMANDN_VMOR_OPCODES(LMUL_4, M4)
1091         CASE_VMXOR_VMANDN_VMOR_OPCODES(LMUL_8, M8)
1092 #undef CASE_VMXOR_VMANDN_VMOR_OPCODES
1093       }
1094       SDValue SEW = CurDAG->getTargetConstant(
1095           Log2_32(Src1VT.getScalarSizeInBits()), DL, XLenVT);
1096       SDValue MaskSEW = CurDAG->getTargetConstant(0, DL, XLenVT);
1097       SDValue VL;
1098       selectVLOp(Node->getOperand(5), VL);
1099       SDValue MaskedOff = Node->getOperand(1);
1100       SDValue Mask = Node->getOperand(4);
1101 
1102       // If vmsgeu_mask with 0 immediate, expand it to vmor mask, maskedoff.
1103       if (IsCmpUnsignedZero) {
1104         // We don't need vmor if the MaskedOff and the Mask are the same
1105         // value.
1106         if (Mask == MaskedOff) {
1107           ReplaceUses(Node, Mask.getNode());
1108           return;
1109         }
1110         ReplaceNode(Node,
1111                     CurDAG->getMachineNode(VMOROpcode, DL, VT,
1112                                            {Mask, MaskedOff, VL, MaskSEW}));
1113         return;
1114       }
1115 
1116       // If the MaskedOff value and the Mask are the same value use
1117       // vmslt{u}.vx vt, va, x;  vmandn.mm vd, vd, vt
1118       // This avoids needing to copy v0 to vd before starting the next sequence.
1119       if (Mask == MaskedOff) {
1120         SDValue Cmp = SDValue(
1121             CurDAG->getMachineNode(VMSLTOpcode, DL, VT, {Src1, Src2, VL, SEW}),
1122             0);
1123         ReplaceNode(Node, CurDAG->getMachineNode(VMANDNOpcode, DL, VT,
1124                                                  {Mask, Cmp, VL, MaskSEW}));
1125         return;
1126       }
1127 
1128       // Mask needs to be copied to V0.
1129       SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), DL,
1130                                            RISCV::V0, Mask, SDValue());
1131       SDValue Glue = Chain.getValue(1);
1132       SDValue V0 = CurDAG->getRegister(RISCV::V0, VT);
1133 
1134       // Otherwise use
1135       // vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
1136       // The result is mask undisturbed.
1137       // We use the same instructions to emulate mask agnostic behavior, because
1138       // the agnostic result can be either undisturbed or all 1.
1139       SDValue Cmp = SDValue(
1140           CurDAG->getMachineNode(VMSLTMaskOpcode, DL, VT,
1141                                  {MaskedOff, Src1, Src2, V0, VL, SEW, Glue}),
1142           0);
1143       // vmxor.mm vd, vd, v0 is used to update active value.
1144       ReplaceNode(Node, CurDAG->getMachineNode(VMXOROpcode, DL, VT,
1145                                                {Cmp, Mask, VL, MaskSEW}));
1146       return;
1147     }
1148     case Intrinsic::riscv_vsetvli_opt:
1149     case Intrinsic::riscv_vsetvlimax_opt:
1150       return selectVSETVLI(Node);
1151     }
1152     break;
1153   }
1154   case ISD::INTRINSIC_W_CHAIN: {
1155     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
1156     switch (IntNo) {
1157       // By default we do not custom select any intrinsic.
1158     default:
1159       break;
1160     case Intrinsic::riscv_vsetvli:
1161     case Intrinsic::riscv_vsetvlimax:
1162       return selectVSETVLI(Node);
1163     case Intrinsic::riscv_vlseg2:
1164     case Intrinsic::riscv_vlseg3:
1165     case Intrinsic::riscv_vlseg4:
1166     case Intrinsic::riscv_vlseg5:
1167     case Intrinsic::riscv_vlseg6:
1168     case Intrinsic::riscv_vlseg7:
1169     case Intrinsic::riscv_vlseg8: {
1170       selectVLSEG(Node, /*IsMasked*/ false, /*IsStrided*/ false);
1171       return;
1172     }
1173     case Intrinsic::riscv_vlseg2_mask:
1174     case Intrinsic::riscv_vlseg3_mask:
1175     case Intrinsic::riscv_vlseg4_mask:
1176     case Intrinsic::riscv_vlseg5_mask:
1177     case Intrinsic::riscv_vlseg6_mask:
1178     case Intrinsic::riscv_vlseg7_mask:
1179     case Intrinsic::riscv_vlseg8_mask: {
1180       selectVLSEG(Node, /*IsMasked*/ true, /*IsStrided*/ false);
1181       return;
1182     }
1183     case Intrinsic::riscv_vlsseg2:
1184     case Intrinsic::riscv_vlsseg3:
1185     case Intrinsic::riscv_vlsseg4:
1186     case Intrinsic::riscv_vlsseg5:
1187     case Intrinsic::riscv_vlsseg6:
1188     case Intrinsic::riscv_vlsseg7:
1189     case Intrinsic::riscv_vlsseg8: {
1190       selectVLSEG(Node, /*IsMasked*/ false, /*IsStrided*/ true);
1191       return;
1192     }
1193     case Intrinsic::riscv_vlsseg2_mask:
1194     case Intrinsic::riscv_vlsseg3_mask:
1195     case Intrinsic::riscv_vlsseg4_mask:
1196     case Intrinsic::riscv_vlsseg5_mask:
1197     case Intrinsic::riscv_vlsseg6_mask:
1198     case Intrinsic::riscv_vlsseg7_mask:
1199     case Intrinsic::riscv_vlsseg8_mask: {
1200       selectVLSEG(Node, /*IsMasked*/ true, /*IsStrided*/ true);
1201       return;
1202     }
1203     case Intrinsic::riscv_vloxseg2:
1204     case Intrinsic::riscv_vloxseg3:
1205     case Intrinsic::riscv_vloxseg4:
1206     case Intrinsic::riscv_vloxseg5:
1207     case Intrinsic::riscv_vloxseg6:
1208     case Intrinsic::riscv_vloxseg7:
1209     case Intrinsic::riscv_vloxseg8:
1210       selectVLXSEG(Node, /*IsMasked*/ false, /*IsOrdered*/ true);
1211       return;
1212     case Intrinsic::riscv_vluxseg2:
1213     case Intrinsic::riscv_vluxseg3:
1214     case Intrinsic::riscv_vluxseg4:
1215     case Intrinsic::riscv_vluxseg5:
1216     case Intrinsic::riscv_vluxseg6:
1217     case Intrinsic::riscv_vluxseg7:
1218     case Intrinsic::riscv_vluxseg8:
1219       selectVLXSEG(Node, /*IsMasked*/ false, /*IsOrdered*/ false);
1220       return;
1221     case Intrinsic::riscv_vloxseg2_mask:
1222     case Intrinsic::riscv_vloxseg3_mask:
1223     case Intrinsic::riscv_vloxseg4_mask:
1224     case Intrinsic::riscv_vloxseg5_mask:
1225     case Intrinsic::riscv_vloxseg6_mask:
1226     case Intrinsic::riscv_vloxseg7_mask:
1227     case Intrinsic::riscv_vloxseg8_mask:
1228       selectVLXSEG(Node, /*IsMasked*/ true, /*IsOrdered*/ true);
1229       return;
1230     case Intrinsic::riscv_vluxseg2_mask:
1231     case Intrinsic::riscv_vluxseg3_mask:
1232     case Intrinsic::riscv_vluxseg4_mask:
1233     case Intrinsic::riscv_vluxseg5_mask:
1234     case Intrinsic::riscv_vluxseg6_mask:
1235     case Intrinsic::riscv_vluxseg7_mask:
1236     case Intrinsic::riscv_vluxseg8_mask:
1237       selectVLXSEG(Node, /*IsMasked*/ true, /*IsOrdered*/ false);
1238       return;
1239     case Intrinsic::riscv_vlseg8ff:
1240     case Intrinsic::riscv_vlseg7ff:
1241     case Intrinsic::riscv_vlseg6ff:
1242     case Intrinsic::riscv_vlseg5ff:
1243     case Intrinsic::riscv_vlseg4ff:
1244     case Intrinsic::riscv_vlseg3ff:
1245     case Intrinsic::riscv_vlseg2ff: {
1246       selectVLSEGFF(Node, /*IsMasked*/ false);
1247       return;
1248     }
1249     case Intrinsic::riscv_vlseg8ff_mask:
1250     case Intrinsic::riscv_vlseg7ff_mask:
1251     case Intrinsic::riscv_vlseg6ff_mask:
1252     case Intrinsic::riscv_vlseg5ff_mask:
1253     case Intrinsic::riscv_vlseg4ff_mask:
1254     case Intrinsic::riscv_vlseg3ff_mask:
1255     case Intrinsic::riscv_vlseg2ff_mask: {
1256       selectVLSEGFF(Node, /*IsMasked*/ true);
1257       return;
1258     }
1259     case Intrinsic::riscv_vloxei:
1260     case Intrinsic::riscv_vloxei_mask:
1261     case Intrinsic::riscv_vluxei:
1262     case Intrinsic::riscv_vluxei_mask: {
1263       bool IsMasked = IntNo == Intrinsic::riscv_vloxei_mask ||
1264                       IntNo == Intrinsic::riscv_vluxei_mask;
1265       bool IsOrdered = IntNo == Intrinsic::riscv_vloxei ||
1266                        IntNo == Intrinsic::riscv_vloxei_mask;
1267 
1268       MVT VT = Node->getSimpleValueType(0);
1269       unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
1270 
1271       unsigned CurOp = 2;
1272       // Masked intrinsic only have TU version pseduo instructions.
1273       bool IsTU = IsMasked || (!IsMasked && !Node->getOperand(CurOp).isUndef());
1274       SmallVector<SDValue, 8> Operands;
1275       if (IsTU)
1276         Operands.push_back(Node->getOperand(CurOp++));
1277       else
1278         // Skip the undef passthru operand for nomask TA version pseudo
1279         CurOp++;
1280 
1281       MVT IndexVT;
1282       addVectorLoadStoreOperands(Node, Log2SEW, DL, CurOp, IsMasked,
1283                                  /*IsStridedOrIndexed*/ true, Operands,
1284                                  /*IsLoad=*/true, &IndexVT);
1285 
1286       assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
1287              "Element count mismatch");
1288 
1289       RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
1290       RISCVII::VLMUL IndexLMUL = RISCVTargetLowering::getLMUL(IndexVT);
1291       unsigned IndexLog2EEW = Log2_32(IndexVT.getScalarSizeInBits());
1292       if (IndexLog2EEW == 6 && !Subtarget->is64Bit()) {
1293         report_fatal_error("The V extension does not support EEW=64 for index "
1294                            "values when XLEN=32");
1295       }
1296       const RISCV::VLX_VSXPseudo *P = RISCV::getVLXPseudo(
1297           IsMasked, IsTU, IsOrdered, IndexLog2EEW, static_cast<unsigned>(LMUL),
1298           static_cast<unsigned>(IndexLMUL));
1299       MachineSDNode *Load =
1300           CurDAG->getMachineNode(P->Pseudo, DL, Node->getVTList(), Operands);
1301 
1302       if (auto *MemOp = dyn_cast<MemSDNode>(Node))
1303         CurDAG->setNodeMemRefs(Load, {MemOp->getMemOperand()});
1304 
1305       ReplaceNode(Node, Load);
1306       return;
1307     }
1308     case Intrinsic::riscv_vlm:
1309     case Intrinsic::riscv_vle:
1310     case Intrinsic::riscv_vle_mask:
1311     case Intrinsic::riscv_vlse:
1312     case Intrinsic::riscv_vlse_mask: {
1313       bool IsMasked = IntNo == Intrinsic::riscv_vle_mask ||
1314                       IntNo == Intrinsic::riscv_vlse_mask;
1315       bool IsStrided =
1316           IntNo == Intrinsic::riscv_vlse || IntNo == Intrinsic::riscv_vlse_mask;
1317 
1318       MVT VT = Node->getSimpleValueType(0);
1319       unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
1320 
1321       unsigned CurOp = 2;
1322       // The riscv_vlm intrinsic are always tail agnostic and no passthru operand.
1323       bool HasPassthruOperand = IntNo != Intrinsic::riscv_vlm;
1324       // Masked intrinsic only have TU version pseduo instructions.
1325       bool IsTU =
1326           HasPassthruOperand &&
1327           ((!IsMasked && !Node->getOperand(CurOp).isUndef()) || IsMasked);
1328       SmallVector<SDValue, 8> Operands;
1329       if (IsTU)
1330         Operands.push_back(Node->getOperand(CurOp++));
1331       else if (HasPassthruOperand)
1332         // Skip the undef passthru operand for nomask TA version pseudo
1333         CurOp++;
1334 
1335       addVectorLoadStoreOperands(Node, Log2SEW, DL, CurOp, IsMasked, IsStrided,
1336                                  Operands, /*IsLoad=*/true);
1337 
1338       RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
1339       const RISCV::VLEPseudo *P =
1340           RISCV::getVLEPseudo(IsMasked, IsTU, IsStrided, /*FF*/ false, Log2SEW,
1341                               static_cast<unsigned>(LMUL));
1342       MachineSDNode *Load =
1343           CurDAG->getMachineNode(P->Pseudo, DL, Node->getVTList(), Operands);
1344 
1345       if (auto *MemOp = dyn_cast<MemSDNode>(Node))
1346         CurDAG->setNodeMemRefs(Load, {MemOp->getMemOperand()});
1347 
1348       ReplaceNode(Node, Load);
1349       return;
1350     }
1351     case Intrinsic::riscv_vleff:
1352     case Intrinsic::riscv_vleff_mask: {
1353       bool IsMasked = IntNo == Intrinsic::riscv_vleff_mask;
1354 
1355       MVT VT = Node->getSimpleValueType(0);
1356       unsigned SEW = VT.getScalarSizeInBits();
1357       unsigned Log2SEW = Log2_32(SEW);
1358 
1359       unsigned CurOp = 2;
1360       // Masked intrinsic only have TU version pseduo instructions.
1361       bool IsTU = IsMasked || (!IsMasked && !Node->getOperand(CurOp).isUndef());
1362       SmallVector<SDValue, 7> Operands;
1363       if (IsTU)
1364         Operands.push_back(Node->getOperand(CurOp++));
1365       else
1366         // Skip the undef passthru operand for nomask TA version pseudo
1367         CurOp++;
1368 
1369       addVectorLoadStoreOperands(Node, Log2SEW, DL, CurOp, IsMasked,
1370                                  /*IsStridedOrIndexed*/ false, Operands,
1371                                  /*IsLoad=*/true);
1372 
1373       RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
1374       const RISCV::VLEPseudo *P =
1375           RISCV::getVLEPseudo(IsMasked, IsTU, /*Strided*/ false, /*FF*/ true,
1376                               Log2SEW, static_cast<unsigned>(LMUL));
1377       MachineSDNode *Load =
1378           CurDAG->getMachineNode(P->Pseudo, DL, Node->getValueType(0),
1379                                  MVT::Other, MVT::Glue, Operands);
1380       bool TailAgnostic = !IsTU;
1381       bool MaskAgnostic = false;
1382       if (IsMasked) {
1383         uint64_t Policy =
1384             Node->getConstantOperandVal(Node->getNumOperands() - 1);
1385         TailAgnostic = Policy & RISCVII::TAIL_AGNOSTIC;
1386         MaskAgnostic = Policy & RISCVII::MASK_AGNOSTIC;
1387       }
1388       unsigned VType =
1389           RISCVVType::encodeVTYPE(LMUL, SEW, TailAgnostic, MaskAgnostic);
1390       SDValue VTypeOp = CurDAG->getTargetConstant(VType, DL, XLenVT);
1391       SDNode *ReadVL =
1392           CurDAG->getMachineNode(RISCV::PseudoReadVL, DL, XLenVT, VTypeOp,
1393                                  /*Glue*/ SDValue(Load, 2));
1394 
1395       if (auto *MemOp = dyn_cast<MemSDNode>(Node))
1396         CurDAG->setNodeMemRefs(Load, {MemOp->getMemOperand()});
1397 
1398       ReplaceUses(SDValue(Node, 0), SDValue(Load, 0));
1399       ReplaceUses(SDValue(Node, 1), SDValue(ReadVL, 0)); // VL
1400       ReplaceUses(SDValue(Node, 2), SDValue(Load, 1));   // Chain
1401       CurDAG->RemoveDeadNode(Node);
1402       return;
1403     }
1404     }
1405     break;
1406   }
1407   case ISD::INTRINSIC_VOID: {
1408     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
1409     switch (IntNo) {
1410     case Intrinsic::riscv_vsseg2:
1411     case Intrinsic::riscv_vsseg3:
1412     case Intrinsic::riscv_vsseg4:
1413     case Intrinsic::riscv_vsseg5:
1414     case Intrinsic::riscv_vsseg6:
1415     case Intrinsic::riscv_vsseg7:
1416     case Intrinsic::riscv_vsseg8: {
1417       selectVSSEG(Node, /*IsMasked*/ false, /*IsStrided*/ false);
1418       return;
1419     }
1420     case Intrinsic::riscv_vsseg2_mask:
1421     case Intrinsic::riscv_vsseg3_mask:
1422     case Intrinsic::riscv_vsseg4_mask:
1423     case Intrinsic::riscv_vsseg5_mask:
1424     case Intrinsic::riscv_vsseg6_mask:
1425     case Intrinsic::riscv_vsseg7_mask:
1426     case Intrinsic::riscv_vsseg8_mask: {
1427       selectVSSEG(Node, /*IsMasked*/ true, /*IsStrided*/ false);
1428       return;
1429     }
1430     case Intrinsic::riscv_vssseg2:
1431     case Intrinsic::riscv_vssseg3:
1432     case Intrinsic::riscv_vssseg4:
1433     case Intrinsic::riscv_vssseg5:
1434     case Intrinsic::riscv_vssseg6:
1435     case Intrinsic::riscv_vssseg7:
1436     case Intrinsic::riscv_vssseg8: {
1437       selectVSSEG(Node, /*IsMasked*/ false, /*IsStrided*/ true);
1438       return;
1439     }
1440     case Intrinsic::riscv_vssseg2_mask:
1441     case Intrinsic::riscv_vssseg3_mask:
1442     case Intrinsic::riscv_vssseg4_mask:
1443     case Intrinsic::riscv_vssseg5_mask:
1444     case Intrinsic::riscv_vssseg6_mask:
1445     case Intrinsic::riscv_vssseg7_mask:
1446     case Intrinsic::riscv_vssseg8_mask: {
1447       selectVSSEG(Node, /*IsMasked*/ true, /*IsStrided*/ true);
1448       return;
1449     }
1450     case Intrinsic::riscv_vsoxseg2:
1451     case Intrinsic::riscv_vsoxseg3:
1452     case Intrinsic::riscv_vsoxseg4:
1453     case Intrinsic::riscv_vsoxseg5:
1454     case Intrinsic::riscv_vsoxseg6:
1455     case Intrinsic::riscv_vsoxseg7:
1456     case Intrinsic::riscv_vsoxseg8:
1457       selectVSXSEG(Node, /*IsMasked*/ false, /*IsOrdered*/ true);
1458       return;
1459     case Intrinsic::riscv_vsuxseg2:
1460     case Intrinsic::riscv_vsuxseg3:
1461     case Intrinsic::riscv_vsuxseg4:
1462     case Intrinsic::riscv_vsuxseg5:
1463     case Intrinsic::riscv_vsuxseg6:
1464     case Intrinsic::riscv_vsuxseg7:
1465     case Intrinsic::riscv_vsuxseg8:
1466       selectVSXSEG(Node, /*IsMasked*/ false, /*IsOrdered*/ false);
1467       return;
1468     case Intrinsic::riscv_vsoxseg2_mask:
1469     case Intrinsic::riscv_vsoxseg3_mask:
1470     case Intrinsic::riscv_vsoxseg4_mask:
1471     case Intrinsic::riscv_vsoxseg5_mask:
1472     case Intrinsic::riscv_vsoxseg6_mask:
1473     case Intrinsic::riscv_vsoxseg7_mask:
1474     case Intrinsic::riscv_vsoxseg8_mask:
1475       selectVSXSEG(Node, /*IsMasked*/ true, /*IsOrdered*/ true);
1476       return;
1477     case Intrinsic::riscv_vsuxseg2_mask:
1478     case Intrinsic::riscv_vsuxseg3_mask:
1479     case Intrinsic::riscv_vsuxseg4_mask:
1480     case Intrinsic::riscv_vsuxseg5_mask:
1481     case Intrinsic::riscv_vsuxseg6_mask:
1482     case Intrinsic::riscv_vsuxseg7_mask:
1483     case Intrinsic::riscv_vsuxseg8_mask:
1484       selectVSXSEG(Node, /*IsMasked*/ true, /*IsOrdered*/ false);
1485       return;
1486     case Intrinsic::riscv_vsoxei:
1487     case Intrinsic::riscv_vsoxei_mask:
1488     case Intrinsic::riscv_vsuxei:
1489     case Intrinsic::riscv_vsuxei_mask: {
1490       bool IsMasked = IntNo == Intrinsic::riscv_vsoxei_mask ||
1491                       IntNo == Intrinsic::riscv_vsuxei_mask;
1492       bool IsOrdered = IntNo == Intrinsic::riscv_vsoxei ||
1493                        IntNo == Intrinsic::riscv_vsoxei_mask;
1494 
1495       MVT VT = Node->getOperand(2)->getSimpleValueType(0);
1496       unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
1497 
1498       unsigned CurOp = 2;
1499       SmallVector<SDValue, 8> Operands;
1500       Operands.push_back(Node->getOperand(CurOp++)); // Store value.
1501 
1502       MVT IndexVT;
1503       addVectorLoadStoreOperands(Node, Log2SEW, DL, CurOp, IsMasked,
1504                                  /*IsStridedOrIndexed*/ true, Operands,
1505                                  /*IsLoad=*/false, &IndexVT);
1506 
1507       assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
1508              "Element count mismatch");
1509 
1510       RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
1511       RISCVII::VLMUL IndexLMUL = RISCVTargetLowering::getLMUL(IndexVT);
1512       unsigned IndexLog2EEW = Log2_32(IndexVT.getScalarSizeInBits());
1513       if (IndexLog2EEW == 6 && !Subtarget->is64Bit()) {
1514         report_fatal_error("The V extension does not support EEW=64 for index "
1515                            "values when XLEN=32");
1516       }
1517       const RISCV::VLX_VSXPseudo *P = RISCV::getVSXPseudo(
1518           IsMasked, /*TU*/ false, IsOrdered, IndexLog2EEW,
1519           static_cast<unsigned>(LMUL), static_cast<unsigned>(IndexLMUL));
1520       MachineSDNode *Store =
1521           CurDAG->getMachineNode(P->Pseudo, DL, Node->getVTList(), Operands);
1522 
1523       if (auto *MemOp = dyn_cast<MemSDNode>(Node))
1524         CurDAG->setNodeMemRefs(Store, {MemOp->getMemOperand()});
1525 
1526       ReplaceNode(Node, Store);
1527       return;
1528     }
1529     case Intrinsic::riscv_vsm:
1530     case Intrinsic::riscv_vse:
1531     case Intrinsic::riscv_vse_mask:
1532     case Intrinsic::riscv_vsse:
1533     case Intrinsic::riscv_vsse_mask: {
1534       bool IsMasked = IntNo == Intrinsic::riscv_vse_mask ||
1535                       IntNo == Intrinsic::riscv_vsse_mask;
1536       bool IsStrided =
1537           IntNo == Intrinsic::riscv_vsse || IntNo == Intrinsic::riscv_vsse_mask;
1538 
1539       MVT VT = Node->getOperand(2)->getSimpleValueType(0);
1540       unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
1541 
1542       unsigned CurOp = 2;
1543       SmallVector<SDValue, 8> Operands;
1544       Operands.push_back(Node->getOperand(CurOp++)); // Store value.
1545 
1546       addVectorLoadStoreOperands(Node, Log2SEW, DL, CurOp, IsMasked, IsStrided,
1547                                  Operands);
1548 
1549       RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
1550       const RISCV::VSEPseudo *P = RISCV::getVSEPseudo(
1551           IsMasked, IsStrided, Log2SEW, static_cast<unsigned>(LMUL));
1552       MachineSDNode *Store =
1553           CurDAG->getMachineNode(P->Pseudo, DL, Node->getVTList(), Operands);
1554       if (auto *MemOp = dyn_cast<MemSDNode>(Node))
1555         CurDAG->setNodeMemRefs(Store, {MemOp->getMemOperand()});
1556 
1557       ReplaceNode(Node, Store);
1558       return;
1559     }
1560     }
1561     break;
1562   }
1563   case ISD::BITCAST: {
1564     MVT SrcVT = Node->getOperand(0).getSimpleValueType();
1565     // Just drop bitcasts between vectors if both are fixed or both are
1566     // scalable.
1567     if ((VT.isScalableVector() && SrcVT.isScalableVector()) ||
1568         (VT.isFixedLengthVector() && SrcVT.isFixedLengthVector())) {
1569       ReplaceUses(SDValue(Node, 0), Node->getOperand(0));
1570       CurDAG->RemoveDeadNode(Node);
1571       return;
1572     }
1573     break;
1574   }
1575   case ISD::INSERT_SUBVECTOR: {
1576     SDValue V = Node->getOperand(0);
1577     SDValue SubV = Node->getOperand(1);
1578     SDLoc DL(SubV);
1579     auto Idx = Node->getConstantOperandVal(2);
1580     MVT SubVecVT = SubV.getSimpleValueType();
1581 
1582     const RISCVTargetLowering &TLI = *Subtarget->getTargetLowering();
1583     MVT SubVecContainerVT = SubVecVT;
1584     // Establish the correct scalable-vector types for any fixed-length type.
1585     if (SubVecVT.isFixedLengthVector())
1586       SubVecContainerVT = TLI.getContainerForFixedLengthVector(SubVecVT);
1587     if (VT.isFixedLengthVector())
1588       VT = TLI.getContainerForFixedLengthVector(VT);
1589 
1590     const auto *TRI = Subtarget->getRegisterInfo();
1591     unsigned SubRegIdx;
1592     std::tie(SubRegIdx, Idx) =
1593         RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1594             VT, SubVecContainerVT, Idx, TRI);
1595 
1596     // If the Idx hasn't been completely eliminated then this is a subvector
1597     // insert which doesn't naturally align to a vector register. These must
1598     // be handled using instructions to manipulate the vector registers.
1599     if (Idx != 0)
1600       break;
1601 
1602     RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecContainerVT);
1603     bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
1604                            SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
1605                            SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
1606     (void)IsSubVecPartReg; // Silence unused variable warning without asserts.
1607     assert((!IsSubVecPartReg || V.isUndef()) &&
1608            "Expecting lowering to have created legal INSERT_SUBVECTORs when "
1609            "the subvector is smaller than a full-sized register");
1610 
1611     // If we haven't set a SubRegIdx, then we must be going between
1612     // equally-sized LMUL groups (e.g. VR -> VR). This can be done as a copy.
1613     if (SubRegIdx == RISCV::NoSubRegister) {
1614       unsigned InRegClassID = RISCVTargetLowering::getRegClassIDForVecVT(VT);
1615       assert(RISCVTargetLowering::getRegClassIDForVecVT(SubVecContainerVT) ==
1616                  InRegClassID &&
1617              "Unexpected subvector extraction");
1618       SDValue RC = CurDAG->getTargetConstant(InRegClassID, DL, XLenVT);
1619       SDNode *NewNode = CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1620                                                DL, VT, SubV, RC);
1621       ReplaceNode(Node, NewNode);
1622       return;
1623     }
1624 
1625     SDValue Insert = CurDAG->getTargetInsertSubreg(SubRegIdx, DL, VT, V, SubV);
1626     ReplaceNode(Node, Insert.getNode());
1627     return;
1628   }
1629   case ISD::EXTRACT_SUBVECTOR: {
1630     SDValue V = Node->getOperand(0);
1631     auto Idx = Node->getConstantOperandVal(1);
1632     MVT InVT = V.getSimpleValueType();
1633     SDLoc DL(V);
1634 
1635     const RISCVTargetLowering &TLI = *Subtarget->getTargetLowering();
1636     MVT SubVecContainerVT = VT;
1637     // Establish the correct scalable-vector types for any fixed-length type.
1638     if (VT.isFixedLengthVector())
1639       SubVecContainerVT = TLI.getContainerForFixedLengthVector(VT);
1640     if (InVT.isFixedLengthVector())
1641       InVT = TLI.getContainerForFixedLengthVector(InVT);
1642 
1643     const auto *TRI = Subtarget->getRegisterInfo();
1644     unsigned SubRegIdx;
1645     std::tie(SubRegIdx, Idx) =
1646         RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1647             InVT, SubVecContainerVT, Idx, TRI);
1648 
1649     // If the Idx hasn't been completely eliminated then this is a subvector
1650     // extract which doesn't naturally align to a vector register. These must
1651     // be handled using instructions to manipulate the vector registers.
1652     if (Idx != 0)
1653       break;
1654 
1655     // If we haven't set a SubRegIdx, then we must be going between
1656     // equally-sized LMUL types (e.g. VR -> VR). This can be done as a copy.
1657     if (SubRegIdx == RISCV::NoSubRegister) {
1658       unsigned InRegClassID = RISCVTargetLowering::getRegClassIDForVecVT(InVT);
1659       assert(RISCVTargetLowering::getRegClassIDForVecVT(SubVecContainerVT) ==
1660                  InRegClassID &&
1661              "Unexpected subvector extraction");
1662       SDValue RC = CurDAG->getTargetConstant(InRegClassID, DL, XLenVT);
1663       SDNode *NewNode =
1664           CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, DL, VT, V, RC);
1665       ReplaceNode(Node, NewNode);
1666       return;
1667     }
1668 
1669     SDValue Extract = CurDAG->getTargetExtractSubreg(SubRegIdx, DL, VT, V);
1670     ReplaceNode(Node, Extract.getNode());
1671     return;
1672   }
1673   case ISD::SPLAT_VECTOR:
1674   case RISCVISD::VMV_S_X_VL:
1675   case RISCVISD::VFMV_S_F_VL:
1676   case RISCVISD::VMV_V_X_VL:
1677   case RISCVISD::VFMV_V_F_VL: {
1678     // Try to match splat of a scalar load to a strided load with stride of x0.
1679     bool IsScalarMove = Node->getOpcode() == RISCVISD::VMV_S_X_VL ||
1680                         Node->getOpcode() == RISCVISD::VFMV_S_F_VL;
1681     bool HasPassthruOperand = Node->getOpcode() != ISD::SPLAT_VECTOR;
1682     if (HasPassthruOperand && !Node->getOperand(0).isUndef())
1683       break;
1684     SDValue Src = HasPassthruOperand ? Node->getOperand(1) : Node->getOperand(0);
1685     auto *Ld = dyn_cast<LoadSDNode>(Src);
1686     if (!Ld)
1687       break;
1688     EVT MemVT = Ld->getMemoryVT();
1689     // The memory VT should be the same size as the element type.
1690     if (MemVT.getStoreSize() != VT.getVectorElementType().getStoreSize())
1691       break;
1692     if (!IsProfitableToFold(Src, Node, Node) ||
1693         !IsLegalToFold(Src, Node, Node, TM.getOptLevel()))
1694       break;
1695 
1696     SDValue VL;
1697     if (Node->getOpcode() == ISD::SPLAT_VECTOR)
1698       VL = CurDAG->getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1699     else if (IsScalarMove) {
1700       // We could deal with more VL if we update the VSETVLI insert pass to
1701       // avoid introducing more VSETVLI.
1702       if (!isOneConstant(Node->getOperand(2)))
1703         break;
1704       selectVLOp(Node->getOperand(2), VL);
1705     } else
1706       selectVLOp(Node->getOperand(2), VL);
1707 
1708     unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
1709     SDValue SEW = CurDAG->getTargetConstant(Log2SEW, DL, XLenVT);
1710 
1711     SDValue Operands[] = {Ld->getBasePtr(),
1712                           CurDAG->getRegister(RISCV::X0, XLenVT), VL, SEW,
1713                           Ld->getChain()};
1714 
1715     RISCVII::VLMUL LMUL = RISCVTargetLowering::getLMUL(VT);
1716     const RISCV::VLEPseudo *P = RISCV::getVLEPseudo(
1717         /*IsMasked*/ false, /*IsTU*/ false, /*IsStrided*/ true, /*FF*/ false,
1718         Log2SEW, static_cast<unsigned>(LMUL));
1719     MachineSDNode *Load =
1720         CurDAG->getMachineNode(P->Pseudo, DL, Node->getVTList(), Operands);
1721 
1722     CurDAG->setNodeMemRefs(Load, {Ld->getMemOperand()});
1723 
1724     ReplaceNode(Node, Load);
1725     return;
1726   }
1727   }
1728 
1729   // Select the default instruction.
1730   SelectCode(Node);
1731 }
1732 
1733 bool RISCVDAGToDAGISel::SelectInlineAsmMemoryOperand(
1734     const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) {
1735   switch (ConstraintID) {
1736   case InlineAsm::Constraint_m:
1737     // We just support simple memory operands that have a single address
1738     // operand and need no special handling.
1739     OutOps.push_back(Op);
1740     return false;
1741   case InlineAsm::Constraint_A:
1742     OutOps.push_back(Op);
1743     return false;
1744   default:
1745     break;
1746   }
1747 
1748   return true;
1749 }
1750 
1751 bool RISCVDAGToDAGISel::SelectAddrFI(SDValue Addr, SDValue &Base) {
1752   if (auto *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1753     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), Subtarget->getXLenVT());
1754     return true;
1755   }
1756   return false;
1757 }
1758 
1759 bool RISCVDAGToDAGISel::SelectBaseAddr(SDValue Addr, SDValue &Base) {
1760   // If this is FrameIndex, select it directly. Otherwise just let it get
1761   // selected to a register independently.
1762   if (auto *FIN = dyn_cast<FrameIndexSDNode>(Addr))
1763     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), Subtarget->getXLenVT());
1764   else
1765     Base = Addr;
1766   return true;
1767 }
1768 
1769 bool RISCVDAGToDAGISel::selectShiftMask(SDValue N, unsigned ShiftWidth,
1770                                         SDValue &ShAmt) {
1771   // Shift instructions on RISCV only read the lower 5 or 6 bits of the shift
1772   // amount. If there is an AND on the shift amount, we can bypass it if it
1773   // doesn't affect any of those bits.
1774   if (N.getOpcode() == ISD::AND && isa<ConstantSDNode>(N.getOperand(1))) {
1775     const APInt &AndMask = N->getConstantOperandAPInt(1);
1776 
1777     // Since the max shift amount is a power of 2 we can subtract 1 to make a
1778     // mask that covers the bits needed to represent all shift amounts.
1779     assert(isPowerOf2_32(ShiftWidth) && "Unexpected max shift amount!");
1780     APInt ShMask(AndMask.getBitWidth(), ShiftWidth - 1);
1781 
1782     if (ShMask.isSubsetOf(AndMask)) {
1783       ShAmt = N.getOperand(0);
1784       return true;
1785     }
1786 
1787     // SimplifyDemandedBits may have optimized the mask so try restoring any
1788     // bits that are known zero.
1789     KnownBits Known = CurDAG->computeKnownBits(N->getOperand(0));
1790     if (ShMask.isSubsetOf(AndMask | Known.Zero)) {
1791       ShAmt = N.getOperand(0);
1792       return true;
1793     }
1794   } else if (N.getOpcode() == ISD::SUB &&
1795              isa<ConstantSDNode>(N.getOperand(0))) {
1796     uint64_t Imm = N.getConstantOperandVal(0);
1797     // If we are shifting by N-X where N == 0 mod Size, then just shift by -X to
1798     // generate a NEG instead of a SUB of a constant.
1799     if (Imm != 0 && Imm % ShiftWidth == 0) {
1800       SDLoc DL(N);
1801       EVT VT = N.getValueType();
1802       SDValue Zero =
1803           CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL, RISCV::X0, VT);
1804       unsigned NegOpc = VT == MVT::i64 ? RISCV::SUBW : RISCV::SUB;
1805       MachineSDNode *Neg = CurDAG->getMachineNode(NegOpc, DL, VT, Zero,
1806                                                   N.getOperand(1));
1807       ShAmt = SDValue(Neg, 0);
1808       return true;
1809     }
1810   }
1811 
1812   ShAmt = N;
1813   return true;
1814 }
1815 
1816 bool RISCVDAGToDAGISel::selectSExti32(SDValue N, SDValue &Val) {
1817   if (N.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1818       cast<VTSDNode>(N.getOperand(1))->getVT() == MVT::i32) {
1819     Val = N.getOperand(0);
1820     return true;
1821   }
1822   MVT VT = N.getSimpleValueType();
1823   if (CurDAG->ComputeNumSignBits(N) > (VT.getSizeInBits() - 32)) {
1824     Val = N;
1825     return true;
1826   }
1827 
1828   return false;
1829 }
1830 
1831 bool RISCVDAGToDAGISel::selectZExti32(SDValue N, SDValue &Val) {
1832   if (N.getOpcode() == ISD::AND) {
1833     auto *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
1834     if (C && C->getZExtValue() == UINT64_C(0xFFFFFFFF)) {
1835       Val = N.getOperand(0);
1836       return true;
1837     }
1838   }
1839   MVT VT = N.getSimpleValueType();
1840   APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 32);
1841   if (CurDAG->MaskedValueIsZero(N, Mask)) {
1842     Val = N;
1843     return true;
1844   }
1845 
1846   return false;
1847 }
1848 
1849 // Return true if all users of this SDNode* only consume the lower \p Bits.
1850 // This can be used to form W instructions for add/sub/mul/shl even when the
1851 // root isn't a sext_inreg. This can allow the ADDW/SUBW/MULW/SLLIW to CSE if
1852 // SimplifyDemandedBits has made it so some users see a sext_inreg and some
1853 // don't. The sext_inreg+add/sub/mul/shl will get selected, but still leave
1854 // the add/sub/mul/shl to become non-W instructions. By checking the users we
1855 // may be able to use a W instruction and CSE with the other instruction if
1856 // this has happened. We could try to detect that the CSE opportunity exists
1857 // before doing this, but that would be more complicated.
1858 // TODO: Does this need to look through AND/OR/XOR to their users to find more
1859 // opportunities.
1860 bool RISCVDAGToDAGISel::hasAllNBitUsers(SDNode *Node, unsigned Bits) const {
1861   assert((Node->getOpcode() == ISD::ADD || Node->getOpcode() == ISD::SUB ||
1862           Node->getOpcode() == ISD::MUL || Node->getOpcode() == ISD::SHL ||
1863           Node->getOpcode() == ISD::SRL ||
1864           Node->getOpcode() == ISD::SIGN_EXTEND_INREG ||
1865           Node->getOpcode() == RISCVISD::GREV ||
1866           Node->getOpcode() == RISCVISD::GORC ||
1867           isa<ConstantSDNode>(Node)) &&
1868          "Unexpected opcode");
1869 
1870   for (auto UI = Node->use_begin(), UE = Node->use_end(); UI != UE; ++UI) {
1871     SDNode *User = *UI;
1872     // Users of this node should have already been instruction selected
1873     if (!User->isMachineOpcode())
1874       return false;
1875 
1876     // TODO: Add more opcodes?
1877     switch (User->getMachineOpcode()) {
1878     default:
1879       return false;
1880     case RISCV::ADDW:
1881     case RISCV::ADDIW:
1882     case RISCV::SUBW:
1883     case RISCV::MULW:
1884     case RISCV::SLLW:
1885     case RISCV::SLLIW:
1886     case RISCV::SRAW:
1887     case RISCV::SRAIW:
1888     case RISCV::SRLW:
1889     case RISCV::SRLIW:
1890     case RISCV::DIVW:
1891     case RISCV::DIVUW:
1892     case RISCV::REMW:
1893     case RISCV::REMUW:
1894     case RISCV::ROLW:
1895     case RISCV::RORW:
1896     case RISCV::RORIW:
1897     case RISCV::CLZW:
1898     case RISCV::CTZW:
1899     case RISCV::CPOPW:
1900     case RISCV::SLLI_UW:
1901     case RISCV::FMV_W_X:
1902     case RISCV::FCVT_H_W:
1903     case RISCV::FCVT_H_WU:
1904     case RISCV::FCVT_S_W:
1905     case RISCV::FCVT_S_WU:
1906     case RISCV::FCVT_D_W:
1907     case RISCV::FCVT_D_WU:
1908       if (Bits < 32)
1909         return false;
1910       break;
1911     case RISCV::SLLI:
1912       // SLLI only uses the lower (XLen - ShAmt) bits.
1913       if (Bits < Subtarget->getXLen() - User->getConstantOperandVal(1))
1914         return false;
1915       break;
1916     case RISCV::ANDI:
1917       if (Bits < (64 - countLeadingZeros(User->getConstantOperandVal(1))))
1918         return false;
1919       break;
1920     case RISCV::SEXT_B:
1921       if (Bits < 8)
1922         return false;
1923       break;
1924     case RISCV::SEXT_H:
1925     case RISCV::FMV_H_X:
1926     case RISCV::ZEXT_H_RV32:
1927     case RISCV::ZEXT_H_RV64:
1928       if (Bits < 16)
1929         return false;
1930       break;
1931     case RISCV::ADD_UW:
1932     case RISCV::SH1ADD_UW:
1933     case RISCV::SH2ADD_UW:
1934     case RISCV::SH3ADD_UW:
1935       // The first operand to add.uw/shXadd.uw is implicitly zero extended from
1936       // 32 bits.
1937       if (UI.getOperandNo() != 0 || Bits < 32)
1938         return false;
1939       break;
1940     case RISCV::SB:
1941       if (UI.getOperandNo() != 0 || Bits < 8)
1942         return false;
1943       break;
1944     case RISCV::SH:
1945       if (UI.getOperandNo() != 0 || Bits < 16)
1946         return false;
1947       break;
1948     case RISCV::SW:
1949       if (UI.getOperandNo() != 0 || Bits < 32)
1950         return false;
1951       break;
1952     }
1953   }
1954 
1955   return true;
1956 }
1957 
1958 // Select VL as a 5 bit immediate or a value that will become a register. This
1959 // allows us to choose betwen VSETIVLI or VSETVLI later.
1960 bool RISCVDAGToDAGISel::selectVLOp(SDValue N, SDValue &VL) {
1961   auto *C = dyn_cast<ConstantSDNode>(N);
1962   if (C && isUInt<5>(C->getZExtValue())) {
1963     VL = CurDAG->getTargetConstant(C->getZExtValue(), SDLoc(N),
1964                                    N->getValueType(0));
1965   } else if (C && C->isAllOnesValue()) {
1966     // Treat all ones as VLMax.
1967     VL = CurDAG->getTargetConstant(RISCV::VLMaxSentinel, SDLoc(N),
1968                                    N->getValueType(0));
1969   } else if (isa<RegisterSDNode>(N) &&
1970              cast<RegisterSDNode>(N)->getReg() == RISCV::X0) {
1971     // All our VL operands use an operand that allows GPRNoX0 or an immediate
1972     // as the register class. Convert X0 to a special immediate to pass the
1973     // MachineVerifier. This is recognized specially by the vsetvli insertion
1974     // pass.
1975     VL = CurDAG->getTargetConstant(RISCV::VLMaxSentinel, SDLoc(N),
1976                                    N->getValueType(0));
1977   } else {
1978     VL = N;
1979   }
1980 
1981   return true;
1982 }
1983 
1984 bool RISCVDAGToDAGISel::selectVSplat(SDValue N, SDValue &SplatVal) {
1985   if (N.getOpcode() != RISCVISD::VMV_V_X_VL || !N.getOperand(0).isUndef())
1986     return false;
1987   SplatVal = N.getOperand(1);
1988   return true;
1989 }
1990 
1991 using ValidateFn = bool (*)(int64_t);
1992 
1993 static bool selectVSplatSimmHelper(SDValue N, SDValue &SplatVal,
1994                                    SelectionDAG &DAG,
1995                                    const RISCVSubtarget &Subtarget,
1996                                    ValidateFn ValidateImm) {
1997   if (N.getOpcode() != RISCVISD::VMV_V_X_VL || !N.getOperand(0).isUndef() ||
1998       !isa<ConstantSDNode>(N.getOperand(1)))
1999     return false;
2000 
2001   int64_t SplatImm =
2002       cast<ConstantSDNode>(N.getOperand(1))->getSExtValue();
2003 
2004   // The semantics of RISCVISD::VMV_V_X_VL is that when the operand
2005   // type is wider than the resulting vector element type: an implicit
2006   // truncation first takes place. Therefore, perform a manual
2007   // truncation/sign-extension in order to ignore any truncated bits and catch
2008   // any zero-extended immediate.
2009   // For example, we wish to match (i8 -1) -> (XLenVT 255) as a simm5 by first
2010   // sign-extending to (XLenVT -1).
2011   MVT XLenVT = Subtarget.getXLenVT();
2012   assert(XLenVT == N.getOperand(1).getSimpleValueType() &&
2013          "Unexpected splat operand type");
2014   MVT EltVT = N.getSimpleValueType().getVectorElementType();
2015   if (EltVT.bitsLT(XLenVT))
2016     SplatImm = SignExtend64(SplatImm, EltVT.getSizeInBits());
2017 
2018   if (!ValidateImm(SplatImm))
2019     return false;
2020 
2021   SplatVal = DAG.getTargetConstant(SplatImm, SDLoc(N), XLenVT);
2022   return true;
2023 }
2024 
2025 bool RISCVDAGToDAGISel::selectVSplatSimm5(SDValue N, SDValue &SplatVal) {
2026   return selectVSplatSimmHelper(N, SplatVal, *CurDAG, *Subtarget,
2027                                 [](int64_t Imm) { return isInt<5>(Imm); });
2028 }
2029 
2030 bool RISCVDAGToDAGISel::selectVSplatSimm5Plus1(SDValue N, SDValue &SplatVal) {
2031   return selectVSplatSimmHelper(
2032       N, SplatVal, *CurDAG, *Subtarget,
2033       [](int64_t Imm) { return (isInt<5>(Imm) && Imm != -16) || Imm == 16; });
2034 }
2035 
2036 bool RISCVDAGToDAGISel::selectVSplatSimm5Plus1NonZero(SDValue N,
2037                                                       SDValue &SplatVal) {
2038   return selectVSplatSimmHelper(
2039       N, SplatVal, *CurDAG, *Subtarget, [](int64_t Imm) {
2040         return Imm != 0 && ((isInt<5>(Imm) && Imm != -16) || Imm == 16);
2041       });
2042 }
2043 
2044 bool RISCVDAGToDAGISel::selectVSplatUimm5(SDValue N, SDValue &SplatVal) {
2045   if (N.getOpcode() != RISCVISD::VMV_V_X_VL || !N.getOperand(0).isUndef() ||
2046       !isa<ConstantSDNode>(N.getOperand(1)))
2047     return false;
2048 
2049   int64_t SplatImm =
2050       cast<ConstantSDNode>(N.getOperand(1))->getSExtValue();
2051 
2052   if (!isUInt<5>(SplatImm))
2053     return false;
2054 
2055   SplatVal =
2056       CurDAG->getTargetConstant(SplatImm, SDLoc(N), Subtarget->getXLenVT());
2057 
2058   return true;
2059 }
2060 
2061 bool RISCVDAGToDAGISel::selectRVVSimm5(SDValue N, unsigned Width,
2062                                        SDValue &Imm) {
2063   if (auto *C = dyn_cast<ConstantSDNode>(N)) {
2064     int64_t ImmVal = SignExtend64(C->getSExtValue(), Width);
2065 
2066     if (!isInt<5>(ImmVal))
2067       return false;
2068 
2069     Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), Subtarget->getXLenVT());
2070     return true;
2071   }
2072 
2073   return false;
2074 }
2075 
2076 // Merge an ADDI into the offset of a load/store instruction where possible.
2077 // (load (addi base, off1), off2) -> (load base, off1+off2)
2078 // (store val, (addi base, off1), off2) -> (store val, base, off1+off2)
2079 // (load (add base, (addi src, off1)), off2)
2080 //    -> (load (add base, src), off1+off2)
2081 // (store val, (add base, (addi src, off1)), off2)
2082 //    -> (store val, (add base, src), off1+off2)
2083 // This is possible when off1+off2 fits a 12-bit immediate.
2084 bool RISCVDAGToDAGISel::doPeepholeLoadStoreADDI(SDNode *N) {
2085   int OffsetOpIdx;
2086   int BaseOpIdx;
2087 
2088   // Only attempt this optimisation for I-type loads and S-type stores.
2089   switch (N->getMachineOpcode()) {
2090   default:
2091     return false;
2092   case RISCV::LB:
2093   case RISCV::LH:
2094   case RISCV::LW:
2095   case RISCV::LBU:
2096   case RISCV::LHU:
2097   case RISCV::LWU:
2098   case RISCV::LD:
2099   case RISCV::FLH:
2100   case RISCV::FLW:
2101   case RISCV::FLD:
2102     BaseOpIdx = 0;
2103     OffsetOpIdx = 1;
2104     break;
2105   case RISCV::SB:
2106   case RISCV::SH:
2107   case RISCV::SW:
2108   case RISCV::SD:
2109   case RISCV::FSH:
2110   case RISCV::FSW:
2111   case RISCV::FSD:
2112     BaseOpIdx = 1;
2113     OffsetOpIdx = 2;
2114     break;
2115   }
2116 
2117   if (!isa<ConstantSDNode>(N->getOperand(OffsetOpIdx)))
2118     return false;
2119 
2120   SDValue Base = N->getOperand(BaseOpIdx);
2121 
2122   if (!Base.isMachineOpcode())
2123     return false;
2124 
2125   // There is a ADD between ADDI and load/store. We can only fold ADDI that
2126   // do not have a FrameIndex operand.
2127   SDValue Add;
2128   unsigned AddBaseIdx;
2129   if (Base.getMachineOpcode() == RISCV::ADD && Base.hasOneUse()) {
2130     Add = Base;
2131     SDValue Op0 = Base.getOperand(0);
2132     SDValue Op1 = Base.getOperand(1);
2133     if (Op0.isMachineOpcode() && Op0.getMachineOpcode() == RISCV::ADDI &&
2134         !isa<FrameIndexSDNode>(Op0.getOperand(0)) &&
2135         isa<ConstantSDNode>(Op0.getOperand(1))) {
2136       AddBaseIdx = 1;
2137       Base = Op0;
2138     } else if (Op1.isMachineOpcode() && Op1.getMachineOpcode() == RISCV::ADDI &&
2139                !isa<FrameIndexSDNode>(Op1.getOperand(0)) &&
2140                isa<ConstantSDNode>(Op1.getOperand(1))) {
2141       AddBaseIdx = 0;
2142       Base = Op1;
2143     } else if (Op1.isMachineOpcode() &&
2144                Op1.getMachineOpcode() == RISCV::ADDIW &&
2145                isa<ConstantSDNode>(Op1.getOperand(1)) &&
2146                Op1.getOperand(0).isMachineOpcode() &&
2147                Op1.getOperand(0).getMachineOpcode() == RISCV::LUI) {
2148       // We found an LUI+ADDIW constant materialization. We might be able to
2149       // fold the ADDIW offset if it could be treated as ADDI.
2150       // Emulate the constant materialization to see if the result would be
2151       // a simm32 if ADDI was used instead of ADDIW.
2152 
2153       // First the LUI.
2154       uint64_t Imm = Op1.getOperand(0).getConstantOperandVal(0);
2155       Imm <<= 12;
2156       Imm = SignExtend64(Imm, 32);
2157 
2158       // Then the ADDI.
2159       uint64_t LoImm = cast<ConstantSDNode>(Op1.getOperand(1))->getSExtValue();
2160       Imm += LoImm;
2161 
2162       // If the result isn't a simm32, we can't do the optimization.
2163       if (!isInt<32>(Imm))
2164         return false;
2165 
2166       AddBaseIdx = 0;
2167       Base = Op1;
2168     } else
2169       return false;
2170   } else if (Base.getMachineOpcode() == RISCV::ADDI) {
2171     // If the base is an ADDI, we can merge it in to the load/store.
2172   } else
2173     return false;
2174 
2175   SDValue ImmOperand = Base.getOperand(1);
2176   uint64_t Offset2 = N->getConstantOperandVal(OffsetOpIdx);
2177 
2178   if (auto *Const = dyn_cast<ConstantSDNode>(ImmOperand)) {
2179     int64_t Offset1 = Const->getSExtValue();
2180     int64_t CombinedOffset = Offset1 + Offset2;
2181     if (!isInt<12>(CombinedOffset))
2182       return false;
2183     ImmOperand = CurDAG->getTargetConstant(CombinedOffset, SDLoc(ImmOperand),
2184                                            ImmOperand.getValueType());
2185   } else if (auto *GA = dyn_cast<GlobalAddressSDNode>(ImmOperand)) {
2186     // If the off1 in (addi base, off1) is a global variable's address (its
2187     // low part, really), then we can rely on the alignment of that variable
2188     // to provide a margin of safety before off1 can overflow the 12 bits.
2189     // Check if off2 falls within that margin; if so off1+off2 can't overflow.
2190     const DataLayout &DL = CurDAG->getDataLayout();
2191     Align Alignment = GA->getGlobal()->getPointerAlignment(DL);
2192     if (Offset2 != 0 && Alignment <= Offset2)
2193       return false;
2194     int64_t Offset1 = GA->getOffset();
2195     int64_t CombinedOffset = Offset1 + Offset2;
2196     ImmOperand = CurDAG->getTargetGlobalAddress(
2197         GA->getGlobal(), SDLoc(ImmOperand), ImmOperand.getValueType(),
2198         CombinedOffset, GA->getTargetFlags());
2199   } else if (auto *CP = dyn_cast<ConstantPoolSDNode>(ImmOperand)) {
2200     // Ditto.
2201     Align Alignment = CP->getAlign();
2202     if (Offset2 != 0 && Alignment <= Offset2)
2203       return false;
2204     int64_t Offset1 = CP->getOffset();
2205     int64_t CombinedOffset = Offset1 + Offset2;
2206     ImmOperand = CurDAG->getTargetConstantPool(
2207         CP->getConstVal(), ImmOperand.getValueType(), CP->getAlign(),
2208         CombinedOffset, CP->getTargetFlags());
2209   } else {
2210     return false;
2211   }
2212 
2213   LLVM_DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
2214   LLVM_DEBUG(Base->dump(CurDAG));
2215   LLVM_DEBUG(dbgs() << "\nN: ");
2216   LLVM_DEBUG(N->dump(CurDAG));
2217   LLVM_DEBUG(dbgs() << "\n");
2218 
2219   if (Add)
2220     Add = SDValue(CurDAG->UpdateNodeOperands(Add.getNode(),
2221                                              Add.getOperand(AddBaseIdx),
2222                                              Base.getOperand(0)),
2223                   0);
2224 
2225   // Modify the offset operand of the load/store.
2226   if (BaseOpIdx == 0) { // Load
2227     if (Add)
2228       N = CurDAG->UpdateNodeOperands(N, Add, ImmOperand, N->getOperand(2));
2229     else
2230       N = CurDAG->UpdateNodeOperands(N, Base.getOperand(0), ImmOperand,
2231                                      N->getOperand(2));
2232   } else { // Store
2233     if (Add)
2234       N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), Add, ImmOperand,
2235                                      N->getOperand(3));
2236     else
2237       N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), Base.getOperand(0),
2238                                      ImmOperand, N->getOperand(3));
2239   }
2240 
2241   return true;
2242 }
2243 
2244 // Try to remove sext.w if the input is a W instruction or can be made into
2245 // a W instruction cheaply.
2246 bool RISCVDAGToDAGISel::doPeepholeSExtW(SDNode *N) {
2247   // Look for the sext.w pattern, addiw rd, rs1, 0.
2248   if (N->getMachineOpcode() != RISCV::ADDIW ||
2249       !isNullConstant(N->getOperand(1)))
2250     return false;
2251 
2252   SDValue N0 = N->getOperand(0);
2253   if (!N0.isMachineOpcode())
2254     return false;
2255 
2256   switch (N0.getMachineOpcode()) {
2257   default:
2258     break;
2259   case RISCV::ADD:
2260   case RISCV::ADDI:
2261   case RISCV::SUB:
2262   case RISCV::MUL:
2263   case RISCV::SLLI: {
2264     // Convert sext.w+add/sub/mul to their W instructions. This will create
2265     // a new independent instruction. This improves latency.
2266     unsigned Opc;
2267     switch (N0.getMachineOpcode()) {
2268     default:
2269       llvm_unreachable("Unexpected opcode!");
2270     case RISCV::ADD:  Opc = RISCV::ADDW;  break;
2271     case RISCV::ADDI: Opc = RISCV::ADDIW; break;
2272     case RISCV::SUB:  Opc = RISCV::SUBW;  break;
2273     case RISCV::MUL:  Opc = RISCV::MULW;  break;
2274     case RISCV::SLLI: Opc = RISCV::SLLIW; break;
2275     }
2276 
2277     SDValue N00 = N0.getOperand(0);
2278     SDValue N01 = N0.getOperand(1);
2279 
2280     // Shift amount needs to be uimm5.
2281     if (N0.getMachineOpcode() == RISCV::SLLI &&
2282         !isUInt<5>(cast<ConstantSDNode>(N01)->getSExtValue()))
2283       break;
2284 
2285     SDNode *Result =
2286         CurDAG->getMachineNode(Opc, SDLoc(N), N->getValueType(0),
2287                                N00, N01);
2288     ReplaceUses(N, Result);
2289     return true;
2290   }
2291   case RISCV::ADDW:
2292   case RISCV::ADDIW:
2293   case RISCV::SUBW:
2294   case RISCV::MULW:
2295   case RISCV::SLLIW:
2296   case RISCV::GREVIW:
2297   case RISCV::GORCIW:
2298     // Result is already sign extended just remove the sext.w.
2299     // NOTE: We only handle the nodes that are selected with hasAllWUsers.
2300     ReplaceUses(N, N0.getNode());
2301     return true;
2302   }
2303 
2304   return false;
2305 }
2306 
2307 // Optimize masked RVV pseudo instructions with a known all-ones mask to their
2308 // corresponding "unmasked" pseudo versions. The mask we're interested in will
2309 // take the form of a V0 physical register operand, with a glued
2310 // register-setting instruction.
2311 bool RISCVDAGToDAGISel::doPeepholeMaskedRVV(SDNode *N) {
2312   const RISCV::RISCVMaskedPseudoInfo *I =
2313       RISCV::getMaskedPseudoInfo(N->getMachineOpcode());
2314   if (!I)
2315     return false;
2316 
2317   unsigned MaskOpIdx = I->MaskOpIdx;
2318 
2319   // Check that we're using V0 as a mask register.
2320   if (!isa<RegisterSDNode>(N->getOperand(MaskOpIdx)) ||
2321       cast<RegisterSDNode>(N->getOperand(MaskOpIdx))->getReg() != RISCV::V0)
2322     return false;
2323 
2324   // The glued user defines V0.
2325   const auto *Glued = N->getGluedNode();
2326 
2327   if (!Glued || Glued->getOpcode() != ISD::CopyToReg)
2328     return false;
2329 
2330   // Check that we're defining V0 as a mask register.
2331   if (!isa<RegisterSDNode>(Glued->getOperand(1)) ||
2332       cast<RegisterSDNode>(Glued->getOperand(1))->getReg() != RISCV::V0)
2333     return false;
2334 
2335   // Check the instruction defining V0; it needs to be a VMSET pseudo.
2336   SDValue MaskSetter = Glued->getOperand(2);
2337 
2338   const auto IsVMSet = [](unsigned Opc) {
2339     return Opc == RISCV::PseudoVMSET_M_B1 || Opc == RISCV::PseudoVMSET_M_B16 ||
2340            Opc == RISCV::PseudoVMSET_M_B2 || Opc == RISCV::PseudoVMSET_M_B32 ||
2341            Opc == RISCV::PseudoVMSET_M_B4 || Opc == RISCV::PseudoVMSET_M_B64 ||
2342            Opc == RISCV::PseudoVMSET_M_B8;
2343   };
2344 
2345   // TODO: Check that the VMSET is the expected bitwidth? The pseudo has
2346   // undefined behaviour if it's the wrong bitwidth, so we could choose to
2347   // assume that it's all-ones? Same applies to its VL.
2348   if (!MaskSetter->isMachineOpcode() || !IsVMSet(MaskSetter.getMachineOpcode()))
2349     return false;
2350 
2351   // Retrieve the tail policy operand index, if any.
2352   Optional<unsigned> TailPolicyOpIdx;
2353   const RISCVInstrInfo *TII = static_cast<const RISCVInstrInfo *>(
2354       CurDAG->getSubtarget().getInstrInfo());
2355 
2356   const MCInstrDesc &MaskedMCID = TII->get(N->getMachineOpcode());
2357 
2358   bool IsTA = true;
2359   if (RISCVII::hasVecPolicyOp(MaskedMCID.TSFlags)) {
2360     // The last operand of the pseudo is the policy op, but we might have a
2361     // Glue operand last. We might also have a chain.
2362     TailPolicyOpIdx = N->getNumOperands() - 1;
2363     if (N->getOperand(*TailPolicyOpIdx).getValueType() == MVT::Glue)
2364       (*TailPolicyOpIdx)--;
2365     if (N->getOperand(*TailPolicyOpIdx).getValueType() == MVT::Other)
2366       (*TailPolicyOpIdx)--;
2367 
2368     if (!(N->getConstantOperandVal(*TailPolicyOpIdx) &
2369           RISCVII::TAIL_AGNOSTIC)) {
2370       // Keep the true-masked instruction when there is no unmasked TU
2371       // instruction
2372       if (I->UnmaskedTUPseudo == I->MaskedPseudo && !N->getOperand(0).isUndef())
2373         return false;
2374       // We can't use TA if the tie-operand is not IMPLICIT_DEF
2375       if (!N->getOperand(0).isUndef())
2376         IsTA = false;
2377     }
2378   }
2379 
2380   if (IsTA) {
2381     uint64_t TSFlags = TII->get(I->UnmaskedPseudo).TSFlags;
2382 
2383     // Check that we're dropping the merge operand, the mask operand, and any
2384     // policy operand when we transform to this unmasked pseudo.
2385     assert(!RISCVII::hasMergeOp(TSFlags) && RISCVII::hasDummyMaskOp(TSFlags) &&
2386            !RISCVII::hasVecPolicyOp(TSFlags) &&
2387            "Unexpected pseudo to transform to");
2388     (void)TSFlags;
2389   } else {
2390     uint64_t TSFlags = TII->get(I->UnmaskedTUPseudo).TSFlags;
2391 
2392     // Check that we're dropping the mask operand, and any policy operand
2393     // when we transform to this unmasked tu pseudo.
2394     assert(RISCVII::hasMergeOp(TSFlags) && RISCVII::hasDummyMaskOp(TSFlags) &&
2395            !RISCVII::hasVecPolicyOp(TSFlags) &&
2396            "Unexpected pseudo to transform to");
2397     (void)TSFlags;
2398   }
2399 
2400   unsigned Opc = IsTA ? I->UnmaskedPseudo : I->UnmaskedTUPseudo;
2401   SmallVector<SDValue, 8> Ops;
2402   // Skip the merge operand at index 0 if IsTA
2403   for (unsigned I = IsTA, E = N->getNumOperands(); I != E; I++) {
2404     // Skip the mask, the policy, and the Glue.
2405     SDValue Op = N->getOperand(I);
2406     if (I == MaskOpIdx || I == TailPolicyOpIdx ||
2407         Op.getValueType() == MVT::Glue)
2408       continue;
2409     Ops.push_back(Op);
2410   }
2411 
2412   // Transitively apply any node glued to our new node.
2413   if (auto *TGlued = Glued->getGluedNode())
2414     Ops.push_back(SDValue(TGlued, TGlued->getNumValues() - 1));
2415 
2416   SDNode *Result = CurDAG->getMachineNode(Opc, SDLoc(N), N->getVTList(), Ops);
2417   ReplaceUses(N, Result);
2418 
2419   return true;
2420 }
2421 
2422 // This pass converts a legalized DAG into a RISCV-specific DAG, ready
2423 // for instruction scheduling.
2424 FunctionPass *llvm::createRISCVISelDag(RISCVTargetMachine &TM) {
2425   return new RISCVDAGToDAGISel(TM);
2426 }
2427