1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
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 #include "RISCVISelLowering.h"
15 #include "RISCV.h"
16 #include "RISCVMachineFunctionInfo.h"
17 #include "RISCVRegisterInfo.h"
18 #include "RISCVSubtarget.h"
19 #include "RISCVTargetMachine.h"
20 #include "Utils/RISCVMatInt.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/IntrinsicsRISCV.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "riscv-lower"
41 
42 STATISTIC(NumTailCalls, "Number of tail calls");
43 
44 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
45                                          const RISCVSubtarget &STI)
46     : TargetLowering(TM), Subtarget(STI) {
47 
48   if (Subtarget.isRV32E())
49     report_fatal_error("Codegen not yet implemented for RV32E");
50 
51   RISCVABI::ABI ABI = Subtarget.getTargetABI();
52   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
53 
54   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
55       !Subtarget.hasStdExtF()) {
56     errs() << "Hard-float 'f' ABI can't be used for a target that "
57                 "doesn't support the F instruction set extension (ignoring "
58                           "target-abi)\n";
59     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
60   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
61              !Subtarget.hasStdExtD()) {
62     errs() << "Hard-float 'd' ABI can't be used for a target that "
63               "doesn't support the D instruction set extension (ignoring "
64               "target-abi)\n";
65     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
66   }
67 
68   switch (ABI) {
69   default:
70     report_fatal_error("Don't know how to lower this ABI");
71   case RISCVABI::ABI_ILP32:
72   case RISCVABI::ABI_ILP32F:
73   case RISCVABI::ABI_ILP32D:
74   case RISCVABI::ABI_LP64:
75   case RISCVABI::ABI_LP64F:
76   case RISCVABI::ABI_LP64D:
77     break;
78   }
79 
80   MVT XLenVT = Subtarget.getXLenVT();
81 
82   // Set up the register classes.
83   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
84 
85   if (Subtarget.hasStdExtF())
86     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
87   if (Subtarget.hasStdExtD())
88     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
89 
90   // Compute derived properties from the register classes.
91   computeRegisterProperties(STI.getRegisterInfo());
92 
93   setStackPointerRegisterToSaveRestore(RISCV::X2);
94 
95   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
96     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
97 
98   // TODO: add all necessary setOperationAction calls.
99   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
100 
101   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
102   setOperationAction(ISD::BR_CC, XLenVT, Expand);
103   setOperationAction(ISD::SELECT, XLenVT, Custom);
104   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
105 
106   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
107   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
108 
109   setOperationAction(ISD::VASTART, MVT::Other, Custom);
110   setOperationAction(ISD::VAARG, MVT::Other, Expand);
111   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
112   setOperationAction(ISD::VAEND, MVT::Other, Expand);
113 
114   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
115   if (!Subtarget.hasStdExtZbb()) {
116     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
117     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
118   }
119 
120   if (Subtarget.is64Bit()) {
121     setOperationAction(ISD::ADD, MVT::i32, Custom);
122     setOperationAction(ISD::SUB, MVT::i32, Custom);
123     setOperationAction(ISD::SHL, MVT::i32, Custom);
124     setOperationAction(ISD::SRA, MVT::i32, Custom);
125     setOperationAction(ISD::SRL, MVT::i32, Custom);
126   }
127 
128   if (!Subtarget.hasStdExtM()) {
129     setOperationAction(ISD::MUL, XLenVT, Expand);
130     setOperationAction(ISD::MULHS, XLenVT, Expand);
131     setOperationAction(ISD::MULHU, XLenVT, Expand);
132     setOperationAction(ISD::SDIV, XLenVT, Expand);
133     setOperationAction(ISD::UDIV, XLenVT, Expand);
134     setOperationAction(ISD::SREM, XLenVT, Expand);
135     setOperationAction(ISD::UREM, XLenVT, Expand);
136   }
137 
138   if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) {
139     setOperationAction(ISD::MUL, MVT::i32, Custom);
140     setOperationAction(ISD::SDIV, MVT::i32, Custom);
141     setOperationAction(ISD::UDIV, MVT::i32, Custom);
142     setOperationAction(ISD::UREM, MVT::i32, Custom);
143   }
144 
145   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
146   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
147   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
148   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
149 
150   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
151   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
152   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
153 
154   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
155     if (Subtarget.is64Bit()) {
156       setOperationAction(ISD::ROTL, MVT::i32, Custom);
157       setOperationAction(ISD::ROTR, MVT::i32, Custom);
158     }
159   } else {
160     setOperationAction(ISD::ROTL, XLenVT, Expand);
161     setOperationAction(ISD::ROTR, XLenVT, Expand);
162   }
163 
164   if (Subtarget.hasStdExtZbp()) {
165     setOperationAction(ISD::BITREVERSE, XLenVT, Legal);
166 
167     if (Subtarget.is64Bit()) {
168       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
169       setOperationAction(ISD::BSWAP, MVT::i32, Custom);
170     }
171   } else {
172     setOperationAction(ISD::BSWAP, XLenVT, Expand);
173   }
174 
175   if (!Subtarget.hasStdExtZbb()) {
176     setOperationAction(ISD::CTTZ, XLenVT, Expand);
177     setOperationAction(ISD::CTLZ, XLenVT, Expand);
178     setOperationAction(ISD::CTPOP, XLenVT, Expand);
179   }
180 
181   if (Subtarget.hasStdExtZbt()) {
182     setOperationAction(ISD::FSHL, XLenVT, Legal);
183     setOperationAction(ISD::FSHR, XLenVT, Legal);
184   }
185 
186   ISD::CondCode FPCCToExtend[] = {
187       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
188       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
189       ISD::SETGE,  ISD::SETNE};
190 
191   ISD::NodeType FPOpToExtend[] = {
192       ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP,
193       ISD::FP_TO_FP16};
194 
195   if (Subtarget.hasStdExtF()) {
196     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
197     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
198     for (auto CC : FPCCToExtend)
199       setCondCodeAction(CC, MVT::f32, Expand);
200     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
201     setOperationAction(ISD::SELECT, MVT::f32, Custom);
202     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
203     for (auto Op : FPOpToExtend)
204       setOperationAction(Op, MVT::f32, Expand);
205     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
206     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
207   }
208 
209   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
210     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
211 
212   if (Subtarget.hasStdExtD()) {
213     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
214     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
215     for (auto CC : FPCCToExtend)
216       setCondCodeAction(CC, MVT::f64, Expand);
217     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
218     setOperationAction(ISD::SELECT, MVT::f64, Custom);
219     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
220     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
221     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
222     for (auto Op : FPOpToExtend)
223       setOperationAction(Op, MVT::f64, Expand);
224     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
225     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
226   }
227 
228   if (Subtarget.is64Bit()) {
229     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
230     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
231     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
232     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
233   }
234 
235   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
236   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
237   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
238 
239   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
240 
241   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
242   // Unfortunately this can't be determined just from the ISA naming string.
243   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
244                      Subtarget.is64Bit() ? Legal : Custom);
245 
246   setOperationAction(ISD::TRAP, MVT::Other, Legal);
247   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
248   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
249 
250   if (Subtarget.hasStdExtA()) {
251     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
252     setMinCmpXchgSizeInBits(32);
253   } else {
254     setMaxAtomicSizeInBitsSupported(0);
255   }
256 
257   setBooleanContents(ZeroOrOneBooleanContent);
258 
259   // Function alignments.
260   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
261   setMinFunctionAlignment(FunctionAlignment);
262   setPrefFunctionAlignment(FunctionAlignment);
263 
264   // Effectively disable jump table generation.
265   setMinimumJumpTableEntries(INT_MAX);
266 
267   // Jumps are expensive, compared to logic
268   setJumpIsExpensive();
269 
270   // We can use any register for comparisons
271   setHasMultipleConditionRegisters();
272 
273   if (Subtarget.hasStdExtZbp()) {
274     setTargetDAGCombine(ISD::OR);
275   }
276 }
277 
278 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
279                                             EVT VT) const {
280   if (!VT.isVector())
281     return getPointerTy(DL);
282   return VT.changeVectorElementTypeToInteger();
283 }
284 
285 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
286                                              const CallInst &I,
287                                              MachineFunction &MF,
288                                              unsigned Intrinsic) const {
289   switch (Intrinsic) {
290   default:
291     return false;
292   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
293   case Intrinsic::riscv_masked_atomicrmw_add_i32:
294   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
295   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
296   case Intrinsic::riscv_masked_atomicrmw_max_i32:
297   case Intrinsic::riscv_masked_atomicrmw_min_i32:
298   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
299   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
300   case Intrinsic::riscv_masked_cmpxchg_i32:
301     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
302     Info.opc = ISD::INTRINSIC_W_CHAIN;
303     Info.memVT = MVT::getVT(PtrTy->getElementType());
304     Info.ptrVal = I.getArgOperand(0);
305     Info.offset = 0;
306     Info.align = Align(4);
307     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
308                  MachineMemOperand::MOVolatile;
309     return true;
310   }
311 }
312 
313 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
314                                                 const AddrMode &AM, Type *Ty,
315                                                 unsigned AS,
316                                                 Instruction *I) const {
317   // No global is ever allowed as a base.
318   if (AM.BaseGV)
319     return false;
320 
321   // Require a 12-bit signed offset.
322   if (!isInt<12>(AM.BaseOffs))
323     return false;
324 
325   switch (AM.Scale) {
326   case 0: // "r+i" or just "i", depending on HasBaseReg.
327     break;
328   case 1:
329     if (!AM.HasBaseReg) // allow "r+i".
330       break;
331     return false; // disallow "r+r" or "r+r+i".
332   default:
333     return false;
334   }
335 
336   return true;
337 }
338 
339 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
340   return isInt<12>(Imm);
341 }
342 
343 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
344   return isInt<12>(Imm);
345 }
346 
347 // On RV32, 64-bit integers are split into their high and low parts and held
348 // in two different registers, so the trunc is free since the low register can
349 // just be used.
350 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
351   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
352     return false;
353   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
354   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
355   return (SrcBits == 64 && DestBits == 32);
356 }
357 
358 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
359   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
360       !SrcVT.isInteger() || !DstVT.isInteger())
361     return false;
362   unsigned SrcBits = SrcVT.getSizeInBits();
363   unsigned DestBits = DstVT.getSizeInBits();
364   return (SrcBits == 64 && DestBits == 32);
365 }
366 
367 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
368   // Zexts are free if they can be combined with a load.
369   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
370     EVT MemVT = LD->getMemoryVT();
371     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
372          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
373         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
374          LD->getExtensionType() == ISD::ZEXTLOAD))
375       return true;
376   }
377 
378   return TargetLowering::isZExtFree(Val, VT2);
379 }
380 
381 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
382   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
383 }
384 
385 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
386   return Subtarget.hasStdExtZbb();
387 }
388 
389 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
390   return Subtarget.hasStdExtZbb();
391 }
392 
393 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
394                                        bool ForCodeSize) const {
395   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
396     return false;
397   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
398     return false;
399   if (Imm.isNegZero())
400     return false;
401   return Imm.isZero();
402 }
403 
404 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
405   return (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
406          (VT == MVT::f64 && Subtarget.hasStdExtD());
407 }
408 
409 // Changes the condition code and swaps operands if necessary, so the SetCC
410 // operation matches one of the comparisons supported directly in the RISC-V
411 // ISA.
412 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
413   switch (CC) {
414   default:
415     break;
416   case ISD::SETGT:
417   case ISD::SETLE:
418   case ISD::SETUGT:
419   case ISD::SETULE:
420     CC = ISD::getSetCCSwappedOperands(CC);
421     std::swap(LHS, RHS);
422     break;
423   }
424 }
425 
426 // Return the RISC-V branch opcode that matches the given DAG integer
427 // condition code. The CondCode must be one of those supported by the RISC-V
428 // ISA (see normaliseSetCC).
429 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
430   switch (CC) {
431   default:
432     llvm_unreachable("Unsupported CondCode");
433   case ISD::SETEQ:
434     return RISCV::BEQ;
435   case ISD::SETNE:
436     return RISCV::BNE;
437   case ISD::SETLT:
438     return RISCV::BLT;
439   case ISD::SETGE:
440     return RISCV::BGE;
441   case ISD::SETULT:
442     return RISCV::BLTU;
443   case ISD::SETUGE:
444     return RISCV::BGEU;
445   }
446 }
447 
448 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
449                                             SelectionDAG &DAG) const {
450   switch (Op.getOpcode()) {
451   default:
452     report_fatal_error("unimplemented operand");
453   case ISD::GlobalAddress:
454     return lowerGlobalAddress(Op, DAG);
455   case ISD::BlockAddress:
456     return lowerBlockAddress(Op, DAG);
457   case ISD::ConstantPool:
458     return lowerConstantPool(Op, DAG);
459   case ISD::GlobalTLSAddress:
460     return lowerGlobalTLSAddress(Op, DAG);
461   case ISD::SELECT:
462     return lowerSELECT(Op, DAG);
463   case ISD::VASTART:
464     return lowerVASTART(Op, DAG);
465   case ISD::FRAMEADDR:
466     return lowerFRAMEADDR(Op, DAG);
467   case ISD::RETURNADDR:
468     return lowerRETURNADDR(Op, DAG);
469   case ISD::SHL_PARTS:
470     return lowerShiftLeftParts(Op, DAG);
471   case ISD::SRA_PARTS:
472     return lowerShiftRightParts(Op, DAG, true);
473   case ISD::SRL_PARTS:
474     return lowerShiftRightParts(Op, DAG, false);
475   case ISD::BITCAST: {
476     assert(Subtarget.is64Bit() && Subtarget.hasStdExtF() &&
477            "Unexpected custom legalisation");
478     SDLoc DL(Op);
479     SDValue Op0 = Op.getOperand(0);
480     if (Op.getValueType() != MVT::f32 || Op0.getValueType() != MVT::i32)
481       return SDValue();
482     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
483     SDValue FPConv = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
484     return FPConv;
485   }
486   case ISD::INTRINSIC_WO_CHAIN:
487     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
488   }
489 }
490 
491 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
492                              SelectionDAG &DAG, unsigned Flags) {
493   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
494 }
495 
496 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
497                              SelectionDAG &DAG, unsigned Flags) {
498   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
499                                    Flags);
500 }
501 
502 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
503                              SelectionDAG &DAG, unsigned Flags) {
504   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
505                                    N->getOffset(), Flags);
506 }
507 
508 template <class NodeTy>
509 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
510                                      bool IsLocal) const {
511   SDLoc DL(N);
512   EVT Ty = getPointerTy(DAG.getDataLayout());
513 
514   if (isPositionIndependent()) {
515     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
516     if (IsLocal)
517       // Use PC-relative addressing to access the symbol. This generates the
518       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
519       // %pcrel_lo(auipc)).
520       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
521 
522     // Use PC-relative addressing to access the GOT for this symbol, then load
523     // the address from the GOT. This generates the pattern (PseudoLA sym),
524     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
525     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
526   }
527 
528   switch (getTargetMachine().getCodeModel()) {
529   default:
530     report_fatal_error("Unsupported code model for lowering");
531   case CodeModel::Small: {
532     // Generate a sequence for accessing addresses within the first 2 GiB of
533     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
534     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
535     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
536     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
537     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
538   }
539   case CodeModel::Medium: {
540     // Generate a sequence for accessing addresses within any 2GiB range within
541     // the address space. This generates the pattern (PseudoLLA sym), which
542     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
543     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
544     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
545   }
546   }
547 }
548 
549 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
550                                                 SelectionDAG &DAG) const {
551   SDLoc DL(Op);
552   EVT Ty = Op.getValueType();
553   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
554   int64_t Offset = N->getOffset();
555   MVT XLenVT = Subtarget.getXLenVT();
556 
557   const GlobalValue *GV = N->getGlobal();
558   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
559   SDValue Addr = getAddr(N, DAG, IsLocal);
560 
561   // In order to maximise the opportunity for common subexpression elimination,
562   // emit a separate ADD node for the global address offset instead of folding
563   // it in the global address node. Later peephole optimisations may choose to
564   // fold it back in when profitable.
565   if (Offset != 0)
566     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
567                        DAG.getConstant(Offset, DL, XLenVT));
568   return Addr;
569 }
570 
571 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
572                                                SelectionDAG &DAG) const {
573   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
574 
575   return getAddr(N, DAG);
576 }
577 
578 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
579                                                SelectionDAG &DAG) const {
580   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
581 
582   return getAddr(N, DAG);
583 }
584 
585 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
586                                               SelectionDAG &DAG,
587                                               bool UseGOT) const {
588   SDLoc DL(N);
589   EVT Ty = getPointerTy(DAG.getDataLayout());
590   const GlobalValue *GV = N->getGlobal();
591   MVT XLenVT = Subtarget.getXLenVT();
592 
593   if (UseGOT) {
594     // Use PC-relative addressing to access the GOT for this TLS symbol, then
595     // load the address from the GOT and add the thread pointer. This generates
596     // the pattern (PseudoLA_TLS_IE sym), which expands to
597     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
598     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
599     SDValue Load =
600         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
601 
602     // Add the thread pointer.
603     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
604     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
605   }
606 
607   // Generate a sequence for accessing the address relative to the thread
608   // pointer, with the appropriate adjustment for the thread pointer offset.
609   // This generates the pattern
610   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
611   SDValue AddrHi =
612       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
613   SDValue AddrAdd =
614       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
615   SDValue AddrLo =
616       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
617 
618   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
619   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
620   SDValue MNAdd = SDValue(
621       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
622       0);
623   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
624 }
625 
626 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
627                                                SelectionDAG &DAG) const {
628   SDLoc DL(N);
629   EVT Ty = getPointerTy(DAG.getDataLayout());
630   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
631   const GlobalValue *GV = N->getGlobal();
632 
633   // Use a PC-relative addressing mode to access the global dynamic GOT address.
634   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
635   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
636   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
637   SDValue Load =
638       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
639 
640   // Prepare argument list to generate call.
641   ArgListTy Args;
642   ArgListEntry Entry;
643   Entry.Node = Load;
644   Entry.Ty = CallTy;
645   Args.push_back(Entry);
646 
647   // Setup call to __tls_get_addr.
648   TargetLowering::CallLoweringInfo CLI(DAG);
649   CLI.setDebugLoc(DL)
650       .setChain(DAG.getEntryNode())
651       .setLibCallee(CallingConv::C, CallTy,
652                     DAG.getExternalSymbol("__tls_get_addr", Ty),
653                     std::move(Args));
654 
655   return LowerCallTo(CLI).first;
656 }
657 
658 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
659                                                    SelectionDAG &DAG) const {
660   SDLoc DL(Op);
661   EVT Ty = Op.getValueType();
662   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
663   int64_t Offset = N->getOffset();
664   MVT XLenVT = Subtarget.getXLenVT();
665 
666   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
667 
668   SDValue Addr;
669   switch (Model) {
670   case TLSModel::LocalExec:
671     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
672     break;
673   case TLSModel::InitialExec:
674     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
675     break;
676   case TLSModel::LocalDynamic:
677   case TLSModel::GeneralDynamic:
678     Addr = getDynamicTLSAddr(N, DAG);
679     break;
680   }
681 
682   // In order to maximise the opportunity for common subexpression elimination,
683   // emit a separate ADD node for the global address offset instead of folding
684   // it in the global address node. Later peephole optimisations may choose to
685   // fold it back in when profitable.
686   if (Offset != 0)
687     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
688                        DAG.getConstant(Offset, DL, XLenVT));
689   return Addr;
690 }
691 
692 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
693   SDValue CondV = Op.getOperand(0);
694   SDValue TrueV = Op.getOperand(1);
695   SDValue FalseV = Op.getOperand(2);
696   SDLoc DL(Op);
697   MVT XLenVT = Subtarget.getXLenVT();
698 
699   // If the result type is XLenVT and CondV is the output of a SETCC node
700   // which also operated on XLenVT inputs, then merge the SETCC node into the
701   // lowered RISCVISD::SELECT_CC to take advantage of the integer
702   // compare+branch instructions. i.e.:
703   // (select (setcc lhs, rhs, cc), truev, falsev)
704   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
705   if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
706       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
707     SDValue LHS = CondV.getOperand(0);
708     SDValue RHS = CondV.getOperand(1);
709     auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
710     ISD::CondCode CCVal = CC->get();
711 
712     normaliseSetCC(LHS, RHS, CCVal);
713 
714     SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
715     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
716     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
717   }
718 
719   // Otherwise:
720   // (select condv, truev, falsev)
721   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
722   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
723   SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
724 
725   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
726 
727   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
728 }
729 
730 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
731   MachineFunction &MF = DAG.getMachineFunction();
732   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
733 
734   SDLoc DL(Op);
735   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
736                                  getPointerTy(MF.getDataLayout()));
737 
738   // vastart just stores the address of the VarArgsFrameIndex slot into the
739   // memory location argument.
740   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
741   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
742                       MachinePointerInfo(SV));
743 }
744 
745 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
746                                             SelectionDAG &DAG) const {
747   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
748   MachineFunction &MF = DAG.getMachineFunction();
749   MachineFrameInfo &MFI = MF.getFrameInfo();
750   MFI.setFrameAddressIsTaken(true);
751   Register FrameReg = RI.getFrameRegister(MF);
752   int XLenInBytes = Subtarget.getXLen() / 8;
753 
754   EVT VT = Op.getValueType();
755   SDLoc DL(Op);
756   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
757   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
758   while (Depth--) {
759     int Offset = -(XLenInBytes * 2);
760     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
761                               DAG.getIntPtrConstant(Offset, DL));
762     FrameAddr =
763         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
764   }
765   return FrameAddr;
766 }
767 
768 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
769                                              SelectionDAG &DAG) const {
770   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
771   MachineFunction &MF = DAG.getMachineFunction();
772   MachineFrameInfo &MFI = MF.getFrameInfo();
773   MFI.setReturnAddressIsTaken(true);
774   MVT XLenVT = Subtarget.getXLenVT();
775   int XLenInBytes = Subtarget.getXLen() / 8;
776 
777   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
778     return SDValue();
779 
780   EVT VT = Op.getValueType();
781   SDLoc DL(Op);
782   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
783   if (Depth) {
784     int Off = -XLenInBytes;
785     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
786     SDValue Offset = DAG.getConstant(Off, DL, VT);
787     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
788                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
789                        MachinePointerInfo());
790   }
791 
792   // Return the value of the return address register, marking it an implicit
793   // live-in.
794   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
795   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
796 }
797 
798 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
799                                                  SelectionDAG &DAG) const {
800   SDLoc DL(Op);
801   SDValue Lo = Op.getOperand(0);
802   SDValue Hi = Op.getOperand(1);
803   SDValue Shamt = Op.getOperand(2);
804   EVT VT = Lo.getValueType();
805 
806   // if Shamt-XLEN < 0: // Shamt < XLEN
807   //   Lo = Lo << Shamt
808   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
809   // else:
810   //   Lo = 0
811   //   Hi = Lo << (Shamt-XLEN)
812 
813   SDValue Zero = DAG.getConstant(0, DL, VT);
814   SDValue One = DAG.getConstant(1, DL, VT);
815   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
816   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
817   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
818   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
819 
820   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
821   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
822   SDValue ShiftRightLo =
823       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
824   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
825   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
826   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
827 
828   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
829 
830   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
831   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
832 
833   SDValue Parts[2] = {Lo, Hi};
834   return DAG.getMergeValues(Parts, DL);
835 }
836 
837 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
838                                                   bool IsSRA) const {
839   SDLoc DL(Op);
840   SDValue Lo = Op.getOperand(0);
841   SDValue Hi = Op.getOperand(1);
842   SDValue Shamt = Op.getOperand(2);
843   EVT VT = Lo.getValueType();
844 
845   // SRA expansion:
846   //   if Shamt-XLEN < 0: // Shamt < XLEN
847   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
848   //     Hi = Hi >>s Shamt
849   //   else:
850   //     Lo = Hi >>s (Shamt-XLEN);
851   //     Hi = Hi >>s (XLEN-1)
852   //
853   // SRL expansion:
854   //   if Shamt-XLEN < 0: // Shamt < XLEN
855   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
856   //     Hi = Hi >>u Shamt
857   //   else:
858   //     Lo = Hi >>u (Shamt-XLEN);
859   //     Hi = 0;
860 
861   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
862 
863   SDValue Zero = DAG.getConstant(0, DL, VT);
864   SDValue One = DAG.getConstant(1, DL, VT);
865   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
866   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
867   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
868   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
869 
870   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
871   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
872   SDValue ShiftLeftHi =
873       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
874   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
875   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
876   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
877   SDValue HiFalse =
878       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
879 
880   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
881 
882   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
883   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
884 
885   SDValue Parts[2] = {Lo, Hi};
886   return DAG.getMergeValues(Parts, DL);
887 }
888 
889 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
890                                                      SelectionDAG &DAG) const {
891   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
892   SDLoc DL(Op);
893   switch (IntNo) {
894   default:
895     return SDValue();    // Don't custom lower most intrinsics.
896   case Intrinsic::thread_pointer: {
897     EVT PtrVT = getPointerTy(DAG.getDataLayout());
898     return DAG.getRegister(RISCV::X4, PtrVT);
899   }
900   }
901 }
902 
903 // Returns the opcode of the target-specific SDNode that implements the 32-bit
904 // form of the given Opcode.
905 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
906   switch (Opcode) {
907   default:
908     llvm_unreachable("Unexpected opcode");
909   case ISD::SHL:
910     return RISCVISD::SLLW;
911   case ISD::SRA:
912     return RISCVISD::SRAW;
913   case ISD::SRL:
914     return RISCVISD::SRLW;
915   case ISD::SDIV:
916     return RISCVISD::DIVW;
917   case ISD::UDIV:
918     return RISCVISD::DIVUW;
919   case ISD::UREM:
920     return RISCVISD::REMUW;
921   case ISD::ROTL:
922     return RISCVISD::ROLW;
923   case ISD::ROTR:
924     return RISCVISD::RORW;
925   case RISCVISD::GREVI:
926     return RISCVISD::GREVIW;
927   case RISCVISD::GORCI:
928     return RISCVISD::GORCIW;
929   }
930 }
931 
932 // Converts the given 32-bit operation to a target-specific SelectionDAG node.
933 // Because i32 isn't a legal type for RV64, these operations would otherwise
934 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W
935 // later one because the fact the operation was originally of type i32 is
936 // lost.
937 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG) {
938   SDLoc DL(N);
939   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
940   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
941   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
942   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
943   // ReplaceNodeResults requires we maintain the same type for the return value.
944   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
945 }
946 
947 // Converts the given 32-bit operation to a i64 operation with signed extension
948 // semantic to reduce the signed extension instructions.
949 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
950   SDLoc DL(N);
951   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
952   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
953   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
954   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
955                                DAG.getValueType(MVT::i32));
956   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
957 }
958 
959 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
960                                              SmallVectorImpl<SDValue> &Results,
961                                              SelectionDAG &DAG) const {
962   SDLoc DL(N);
963   switch (N->getOpcode()) {
964   default:
965     llvm_unreachable("Don't know how to custom type legalize this operation!");
966   case ISD::STRICT_FP_TO_SINT:
967   case ISD::STRICT_FP_TO_UINT:
968   case ISD::FP_TO_SINT:
969   case ISD::FP_TO_UINT: {
970     bool IsStrict = N->isStrictFPOpcode();
971     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
972            "Unexpected custom legalisation");
973     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
974     // If the FP type needs to be softened, emit a library call using the 'si'
975     // version. If we left it to default legalization we'd end up with 'di'. If
976     // the FP type doesn't need to be softened just let generic type
977     // legalization promote the result type.
978     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
979         TargetLowering::TypeSoftenFloat)
980       return;
981     RTLIB::Libcall LC;
982     if (N->getOpcode() == ISD::FP_TO_SINT ||
983         N->getOpcode() == ISD::STRICT_FP_TO_SINT)
984       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
985     else
986       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
987     MakeLibCallOptions CallOptions;
988     EVT OpVT = Op0.getValueType();
989     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
990     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
991     SDValue Result;
992     std::tie(Result, Chain) =
993         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
994     Results.push_back(Result);
995     if (IsStrict)
996       Results.push_back(Chain);
997     break;
998   }
999   case ISD::READCYCLECOUNTER: {
1000     assert(!Subtarget.is64Bit() &&
1001            "READCYCLECOUNTER only has custom type legalization on riscv32");
1002 
1003     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
1004     SDValue RCW =
1005         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
1006 
1007     Results.push_back(
1008         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
1009     Results.push_back(RCW.getValue(2));
1010     break;
1011   }
1012   case ISD::ADD:
1013   case ISD::SUB:
1014   case ISD::MUL:
1015     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1016            "Unexpected custom legalisation");
1017     if (N->getOperand(1).getOpcode() == ISD::Constant)
1018       return;
1019     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
1020     break;
1021   case ISD::SHL:
1022   case ISD::SRA:
1023   case ISD::SRL:
1024     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1025            "Unexpected custom legalisation");
1026     if (N->getOperand(1).getOpcode() == ISD::Constant)
1027       return;
1028     Results.push_back(customLegalizeToWOp(N, DAG));
1029     break;
1030   case ISD::ROTL:
1031   case ISD::ROTR:
1032     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1033            "Unexpected custom legalisation");
1034     Results.push_back(customLegalizeToWOp(N, DAG));
1035     break;
1036   case ISD::SDIV:
1037   case ISD::UDIV:
1038   case ISD::UREM:
1039     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1040            Subtarget.hasStdExtM() && "Unexpected custom legalisation");
1041     if (N->getOperand(0).getOpcode() == ISD::Constant ||
1042         N->getOperand(1).getOpcode() == ISD::Constant)
1043       return;
1044     Results.push_back(customLegalizeToWOp(N, DAG));
1045     break;
1046   case ISD::BITCAST: {
1047     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1048            Subtarget.hasStdExtF() && "Unexpected custom legalisation");
1049     SDValue Op0 = N->getOperand(0);
1050     if (Op0.getValueType() != MVT::f32)
1051       return;
1052     SDValue FPConv =
1053         DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
1054     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
1055     break;
1056   }
1057   case RISCVISD::GREVI:
1058   case RISCVISD::GORCI: {
1059     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1060            "Unexpected custom legalisation");
1061     // This is similar to customLegalizeToWOp, except that we pass the second
1062     // operand (a TargetConstant) straight through: it is already of type
1063     // XLenVT.
1064     SDLoc DL(N);
1065     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
1066     SDValue NewOp0 =
1067         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
1068     SDValue NewRes =
1069         DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, N->getOperand(1));
1070     // ReplaceNodeResults requires we maintain the same type for the return
1071     // value.
1072     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
1073     break;
1074   }
1075   case ISD::BSWAP:
1076   case ISD::BITREVERSE: {
1077     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1078            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
1079     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
1080                                  N->getOperand(0));
1081     unsigned Imm = N->getOpcode() == ISD::BITREVERSE ? 31 : 24;
1082     SDValue GREVIW = DAG.getNode(RISCVISD::GREVIW, DL, MVT::i64, NewOp0,
1083                                  DAG.getTargetConstant(Imm, DL,
1084                                                        Subtarget.getXLenVT()));
1085     // ReplaceNodeResults requires we maintain the same type for the return
1086     // value.
1087     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, GREVIW));
1088     break;
1089   }
1090   }
1091 }
1092 
1093 // A structure to hold one of the bit-manipulation patterns below. Together, a
1094 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
1095 //   (or (and (shl x, 1), 0xAAAAAAAA),
1096 //       (and (srl x, 1), 0x55555555))
1097 struct RISCVBitmanipPat {
1098   SDValue Op;
1099   unsigned ShAmt;
1100   bool IsSHL;
1101 
1102   bool formsPairWith(const RISCVBitmanipPat &Other) const {
1103     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
1104   }
1105 };
1106 
1107 // Matches any of the following bit-manipulation patterns:
1108 //   (and (shl x, 1), (0x55555555 << 1))
1109 //   (and (srl x, 1), 0x55555555)
1110 //   (shl (and x, 0x55555555), 1)
1111 //   (srl (and x, (0x55555555 << 1)), 1)
1112 // where the shift amount and mask may vary thus:
1113 //   [1]  = 0x55555555 / 0xAAAAAAAA
1114 //   [2]  = 0x33333333 / 0xCCCCCCCC
1115 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
1116 //   [8]  = 0x00FF00FF / 0xFF00FF00
1117 //   [16] = 0x0000FFFF / 0xFFFFFFFF
1118 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
1119 static Optional<RISCVBitmanipPat> matchRISCVBitmanipPat(SDValue Op) {
1120   Optional<uint64_t> Mask;
1121   // Optionally consume a mask around the shift operation.
1122   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
1123     Mask = Op.getConstantOperandVal(1);
1124     Op = Op.getOperand(0);
1125   }
1126   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
1127     return None;
1128   bool IsSHL = Op.getOpcode() == ISD::SHL;
1129 
1130   if (!isa<ConstantSDNode>(Op.getOperand(1)))
1131     return None;
1132   auto ShAmt = Op.getConstantOperandVal(1);
1133 
1134   if (!isPowerOf2_64(ShAmt))
1135     return None;
1136 
1137   // These are the unshifted masks which we use to match bit-manipulation
1138   // patterns. They may be shifted left in certain circumstances.
1139   static const uint64_t BitmanipMasks[] = {
1140       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
1141       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL,
1142   };
1143 
1144   unsigned MaskIdx = Log2_64(ShAmt);
1145   if (MaskIdx >= array_lengthof(BitmanipMasks))
1146     return None;
1147 
1148   auto Src = Op.getOperand(0);
1149 
1150   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
1151   auto ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
1152 
1153   // The expected mask is shifted left when the AND is found around SHL
1154   // patterns.
1155   //   ((x >> 1) & 0x55555555)
1156   //   ((x << 1) & 0xAAAAAAAA)
1157   bool SHLExpMask = IsSHL;
1158 
1159   if (!Mask) {
1160     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
1161     // the mask is all ones: consume that now.
1162     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
1163       Mask = Src.getConstantOperandVal(1);
1164       Src = Src.getOperand(0);
1165       // The expected mask is now in fact shifted left for SRL, so reverse the
1166       // decision.
1167       //   ((x & 0xAAAAAAAA) >> 1)
1168       //   ((x & 0x55555555) << 1)
1169       SHLExpMask = !SHLExpMask;
1170     } else {
1171       // Use a default shifted mask of all-ones if there's no AND, truncated
1172       // down to the expected width. This simplifies the logic later on.
1173       Mask = maskTrailingOnes<uint64_t>(Width);
1174       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
1175     }
1176   }
1177 
1178   if (SHLExpMask)
1179     ExpMask <<= ShAmt;
1180 
1181   if (Mask != ExpMask)
1182     return None;
1183 
1184   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
1185 }
1186 
1187 // Match the following pattern as a GREVI(W) operation
1188 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
1189 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
1190                                const RISCVSubtarget &Subtarget) {
1191   if (Op.getSimpleValueType() == Subtarget.getXLenVT() ||
1192       (Subtarget.is64Bit() && Op.getSimpleValueType() == MVT::i32)) {
1193     auto LHS = matchRISCVBitmanipPat(Op.getOperand(0));
1194     auto RHS = matchRISCVBitmanipPat(Op.getOperand(1));
1195     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
1196       SDLoc DL(Op);
1197       return DAG.getNode(
1198           RISCVISD::GREVI, DL, Op.getValueType(), LHS->Op,
1199           DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT()));
1200     }
1201   }
1202   return SDValue();
1203 }
1204 
1205 // Matches any the following pattern as a GORCI(W) operation
1206 // 1.  (or (GREVI x, shamt), x)
1207 // 2.  (or x, (GREVI x, shamt))
1208 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
1209 // Note that with the variant of 3.,
1210 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
1211 // the inner pattern will first be matched as GREVI and then the outer
1212 // pattern will be matched to GORC via the first rule above.
1213 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
1214                                const RISCVSubtarget &Subtarget) {
1215   if (Op.getSimpleValueType() == Subtarget.getXLenVT() ||
1216       (Subtarget.is64Bit() && Op.getSimpleValueType() == MVT::i32)) {
1217     SDLoc DL(Op);
1218     SDValue Op0 = Op.getOperand(0);
1219     SDValue Op1 = Op.getOperand(1);
1220 
1221     // Check for either commutable permutation of (or (GREVI x, shamt), x)
1222     for (const auto &OpPair :
1223          {std::make_pair(Op0, Op1), std::make_pair(Op1, Op0)}) {
1224       if (OpPair.first.getOpcode() == RISCVISD::GREVI &&
1225           OpPair.first.getOperand(0) == OpPair.second)
1226         return DAG.getNode(RISCVISD::GORCI, DL, Op.getValueType(),
1227                            OpPair.second, OpPair.first.getOperand(1));
1228     }
1229 
1230     // OR is commutable so canonicalize its OR operand to the left
1231     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
1232       std::swap(Op0, Op1);
1233     if (Op0.getOpcode() != ISD::OR)
1234       return SDValue();
1235     SDValue OrOp0 = Op0.getOperand(0);
1236     SDValue OrOp1 = Op0.getOperand(1);
1237     auto LHS = matchRISCVBitmanipPat(OrOp0);
1238     // OR is commutable so swap the operands and try again: x might have been
1239     // on the left
1240     if (!LHS) {
1241       std::swap(OrOp0, OrOp1);
1242       LHS = matchRISCVBitmanipPat(OrOp0);
1243     }
1244     auto RHS = matchRISCVBitmanipPat(Op1);
1245     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
1246       return DAG.getNode(
1247           RISCVISD::GORCI, DL, Op.getValueType(), LHS->Op,
1248           DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT()));
1249     }
1250   }
1251   return SDValue();
1252 }
1253 
1254 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
1255                                                DAGCombinerInfo &DCI) const {
1256   SelectionDAG &DAG = DCI.DAG;
1257 
1258   switch (N->getOpcode()) {
1259   default:
1260     break;
1261   case RISCVISD::SplitF64: {
1262     SDValue Op0 = N->getOperand(0);
1263     // If the input to SplitF64 is just BuildPairF64 then the operation is
1264     // redundant. Instead, use BuildPairF64's operands directly.
1265     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
1266       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
1267 
1268     SDLoc DL(N);
1269 
1270     // It's cheaper to materialise two 32-bit integers than to load a double
1271     // from the constant pool and transfer it to integer registers through the
1272     // stack.
1273     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
1274       APInt V = C->getValueAPF().bitcastToAPInt();
1275       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
1276       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
1277       return DCI.CombineTo(N, Lo, Hi);
1278     }
1279 
1280     // This is a target-specific version of a DAGCombine performed in
1281     // DAGCombiner::visitBITCAST. It performs the equivalent of:
1282     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
1283     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
1284     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
1285         !Op0.getNode()->hasOneUse())
1286       break;
1287     SDValue NewSplitF64 =
1288         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
1289                     Op0.getOperand(0));
1290     SDValue Lo = NewSplitF64.getValue(0);
1291     SDValue Hi = NewSplitF64.getValue(1);
1292     APInt SignBit = APInt::getSignMask(32);
1293     if (Op0.getOpcode() == ISD::FNEG) {
1294       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
1295                                   DAG.getConstant(SignBit, DL, MVT::i32));
1296       return DCI.CombineTo(N, Lo, NewHi);
1297     }
1298     assert(Op0.getOpcode() == ISD::FABS);
1299     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
1300                                 DAG.getConstant(~SignBit, DL, MVT::i32));
1301     return DCI.CombineTo(N, Lo, NewHi);
1302   }
1303   case RISCVISD::SLLW:
1304   case RISCVISD::SRAW:
1305   case RISCVISD::SRLW:
1306   case RISCVISD::ROLW:
1307   case RISCVISD::RORW: {
1308     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
1309     SDValue LHS = N->getOperand(0);
1310     SDValue RHS = N->getOperand(1);
1311     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
1312     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
1313     if (SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI) ||
1314         SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)) {
1315       if (N->getOpcode() != ISD::DELETED_NODE)
1316         DCI.AddToWorklist(N);
1317       return SDValue(N, 0);
1318     }
1319     break;
1320   }
1321   case RISCVISD::GREVIW:
1322   case RISCVISD::GORCIW: {
1323     // Only the lower 32 bits of the first operand are read
1324     SDValue Op0 = N->getOperand(0);
1325     APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
1326     if (SimplifyDemandedBits(Op0, Mask, DCI)) {
1327       if (N->getOpcode() != ISD::DELETED_NODE)
1328         DCI.AddToWorklist(N);
1329       return SDValue(N, 0);
1330     }
1331     break;
1332   }
1333   case RISCVISD::FMV_X_ANYEXTW_RV64: {
1334     SDLoc DL(N);
1335     SDValue Op0 = N->getOperand(0);
1336     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
1337     // conversion is unnecessary and can be replaced with an ANY_EXTEND
1338     // of the FMV_W_X_RV64 operand.
1339     if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) {
1340       assert(Op0.getOperand(0).getValueType() == MVT::i64 &&
1341              "Unexpected value type!");
1342       return Op0.getOperand(0);
1343     }
1344 
1345     // This is a target-specific version of a DAGCombine performed in
1346     // DAGCombiner::visitBITCAST. It performs the equivalent of:
1347     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
1348     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
1349     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
1350         !Op0.getNode()->hasOneUse())
1351       break;
1352     SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64,
1353                                  Op0.getOperand(0));
1354     APInt SignBit = APInt::getSignMask(32).sext(64);
1355     if (Op0.getOpcode() == ISD::FNEG)
1356       return DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV,
1357                          DAG.getConstant(SignBit, DL, MVT::i64));
1358 
1359     assert(Op0.getOpcode() == ISD::FABS);
1360     return DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV,
1361                        DAG.getConstant(~SignBit, DL, MVT::i64));
1362   }
1363   case RISCVISD::GREVI: {
1364     // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
1365     // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
1366     SDLoc DL(N);
1367     auto GREVSrc = N->getOperand(0);
1368     uint64_t ShAmt1 = N->getConstantOperandVal(1);
1369     if (GREVSrc->getOpcode() != RISCVISD::GREVI)
1370       break;
1371     uint64_t ShAmt2 = GREVSrc.getConstantOperandVal(1);
1372     GREVSrc = GREVSrc->getOperand(0);
1373     uint64_t CombinedShAmt = ShAmt1 ^ ShAmt2;
1374     if (CombinedShAmt == 0)
1375       return GREVSrc;
1376     return DAG.getNode(
1377         RISCVISD::GREVI, DL, N->getValueType(0), GREVSrc,
1378         DAG.getTargetConstant(CombinedShAmt, DL, Subtarget.getXLenVT()));
1379   }
1380   case ISD::OR:
1381     if (auto GREV = combineORToGREV(SDValue(N, 0), DCI.DAG, Subtarget))
1382       return GREV;
1383     if (auto GORC = combineORToGORC(SDValue(N, 0), DCI.DAG, Subtarget))
1384       return GORC;
1385     break;
1386   }
1387 
1388   return SDValue();
1389 }
1390 
1391 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
1392     const SDNode *N, CombineLevel Level) const {
1393   // The following folds are only desirable if `(OP _, c1 << c2)` can be
1394   // materialised in fewer instructions than `(OP _, c1)`:
1395   //
1396   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
1397   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
1398   SDValue N0 = N->getOperand(0);
1399   EVT Ty = N0.getValueType();
1400   if (Ty.isScalarInteger() &&
1401       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
1402     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
1403     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
1404     if (C1 && C2) {
1405       APInt C1Int = C1->getAPIntValue();
1406       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
1407 
1408       // We can materialise `c1 << c2` into an add immediate, so it's "free",
1409       // and the combine should happen, to potentially allow further combines
1410       // later.
1411       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
1412           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
1413         return true;
1414 
1415       // We can materialise `c1` in an add immediate, so it's "free", and the
1416       // combine should be prevented.
1417       if (C1Int.getMinSignedBits() <= 64 &&
1418           isLegalAddImmediate(C1Int.getSExtValue()))
1419         return false;
1420 
1421       // Neither constant will fit into an immediate, so find materialisation
1422       // costs.
1423       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
1424                                               Subtarget.is64Bit());
1425       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
1426           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit());
1427 
1428       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
1429       // combine should be prevented.
1430       if (C1Cost < ShiftedC1Cost)
1431         return false;
1432     }
1433   }
1434   return true;
1435 }
1436 
1437 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
1438     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
1439     unsigned Depth) const {
1440   switch (Op.getOpcode()) {
1441   default:
1442     break;
1443   case RISCVISD::SLLW:
1444   case RISCVISD::SRAW:
1445   case RISCVISD::SRLW:
1446   case RISCVISD::DIVW:
1447   case RISCVISD::DIVUW:
1448   case RISCVISD::REMUW:
1449   case RISCVISD::ROLW:
1450   case RISCVISD::RORW:
1451   case RISCVISD::GREVIW:
1452   case RISCVISD::GORCIW:
1453     // TODO: As the result is sign-extended, this is conservatively correct. A
1454     // more precise answer could be calculated for SRAW depending on known
1455     // bits in the shift amount.
1456     return 33;
1457   }
1458 
1459   return 1;
1460 }
1461 
1462 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
1463                                                   MachineBasicBlock *BB) {
1464   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
1465 
1466   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
1467   // Should the count have wrapped while it was being read, we need to try
1468   // again.
1469   // ...
1470   // read:
1471   // rdcycleh x3 # load high word of cycle
1472   // rdcycle  x2 # load low word of cycle
1473   // rdcycleh x4 # load high word of cycle
1474   // bne x3, x4, read # check if high word reads match, otherwise try again
1475   // ...
1476 
1477   MachineFunction &MF = *BB->getParent();
1478   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1479   MachineFunction::iterator It = ++BB->getIterator();
1480 
1481   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1482   MF.insert(It, LoopMBB);
1483 
1484   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1485   MF.insert(It, DoneMBB);
1486 
1487   // Transfer the remainder of BB and its successor edges to DoneMBB.
1488   DoneMBB->splice(DoneMBB->begin(), BB,
1489                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1490   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
1491 
1492   BB->addSuccessor(LoopMBB);
1493 
1494   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1495   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1496   Register LoReg = MI.getOperand(0).getReg();
1497   Register HiReg = MI.getOperand(1).getReg();
1498   DebugLoc DL = MI.getDebugLoc();
1499 
1500   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1501   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
1502       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
1503       .addReg(RISCV::X0);
1504   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
1505       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
1506       .addReg(RISCV::X0);
1507   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
1508       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
1509       .addReg(RISCV::X0);
1510 
1511   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
1512       .addReg(HiReg)
1513       .addReg(ReadAgainReg)
1514       .addMBB(LoopMBB);
1515 
1516   LoopMBB->addSuccessor(LoopMBB);
1517   LoopMBB->addSuccessor(DoneMBB);
1518 
1519   MI.eraseFromParent();
1520 
1521   return DoneMBB;
1522 }
1523 
1524 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
1525                                              MachineBasicBlock *BB) {
1526   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
1527 
1528   MachineFunction &MF = *BB->getParent();
1529   DebugLoc DL = MI.getDebugLoc();
1530   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1531   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
1532   Register LoReg = MI.getOperand(0).getReg();
1533   Register HiReg = MI.getOperand(1).getReg();
1534   Register SrcReg = MI.getOperand(2).getReg();
1535   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
1536   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
1537 
1538   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
1539                           RI);
1540   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
1541   MachineMemOperand *MMOLo =
1542       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
1543   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
1544       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
1545   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
1546       .addFrameIndex(FI)
1547       .addImm(0)
1548       .addMemOperand(MMOLo);
1549   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
1550       .addFrameIndex(FI)
1551       .addImm(4)
1552       .addMemOperand(MMOHi);
1553   MI.eraseFromParent(); // The pseudo instruction is gone now.
1554   return BB;
1555 }
1556 
1557 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
1558                                                  MachineBasicBlock *BB) {
1559   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
1560          "Unexpected instruction");
1561 
1562   MachineFunction &MF = *BB->getParent();
1563   DebugLoc DL = MI.getDebugLoc();
1564   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1565   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
1566   Register DstReg = MI.getOperand(0).getReg();
1567   Register LoReg = MI.getOperand(1).getReg();
1568   Register HiReg = MI.getOperand(2).getReg();
1569   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
1570   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
1571 
1572   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
1573   MachineMemOperand *MMOLo =
1574       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
1575   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
1576       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
1577   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
1578       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
1579       .addFrameIndex(FI)
1580       .addImm(0)
1581       .addMemOperand(MMOLo);
1582   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
1583       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
1584       .addFrameIndex(FI)
1585       .addImm(4)
1586       .addMemOperand(MMOHi);
1587   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
1588   MI.eraseFromParent(); // The pseudo instruction is gone now.
1589   return BB;
1590 }
1591 
1592 static bool isSelectPseudo(MachineInstr &MI) {
1593   switch (MI.getOpcode()) {
1594   default:
1595     return false;
1596   case RISCV::Select_GPR_Using_CC_GPR:
1597   case RISCV::Select_FPR32_Using_CC_GPR:
1598   case RISCV::Select_FPR64_Using_CC_GPR:
1599     return true;
1600   }
1601 }
1602 
1603 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
1604                                            MachineBasicBlock *BB) {
1605   // To "insert" Select_* instructions, we actually have to insert the triangle
1606   // control-flow pattern.  The incoming instructions know the destination vreg
1607   // to set, the condition code register to branch on, the true/false values to
1608   // select between, and the condcode to use to select the appropriate branch.
1609   //
1610   // We produce the following control flow:
1611   //     HeadMBB
1612   //     |  \
1613   //     |  IfFalseMBB
1614   //     | /
1615   //    TailMBB
1616   //
1617   // When we find a sequence of selects we attempt to optimize their emission
1618   // by sharing the control flow. Currently we only handle cases where we have
1619   // multiple selects with the exact same condition (same LHS, RHS and CC).
1620   // The selects may be interleaved with other instructions if the other
1621   // instructions meet some requirements we deem safe:
1622   // - They are debug instructions. Otherwise,
1623   // - They do not have side-effects, do not access memory and their inputs do
1624   //   not depend on the results of the select pseudo-instructions.
1625   // The TrueV/FalseV operands of the selects cannot depend on the result of
1626   // previous selects in the sequence.
1627   // These conditions could be further relaxed. See the X86 target for a
1628   // related approach and more information.
1629   Register LHS = MI.getOperand(1).getReg();
1630   Register RHS = MI.getOperand(2).getReg();
1631   auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
1632 
1633   SmallVector<MachineInstr *, 4> SelectDebugValues;
1634   SmallSet<Register, 4> SelectDests;
1635   SelectDests.insert(MI.getOperand(0).getReg());
1636 
1637   MachineInstr *LastSelectPseudo = &MI;
1638 
1639   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
1640        SequenceMBBI != E; ++SequenceMBBI) {
1641     if (SequenceMBBI->isDebugInstr())
1642       continue;
1643     else if (isSelectPseudo(*SequenceMBBI)) {
1644       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
1645           SequenceMBBI->getOperand(2).getReg() != RHS ||
1646           SequenceMBBI->getOperand(3).getImm() != CC ||
1647           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
1648           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
1649         break;
1650       LastSelectPseudo = &*SequenceMBBI;
1651       SequenceMBBI->collectDebugValues(SelectDebugValues);
1652       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
1653     } else {
1654       if (SequenceMBBI->hasUnmodeledSideEffects() ||
1655           SequenceMBBI->mayLoadOrStore())
1656         break;
1657       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
1658             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
1659           }))
1660         break;
1661     }
1662   }
1663 
1664   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1665   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1666   DebugLoc DL = MI.getDebugLoc();
1667   MachineFunction::iterator I = ++BB->getIterator();
1668 
1669   MachineBasicBlock *HeadMBB = BB;
1670   MachineFunction *F = BB->getParent();
1671   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
1672   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
1673 
1674   F->insert(I, IfFalseMBB);
1675   F->insert(I, TailMBB);
1676 
1677   // Transfer debug instructions associated with the selects to TailMBB.
1678   for (MachineInstr *DebugInstr : SelectDebugValues) {
1679     TailMBB->push_back(DebugInstr->removeFromParent());
1680   }
1681 
1682   // Move all instructions after the sequence to TailMBB.
1683   TailMBB->splice(TailMBB->end(), HeadMBB,
1684                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
1685   // Update machine-CFG edges by transferring all successors of the current
1686   // block to the new block which will contain the Phi nodes for the selects.
1687   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
1688   // Set the successors for HeadMBB.
1689   HeadMBB->addSuccessor(IfFalseMBB);
1690   HeadMBB->addSuccessor(TailMBB);
1691 
1692   // Insert appropriate branch.
1693   unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
1694 
1695   BuildMI(HeadMBB, DL, TII.get(Opcode))
1696     .addReg(LHS)
1697     .addReg(RHS)
1698     .addMBB(TailMBB);
1699 
1700   // IfFalseMBB just falls through to TailMBB.
1701   IfFalseMBB->addSuccessor(TailMBB);
1702 
1703   // Create PHIs for all of the select pseudo-instructions.
1704   auto SelectMBBI = MI.getIterator();
1705   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
1706   auto InsertionPoint = TailMBB->begin();
1707   while (SelectMBBI != SelectEnd) {
1708     auto Next = std::next(SelectMBBI);
1709     if (isSelectPseudo(*SelectMBBI)) {
1710       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
1711       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
1712               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
1713           .addReg(SelectMBBI->getOperand(4).getReg())
1714           .addMBB(HeadMBB)
1715           .addReg(SelectMBBI->getOperand(5).getReg())
1716           .addMBB(IfFalseMBB);
1717       SelectMBBI->eraseFromParent();
1718     }
1719     SelectMBBI = Next;
1720   }
1721 
1722   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
1723   return TailMBB;
1724 }
1725 
1726 MachineBasicBlock *
1727 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1728                                                  MachineBasicBlock *BB) const {
1729   switch (MI.getOpcode()) {
1730   default:
1731     llvm_unreachable("Unexpected instr type to insert");
1732   case RISCV::ReadCycleWide:
1733     assert(!Subtarget.is64Bit() &&
1734            "ReadCycleWrite is only to be used on riscv32");
1735     return emitReadCycleWidePseudo(MI, BB);
1736   case RISCV::Select_GPR_Using_CC_GPR:
1737   case RISCV::Select_FPR32_Using_CC_GPR:
1738   case RISCV::Select_FPR64_Using_CC_GPR:
1739     return emitSelectPseudo(MI, BB);
1740   case RISCV::BuildPairF64Pseudo:
1741     return emitBuildPairF64Pseudo(MI, BB);
1742   case RISCV::SplitF64Pseudo:
1743     return emitSplitF64Pseudo(MI, BB);
1744   }
1745 }
1746 
1747 // Calling Convention Implementation.
1748 // The expectations for frontend ABI lowering vary from target to target.
1749 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
1750 // details, but this is a longer term goal. For now, we simply try to keep the
1751 // role of the frontend as simple and well-defined as possible. The rules can
1752 // be summarised as:
1753 // * Never split up large scalar arguments. We handle them here.
1754 // * If a hardfloat calling convention is being used, and the struct may be
1755 // passed in a pair of registers (fp+fp, int+fp), and both registers are
1756 // available, then pass as two separate arguments. If either the GPRs or FPRs
1757 // are exhausted, then pass according to the rule below.
1758 // * If a struct could never be passed in registers or directly in a stack
1759 // slot (as it is larger than 2*XLEN and the floating point rules don't
1760 // apply), then pass it using a pointer with the byval attribute.
1761 // * If a struct is less than 2*XLEN, then coerce to either a two-element
1762 // word-sized array or a 2*XLEN scalar (depending on alignment).
1763 // * The frontend can determine whether a struct is returned by reference or
1764 // not based on its size and fields. If it will be returned by reference, the
1765 // frontend must modify the prototype so a pointer with the sret annotation is
1766 // passed as the first argument. This is not necessary for large scalar
1767 // returns.
1768 // * Struct return values and varargs should be coerced to structs containing
1769 // register-size fields in the same situations they would be for fixed
1770 // arguments.
1771 
1772 static const MCPhysReg ArgGPRs[] = {
1773   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
1774   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
1775 };
1776 static const MCPhysReg ArgFPR32s[] = {
1777   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
1778   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
1779 };
1780 static const MCPhysReg ArgFPR64s[] = {
1781   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
1782   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
1783 };
1784 
1785 // Pass a 2*XLEN argument that has been split into two XLEN values through
1786 // registers or the stack as necessary.
1787 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
1788                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
1789                                 MVT ValVT2, MVT LocVT2,
1790                                 ISD::ArgFlagsTy ArgFlags2) {
1791   unsigned XLenInBytes = XLen / 8;
1792   if (Register Reg = State.AllocateReg(ArgGPRs)) {
1793     // At least one half can be passed via register.
1794     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
1795                                      VA1.getLocVT(), CCValAssign::Full));
1796   } else {
1797     // Both halves must be passed on the stack, with proper alignment.
1798     Align StackAlign =
1799         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
1800     State.addLoc(
1801         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
1802                             State.AllocateStack(XLenInBytes, StackAlign),
1803                             VA1.getLocVT(), CCValAssign::Full));
1804     State.addLoc(CCValAssign::getMem(
1805         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
1806         LocVT2, CCValAssign::Full));
1807     return false;
1808   }
1809 
1810   if (Register Reg = State.AllocateReg(ArgGPRs)) {
1811     // The second half can also be passed via register.
1812     State.addLoc(
1813         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
1814   } else {
1815     // The second half is passed via the stack, without additional alignment.
1816     State.addLoc(CCValAssign::getMem(
1817         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
1818         LocVT2, CCValAssign::Full));
1819   }
1820 
1821   return false;
1822 }
1823 
1824 // Implements the RISC-V calling convention. Returns true upon failure.
1825 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
1826                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
1827                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
1828                      bool IsRet, Type *OrigTy) {
1829   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
1830   assert(XLen == 32 || XLen == 64);
1831   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
1832 
1833   // Any return value split in to more than two values can't be returned
1834   // directly.
1835   if (IsRet && ValNo > 1)
1836     return true;
1837 
1838   // UseGPRForF32 if targeting one of the soft-float ABIs, if passing a
1839   // variadic argument, or if no F32 argument registers are available.
1840   bool UseGPRForF32 = true;
1841   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
1842   // variadic argument, or if no F64 argument registers are available.
1843   bool UseGPRForF64 = true;
1844 
1845   switch (ABI) {
1846   default:
1847     llvm_unreachable("Unexpected ABI");
1848   case RISCVABI::ABI_ILP32:
1849   case RISCVABI::ABI_LP64:
1850     break;
1851   case RISCVABI::ABI_ILP32F:
1852   case RISCVABI::ABI_LP64F:
1853     UseGPRForF32 = !IsFixed;
1854     break;
1855   case RISCVABI::ABI_ILP32D:
1856   case RISCVABI::ABI_LP64D:
1857     UseGPRForF32 = !IsFixed;
1858     UseGPRForF64 = !IsFixed;
1859     break;
1860   }
1861 
1862   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s))
1863     UseGPRForF32 = true;
1864   if (State.getFirstUnallocated(ArgFPR64s) == array_lengthof(ArgFPR64s))
1865     UseGPRForF64 = true;
1866 
1867   // From this point on, rely on UseGPRForF32, UseGPRForF64 and similar local
1868   // variables rather than directly checking against the target ABI.
1869 
1870   if (UseGPRForF32 && ValVT == MVT::f32) {
1871     LocVT = XLenVT;
1872     LocInfo = CCValAssign::BCvt;
1873   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
1874     LocVT = MVT::i64;
1875     LocInfo = CCValAssign::BCvt;
1876   }
1877 
1878   // If this is a variadic argument, the RISC-V calling convention requires
1879   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
1880   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
1881   // be used regardless of whether the original argument was split during
1882   // legalisation or not. The argument will not be passed by registers if the
1883   // original type is larger than 2*XLEN, so the register alignment rule does
1884   // not apply.
1885   unsigned TwoXLenInBytes = (2 * XLen) / 8;
1886   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
1887       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
1888     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
1889     // Skip 'odd' register if necessary.
1890     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
1891       State.AllocateReg(ArgGPRs);
1892   }
1893 
1894   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
1895   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
1896       State.getPendingArgFlags();
1897 
1898   assert(PendingLocs.size() == PendingArgFlags.size() &&
1899          "PendingLocs and PendingArgFlags out of sync");
1900 
1901   // Handle passing f64 on RV32D with a soft float ABI or when floating point
1902   // registers are exhausted.
1903   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
1904     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
1905            "Can't lower f64 if it is split");
1906     // Depending on available argument GPRS, f64 may be passed in a pair of
1907     // GPRs, split between a GPR and the stack, or passed completely on the
1908     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
1909     // cases.
1910     Register Reg = State.AllocateReg(ArgGPRs);
1911     LocVT = MVT::i32;
1912     if (!Reg) {
1913       unsigned StackOffset = State.AllocateStack(8, Align(8));
1914       State.addLoc(
1915           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
1916       return false;
1917     }
1918     if (!State.AllocateReg(ArgGPRs))
1919       State.AllocateStack(4, Align(4));
1920     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1921     return false;
1922   }
1923 
1924   // Split arguments might be passed indirectly, so keep track of the pending
1925   // values.
1926   if (ArgFlags.isSplit() || !PendingLocs.empty()) {
1927     LocVT = XLenVT;
1928     LocInfo = CCValAssign::Indirect;
1929     PendingLocs.push_back(
1930         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
1931     PendingArgFlags.push_back(ArgFlags);
1932     if (!ArgFlags.isSplitEnd()) {
1933       return false;
1934     }
1935   }
1936 
1937   // If the split argument only had two elements, it should be passed directly
1938   // in registers or on the stack.
1939   if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
1940     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
1941     // Apply the normal calling convention rules to the first half of the
1942     // split argument.
1943     CCValAssign VA = PendingLocs[0];
1944     ISD::ArgFlagsTy AF = PendingArgFlags[0];
1945     PendingLocs.clear();
1946     PendingArgFlags.clear();
1947     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
1948                                ArgFlags);
1949   }
1950 
1951   // Allocate to a register if possible, or else a stack slot.
1952   Register Reg;
1953   if (ValVT == MVT::f32 && !UseGPRForF32)
1954     Reg = State.AllocateReg(ArgFPR32s);
1955   else if (ValVT == MVT::f64 && !UseGPRForF64)
1956     Reg = State.AllocateReg(ArgFPR64s);
1957   else
1958     Reg = State.AllocateReg(ArgGPRs);
1959   unsigned StackOffset =
1960       Reg ? 0 : State.AllocateStack(XLen / 8, Align(XLen / 8));
1961 
1962   // If we reach this point and PendingLocs is non-empty, we must be at the
1963   // end of a split argument that must be passed indirectly.
1964   if (!PendingLocs.empty()) {
1965     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
1966     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
1967 
1968     for (auto &It : PendingLocs) {
1969       if (Reg)
1970         It.convertToReg(Reg);
1971       else
1972         It.convertToMem(StackOffset);
1973       State.addLoc(It);
1974     }
1975     PendingLocs.clear();
1976     PendingArgFlags.clear();
1977     return false;
1978   }
1979 
1980   assert((!UseGPRForF32 || !UseGPRForF64 || LocVT == XLenVT) &&
1981          "Expected an XLenVT at this stage");
1982 
1983   if (Reg) {
1984     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1985     return false;
1986   }
1987 
1988   // When an f32 or f64 is passed on the stack, no bit-conversion is needed.
1989   if (ValVT == MVT::f32 || ValVT == MVT::f64) {
1990     LocVT = ValVT;
1991     LocInfo = CCValAssign::Full;
1992   }
1993   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
1994   return false;
1995 }
1996 
1997 void RISCVTargetLowering::analyzeInputArgs(
1998     MachineFunction &MF, CCState &CCInfo,
1999     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
2000   unsigned NumArgs = Ins.size();
2001   FunctionType *FType = MF.getFunction().getFunctionType();
2002 
2003   for (unsigned i = 0; i != NumArgs; ++i) {
2004     MVT ArgVT = Ins[i].VT;
2005     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
2006 
2007     Type *ArgTy = nullptr;
2008     if (IsRet)
2009       ArgTy = FType->getReturnType();
2010     else if (Ins[i].isOrigArg())
2011       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
2012 
2013     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
2014     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
2015                  ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy)) {
2016       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
2017                         << EVT(ArgVT).getEVTString() << '\n');
2018       llvm_unreachable(nullptr);
2019     }
2020   }
2021 }
2022 
2023 void RISCVTargetLowering::analyzeOutputArgs(
2024     MachineFunction &MF, CCState &CCInfo,
2025     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
2026     CallLoweringInfo *CLI) const {
2027   unsigned NumArgs = Outs.size();
2028 
2029   for (unsigned i = 0; i != NumArgs; i++) {
2030     MVT ArgVT = Outs[i].VT;
2031     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2032     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
2033 
2034     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
2035     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
2036                  ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
2037       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
2038                         << EVT(ArgVT).getEVTString() << "\n");
2039       llvm_unreachable(nullptr);
2040     }
2041   }
2042 }
2043 
2044 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
2045 // values.
2046 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
2047                                    const CCValAssign &VA, const SDLoc &DL) {
2048   switch (VA.getLocInfo()) {
2049   default:
2050     llvm_unreachable("Unexpected CCValAssign::LocInfo");
2051   case CCValAssign::Full:
2052     break;
2053   case CCValAssign::BCvt:
2054     if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) {
2055       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
2056       break;
2057     }
2058     Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2059     break;
2060   }
2061   return Val;
2062 }
2063 
2064 // The caller is responsible for loading the full value if the argument is
2065 // passed with CCValAssign::Indirect.
2066 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
2067                                 const CCValAssign &VA, const SDLoc &DL) {
2068   MachineFunction &MF = DAG.getMachineFunction();
2069   MachineRegisterInfo &RegInfo = MF.getRegInfo();
2070   EVT LocVT = VA.getLocVT();
2071   SDValue Val;
2072   const TargetRegisterClass *RC;
2073 
2074   switch (LocVT.getSimpleVT().SimpleTy) {
2075   default:
2076     llvm_unreachable("Unexpected register type");
2077   case MVT::i32:
2078   case MVT::i64:
2079     RC = &RISCV::GPRRegClass;
2080     break;
2081   case MVT::f32:
2082     RC = &RISCV::FPR32RegClass;
2083     break;
2084   case MVT::f64:
2085     RC = &RISCV::FPR64RegClass;
2086     break;
2087   }
2088 
2089   Register VReg = RegInfo.createVirtualRegister(RC);
2090   RegInfo.addLiveIn(VA.getLocReg(), VReg);
2091   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
2092 
2093   if (VA.getLocInfo() == CCValAssign::Indirect)
2094     return Val;
2095 
2096   return convertLocVTToValVT(DAG, Val, VA, DL);
2097 }
2098 
2099 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
2100                                    const CCValAssign &VA, const SDLoc &DL) {
2101   EVT LocVT = VA.getLocVT();
2102 
2103   switch (VA.getLocInfo()) {
2104   default:
2105     llvm_unreachable("Unexpected CCValAssign::LocInfo");
2106   case CCValAssign::Full:
2107     break;
2108   case CCValAssign::BCvt:
2109     if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) {
2110       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
2111       break;
2112     }
2113     Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
2114     break;
2115   }
2116   return Val;
2117 }
2118 
2119 // The caller is responsible for loading the full value if the argument is
2120 // passed with CCValAssign::Indirect.
2121 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
2122                                 const CCValAssign &VA, const SDLoc &DL) {
2123   MachineFunction &MF = DAG.getMachineFunction();
2124   MachineFrameInfo &MFI = MF.getFrameInfo();
2125   EVT LocVT = VA.getLocVT();
2126   EVT ValVT = VA.getValVT();
2127   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
2128   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
2129                                  VA.getLocMemOffset(), /*Immutable=*/true);
2130   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2131   SDValue Val;
2132 
2133   ISD::LoadExtType ExtType;
2134   switch (VA.getLocInfo()) {
2135   default:
2136     llvm_unreachable("Unexpected CCValAssign::LocInfo");
2137   case CCValAssign::Full:
2138   case CCValAssign::Indirect:
2139   case CCValAssign::BCvt:
2140     ExtType = ISD::NON_EXTLOAD;
2141     break;
2142   }
2143   Val = DAG.getExtLoad(
2144       ExtType, DL, LocVT, Chain, FIN,
2145       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
2146   return Val;
2147 }
2148 
2149 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
2150                                        const CCValAssign &VA, const SDLoc &DL) {
2151   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
2152          "Unexpected VA");
2153   MachineFunction &MF = DAG.getMachineFunction();
2154   MachineFrameInfo &MFI = MF.getFrameInfo();
2155   MachineRegisterInfo &RegInfo = MF.getRegInfo();
2156 
2157   if (VA.isMemLoc()) {
2158     // f64 is passed on the stack.
2159     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
2160     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
2161     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
2162                        MachinePointerInfo::getFixedStack(MF, FI));
2163   }
2164 
2165   assert(VA.isRegLoc() && "Expected register VA assignment");
2166 
2167   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
2168   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
2169   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
2170   SDValue Hi;
2171   if (VA.getLocReg() == RISCV::X17) {
2172     // Second half of f64 is passed on the stack.
2173     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
2174     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
2175     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
2176                      MachinePointerInfo::getFixedStack(MF, FI));
2177   } else {
2178     // Second half of f64 is passed in another GPR.
2179     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
2180     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
2181     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
2182   }
2183   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
2184 }
2185 
2186 // FastCC has less than 1% performance improvement for some particular
2187 // benchmark. But theoretically, it may has benenfit for some cases.
2188 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT,
2189                             CCValAssign::LocInfo LocInfo,
2190                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2191 
2192   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
2193     // X5 and X6 might be used for save-restore libcall.
2194     static const MCPhysReg GPRList[] = {
2195         RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
2196         RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
2197         RISCV::X29, RISCV::X30, RISCV::X31};
2198     if (unsigned Reg = State.AllocateReg(GPRList)) {
2199       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2200       return false;
2201     }
2202   }
2203 
2204   if (LocVT == MVT::f32) {
2205     static const MCPhysReg FPR32List[] = {
2206         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
2207         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
2208         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
2209         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
2210     if (unsigned Reg = State.AllocateReg(FPR32List)) {
2211       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2212       return false;
2213     }
2214   }
2215 
2216   if (LocVT == MVT::f64) {
2217     static const MCPhysReg FPR64List[] = {
2218         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
2219         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
2220         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
2221         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
2222     if (unsigned Reg = State.AllocateReg(FPR64List)) {
2223       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2224       return false;
2225     }
2226   }
2227 
2228   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
2229     unsigned Offset4 = State.AllocateStack(4, Align(4));
2230     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
2231     return false;
2232   }
2233 
2234   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
2235     unsigned Offset5 = State.AllocateStack(8, Align(8));
2236     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
2237     return false;
2238   }
2239 
2240   return true; // CC didn't match.
2241 }
2242 
2243 // Transform physical registers into virtual registers.
2244 SDValue RISCVTargetLowering::LowerFormalArguments(
2245     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
2246     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2247     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2248 
2249   switch (CallConv) {
2250   default:
2251     report_fatal_error("Unsupported calling convention");
2252   case CallingConv::C:
2253   case CallingConv::Fast:
2254     break;
2255   }
2256 
2257   MachineFunction &MF = DAG.getMachineFunction();
2258 
2259   const Function &Func = MF.getFunction();
2260   if (Func.hasFnAttribute("interrupt")) {
2261     if (!Func.arg_empty())
2262       report_fatal_error(
2263         "Functions with the interrupt attribute cannot have arguments!");
2264 
2265     StringRef Kind =
2266       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
2267 
2268     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
2269       report_fatal_error(
2270         "Function interrupt attribute argument not supported!");
2271   }
2272 
2273   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2274   MVT XLenVT = Subtarget.getXLenVT();
2275   unsigned XLenInBytes = Subtarget.getXLen() / 8;
2276   // Used with vargs to acumulate store chains.
2277   std::vector<SDValue> OutChains;
2278 
2279   // Assign locations to all of the incoming arguments.
2280   SmallVector<CCValAssign, 16> ArgLocs;
2281   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2282 
2283   if (CallConv == CallingConv::Fast)
2284     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC);
2285   else
2286     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
2287 
2288   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2289     CCValAssign &VA = ArgLocs[i];
2290     SDValue ArgValue;
2291     // Passing f64 on RV32D with a soft float ABI must be handled as a special
2292     // case.
2293     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
2294       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
2295     else if (VA.isRegLoc())
2296       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
2297     else
2298       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
2299 
2300     if (VA.getLocInfo() == CCValAssign::Indirect) {
2301       // If the original argument was split and passed by reference (e.g. i128
2302       // on RV32), we need to load all parts of it here (using the same
2303       // address).
2304       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
2305                                    MachinePointerInfo()));
2306       unsigned ArgIndex = Ins[i].OrigArgIndex;
2307       assert(Ins[i].PartOffset == 0);
2308       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
2309         CCValAssign &PartVA = ArgLocs[i + 1];
2310         unsigned PartOffset = Ins[i + 1].PartOffset;
2311         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
2312                                       DAG.getIntPtrConstant(PartOffset, DL));
2313         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
2314                                      MachinePointerInfo()));
2315         ++i;
2316       }
2317       continue;
2318     }
2319     InVals.push_back(ArgValue);
2320   }
2321 
2322   if (IsVarArg) {
2323     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
2324     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
2325     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
2326     MachineFrameInfo &MFI = MF.getFrameInfo();
2327     MachineRegisterInfo &RegInfo = MF.getRegInfo();
2328     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2329 
2330     // Offset of the first variable argument from stack pointer, and size of
2331     // the vararg save area. For now, the varargs save area is either zero or
2332     // large enough to hold a0-a7.
2333     int VaArgOffset, VarArgsSaveSize;
2334 
2335     // If all registers are allocated, then all varargs must be passed on the
2336     // stack and we don't need to save any argregs.
2337     if (ArgRegs.size() == Idx) {
2338       VaArgOffset = CCInfo.getNextStackOffset();
2339       VarArgsSaveSize = 0;
2340     } else {
2341       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
2342       VaArgOffset = -VarArgsSaveSize;
2343     }
2344 
2345     // Record the frame index of the first variable argument
2346     // which is a value necessary to VASTART.
2347     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
2348     RVFI->setVarArgsFrameIndex(FI);
2349 
2350     // If saving an odd number of registers then create an extra stack slot to
2351     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
2352     // offsets to even-numbered registered remain 2*XLEN-aligned.
2353     if (Idx % 2) {
2354       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
2355       VarArgsSaveSize += XLenInBytes;
2356     }
2357 
2358     // Copy the integer registers that may have been used for passing varargs
2359     // to the vararg save area.
2360     for (unsigned I = Idx; I < ArgRegs.size();
2361          ++I, VaArgOffset += XLenInBytes) {
2362       const Register Reg = RegInfo.createVirtualRegister(RC);
2363       RegInfo.addLiveIn(ArgRegs[I], Reg);
2364       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
2365       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
2366       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2367       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
2368                                    MachinePointerInfo::getFixedStack(MF, FI));
2369       cast<StoreSDNode>(Store.getNode())
2370           ->getMemOperand()
2371           ->setValue((Value *)nullptr);
2372       OutChains.push_back(Store);
2373     }
2374     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
2375   }
2376 
2377   // All stores are grouped in one node to allow the matching between
2378   // the size of Ins and InVals. This only happens for vararg functions.
2379   if (!OutChains.empty()) {
2380     OutChains.push_back(Chain);
2381     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2382   }
2383 
2384   return Chain;
2385 }
2386 
2387 /// isEligibleForTailCallOptimization - Check whether the call is eligible
2388 /// for tail call optimization.
2389 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
2390 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
2391     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
2392     const SmallVector<CCValAssign, 16> &ArgLocs) const {
2393 
2394   auto &Callee = CLI.Callee;
2395   auto CalleeCC = CLI.CallConv;
2396   auto &Outs = CLI.Outs;
2397   auto &Caller = MF.getFunction();
2398   auto CallerCC = Caller.getCallingConv();
2399 
2400   // Exception-handling functions need a special set of instructions to
2401   // indicate a return to the hardware. Tail-calling another function would
2402   // probably break this.
2403   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
2404   // should be expanded as new function attributes are introduced.
2405   if (Caller.hasFnAttribute("interrupt"))
2406     return false;
2407 
2408   // Do not tail call opt if the stack is used to pass parameters.
2409   if (CCInfo.getNextStackOffset() != 0)
2410     return false;
2411 
2412   // Do not tail call opt if any parameters need to be passed indirectly.
2413   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
2414   // passed indirectly. So the address of the value will be passed in a
2415   // register, or if not available, then the address is put on the stack. In
2416   // order to pass indirectly, space on the stack often needs to be allocated
2417   // in order to store the value. In this case the CCInfo.getNextStackOffset()
2418   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
2419   // are passed CCValAssign::Indirect.
2420   for (auto &VA : ArgLocs)
2421     if (VA.getLocInfo() == CCValAssign::Indirect)
2422       return false;
2423 
2424   // Do not tail call opt if either caller or callee uses struct return
2425   // semantics.
2426   auto IsCallerStructRet = Caller.hasStructRetAttr();
2427   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
2428   if (IsCallerStructRet || IsCalleeStructRet)
2429     return false;
2430 
2431   // Externally-defined functions with weak linkage should not be
2432   // tail-called. The behaviour of branch instructions in this situation (as
2433   // used for tail calls) is implementation-defined, so we cannot rely on the
2434   // linker replacing the tail call with a return.
2435   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2436     const GlobalValue *GV = G->getGlobal();
2437     if (GV->hasExternalWeakLinkage())
2438       return false;
2439   }
2440 
2441   // The callee has to preserve all registers the caller needs to preserve.
2442   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
2443   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2444   if (CalleeCC != CallerCC) {
2445     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2446     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2447       return false;
2448   }
2449 
2450   // Byval parameters hand the function a pointer directly into the stack area
2451   // we want to reuse during a tail call. Working around this *is* possible
2452   // but less efficient and uglier in LowerCall.
2453   for (auto &Arg : Outs)
2454     if (Arg.Flags.isByVal())
2455       return false;
2456 
2457   return true;
2458 }
2459 
2460 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
2461 // and output parameter nodes.
2462 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
2463                                        SmallVectorImpl<SDValue> &InVals) const {
2464   SelectionDAG &DAG = CLI.DAG;
2465   SDLoc &DL = CLI.DL;
2466   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2467   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2468   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2469   SDValue Chain = CLI.Chain;
2470   SDValue Callee = CLI.Callee;
2471   bool &IsTailCall = CLI.IsTailCall;
2472   CallingConv::ID CallConv = CLI.CallConv;
2473   bool IsVarArg = CLI.IsVarArg;
2474   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2475   MVT XLenVT = Subtarget.getXLenVT();
2476 
2477   MachineFunction &MF = DAG.getMachineFunction();
2478 
2479   // Analyze the operands of the call, assigning locations to each operand.
2480   SmallVector<CCValAssign, 16> ArgLocs;
2481   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2482 
2483   if (CallConv == CallingConv::Fast)
2484     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC);
2485   else
2486     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
2487 
2488   // Check if it's really possible to do a tail call.
2489   if (IsTailCall)
2490     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
2491 
2492   if (IsTailCall)
2493     ++NumTailCalls;
2494   else if (CLI.CB && CLI.CB->isMustTailCall())
2495     report_fatal_error("failed to perform tail call elimination on a call "
2496                        "site marked musttail");
2497 
2498   // Get a count of how many bytes are to be pushed on the stack.
2499   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
2500 
2501   // Create local copies for byval args
2502   SmallVector<SDValue, 8> ByValArgs;
2503   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
2504     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2505     if (!Flags.isByVal())
2506       continue;
2507 
2508     SDValue Arg = OutVals[i];
2509     unsigned Size = Flags.getByValSize();
2510     Align Alignment = Flags.getNonZeroByValAlign();
2511 
2512     int FI =
2513         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
2514     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2515     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
2516 
2517     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
2518                           /*IsVolatile=*/false,
2519                           /*AlwaysInline=*/false, IsTailCall,
2520                           MachinePointerInfo(), MachinePointerInfo());
2521     ByValArgs.push_back(FIPtr);
2522   }
2523 
2524   if (!IsTailCall)
2525     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
2526 
2527   // Copy argument values to their designated locations.
2528   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
2529   SmallVector<SDValue, 8> MemOpChains;
2530   SDValue StackPtr;
2531   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
2532     CCValAssign &VA = ArgLocs[i];
2533     SDValue ArgValue = OutVals[i];
2534     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2535 
2536     // Handle passing f64 on RV32D with a soft float ABI as a special case.
2537     bool IsF64OnRV32DSoftABI =
2538         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
2539     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
2540       SDValue SplitF64 = DAG.getNode(
2541           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
2542       SDValue Lo = SplitF64.getValue(0);
2543       SDValue Hi = SplitF64.getValue(1);
2544 
2545       Register RegLo = VA.getLocReg();
2546       RegsToPass.push_back(std::make_pair(RegLo, Lo));
2547 
2548       if (RegLo == RISCV::X17) {
2549         // Second half of f64 is passed on the stack.
2550         // Work out the address of the stack slot.
2551         if (!StackPtr.getNode())
2552           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
2553         // Emit the store.
2554         MemOpChains.push_back(
2555             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
2556       } else {
2557         // Second half of f64 is passed in another GPR.
2558         assert(RegLo < RISCV::X31 && "Invalid register pair");
2559         Register RegHigh = RegLo + 1;
2560         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
2561       }
2562       continue;
2563     }
2564 
2565     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
2566     // as any other MemLoc.
2567 
2568     // Promote the value if needed.
2569     // For now, only handle fully promoted and indirect arguments.
2570     if (VA.getLocInfo() == CCValAssign::Indirect) {
2571       // Store the argument in a stack slot and pass its address.
2572       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
2573       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2574       MemOpChains.push_back(
2575           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
2576                        MachinePointerInfo::getFixedStack(MF, FI)));
2577       // If the original argument was split (e.g. i128), we need
2578       // to store all parts of it here (and pass just one address).
2579       unsigned ArgIndex = Outs[i].OrigArgIndex;
2580       assert(Outs[i].PartOffset == 0);
2581       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
2582         SDValue PartValue = OutVals[i + 1];
2583         unsigned PartOffset = Outs[i + 1].PartOffset;
2584         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2585                                       DAG.getIntPtrConstant(PartOffset, DL));
2586         MemOpChains.push_back(
2587             DAG.getStore(Chain, DL, PartValue, Address,
2588                          MachinePointerInfo::getFixedStack(MF, FI)));
2589         ++i;
2590       }
2591       ArgValue = SpillSlot;
2592     } else {
2593       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
2594     }
2595 
2596     // Use local copy if it is a byval arg.
2597     if (Flags.isByVal())
2598       ArgValue = ByValArgs[j++];
2599 
2600     if (VA.isRegLoc()) {
2601       // Queue up the argument copies and emit them at the end.
2602       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2603     } else {
2604       assert(VA.isMemLoc() && "Argument not register or memory");
2605       assert(!IsTailCall && "Tail call not allowed if stack is used "
2606                             "for passing parameters");
2607 
2608       // Work out the address of the stack slot.
2609       if (!StackPtr.getNode())
2610         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
2611       SDValue Address =
2612           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2613                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
2614 
2615       // Emit the store.
2616       MemOpChains.push_back(
2617           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2618     }
2619   }
2620 
2621   // Join the stores, which are independent of one another.
2622   if (!MemOpChains.empty())
2623     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2624 
2625   SDValue Glue;
2626 
2627   // Build a sequence of copy-to-reg nodes, chained and glued together.
2628   for (auto &Reg : RegsToPass) {
2629     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
2630     Glue = Chain.getValue(1);
2631   }
2632 
2633   // Validate that none of the argument registers have been marked as
2634   // reserved, if so report an error. Do the same for the return address if this
2635   // is not a tailcall.
2636   validateCCReservedRegs(RegsToPass, MF);
2637   if (!IsTailCall &&
2638       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
2639     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
2640         MF.getFunction(),
2641         "Return address register required, but has been reserved."});
2642 
2643   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
2644   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
2645   // split it and then direct call can be matched by PseudoCALL.
2646   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
2647     const GlobalValue *GV = S->getGlobal();
2648 
2649     unsigned OpFlags = RISCVII::MO_CALL;
2650     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
2651       OpFlags = RISCVII::MO_PLT;
2652 
2653     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2654   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2655     unsigned OpFlags = RISCVII::MO_CALL;
2656 
2657     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
2658                                                  nullptr))
2659       OpFlags = RISCVII::MO_PLT;
2660 
2661     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
2662   }
2663 
2664   // The first call operand is the chain and the second is the target address.
2665   SmallVector<SDValue, 8> Ops;
2666   Ops.push_back(Chain);
2667   Ops.push_back(Callee);
2668 
2669   // Add argument registers to the end of the list so that they are
2670   // known live into the call.
2671   for (auto &Reg : RegsToPass)
2672     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2673 
2674   if (!IsTailCall) {
2675     // Add a register mask operand representing the call-preserved registers.
2676     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2677     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2678     assert(Mask && "Missing call preserved mask for calling convention");
2679     Ops.push_back(DAG.getRegisterMask(Mask));
2680   }
2681 
2682   // Glue the call to the argument copies, if any.
2683   if (Glue.getNode())
2684     Ops.push_back(Glue);
2685 
2686   // Emit the call.
2687   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2688 
2689   if (IsTailCall) {
2690     MF.getFrameInfo().setHasTailCall();
2691     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
2692   }
2693 
2694   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
2695   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2696   Glue = Chain.getValue(1);
2697 
2698   // Mark the end of the call, which is glued to the call itself.
2699   Chain = DAG.getCALLSEQ_END(Chain,
2700                              DAG.getConstant(NumBytes, DL, PtrVT, true),
2701                              DAG.getConstant(0, DL, PtrVT, true),
2702                              Glue, DL);
2703   Glue = Chain.getValue(1);
2704 
2705   // Assign locations to each value returned by this call.
2706   SmallVector<CCValAssign, 16> RVLocs;
2707   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
2708   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
2709 
2710   // Copy all of the result registers out of their specified physreg.
2711   for (auto &VA : RVLocs) {
2712     // Copy the value out
2713     SDValue RetValue =
2714         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
2715     // Glue the RetValue to the end of the call sequence
2716     Chain = RetValue.getValue(1);
2717     Glue = RetValue.getValue(2);
2718 
2719     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
2720       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
2721       SDValue RetValue2 =
2722           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
2723       Chain = RetValue2.getValue(1);
2724       Glue = RetValue2.getValue(2);
2725       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
2726                              RetValue2);
2727     }
2728 
2729     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
2730 
2731     InVals.push_back(RetValue);
2732   }
2733 
2734   return Chain;
2735 }
2736 
2737 bool RISCVTargetLowering::CanLowerReturn(
2738     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
2739     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2740   SmallVector<CCValAssign, 16> RVLocs;
2741   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2742   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
2743     MVT VT = Outs[i].VT;
2744     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2745     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
2746     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
2747                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
2748       return false;
2749   }
2750   return true;
2751 }
2752 
2753 SDValue
2754 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2755                                  bool IsVarArg,
2756                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
2757                                  const SmallVectorImpl<SDValue> &OutVals,
2758                                  const SDLoc &DL, SelectionDAG &DAG) const {
2759   const MachineFunction &MF = DAG.getMachineFunction();
2760   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
2761 
2762   // Stores the assignment of the return value to a location.
2763   SmallVector<CCValAssign, 16> RVLocs;
2764 
2765   // Info about the registers and stack slot.
2766   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2767                  *DAG.getContext());
2768 
2769   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
2770                     nullptr);
2771 
2772   SDValue Glue;
2773   SmallVector<SDValue, 4> RetOps(1, Chain);
2774 
2775   // Copy the result values into the output registers.
2776   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
2777     SDValue Val = OutVals[i];
2778     CCValAssign &VA = RVLocs[i];
2779     assert(VA.isRegLoc() && "Can only return in registers!");
2780 
2781     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
2782       // Handle returning f64 on RV32D with a soft float ABI.
2783       assert(VA.isRegLoc() && "Expected return via registers");
2784       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
2785                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
2786       SDValue Lo = SplitF64.getValue(0);
2787       SDValue Hi = SplitF64.getValue(1);
2788       Register RegLo = VA.getLocReg();
2789       assert(RegLo < RISCV::X31 && "Invalid register pair");
2790       Register RegHi = RegLo + 1;
2791 
2792       if (STI.isRegisterReservedByUser(RegLo) ||
2793           STI.isRegisterReservedByUser(RegHi))
2794         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
2795             MF.getFunction(),
2796             "Return value register required, but has been reserved."});
2797 
2798       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
2799       Glue = Chain.getValue(1);
2800       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
2801       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
2802       Glue = Chain.getValue(1);
2803       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
2804     } else {
2805       // Handle a 'normal' return.
2806       Val = convertValVTToLocVT(DAG, Val, VA, DL);
2807       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
2808 
2809       if (STI.isRegisterReservedByUser(VA.getLocReg()))
2810         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
2811             MF.getFunction(),
2812             "Return value register required, but has been reserved."});
2813 
2814       // Guarantee that all emitted copies are stuck together.
2815       Glue = Chain.getValue(1);
2816       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2817     }
2818   }
2819 
2820   RetOps[0] = Chain; // Update chain.
2821 
2822   // Add the glue node if we have it.
2823   if (Glue.getNode()) {
2824     RetOps.push_back(Glue);
2825   }
2826 
2827   // Interrupt service routines use different return instructions.
2828   const Function &Func = DAG.getMachineFunction().getFunction();
2829   if (Func.hasFnAttribute("interrupt")) {
2830     if (!Func.getReturnType()->isVoidTy())
2831       report_fatal_error(
2832           "Functions with the interrupt attribute must have void return type!");
2833 
2834     MachineFunction &MF = DAG.getMachineFunction();
2835     StringRef Kind =
2836       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
2837 
2838     unsigned RetOpc;
2839     if (Kind == "user")
2840       RetOpc = RISCVISD::URET_FLAG;
2841     else if (Kind == "supervisor")
2842       RetOpc = RISCVISD::SRET_FLAG;
2843     else
2844       RetOpc = RISCVISD::MRET_FLAG;
2845 
2846     return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
2847   }
2848 
2849   return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
2850 }
2851 
2852 void RISCVTargetLowering::validateCCReservedRegs(
2853     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
2854     MachineFunction &MF) const {
2855   const Function &F = MF.getFunction();
2856   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
2857 
2858   if (std::any_of(std::begin(Regs), std::end(Regs), [&STI](auto Reg) {
2859         return STI.isRegisterReservedByUser(Reg.first);
2860       }))
2861     F.getContext().diagnose(DiagnosticInfoUnsupported{
2862         F, "Argument register required, but has been reserved."});
2863 }
2864 
2865 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2866   return CI->isTailCall();
2867 }
2868 
2869 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
2870 #define NODE_NAME_CASE(NODE)                                                   \
2871   case RISCVISD::NODE:                                                         \
2872     return "RISCVISD::" #NODE;
2873   // clang-format off
2874   switch ((RISCVISD::NodeType)Opcode) {
2875   case RISCVISD::FIRST_NUMBER:
2876     break;
2877   NODE_NAME_CASE(RET_FLAG)
2878   NODE_NAME_CASE(URET_FLAG)
2879   NODE_NAME_CASE(SRET_FLAG)
2880   NODE_NAME_CASE(MRET_FLAG)
2881   NODE_NAME_CASE(CALL)
2882   NODE_NAME_CASE(SELECT_CC)
2883   NODE_NAME_CASE(BuildPairF64)
2884   NODE_NAME_CASE(SplitF64)
2885   NODE_NAME_CASE(TAIL)
2886   NODE_NAME_CASE(SLLW)
2887   NODE_NAME_CASE(SRAW)
2888   NODE_NAME_CASE(SRLW)
2889   NODE_NAME_CASE(DIVW)
2890   NODE_NAME_CASE(DIVUW)
2891   NODE_NAME_CASE(REMUW)
2892   NODE_NAME_CASE(ROLW)
2893   NODE_NAME_CASE(RORW)
2894   NODE_NAME_CASE(FMV_W_X_RV64)
2895   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
2896   NODE_NAME_CASE(READ_CYCLE_WIDE)
2897   NODE_NAME_CASE(GREVI)
2898   NODE_NAME_CASE(GREVIW)
2899   NODE_NAME_CASE(GORCI)
2900   NODE_NAME_CASE(GORCIW)
2901   }
2902   // clang-format on
2903   return nullptr;
2904 #undef NODE_NAME_CASE
2905 }
2906 
2907 /// getConstraintType - Given a constraint letter, return the type of
2908 /// constraint it is for this target.
2909 RISCVTargetLowering::ConstraintType
2910 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
2911   if (Constraint.size() == 1) {
2912     switch (Constraint[0]) {
2913     default:
2914       break;
2915     case 'f':
2916       return C_RegisterClass;
2917     case 'I':
2918     case 'J':
2919     case 'K':
2920       return C_Immediate;
2921     case 'A':
2922       return C_Memory;
2923     }
2924   }
2925   return TargetLowering::getConstraintType(Constraint);
2926 }
2927 
2928 std::pair<unsigned, const TargetRegisterClass *>
2929 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2930                                                   StringRef Constraint,
2931                                                   MVT VT) const {
2932   // First, see if this is a constraint that directly corresponds to a
2933   // RISCV register class.
2934   if (Constraint.size() == 1) {
2935     switch (Constraint[0]) {
2936     case 'r':
2937       return std::make_pair(0U, &RISCV::GPRRegClass);
2938     case 'f':
2939       if (Subtarget.hasStdExtF() && VT == MVT::f32)
2940         return std::make_pair(0U, &RISCV::FPR32RegClass);
2941       if (Subtarget.hasStdExtD() && VT == MVT::f64)
2942         return std::make_pair(0U, &RISCV::FPR64RegClass);
2943       break;
2944     default:
2945       break;
2946     }
2947   }
2948 
2949   // Clang will correctly decode the usage of register name aliases into their
2950   // official names. However, other frontends like `rustc` do not. This allows
2951   // users of these frontends to use the ABI names for registers in LLVM-style
2952   // register constraints.
2953   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
2954                                .Case("{zero}", RISCV::X0)
2955                                .Case("{ra}", RISCV::X1)
2956                                .Case("{sp}", RISCV::X2)
2957                                .Case("{gp}", RISCV::X3)
2958                                .Case("{tp}", RISCV::X4)
2959                                .Case("{t0}", RISCV::X5)
2960                                .Case("{t1}", RISCV::X6)
2961                                .Case("{t2}", RISCV::X7)
2962                                .Cases("{s0}", "{fp}", RISCV::X8)
2963                                .Case("{s1}", RISCV::X9)
2964                                .Case("{a0}", RISCV::X10)
2965                                .Case("{a1}", RISCV::X11)
2966                                .Case("{a2}", RISCV::X12)
2967                                .Case("{a3}", RISCV::X13)
2968                                .Case("{a4}", RISCV::X14)
2969                                .Case("{a5}", RISCV::X15)
2970                                .Case("{a6}", RISCV::X16)
2971                                .Case("{a7}", RISCV::X17)
2972                                .Case("{s2}", RISCV::X18)
2973                                .Case("{s3}", RISCV::X19)
2974                                .Case("{s4}", RISCV::X20)
2975                                .Case("{s5}", RISCV::X21)
2976                                .Case("{s6}", RISCV::X22)
2977                                .Case("{s7}", RISCV::X23)
2978                                .Case("{s8}", RISCV::X24)
2979                                .Case("{s9}", RISCV::X25)
2980                                .Case("{s10}", RISCV::X26)
2981                                .Case("{s11}", RISCV::X27)
2982                                .Case("{t3}", RISCV::X28)
2983                                .Case("{t4}", RISCV::X29)
2984                                .Case("{t5}", RISCV::X30)
2985                                .Case("{t6}", RISCV::X31)
2986                                .Default(RISCV::NoRegister);
2987   if (XRegFromAlias != RISCV::NoRegister)
2988     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
2989 
2990   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
2991   // TableGen record rather than the AsmName to choose registers for InlineAsm
2992   // constraints, plus we want to match those names to the widest floating point
2993   // register type available, manually select floating point registers here.
2994   //
2995   // The second case is the ABI name of the register, so that frontends can also
2996   // use the ABI names in register constraint lists.
2997   if (Subtarget.hasStdExtF() || Subtarget.hasStdExtD()) {
2998     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
2999                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
3000                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
3001                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
3002                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
3003                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
3004                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
3005                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
3006                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
3007                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
3008                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
3009                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
3010                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
3011                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
3012                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
3013                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
3014                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
3015                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
3016                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
3017                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
3018                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
3019                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
3020                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
3021                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
3022                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
3023                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
3024                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
3025                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
3026                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
3027                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
3028                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
3029                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
3030                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
3031                         .Default(RISCV::NoRegister);
3032     if (FReg != RISCV::NoRegister) {
3033       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
3034       if (Subtarget.hasStdExtD()) {
3035         unsigned RegNo = FReg - RISCV::F0_F;
3036         unsigned DReg = RISCV::F0_D + RegNo;
3037         return std::make_pair(DReg, &RISCV::FPR64RegClass);
3038       }
3039       return std::make_pair(FReg, &RISCV::FPR32RegClass);
3040     }
3041   }
3042 
3043   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3044 }
3045 
3046 unsigned
3047 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
3048   // Currently only support length 1 constraints.
3049   if (ConstraintCode.size() == 1) {
3050     switch (ConstraintCode[0]) {
3051     case 'A':
3052       return InlineAsm::Constraint_A;
3053     default:
3054       break;
3055     }
3056   }
3057 
3058   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
3059 }
3060 
3061 void RISCVTargetLowering::LowerAsmOperandForConstraint(
3062     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
3063     SelectionDAG &DAG) const {
3064   // Currently only support length 1 constraints.
3065   if (Constraint.length() == 1) {
3066     switch (Constraint[0]) {
3067     case 'I':
3068       // Validate & create a 12-bit signed immediate operand.
3069       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3070         uint64_t CVal = C->getSExtValue();
3071         if (isInt<12>(CVal))
3072           Ops.push_back(
3073               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
3074       }
3075       return;
3076     case 'J':
3077       // Validate & create an integer zero operand.
3078       if (auto *C = dyn_cast<ConstantSDNode>(Op))
3079         if (C->getZExtValue() == 0)
3080           Ops.push_back(
3081               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
3082       return;
3083     case 'K':
3084       // Validate & create a 5-bit unsigned immediate operand.
3085       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3086         uint64_t CVal = C->getZExtValue();
3087         if (isUInt<5>(CVal))
3088           Ops.push_back(
3089               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
3090       }
3091       return;
3092     default:
3093       break;
3094     }
3095   }
3096   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3097 }
3098 
3099 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
3100                                                    Instruction *Inst,
3101                                                    AtomicOrdering Ord) const {
3102   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
3103     return Builder.CreateFence(Ord);
3104   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
3105     return Builder.CreateFence(AtomicOrdering::Release);
3106   return nullptr;
3107 }
3108 
3109 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
3110                                                     Instruction *Inst,
3111                                                     AtomicOrdering Ord) const {
3112   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
3113     return Builder.CreateFence(AtomicOrdering::Acquire);
3114   return nullptr;
3115 }
3116 
3117 TargetLowering::AtomicExpansionKind
3118 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
3119   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
3120   // point operations can't be used in an lr/sc sequence without breaking the
3121   // forward-progress guarantee.
3122   if (AI->isFloatingPointOperation())
3123     return AtomicExpansionKind::CmpXChg;
3124 
3125   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
3126   if (Size == 8 || Size == 16)
3127     return AtomicExpansionKind::MaskedIntrinsic;
3128   return AtomicExpansionKind::None;
3129 }
3130 
3131 static Intrinsic::ID
3132 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
3133   if (XLen == 32) {
3134     switch (BinOp) {
3135     default:
3136       llvm_unreachable("Unexpected AtomicRMW BinOp");
3137     case AtomicRMWInst::Xchg:
3138       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
3139     case AtomicRMWInst::Add:
3140       return Intrinsic::riscv_masked_atomicrmw_add_i32;
3141     case AtomicRMWInst::Sub:
3142       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
3143     case AtomicRMWInst::Nand:
3144       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
3145     case AtomicRMWInst::Max:
3146       return Intrinsic::riscv_masked_atomicrmw_max_i32;
3147     case AtomicRMWInst::Min:
3148       return Intrinsic::riscv_masked_atomicrmw_min_i32;
3149     case AtomicRMWInst::UMax:
3150       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
3151     case AtomicRMWInst::UMin:
3152       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
3153     }
3154   }
3155 
3156   if (XLen == 64) {
3157     switch (BinOp) {
3158     default:
3159       llvm_unreachable("Unexpected AtomicRMW BinOp");
3160     case AtomicRMWInst::Xchg:
3161       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
3162     case AtomicRMWInst::Add:
3163       return Intrinsic::riscv_masked_atomicrmw_add_i64;
3164     case AtomicRMWInst::Sub:
3165       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
3166     case AtomicRMWInst::Nand:
3167       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
3168     case AtomicRMWInst::Max:
3169       return Intrinsic::riscv_masked_atomicrmw_max_i64;
3170     case AtomicRMWInst::Min:
3171       return Intrinsic::riscv_masked_atomicrmw_min_i64;
3172     case AtomicRMWInst::UMax:
3173       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
3174     case AtomicRMWInst::UMin:
3175       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
3176     }
3177   }
3178 
3179   llvm_unreachable("Unexpected XLen\n");
3180 }
3181 
3182 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
3183     IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
3184     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
3185   unsigned XLen = Subtarget.getXLen();
3186   Value *Ordering =
3187       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
3188   Type *Tys[] = {AlignedAddr->getType()};
3189   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
3190       AI->getModule(),
3191       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
3192 
3193   if (XLen == 64) {
3194     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
3195     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
3196     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
3197   }
3198 
3199   Value *Result;
3200 
3201   // Must pass the shift amount needed to sign extend the loaded value prior
3202   // to performing a signed comparison for min/max. ShiftAmt is the number of
3203   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
3204   // is the number of bits to left+right shift the value in order to
3205   // sign-extend.
3206   if (AI->getOperation() == AtomicRMWInst::Min ||
3207       AI->getOperation() == AtomicRMWInst::Max) {
3208     const DataLayout &DL = AI->getModule()->getDataLayout();
3209     unsigned ValWidth =
3210         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
3211     Value *SextShamt =
3212         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
3213     Result = Builder.CreateCall(LrwOpScwLoop,
3214                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
3215   } else {
3216     Result =
3217         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
3218   }
3219 
3220   if (XLen == 64)
3221     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
3222   return Result;
3223 }
3224 
3225 TargetLowering::AtomicExpansionKind
3226 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
3227     AtomicCmpXchgInst *CI) const {
3228   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
3229   if (Size == 8 || Size == 16)
3230     return AtomicExpansionKind::MaskedIntrinsic;
3231   return AtomicExpansionKind::None;
3232 }
3233 
3234 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
3235     IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
3236     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
3237   unsigned XLen = Subtarget.getXLen();
3238   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
3239   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
3240   if (XLen == 64) {
3241     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
3242     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
3243     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
3244     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
3245   }
3246   Type *Tys[] = {AlignedAddr->getType()};
3247   Function *MaskedCmpXchg =
3248       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
3249   Value *Result = Builder.CreateCall(
3250       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
3251   if (XLen == 64)
3252     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
3253   return Result;
3254 }
3255 
3256 Register RISCVTargetLowering::getExceptionPointerRegister(
3257     const Constant *PersonalityFn) const {
3258   return RISCV::X10;
3259 }
3260 
3261 Register RISCVTargetLowering::getExceptionSelectorRegister(
3262     const Constant *PersonalityFn) const {
3263   return RISCV::X11;
3264 }
3265 
3266 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
3267   // Return false to suppress the unnecessary extensions if the LibCall
3268   // arguments or return value is f32 type for LP64 ABI.
3269   RISCVABI::ABI ABI = Subtarget.getTargetABI();
3270   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
3271     return false;
3272 
3273   return true;
3274 }
3275 
3276 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
3277                                                  SDValue C) const {
3278   // Check integral scalar types.
3279   if (VT.isScalarInteger()) {
3280     // Do not perform the transformation on riscv32 with the M extension.
3281     if (!Subtarget.is64Bit() && Subtarget.hasStdExtM())
3282       return false;
3283     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
3284       if (ConstNode->getAPIntValue().getBitWidth() > 8 * sizeof(int64_t))
3285         return false;
3286       int64_t Imm = ConstNode->getSExtValue();
3287       if (isPowerOf2_64(Imm + 1) || isPowerOf2_64(Imm - 1) ||
3288           isPowerOf2_64(1 - Imm) || isPowerOf2_64(-1 - Imm))
3289         return true;
3290     }
3291   }
3292 
3293   return false;
3294 }
3295 
3296 #define GET_REGISTER_MATCHER
3297 #include "RISCVGenAsmMatcher.inc"
3298 
3299 Register
3300 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
3301                                        const MachineFunction &MF) const {
3302   Register Reg = MatchRegisterAltName(RegName);
3303   if (Reg == RISCV::NoRegister)
3304     Reg = MatchRegisterName(RegName);
3305   if (Reg == RISCV::NoRegister)
3306     report_fatal_error(
3307         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
3308   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
3309   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
3310     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
3311                              StringRef(RegName) + "\"."));
3312   return Reg;
3313 }
3314