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