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 namespace RISCVISD {
24 enum NodeType : unsigned {
25   FIRST_NUMBER = ISD::BUILTIN_OP_END,
26   RET_FLAG,
27   URET_FLAG,
28   SRET_FLAG,
29   MRET_FLAG,
30   CALL,
31   SELECT_CC,
32   BuildPairF64,
33   SplitF64,
34   TAIL,
35   // RV64I shifts, directly matching the semantics of the named RISC-V
36   // instructions.
37   SLLW,
38   SRAW,
39   SRLW,
40   // 32-bit operations from RV64M that can't be simply matched with a pattern
41   // at instruction selection time.
42   DIVW,
43   DIVUW,
44   REMUW,
45   // RV64IB rotates, directly matching the semantics of the named RISC-V
46   // instructions.
47   ROLW,
48   RORW,
49   // FPR32<->GPR transfer operations for RV64. Needed as an i32<->f32 bitcast
50   // is not legal on RV64. FMV_W_X_RV64 matches the semantics of the FMV.W.X.
51   // FMV_X_ANYEXTW_RV64 is similar to FMV.X.W but has an any-extended result.
52   // This is a more convenient semantic for producing dagcombines that remove
53   // unnecessary GPR->FPR->GPR moves.
54   FMV_W_X_RV64,
55   FMV_X_ANYEXTW_RV64,
56   // READ_CYCLE_WIDE - A read of the 64-bit cycle CSR on a 32-bit target
57   // (returns (Lo, Hi)). It takes a chain operand.
58   READ_CYCLE_WIDE,
59   // Generalized Reverse and Generalized Or-Combine - directly matching the
60   // semantics of the named RISC-V instructions. Lowered as custom nodes as
61   // TableGen chokes when faced with commutative permutations in deeply-nested
62   // DAGs. Each node takes an input operand and a TargetConstant immediate
63   // shift amount, and outputs a bit-manipulated version of input. All operands
64   // are of type XLenVT.
65   GREVI,
66   GREVIW,
67   GORCI,
68   GORCIW,
69 };
70 } // namespace RISCVISD
71 
72 class RISCVTargetLowering : public TargetLowering {
73   const RISCVSubtarget &Subtarget;
74 
75 public:
76   explicit RISCVTargetLowering(const TargetMachine &TM,
77                                const RISCVSubtarget &STI);
78 
79   bool getTgtMemIntrinsic(IntrinsicInfo &Info, const CallInst &I,
80                           MachineFunction &MF,
81                           unsigned Intrinsic) const override;
82   bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty,
83                              unsigned AS,
84                              Instruction *I = nullptr) const override;
85   bool isLegalICmpImmediate(int64_t Imm) const override;
86   bool isLegalAddImmediate(int64_t Imm) const override;
87   bool isTruncateFree(Type *SrcTy, Type *DstTy) const override;
88   bool isTruncateFree(EVT SrcVT, EVT DstVT) const override;
89   bool isZExtFree(SDValue Val, EVT VT2) const override;
90   bool isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const override;
91   bool isCheapToSpeculateCttz() const override;
92   bool isCheapToSpeculateCtlz() const override;
93   bool isFPImmLegal(const APFloat &Imm, EVT VT,
94                     bool ForCodeSize) const override;
95 
96   bool hasBitPreservingFPLogic(EVT VT) const override;
97 
98   // Provide custom lowering hooks for some operations.
99   SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override;
100   void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
101                           SelectionDAG &DAG) const override;
102 
103   SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override;
104 
105   unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
106                                            const APInt &DemandedElts,
107                                            const SelectionDAG &DAG,
108                                            unsigned Depth) const override;
109 
110   // This method returns the name of a target specific DAG node.
111   const char *getTargetNodeName(unsigned Opcode) const override;
112 
113   ConstraintType getConstraintType(StringRef Constraint) const override;
114 
115   unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const override;
116 
117   std::pair<unsigned, const TargetRegisterClass *>
118   getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
119                                StringRef Constraint, MVT VT) const override;
120 
121   void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
122                                     std::vector<SDValue> &Ops,
123                                     SelectionDAG &DAG) const override;
124 
125   MachineBasicBlock *
126   EmitInstrWithCustomInserter(MachineInstr &MI,
127                               MachineBasicBlock *BB) const override;
128 
129   EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
130                          EVT VT) const override;
131 
132   bool convertSetCCLogicToBitwiseLogic(EVT VT) const override {
133     return VT.isScalarInteger();
134   }
135   bool convertSelectOfConstantsToMath(EVT VT) const override { return true; }
136 
137   bool shouldInsertFencesForAtomic(const Instruction *I) const override {
138     return isa<LoadInst>(I) || isa<StoreInst>(I);
139   }
140   Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
141                                 AtomicOrdering Ord) const override;
142   Instruction *emitTrailingFence(IRBuilder<> &Builder, Instruction *Inst,
143                                  AtomicOrdering Ord) const override;
144 
145   ISD::NodeType getExtendForAtomicOps() const override {
146     return ISD::SIGN_EXTEND;
147   }
148 
149   ISD::NodeType getExtendForAtomicCmpSwapArg() const override {
150     return ISD::SIGN_EXTEND;
151   }
152 
153   bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const override {
154     if (DAG.getMachineFunction().getFunction().hasMinSize())
155       return false;
156     return true;
157   }
158   bool isDesirableToCommuteWithShift(const SDNode *N,
159                                      CombineLevel Level) const override;
160 
161   /// If a physical register, this returns the register that receives the
162   /// exception address on entry to an EH pad.
163   Register
164   getExceptionPointerRegister(const Constant *PersonalityFn) const override;
165 
166   /// If a physical register, this returns the register that receives the
167   /// exception typeid on entry to a landing pad.
168   Register
169   getExceptionSelectorRegister(const Constant *PersonalityFn) const override;
170 
171   bool shouldExtendTypeInLibCall(EVT Type) const override;
172 
173   /// Returns the register with the specified architectural or ABI name. This
174   /// method is necessary to lower the llvm.read_register.* and
175   /// llvm.write_register.* intrinsics. Allocatable registers must be reserved
176   /// with the clang -ffixed-xX flag for access to be allowed.
177   Register getRegisterByName(const char *RegName, LLT VT,
178                              const MachineFunction &MF) const override;
179 
180   // Lower incoming arguments, copy physregs into vregs
181   SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv,
182                                bool IsVarArg,
183                                const SmallVectorImpl<ISD::InputArg> &Ins,
184                                const SDLoc &DL, SelectionDAG &DAG,
185                                SmallVectorImpl<SDValue> &InVals) const override;
186   bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
187                       bool IsVarArg,
188                       const SmallVectorImpl<ISD::OutputArg> &Outs,
189                       LLVMContext &Context) const override;
190   SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
191                       const SmallVectorImpl<ISD::OutputArg> &Outs,
192                       const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
193                       SelectionDAG &DAG) const override;
194   SDValue LowerCall(TargetLowering::CallLoweringInfo &CLI,
195                     SmallVectorImpl<SDValue> &InVals) const override;
196 
197   bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
198                                          Type *Ty) const override {
199     return true;
200   }
201   bool mayBeEmittedAsTailCall(const CallInst *CI) const override;
202   bool shouldConsiderGEPOffsetSplit() const override { return true; }
203 
204   bool decomposeMulByConstant(LLVMContext &Context, EVT VT,
205                               SDValue C) const override;
206 
207   TargetLowering::AtomicExpansionKind
208   shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const override;
209   Value *emitMaskedAtomicRMWIntrinsic(IRBuilder<> &Builder, AtomicRMWInst *AI,
210                                       Value *AlignedAddr, Value *Incr,
211                                       Value *Mask, Value *ShiftAmt,
212                                       AtomicOrdering Ord) const override;
213   TargetLowering::AtomicExpansionKind
214   shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CI) const override;
215   Value *emitMaskedAtomicCmpXchgIntrinsic(IRBuilder<> &Builder,
216                                           AtomicCmpXchgInst *CI,
217                                           Value *AlignedAddr, Value *CmpVal,
218                                           Value *NewVal, Value *Mask,
219                                           AtomicOrdering Ord) const override;
220 
221 private:
222   void analyzeInputArgs(MachineFunction &MF, CCState &CCInfo,
223                         const SmallVectorImpl<ISD::InputArg> &Ins,
224                         bool IsRet) const;
225   void analyzeOutputArgs(MachineFunction &MF, CCState &CCInfo,
226                          const SmallVectorImpl<ISD::OutputArg> &Outs,
227                          bool IsRet, CallLoweringInfo *CLI) const;
228 
229   template <class NodeTy>
230   SDValue getAddr(NodeTy *N, SelectionDAG &DAG, bool IsLocal = true) const;
231 
232   SDValue getStaticTLSAddr(GlobalAddressSDNode *N, SelectionDAG &DAG,
233                            bool UseGOT) const;
234   SDValue getDynamicTLSAddr(GlobalAddressSDNode *N, SelectionDAG &DAG) const;
235 
236   SDValue lowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const;
237   SDValue lowerBlockAddress(SDValue Op, SelectionDAG &DAG) const;
238   SDValue lowerConstantPool(SDValue Op, SelectionDAG &DAG) const;
239   SDValue lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const;
240   SDValue lowerSELECT(SDValue Op, SelectionDAG &DAG) const;
241   SDValue lowerVASTART(SDValue Op, SelectionDAG &DAG) const;
242   SDValue lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const;
243   SDValue lowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const;
244   SDValue lowerShiftLeftParts(SDValue Op, SelectionDAG &DAG) const;
245   SDValue lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, bool IsSRA) const;
246   SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const;
247 
248   bool isEligibleForTailCallOptimization(
249       CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
250       const SmallVector<CCValAssign, 16> &ArgLocs) const;
251 
252   /// Generate error diagnostics if any register used by CC has been marked
253   /// reserved.
254   void validateCCReservedRegs(
255       const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
256       MachineFunction &MF) const;
257 };
258 }
259 
260 #endif
261