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