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