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/SelectionDAG.h"
19 #include "llvm/CodeGen/TargetLowering.h"
20 
21 namespace llvm {
22 class RISCVSubtarget;
23 struct RISCVRegisterInfo;
24 namespace RISCVISD {
25 enum NodeType : unsigned {
26   FIRST_NUMBER = ISD::BUILTIN_OP_END,
27   RET_FLAG,
28   URET_FLAG,
29   SRET_FLAG,
30   MRET_FLAG,
31   CALL,
32   /// Select with condition operator - This selects between a true value and
33   /// a false value (ops #3 and #4) based on the boolean result of comparing
34   /// the lhs and rhs (ops #0 and #1) of a conditional expression with the
35   /// condition code in op #2, a XLenVT constant from the ISD::CondCode enum.
36   /// The lhs and rhs are XLenVT integers. The true and false values can be
37   /// integer or floating point.
38   SELECT_CC,
39   BuildPairF64,
40   SplitF64,
41   TAIL,
42   // RV64I shifts, directly matching the semantics of the named RISC-V
43   // instructions.
44   SLLW,
45   SRAW,
46   SRLW,
47   // 32-bit operations from RV64M that can't be simply matched with a pattern
48   // at instruction selection time. These have undefined behavior for division
49   // by 0 or overflow (divw) like their target independent counterparts.
50   DIVW,
51   DIVUW,
52   REMUW,
53   // RV64IB rotates, directly matching the semantics of the named RISC-V
54   // instructions.
55   ROLW,
56   RORW,
57   // RV64IB/RV32IB funnel shifts, with the semantics of the named RISC-V
58   // instructions, but the same operand order as fshl/fshr intrinsics.
59   FSR,
60   FSL,
61   // RV64IB funnel shifts, with the semantics of the named RISC-V instructions,
62   // but the same operand order as fshl/fshr intrinsics.
63   FSRW,
64   FSLW,
65   // FPR<->GPR transfer operations when the FPR is smaller than XLEN, needed as
66   // XLEN is the only legal integer width.
67   //
68   // FMV_H_X matches the semantics of the FMV.H.X.
69   // FMV_X_ANYEXTH is similar to FMV.X.H but has an any-extended result.
70   // FMV_W_X_RV64 matches the semantics of the FMV.W.X.
71   // FMV_X_ANYEXTW_RV64 is similar to FMV.X.W but has an any-extended result.
72   //
73   // This is a more convenient semantic for producing dagcombines that remove
74   // unnecessary GPR->FPR->GPR moves.
75   FMV_H_X,
76   FMV_X_ANYEXTH,
77   FMV_W_X_RV64,
78   FMV_X_ANYEXTW_RV64,
79   // READ_CYCLE_WIDE - A read of the 64-bit cycle CSR on a 32-bit target
80   // (returns (Lo, Hi)). It takes a chain operand.
81   READ_CYCLE_WIDE,
82   // Generalized Reverse and Generalized Or-Combine - directly matching the
83   // semantics of the named RISC-V instructions. Lowered as custom nodes as
84   // TableGen chokes when faced with commutative permutations in deeply-nested
85   // DAGs. Each node takes an input operand and a TargetConstant immediate
86   // shift amount, and outputs a bit-manipulated version of input. All operands
87   // are of type XLenVT.
88   GREVI,
89   GREVIW,
90   GORCI,
91   GORCIW,
92   SHFLI,
93   // Vector Extension
94   // VMV_V_X_VL matches the semantics of vmv.v.x but includes an extra operand
95   // for the VL value to be used for the operation.
96   VMV_V_X_VL,
97   // VFMV_V_F_VL matches the semantics of vfmv.v.f but includes an extra operand
98   // for the VL value to be used for the operation.
99   VFMV_V_F_VL,
100   // VMV_X_S matches the semantics of vmv.x.s. The result is always XLenVT sign
101   // extended from the vector element size.
102   VMV_X_S,
103   // Splats an i64 scalar to a vector type (with element type i64) where the
104   // scalar is a sign-extended i32.
105   SPLAT_VECTOR_I64,
106   // Read VLENB CSR
107   READ_VLENB,
108   // Truncates a RVV integer vector by one power-of-two. Carries both an extra
109   // mask and VL operand.
110   TRUNCATE_VECTOR_VL,
111   // Unit-stride fault-only-first load
112   VLEFF,
113   VLEFF_MASK,
114   // Matches the semantics of vslideup/vslidedown. The first operand is the
115   // pass-thru operand, the second is the source vector, the third is the
116   // XLenVT index (either constant or non-constant), the fourth is the mask
117   // and the fifth the VL.
118   VSLIDEUP_VL,
119   VSLIDEDOWN_VL,
120   // Matches the semantics of the vid.v instruction, with a mask and VL
121   // operand.
122   VID_VL,
123   // Matches the semantics of the vfcnvt.rod function (Convert double-width
124   // float to single-width float, rounding towards odd). Takes a double-width
125   // float vector and produces a single-width float vector. Also has a mask and
126   // VL operand.
127   VFNCVT_ROD_VL,
128   // These nodes match the semantics of the corresponding RVV vector reduction
129   // instructions. They produce a vector result which is the reduction
130   // performed over the first vector operand plus the first element of the
131   // second vector operand. The first operand is an unconstrained vector type,
132   // and the result and second operand's types are expected to be the
133   // corresponding full-width LMUL=1 type for the first operand:
134   //   nxv8i8 = vecreduce_add nxv32i8, nxv8i8
135   //   nxv2i32 = vecreduce_add nxv8i32, nxv2i32
136   // The different in types does introduce extra vsetvli instructions but
137   // similarly it reduces the number of registers consumed per reduction.
138   VECREDUCE_ADD,
139   VECREDUCE_UMAX,
140   VECREDUCE_SMAX,
141   VECREDUCE_UMIN,
142   VECREDUCE_SMIN,
143   VECREDUCE_AND,
144   VECREDUCE_OR,
145   VECREDUCE_XOR,
146   VECREDUCE_FADD,
147   VECREDUCE_SEQ_FADD,
148 
149   // Vector binary and unary ops with a mask as a third operand, and VL as a
150   // fourth operand.
151   // FIXME: Can we replace these with ISD::VP_*?
152   ADD_VL,
153   AND_VL,
154   MUL_VL,
155   OR_VL,
156   SDIV_VL,
157   SHL_VL,
158   SREM_VL,
159   SRA_VL,
160   SRL_VL,
161   SUB_VL,
162   UDIV_VL,
163   UREM_VL,
164   XOR_VL,
165   FADD_VL,
166   FSUB_VL,
167   FMUL_VL,
168   FDIV_VL,
169   FNEG_VL,
170   FABS_VL,
171   FSQRT_VL,
172   FMA_VL,
173   SMIN_VL,
174   SMAX_VL,
175   UMIN_VL,
176   UMAX_VL,
177   MULHS_VL,
178   MULHU_VL,
179   FP_TO_SINT_VL,
180   FP_TO_UINT_VL,
181   SINT_TO_FP_VL,
182   UINT_TO_FP_VL,
183   FP_ROUND_VL,
184   FP_EXTEND_VL,
185 
186   // Vector compare producing a mask. Fourth operand is input mask. Fifth
187   // operand is VL.
188   SETCC_VL,
189 
190   // Vector select with an additional VL operand. This operation is unmasked.
191   VSELECT_VL,
192 
193   // Mask binary operators.
194   VMAND_VL,
195   VMOR_VL,
196   VMXOR_VL,
197 
198   // Set mask vector to all zeros or ones.
199   VMCLR_VL,
200   VMSET_VL,
201 
202   // Matches the semantics of vrgather.vx with an extra operand for VL.
203   VRGATHER_VX_VL,
204 
205   // Vector sign/zero extend with additional mask & VL operands.
206   VSEXT_VL,
207   VZEXT_VL,
208 
209   // Memory opcodes start here.
210   VLE_VL = ISD::FIRST_TARGET_MEMORY_OPCODE,
211   VSE_VL,
212 
213   // WARNING: Do not add anything in the end unless you want the node to
214   // have memop! In fact, starting from FIRST_TARGET_MEMORY_OPCODE all
215   // opcodes will be thought as target memory ops!
216 };
217 } // namespace RISCVISD
218 
219 class RISCVTargetLowering : public TargetLowering {
220   const RISCVSubtarget &Subtarget;
221 
222 public:
223   explicit RISCVTargetLowering(const TargetMachine &TM,
224                                const RISCVSubtarget &STI);
225 
226   const RISCVSubtarget &getSubtarget() const { return Subtarget; }
227 
228   bool getTgtMemIntrinsic(IntrinsicInfo &Info, const CallInst &I,
229                           MachineFunction &MF,
230                           unsigned Intrinsic) const override;
231   bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty,
232                              unsigned AS,
233                              Instruction *I = nullptr) const override;
234   bool isLegalICmpImmediate(int64_t Imm) const override;
235   bool isLegalAddImmediate(int64_t Imm) const override;
236   bool isTruncateFree(Type *SrcTy, Type *DstTy) const override;
237   bool isTruncateFree(EVT SrcVT, EVT DstVT) const override;
238   bool isZExtFree(SDValue Val, EVT VT2) const override;
239   bool isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const override;
240   bool isCheapToSpeculateCttz() const override;
241   bool isCheapToSpeculateCtlz() const override;
242   bool isFPImmLegal(const APFloat &Imm, EVT VT,
243                     bool ForCodeSize) const override;
244 
245   bool hasBitPreservingFPLogic(EVT VT) const override;
246   bool
247   shouldExpandBuildVectorWithShuffles(EVT VT,
248                                       unsigned DefinedValues) const override;
249 
250   // Provide custom lowering hooks for some operations.
251   SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override;
252   void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
253                           SelectionDAG &DAG) const override;
254 
255   SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override;
256 
257   bool targetShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
258                                     const APInt &DemandedElts,
259                                     TargetLoweringOpt &TLO) const override;
260 
261   void computeKnownBitsForTargetNode(const SDValue Op,
262                                      KnownBits &Known,
263                                      const APInt &DemandedElts,
264                                      const SelectionDAG &DAG,
265                                      unsigned Depth) const override;
266   unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
267                                            const APInt &DemandedElts,
268                                            const SelectionDAG &DAG,
269                                            unsigned Depth) const override;
270 
271   // This method returns the name of a target specific DAG node.
272   const char *getTargetNodeName(unsigned Opcode) const override;
273 
274   ConstraintType getConstraintType(StringRef Constraint) const override;
275 
276   unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const override;
277 
278   std::pair<unsigned, const TargetRegisterClass *>
279   getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
280                                StringRef Constraint, MVT VT) const override;
281 
282   void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
283                                     std::vector<SDValue> &Ops,
284                                     SelectionDAG &DAG) const override;
285 
286   MachineBasicBlock *
287   EmitInstrWithCustomInserter(MachineInstr &MI,
288                               MachineBasicBlock *BB) const override;
289 
290   EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
291                          EVT VT) const override;
292 
293   bool convertSetCCLogicToBitwiseLogic(EVT VT) const override {
294     return VT.isScalarInteger();
295   }
296   bool convertSelectOfConstantsToMath(EVT VT) const override { return true; }
297 
298   bool shouldInsertFencesForAtomic(const Instruction *I) const override {
299     return isa<LoadInst>(I) || isa<StoreInst>(I);
300   }
301   Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
302                                 AtomicOrdering Ord) const override;
303   Instruction *emitTrailingFence(IRBuilder<> &Builder, Instruction *Inst,
304                                  AtomicOrdering Ord) const override;
305 
306   bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
307                                   EVT VT) const override;
308 
309   ISD::NodeType getExtendForAtomicOps() const override {
310     return ISD::SIGN_EXTEND;
311   }
312 
313   ISD::NodeType getExtendForAtomicCmpSwapArg() const override {
314     return ISD::SIGN_EXTEND;
315   }
316 
317   bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const override {
318     if (DAG.getMachineFunction().getFunction().hasMinSize())
319       return false;
320     return true;
321   }
322   bool isDesirableToCommuteWithShift(const SDNode *N,
323                                      CombineLevel Level) const override;
324 
325   /// If a physical register, this returns the register that receives the
326   /// exception address on entry to an EH pad.
327   Register
328   getExceptionPointerRegister(const Constant *PersonalityFn) const override;
329 
330   /// If a physical register, this returns the register that receives the
331   /// exception typeid on entry to a landing pad.
332   Register
333   getExceptionSelectorRegister(const Constant *PersonalityFn) const override;
334 
335   bool shouldExtendTypeInLibCall(EVT Type) const override;
336   bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const override;
337 
338   /// Returns the register with the specified architectural or ABI name. This
339   /// method is necessary to lower the llvm.read_register.* and
340   /// llvm.write_register.* intrinsics. Allocatable registers must be reserved
341   /// with the clang -ffixed-xX flag for access to be allowed.
342   Register getRegisterByName(const char *RegName, LLT VT,
343                              const MachineFunction &MF) const override;
344 
345   // Lower incoming arguments, copy physregs into vregs
346   SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv,
347                                bool IsVarArg,
348                                const SmallVectorImpl<ISD::InputArg> &Ins,
349                                const SDLoc &DL, SelectionDAG &DAG,
350                                SmallVectorImpl<SDValue> &InVals) const override;
351   bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
352                       bool IsVarArg,
353                       const SmallVectorImpl<ISD::OutputArg> &Outs,
354                       LLVMContext &Context) const override;
355   SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
356                       const SmallVectorImpl<ISD::OutputArg> &Outs,
357                       const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
358                       SelectionDAG &DAG) const override;
359   SDValue LowerCall(TargetLowering::CallLoweringInfo &CLI,
360                     SmallVectorImpl<SDValue> &InVals) const override;
361 
362   bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
363                                          Type *Ty) const override {
364     return true;
365   }
366   bool mayBeEmittedAsTailCall(const CallInst *CI) const override;
367   bool shouldConsiderGEPOffsetSplit() const override { return true; }
368 
369   bool decomposeMulByConstant(LLVMContext &Context, EVT VT,
370                               SDValue C) const override;
371 
372   TargetLowering::AtomicExpansionKind
373   shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const override;
374   Value *emitMaskedAtomicRMWIntrinsic(IRBuilder<> &Builder, AtomicRMWInst *AI,
375                                       Value *AlignedAddr, Value *Incr,
376                                       Value *Mask, Value *ShiftAmt,
377                                       AtomicOrdering Ord) const override;
378   TargetLowering::AtomicExpansionKind
379   shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CI) const override;
380   Value *emitMaskedAtomicCmpXchgIntrinsic(IRBuilder<> &Builder,
381                                           AtomicCmpXchgInst *CI,
382                                           Value *AlignedAddr, Value *CmpVal,
383                                           Value *NewVal, Value *Mask,
384                                           AtomicOrdering Ord) const override;
385 
386   /// Returns true if the target allows unaligned memory accesses of the
387   /// specified type.
388   bool allowsMisalignedMemoryAccesses(
389       EVT VT, unsigned AddrSpace = 0, Align Alignment = Align(1),
390       MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
391       bool *Fast = nullptr) const override;
392 
393   static RISCVVLMUL getLMUL(MVT VT);
394   static unsigned getRegClassIDForLMUL(RISCVVLMUL LMul);
395   static unsigned getSubregIndexByMVT(MVT VT, unsigned Index);
396   static unsigned getRegClassIDForVecVT(MVT VT);
397   static std::pair<unsigned, unsigned>
398   decomposeSubvectorInsertExtractToSubRegs(MVT VecVT, MVT SubVecVT,
399                                            unsigned InsertExtractIdx,
400                                            const RISCVRegisterInfo *TRI);
401   static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
402                                               const RISCVSubtarget &Subtarget);
403 
404 private:
405   void analyzeInputArgs(MachineFunction &MF, CCState &CCInfo,
406                         const SmallVectorImpl<ISD::InputArg> &Ins,
407                         bool IsRet) const;
408   void analyzeOutputArgs(MachineFunction &MF, CCState &CCInfo,
409                          const SmallVectorImpl<ISD::OutputArg> &Outs,
410                          bool IsRet, CallLoweringInfo *CLI) const;
411 
412   template <class NodeTy>
413   SDValue getAddr(NodeTy *N, SelectionDAG &DAG, bool IsLocal = true) const;
414 
415   SDValue getStaticTLSAddr(GlobalAddressSDNode *N, SelectionDAG &DAG,
416                            bool UseGOT) const;
417   SDValue getDynamicTLSAddr(GlobalAddressSDNode *N, SelectionDAG &DAG) const;
418 
419   SDValue lowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const;
420   SDValue lowerBlockAddress(SDValue Op, SelectionDAG &DAG) const;
421   SDValue lowerConstantPool(SDValue Op, SelectionDAG &DAG) const;
422   SDValue lowerJumpTable(SDValue Op, SelectionDAG &DAG) const;
423   SDValue lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const;
424   SDValue lowerSELECT(SDValue Op, SelectionDAG &DAG) const;
425   SDValue lowerVASTART(SDValue Op, SelectionDAG &DAG) const;
426   SDValue lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const;
427   SDValue lowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const;
428   SDValue lowerShiftLeftParts(SDValue Op, SelectionDAG &DAG) const;
429   SDValue lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, bool IsSRA) const;
430   SDValue lowerSPLATVECTOR(SDValue Op, SelectionDAG &DAG) const;
431   SDValue lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
432                              int64_t ExtTrueVal) const;
433   SDValue lowerVectorMaskTrunc(SDValue Op, SelectionDAG &DAG) const;
434   SDValue lowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const;
435   SDValue lowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const;
436   SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const;
437   SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const;
438   SDValue lowerVECREDUCE(SDValue Op, SelectionDAG &DAG) const;
439   SDValue lowerFPVECREDUCE(SDValue Op, SelectionDAG &DAG) const;
440   SDValue lowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const;
441   SDValue lowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const;
442   SDValue lowerFixedLengthVectorLoadToRVV(SDValue Op, SelectionDAG &DAG) const;
443   SDValue lowerFixedLengthVectorStoreToRVV(SDValue Op, SelectionDAG &DAG) const;
444   SDValue lowerFixedLengthVectorSetccToRVV(SDValue Op, SelectionDAG &DAG) const;
445   SDValue lowerFixedLengthVectorLogicOpToRVV(SDValue Op, SelectionDAG &DAG,
446                                              unsigned MaskOpc,
447                                              unsigned VecOpc) const;
448   SDValue lowerFixedLengthVectorSelectToRVV(SDValue Op,
449                                             SelectionDAG &DAG) const;
450   SDValue lowerToScalableOp(SDValue Op, SelectionDAG &DAG, unsigned NewOpc,
451                             bool HasMask = true) const;
452   SDValue lowerFixedLengthVectorExtendToRVV(SDValue Op, SelectionDAG &DAG,
453                                             unsigned ExtendOpc) const;
454 
455   bool isEligibleForTailCallOptimization(
456       CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
457       const SmallVector<CCValAssign, 16> &ArgLocs) const;
458 
459   /// Generate error diagnostics if any register used by CC has been marked
460   /// reserved.
461   void validateCCReservedRegs(
462       const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
463       MachineFunction &MF) const;
464 
465   bool useRVVForFixedLengthVectorVT(MVT VT) const;
466 };
467 
468 namespace RISCV {
469 // We use 64 bits as the known part in the scalable vector types.
470 static constexpr unsigned RVVBitsPerBlock = 64;
471 } // namespace RISCV
472 
473 namespace RISCVVIntrinsicsTable {
474 
475 struct RISCVVIntrinsicInfo {
476   unsigned IntrinsicID;
477   uint8_t ExtendedOperand;
478 };
479 
480 using namespace RISCV;
481 
482 #define GET_RISCVVIntrinsicsTable_DECL
483 #include "RISCVGenSearchableTables.inc"
484 
485 } // end namespace RISCVVIntrinsicsTable
486 
487 } // end namespace llvm
488 
489 #endif
490