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