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