1 //===-- RISCVISelLowering.h - RISCV DAG Lowering Interface ------*- C++ -*-===//
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 the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_TARGET_RISCV_RISCVISELLOWERING_H
15 #define LLVM_LIB_TARGET_RISCV_RISCVISELLOWERING_H
16 
17 #include "RISCV.h"
18 #include "llvm/CodeGen/CallingConvLower.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/CodeGen/TargetLowering.h"
21 
22 namespace llvm {
23 class RISCVSubtarget;
24 struct RISCVRegisterInfo;
25 namespace RISCVISD {
26 enum NodeType : unsigned {
27   FIRST_NUMBER = ISD::BUILTIN_OP_END,
28   RET_FLAG,
29   URET_FLAG,
30   SRET_FLAG,
31   MRET_FLAG,
32   CALL,
33   /// Select with condition operator - This selects between a true value and
34   /// a false value (ops #3 and #4) based on the boolean result of comparing
35   /// the lhs and rhs (ops #0 and #1) of a conditional expression with the
36   /// condition code in op #2, a XLenVT constant from the ISD::CondCode enum.
37   /// The lhs and rhs are XLenVT integers. The true and false values can be
38   /// integer or floating point.
39   SELECT_CC,
40   BR_CC,
41   BuildPairF64,
42   SplitF64,
43   TAIL,
44   // Multiply high for signedxunsigned.
45   MULHSU,
46   // RV64I shifts, directly matching the semantics of the named RISC-V
47   // instructions.
48   SLLW,
49   SRAW,
50   SRLW,
51   // 32-bit operations from RV64M that can't be simply matched with a pattern
52   // at instruction selection time. These have undefined behavior for division
53   // by 0 or overflow (divw) like their target independent counterparts.
54   DIVW,
55   DIVUW,
56   REMUW,
57   // RV64IB rotates, directly matching the semantics of the named RISC-V
58   // instructions.
59   ROLW,
60   RORW,
61   // RV64IZbb bit counting instructions directly matching the semantics of the
62   // named RISC-V instructions.
63   CLZW,
64   CTZW,
65   // RV64IB/RV32IB funnel shifts, with the semantics of the named RISC-V
66   // instructions. Operand order is rs1, rs3, rs2/shamt.
67   FSR,
68   FSL,
69   // RV64IB funnel shifts, with the semantics of the named RISC-V instructions.
70   // Operand order is rs1, rs3, rs2/shamt.
71   FSRW,
72   FSLW,
73   // FPR<->GPR transfer operations when the FPR is smaller than XLEN, needed as
74   // XLEN is the only legal integer width.
75   //
76   // FMV_H_X matches the semantics of the FMV.H.X.
77   // FMV_X_ANYEXTH is similar to FMV.X.H but has an any-extended result.
78   // FMV_X_SIGNEXTH is similar to FMV.X.H and has a sign-extended result.
79   // FMV_W_X_RV64 matches the semantics of the FMV.W.X.
80   // FMV_X_ANYEXTW_RV64 is similar to FMV.X.W but has an any-extended result.
81   //
82   // This is a more convenient semantic for producing dagcombines that remove
83   // unnecessary GPR->FPR->GPR moves.
84   FMV_H_X,
85   FMV_X_ANYEXTH,
86   FMV_X_SIGNEXTH,
87   FMV_W_X_RV64,
88   FMV_X_ANYEXTW_RV64,
89   // FP to XLen int conversions. Corresponds to fcvt.l(u).s/d/h on RV64 and
90   // fcvt.w(u).s/d/h on RV32. Unlike FP_TO_S/UINT these saturate out of
91   // range inputs. These are used for FP_TO_S/UINT_SAT lowering. Rounding mode
92   // is passed as a TargetConstant operand using the RISCVFPRndMode enum.
93   FCVT_X,
94   FCVT_XU,
95   // FP to 32 bit int conversions for RV64. These are used to keep track of the
96   // result being sign extended to 64 bit. These saturate out of range inputs.
97   // Used for FP_TO_S/UINT and FP_TO_S/UINT_SAT lowering. Rounding mode
98   // is passed as a TargetConstant operand using the RISCVFPRndMode enum.
99   FCVT_W_RV64,
100   FCVT_WU_RV64,
101   // READ_CYCLE_WIDE - A read of the 64-bit cycle CSR on a 32-bit target
102   // (returns (Lo, Hi)). It takes a chain operand.
103   READ_CYCLE_WIDE,
104   // Generalized Reverse and Generalized Or-Combine - directly matching the
105   // semantics of the named RISC-V instructions. Lowered as custom nodes as
106   // TableGen chokes when faced with commutative permutations in deeply-nested
107   // DAGs. Each node takes an input operand and a control operand and outputs a
108   // bit-manipulated version of input. All operands are i32 or XLenVT.
109   GREV,
110   GREVW,
111   GORC,
112   GORCW,
113   SHFL,
114   SHFLW,
115   UNSHFL,
116   UNSHFLW,
117   // Bit Compress/Decompress implement the generic bit extract and bit deposit
118   // functions. This operation is also referred to as bit gather/scatter, bit
119   // pack/unpack, parallel extract/deposit, compress/expand, or right
120   // compress/right expand.
121   BCOMPRESS,
122   BCOMPRESSW,
123   BDECOMPRESS,
124   BDECOMPRESSW,
125   // The bit field place (bfp) instruction places up to XLEN/2 LSB bits from rs2
126   // into the value in rs1. The upper bits of rs2 control the length of the bit
127   // field and target position. The layout of rs2 is chosen in a way that makes
128   // it possible to construct rs2 easily using pack[h] instructions and/or
129   // andi/lui.
130   BFP,
131   BFPW,
132   // Vector Extension
133   // VMV_V_X_VL matches the semantics of vmv.v.x but includes an extra operand
134   // for the VL value to be used for the operation. The first operand is
135   // passthru operand.
136   VMV_V_X_VL,
137   // VFMV_V_F_VL matches the semantics of vfmv.v.f but includes an extra operand
138   // for the VL value to be used for the operation. The first operand is
139   // passthru operand.
140   VFMV_V_F_VL,
141   // VMV_X_S matches the semantics of vmv.x.s. The result is always XLenVT sign
142   // extended from the vector element size.
143   VMV_X_S,
144   // VMV_S_X_VL matches the semantics of vmv.s.x. It carries a VL operand.
145   VMV_S_X_VL,
146   // VFMV_S_F_VL matches the semantics of vfmv.s.f. It carries a VL operand.
147   VFMV_S_F_VL,
148   // Splats an 64-bit value that has been split into two i32 parts. This is
149   // expanded late to two scalar stores and a stride 0 vector load.
150   // The first operand is passthru operand.
151   SPLAT_VECTOR_SPLIT_I64_VL,
152   // Read VLENB CSR
153   READ_VLENB,
154   // Truncates a RVV integer vector by one power-of-two. Carries both an extra
155   // mask and VL operand.
156   TRUNCATE_VECTOR_VL,
157   // Matches the semantics of vslideup/vslidedown. The first operand is the
158   // pass-thru operand, the second is the source vector, the third is the
159   // XLenVT index (either constant or non-constant), the fourth is the mask
160   // and the fifth the VL.
161   VSLIDEUP_VL,
162   VSLIDEDOWN_VL,
163   // Matches the semantics of vslide1up/slide1down. The first operand is
164   // passthru operand, the second is source vector, third is the XLenVT scalar
165   // value. The fourth and fifth operands are the mask and VL operands.
166   VSLIDE1UP_VL,
167   VSLIDE1DOWN_VL,
168   // Matches the semantics of the vid.v instruction, with a mask and VL
169   // operand.
170   VID_VL,
171   // Matches the semantics of the vfcnvt.rod function (Convert double-width
172   // float to single-width float, rounding towards odd). Takes a double-width
173   // float vector and produces a single-width float vector. Also has a mask and
174   // VL operand.
175   VFNCVT_ROD_VL,
176   // These nodes match the semantics of the corresponding RVV vector reduction
177   // instructions. They produce a vector result which is the reduction
178   // performed over the second vector operand plus the first element of the
179   // third vector operand. The first operand is the pass-thru operand. The
180   // second operand is an unconstrained vector type, and the result, first, and
181   // third operand's types are expected to be the corresponding full-width
182   // LMUL=1 type for the second operand:
183   //   nxv8i8 = vecreduce_add nxv8i8, nxv32i8, nxv8i8
184   //   nxv2i32 = vecreduce_add nxv2i32, nxv8i32, nxv2i32
185   // The different in types does introduce extra vsetvli instructions but
186   // similarly it reduces the number of registers consumed per reduction.
187   // Also has a mask and VL operand.
188   VECREDUCE_ADD_VL,
189   VECREDUCE_UMAX_VL,
190   VECREDUCE_SMAX_VL,
191   VECREDUCE_UMIN_VL,
192   VECREDUCE_SMIN_VL,
193   VECREDUCE_AND_VL,
194   VECREDUCE_OR_VL,
195   VECREDUCE_XOR_VL,
196   VECREDUCE_FADD_VL,
197   VECREDUCE_SEQ_FADD_VL,
198   VECREDUCE_FMIN_VL,
199   VECREDUCE_FMAX_VL,
200 
201   // Vector binary and unary ops with a mask as a third operand, and VL as a
202   // fourth operand.
203   // FIXME: Can we replace these with ISD::VP_*?
204   ADD_VL,
205   AND_VL,
206   MUL_VL,
207   OR_VL,
208   SDIV_VL,
209   SHL_VL,
210   SREM_VL,
211   SRA_VL,
212   SRL_VL,
213   SUB_VL,
214   UDIV_VL,
215   UREM_VL,
216   XOR_VL,
217 
218   SADDSAT_VL,
219   UADDSAT_VL,
220   SSUBSAT_VL,
221   USUBSAT_VL,
222 
223   FADD_VL,
224   FSUB_VL,
225   FMUL_VL,
226   FDIV_VL,
227   FNEG_VL,
228   FABS_VL,
229   FSQRT_VL,
230   FMA_VL,
231   FCOPYSIGN_VL,
232   SMIN_VL,
233   SMAX_VL,
234   UMIN_VL,
235   UMAX_VL,
236   FMINNUM_VL,
237   FMAXNUM_VL,
238   MULHS_VL,
239   MULHU_VL,
240   FP_TO_SINT_VL,
241   FP_TO_UINT_VL,
242   SINT_TO_FP_VL,
243   UINT_TO_FP_VL,
244   FP_ROUND_VL,
245   FP_EXTEND_VL,
246 
247   // Widening instructions
248   VWMUL_VL,
249   VWMULU_VL,
250   VWMULSU_VL,
251   VWADD_VL,
252   VWADDU_VL,
253   VWSUB_VL,
254   VWSUBU_VL,
255   VWADD_W_VL,
256   VWADDU_W_VL,
257   VWSUB_W_VL,
258   VWSUBU_W_VL,
259 
260   // Vector compare producing a mask. Fourth operand is input mask. Fifth
261   // operand is VL.
262   SETCC_VL,
263 
264   // Vector select with an additional VL operand. This operation is unmasked.
265   VSELECT_VL,
266   // Vector select with operand #2 (the value when the condition is false) tied
267   // to the destination and an additional VL operand. This operation is
268   // unmasked.
269   VP_MERGE_VL,
270 
271   // Mask binary operators.
272   VMAND_VL,
273   VMOR_VL,
274   VMXOR_VL,
275 
276   // Set mask vector to all zeros or ones.
277   VMCLR_VL,
278   VMSET_VL,
279 
280   // Matches the semantics of vrgather.vx and vrgather.vv with an extra operand
281   // for VL.
282   VRGATHER_VX_VL,
283   VRGATHER_VV_VL,
284   VRGATHEREI16_VV_VL,
285 
286   // Vector sign/zero extend with additional mask & VL operands.
287   VSEXT_VL,
288   VZEXT_VL,
289 
290   //  vcpop.m with additional mask and VL operands.
291   VCPOP_VL,
292 
293   // Reads value of CSR.
294   // The first operand is a chain pointer. The second specifies address of the
295   // required CSR. Two results are produced, the read value and the new chain
296   // pointer.
297   READ_CSR,
298   // Write value to CSR.
299   // The first operand is a chain pointer, the second specifies address of the
300   // required CSR and the third is the value to write. The result is the new
301   // chain pointer.
302   WRITE_CSR,
303   // Read and write value of CSR.
304   // The first operand is a chain pointer, the second specifies address of the
305   // required CSR and the third is the value to write. Two results are produced,
306   // the value read before the modification and the new chain pointer.
307   SWAP_CSR,
308 
309   // FP to 32 bit int conversions for RV64. These are used to keep track of the
310   // result being sign extended to 64 bit. These saturate out of range inputs.
311   STRICT_FCVT_W_RV64 = ISD::FIRST_TARGET_STRICTFP_OPCODE,
312   STRICT_FCVT_WU_RV64,
313 
314   // WARNING: Do not add anything in the end unless you want the node to
315   // have memop! In fact, starting from FIRST_TARGET_MEMORY_OPCODE all
316   // opcodes will be thought as target memory ops!
317 };
318 } // namespace RISCVISD
319 
320 namespace RISCV {
321 // We use 64 bits as the known part in the scalable vector types.
322 static constexpr unsigned RVVBitsPerBlock = 64;
323 } // namespace RISCV
324 
325 class RISCVTargetLowering : public TargetLowering {
326   const RISCVSubtarget &Subtarget;
327 
328 public:
329   explicit RISCVTargetLowering(const TargetMachine &TM,
330                                const RISCVSubtarget &STI);
331 
332   const RISCVSubtarget &getSubtarget() const { return Subtarget; }
333 
334   bool getTgtMemIntrinsic(IntrinsicInfo &Info, const CallInst &I,
335                           MachineFunction &MF,
336                           unsigned Intrinsic) const override;
337   bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty,
338                              unsigned AS,
339                              Instruction *I = nullptr) const override;
340   bool isLegalICmpImmediate(int64_t Imm) const override;
341   bool isLegalAddImmediate(int64_t Imm) const override;
342   bool isTruncateFree(Type *SrcTy, Type *DstTy) const override;
343   bool isTruncateFree(EVT SrcVT, EVT DstVT) const override;
344   bool isZExtFree(SDValue Val, EVT VT2) const override;
345   bool isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const override;
346   bool signExtendConstant(const ConstantInt *CI) const override;
347   bool isCheapToSpeculateCttz() const override;
348   bool isCheapToSpeculateCtlz() const override;
349   bool hasAndNotCompare(SDValue Y) const override;
350   bool hasBitTest(SDValue X, SDValue Y) const override;
351   bool shouldSinkOperands(Instruction *I,
352                           SmallVectorImpl<Use *> &Ops) const override;
353   bool isFPImmLegal(const APFloat &Imm, EVT VT,
354                     bool ForCodeSize) const override;
355 
356   bool softPromoteHalfType() const override { return true; }
357 
358   /// Return the register type for a given MVT, ensuring vectors are treated
359   /// as a series of gpr sized integers.
360   MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC,
361                                     EVT VT) const override;
362 
363   /// Return the number of registers for a given MVT, ensuring vectors are
364   /// treated as a series of gpr sized integers.
365   unsigned getNumRegistersForCallingConv(LLVMContext &Context,
366                                          CallingConv::ID CC,
367                                          EVT VT) const override;
368 
369   /// Return true if the given shuffle mask can be codegen'd directly, or if it
370   /// should be stack expanded.
371   bool isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const override;
372 
373   bool hasBitPreservingFPLogic(EVT VT) const override;
374   bool
375   shouldExpandBuildVectorWithShuffles(EVT VT,
376                                       unsigned DefinedValues) const override;
377 
378   // Provide custom lowering hooks for some operations.
379   SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override;
380   void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
381                           SelectionDAG &DAG) const override;
382 
383   SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override;
384 
385   bool targetShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
386                                     const APInt &DemandedElts,
387                                     TargetLoweringOpt &TLO) const override;
388 
389   void computeKnownBitsForTargetNode(const SDValue Op,
390                                      KnownBits &Known,
391                                      const APInt &DemandedElts,
392                                      const SelectionDAG &DAG,
393                                      unsigned Depth) const override;
394   unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
395                                            const APInt &DemandedElts,
396                                            const SelectionDAG &DAG,
397                                            unsigned Depth) const override;
398 
399   // This method returns the name of a target specific DAG node.
400   const char *getTargetNodeName(unsigned Opcode) const override;
401 
402   ConstraintType getConstraintType(StringRef Constraint) const override;
403 
404   unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const override;
405 
406   std::pair<unsigned, const TargetRegisterClass *>
407   getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
408                                StringRef Constraint, MVT VT) const override;
409 
410   void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
411                                     std::vector<SDValue> &Ops,
412                                     SelectionDAG &DAG) const override;
413 
414   MachineBasicBlock *
415   EmitInstrWithCustomInserter(MachineInstr &MI,
416                               MachineBasicBlock *BB) const override;
417 
418   void AdjustInstrPostInstrSelection(MachineInstr &MI,
419                                      SDNode *Node) const override;
420 
421   EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
422                          EVT VT) const override;
423 
424   bool convertSetCCLogicToBitwiseLogic(EVT VT) const override {
425     return VT.isScalarInteger();
426   }
427   bool convertSelectOfConstantsToMath(EVT VT) const override { return true; }
428 
429   bool shouldInsertFencesForAtomic(const Instruction *I) const override {
430     return isa<LoadInst>(I) || isa<StoreInst>(I);
431   }
432   Instruction *emitLeadingFence(IRBuilderBase &Builder, Instruction *Inst,
433                                 AtomicOrdering Ord) const override;
434   Instruction *emitTrailingFence(IRBuilderBase &Builder, Instruction *Inst,
435                                  AtomicOrdering Ord) const override;
436 
437   bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
438                                   EVT VT) const override;
439 
440   ISD::NodeType getExtendForAtomicOps() const override {
441     return ISD::SIGN_EXTEND;
442   }
443 
444   ISD::NodeType getExtendForAtomicCmpSwapArg() const override {
445     return ISD::SIGN_EXTEND;
446   }
447 
448   bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const override {
449     if (DAG.getMachineFunction().getFunction().hasMinSize())
450       return false;
451     return true;
452   }
453   bool isDesirableToCommuteWithShift(const SDNode *N,
454                                      CombineLevel Level) const override;
455 
456   /// If a physical register, this returns the register that receives the
457   /// exception address on entry to an EH pad.
458   Register
459   getExceptionPointerRegister(const Constant *PersonalityFn) const override;
460 
461   /// If a physical register, this returns the register that receives the
462   /// exception typeid on entry to a landing pad.
463   Register
464   getExceptionSelectorRegister(const Constant *PersonalityFn) const override;
465 
466   bool shouldExtendTypeInLibCall(EVT Type) const override;
467   bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const override;
468 
469   /// Returns the register with the specified architectural or ABI name. This
470   /// method is necessary to lower the llvm.read_register.* and
471   /// llvm.write_register.* intrinsics. Allocatable registers must be reserved
472   /// with the clang -ffixed-xX flag for access to be allowed.
473   Register getRegisterByName(const char *RegName, LLT VT,
474                              const MachineFunction &MF) const override;
475 
476   // Lower incoming arguments, copy physregs into vregs
477   SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv,
478                                bool IsVarArg,
479                                const SmallVectorImpl<ISD::InputArg> &Ins,
480                                const SDLoc &DL, SelectionDAG &DAG,
481                                SmallVectorImpl<SDValue> &InVals) const override;
482   bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
483                       bool IsVarArg,
484                       const SmallVectorImpl<ISD::OutputArg> &Outs,
485                       LLVMContext &Context) const override;
486   SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
487                       const SmallVectorImpl<ISD::OutputArg> &Outs,
488                       const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
489                       SelectionDAG &DAG) const override;
490   SDValue LowerCall(TargetLowering::CallLoweringInfo &CLI,
491                     SmallVectorImpl<SDValue> &InVals) const override;
492   template <class NodeTy>
493   SDValue getAddr(NodeTy *N, SelectionDAG &DAG, bool IsLocal = true) const;
494 
495   bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
496                                          Type *Ty) const override {
497     return true;
498   }
499   bool mayBeEmittedAsTailCall(const CallInst *CI) const override;
500   bool shouldConsiderGEPOffsetSplit() const override { return true; }
501 
502   bool decomposeMulByConstant(LLVMContext &Context, EVT VT,
503                               SDValue C) const override;
504 
505   bool isMulAddWithConstProfitable(SDValue AddNode,
506                                    SDValue ConstNode) const override;
507 
508   TargetLowering::AtomicExpansionKind
509   shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const override;
510   Value *emitMaskedAtomicRMWIntrinsic(IRBuilderBase &Builder, AtomicRMWInst *AI,
511                                       Value *AlignedAddr, Value *Incr,
512                                       Value *Mask, Value *ShiftAmt,
513                                       AtomicOrdering Ord) const override;
514   TargetLowering::AtomicExpansionKind
515   shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CI) const override;
516   Value *emitMaskedAtomicCmpXchgIntrinsic(IRBuilderBase &Builder,
517                                           AtomicCmpXchgInst *CI,
518                                           Value *AlignedAddr, Value *CmpVal,
519                                           Value *NewVal, Value *Mask,
520                                           AtomicOrdering Ord) const override;
521 
522   /// Returns true if the target allows unaligned memory accesses of the
523   /// specified type.
524   bool allowsMisalignedMemoryAccesses(
525       EVT VT, unsigned AddrSpace = 0, Align Alignment = Align(1),
526       MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
527       bool *Fast = nullptr) const override;
528 
529   bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL,
530                                    SDValue Val, SDValue *Parts,
531                                    unsigned NumParts, MVT PartVT,
532                                    Optional<CallingConv::ID> CC) const override;
533 
534   SDValue
535   joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL,
536                              const SDValue *Parts, unsigned NumParts,
537                              MVT PartVT, EVT ValueVT,
538                              Optional<CallingConv::ID> CC) const override;
539 
540   static RISCVII::VLMUL getLMUL(MVT VT);
541   inline static unsigned computeVLMAX(unsigned VectorBits, unsigned EltSize,
542                                       unsigned MinSize) {
543     // Original equation:
544     //   VLMAX = (VectorBits / EltSize) * LMUL
545     //   where LMUL = MinSize / RISCV::RVVBitsPerBlock
546     // The following equations have been reordered to prevent loss of precision
547     // when calculating fractional LMUL.
548     return ((VectorBits / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
549   };
550   static unsigned getRegClassIDForLMUL(RISCVII::VLMUL LMul);
551   static unsigned getSubregIndexByMVT(MVT VT, unsigned Index);
552   static unsigned getRegClassIDForVecVT(MVT VT);
553   static std::pair<unsigned, unsigned>
554   decomposeSubvectorInsertExtractToSubRegs(MVT VecVT, MVT SubVecVT,
555                                            unsigned InsertExtractIdx,
556                                            const RISCVRegisterInfo *TRI);
557   MVT getContainerForFixedLengthVector(MVT VT) const;
558 
559   bool shouldRemoveExtendFromGSIndex(EVT VT) const override;
560 
561   bool isLegalElementTypeForRVV(Type *ScalarTy) const;
562 
563   bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const override;
564 
565   SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
566                         SmallVectorImpl<SDNode *> &Created) const override;
567 
568   unsigned getJumpTableEncoding() const override;
569 
570   const MCExpr *LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
571                                           const MachineBasicBlock *MBB,
572                                           unsigned uid,
573                                           MCContext &Ctx) const override;
574 
575 private:
576   /// RISCVCCAssignFn - This target-specific function extends the default
577   /// CCValAssign with additional information used to lower RISC-V calling
578   /// conventions.
579   typedef bool RISCVCCAssignFn(const DataLayout &DL, RISCVABI::ABI,
580                                unsigned ValNo, MVT ValVT, MVT LocVT,
581                                CCValAssign::LocInfo LocInfo,
582                                ISD::ArgFlagsTy ArgFlags, CCState &State,
583                                bool IsFixed, bool IsRet, Type *OrigTy,
584                                const RISCVTargetLowering &TLI,
585                                Optional<unsigned> FirstMaskArgument);
586 
587   void analyzeInputArgs(MachineFunction &MF, CCState &CCInfo,
588                         const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
589                         RISCVCCAssignFn Fn) const;
590   void analyzeOutputArgs(MachineFunction &MF, CCState &CCInfo,
591                          const SmallVectorImpl<ISD::OutputArg> &Outs,
592                          bool IsRet, CallLoweringInfo *CLI,
593                          RISCVCCAssignFn Fn) const;
594 
595   SDValue getStaticTLSAddr(GlobalAddressSDNode *N, SelectionDAG &DAG,
596                            bool UseGOT) const;
597   SDValue getDynamicTLSAddr(GlobalAddressSDNode *N, SelectionDAG &DAG) const;
598 
599   SDValue lowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const;
600   SDValue lowerBlockAddress(SDValue Op, SelectionDAG &DAG) const;
601   SDValue lowerConstantPool(SDValue Op, SelectionDAG &DAG) const;
602   SDValue lowerJumpTable(SDValue Op, SelectionDAG &DAG) const;
603   SDValue lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const;
604   SDValue lowerSELECT(SDValue Op, SelectionDAG &DAG) const;
605   SDValue lowerBRCOND(SDValue Op, SelectionDAG &DAG) const;
606   SDValue lowerVASTART(SDValue Op, SelectionDAG &DAG) const;
607   SDValue lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const;
608   SDValue lowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const;
609   SDValue lowerShiftLeftParts(SDValue Op, SelectionDAG &DAG) const;
610   SDValue lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, bool IsSRA) const;
611   SDValue lowerSPLAT_VECTOR_PARTS(SDValue Op, SelectionDAG &DAG) const;
612   SDValue lowerVectorMaskSplat(SDValue Op, SelectionDAG &DAG) const;
613   SDValue lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
614                              int64_t ExtTrueVal) const;
615   SDValue lowerVectorMaskTruncLike(SDValue Op, SelectionDAG &DAG) const;
616   SDValue lowerVectorTruncLike(SDValue Op, SelectionDAG &DAG) const;
617   SDValue lowerVectorFPRoundLike(SDValue Op, SelectionDAG &DAG) const;
618   SDValue lowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const;
619   SDValue lowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const;
620   SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const;
621   SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const;
622   SDValue LowerINTRINSIC_VOID(SDValue Op, SelectionDAG &DAG) const;
623   SDValue lowerVPREDUCE(SDValue Op, SelectionDAG &DAG) const;
624   SDValue lowerVECREDUCE(SDValue Op, SelectionDAG &DAG) const;
625   SDValue lowerVectorMaskVecReduction(SDValue Op, SelectionDAG &DAG,
626                                       bool IsVP) const;
627   SDValue lowerFPVECREDUCE(SDValue Op, SelectionDAG &DAG) const;
628   SDValue lowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const;
629   SDValue lowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const;
630   SDValue lowerSTEP_VECTOR(SDValue Op, SelectionDAG &DAG) const;
631   SDValue lowerVECTOR_REVERSE(SDValue Op, SelectionDAG &DAG) const;
632   SDValue lowerVECTOR_SPLICE(SDValue Op, SelectionDAG &DAG) const;
633   SDValue lowerABS(SDValue Op, SelectionDAG &DAG) const;
634   SDValue lowerMaskedLoad(SDValue Op, SelectionDAG &DAG) const;
635   SDValue lowerMaskedStore(SDValue Op, SelectionDAG &DAG) const;
636   SDValue lowerFixedLengthVectorFCOPYSIGNToRVV(SDValue Op,
637                                                SelectionDAG &DAG) const;
638   SDValue lowerMaskedGather(SDValue Op, SelectionDAG &DAG) const;
639   SDValue lowerMaskedScatter(SDValue Op, SelectionDAG &DAG) const;
640   SDValue lowerFixedLengthVectorLoadToRVV(SDValue Op, SelectionDAG &DAG) const;
641   SDValue lowerFixedLengthVectorStoreToRVV(SDValue Op, SelectionDAG &DAG) const;
642   SDValue lowerFixedLengthVectorSetccToRVV(SDValue Op, SelectionDAG &DAG) const;
643   SDValue lowerFixedLengthVectorLogicOpToRVV(SDValue Op, SelectionDAG &DAG,
644                                              unsigned MaskOpc,
645                                              unsigned VecOpc) const;
646   SDValue lowerFixedLengthVectorShiftToRVV(SDValue Op, SelectionDAG &DAG) const;
647   SDValue lowerFixedLengthVectorSelectToRVV(SDValue Op,
648                                             SelectionDAG &DAG) const;
649   SDValue lowerToScalableOp(SDValue Op, SelectionDAG &DAG, unsigned NewOpc,
650                             bool HasMask = true) const;
651   SDValue lowerVPOp(SDValue Op, SelectionDAG &DAG, unsigned RISCVISDOpc) const;
652   SDValue lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, unsigned MaskOpc,
653                          unsigned VecOpc) const;
654   SDValue lowerVPExtMaskOp(SDValue Op, SelectionDAG &DAG) const;
655   SDValue lowerVPSetCCMaskOp(SDValue Op, SelectionDAG &DAG) const;
656   SDValue lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
657                              unsigned RISCVISDOpc) const;
658   SDValue lowerFixedLengthVectorExtendToRVV(SDValue Op, SelectionDAG &DAG,
659                                             unsigned ExtendOpc) const;
660   SDValue lowerGET_ROUNDING(SDValue Op, SelectionDAG &DAG) const;
661   SDValue lowerSET_ROUNDING(SDValue Op, SelectionDAG &DAG) const;
662 
663   SDValue expandUnalignedRVVLoad(SDValue Op, SelectionDAG &DAG) const;
664   SDValue expandUnalignedRVVStore(SDValue Op, SelectionDAG &DAG) const;
665 
666   bool isEligibleForTailCallOptimization(
667       CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
668       const SmallVector<CCValAssign, 16> &ArgLocs) const;
669 
670   /// Generate error diagnostics if any register used by CC has been marked
671   /// reserved.
672   void validateCCReservedRegs(
673       const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
674       MachineFunction &MF) const;
675 
676   bool useRVVForFixedLengthVectorVT(MVT VT) const;
677 
678   MVT getVPExplicitVectorLengthTy() const override;
679 
680   /// RVV code generation for fixed length vectors does not lower all
681   /// BUILD_VECTORs. This makes BUILD_VECTOR legalisation a source of stores to
682   /// merge. However, merging them creates a BUILD_VECTOR that is just as
683   /// illegal as the original, thus leading to an infinite legalisation loop.
684   /// NOTE: Once BUILD_VECTOR can be custom lowered for all legal vector types,
685   /// this override can be removed.
686   bool mergeStoresAfterLegalization(EVT VT) const override;
687 
688   /// Disable normalizing
689   /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
690   /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y))
691   /// RISCV doesn't have flags so it's better to perform the and/or in a GPR.
692   bool shouldNormalizeToSelectSequence(LLVMContext &, EVT) const override {
693     return false;
694   };
695 };
696 namespace RISCVVIntrinsicsTable {
697 
698 struct RISCVVIntrinsicInfo {
699   unsigned IntrinsicID;
700   uint8_t ScalarOperand;
701   uint8_t VLOperand;
702   bool hasScalarOperand() const {
703     // 0xF is not valid. See NoScalarOperand in IntrinsicsRISCV.td.
704     return ScalarOperand != 0xF;
705   }
706   bool hasVLOperand() const {
707     // 0x1F is not valid. See NoVLOperand in IntrinsicsRISCV.td.
708     return VLOperand != 0x1F;
709   }
710 };
711 
712 using namespace RISCV;
713 
714 #define GET_RISCVVIntrinsicsTable_DECL
715 #include "RISCVGenSearchableTables.inc"
716 
717 } // end namespace RISCVVIntrinsicsTable
718 
719 } // end namespace llvm
720 
721 #endif
722