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 "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/IntrinsicsRISCV.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/KnownBits.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "riscv-lower"
42 
43 STATISTIC(NumTailCalls, "Number of tail calls");
44 
45 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
46                                          const RISCVSubtarget &STI)
47     : TargetLowering(TM), Subtarget(STI) {
48 
49   if (Subtarget.isRV32E())
50     report_fatal_error("Codegen not yet implemented for RV32E");
51 
52   RISCVABI::ABI ABI = Subtarget.getTargetABI();
53   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
54 
55   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
56       !Subtarget.hasStdExtF()) {
57     errs() << "Hard-float 'f' ABI can't be used for a target that "
58                 "doesn't support the F instruction set extension (ignoring "
59                           "target-abi)\n";
60     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
61   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
62              !Subtarget.hasStdExtD()) {
63     errs() << "Hard-float 'd' ABI can't be used for a target that "
64               "doesn't support the D instruction set extension (ignoring "
65               "target-abi)\n";
66     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
67   }
68 
69   switch (ABI) {
70   default:
71     report_fatal_error("Don't know how to lower this ABI");
72   case RISCVABI::ABI_ILP32:
73   case RISCVABI::ABI_ILP32F:
74   case RISCVABI::ABI_ILP32D:
75   case RISCVABI::ABI_LP64:
76   case RISCVABI::ABI_LP64F:
77   case RISCVABI::ABI_LP64D:
78     break;
79   }
80 
81   MVT XLenVT = Subtarget.getXLenVT();
82 
83   // Set up the register classes.
84   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
85 
86   if (Subtarget.hasStdExtZfh())
87     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
88   if (Subtarget.hasStdExtF())
89     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
90   if (Subtarget.hasStdExtD())
91     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
92 
93   static const MVT::SimpleValueType BoolVecVTs[] = {
94       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
95       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
96   static const MVT::SimpleValueType IntVecVTs[] = {
97       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
98       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
99       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
100       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
101       MVT::nxv4i64, MVT::nxv8i64};
102   static const MVT::SimpleValueType F16VecVTs[] = {
103       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
104       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
105   static const MVT::SimpleValueType F32VecVTs[] = {
106       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
107   static const MVT::SimpleValueType F64VecVTs[] = {
108       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
109 
110   if (Subtarget.hasStdExtV()) {
111     auto addRegClassForRVV = [this](MVT VT) {
112       unsigned Size = VT.getSizeInBits().getKnownMinValue();
113       assert(Size <= 512 && isPowerOf2_32(Size));
114       const TargetRegisterClass *RC;
115       if (Size <= 64)
116         RC = &RISCV::VRRegClass;
117       else if (Size == 128)
118         RC = &RISCV::VRM2RegClass;
119       else if (Size == 256)
120         RC = &RISCV::VRM4RegClass;
121       else
122         RC = &RISCV::VRM8RegClass;
123 
124       addRegisterClass(VT, RC);
125     };
126 
127     for (MVT VT : BoolVecVTs)
128       addRegClassForRVV(VT);
129     for (MVT VT : IntVecVTs)
130       addRegClassForRVV(VT);
131 
132     if (Subtarget.hasStdExtZfh())
133       for (MVT VT : F16VecVTs)
134         addRegClassForRVV(VT);
135 
136     if (Subtarget.hasStdExtF())
137       for (MVT VT : F32VecVTs)
138         addRegClassForRVV(VT);
139 
140     if (Subtarget.hasStdExtD())
141       for (MVT VT : F64VecVTs)
142         addRegClassForRVV(VT);
143   }
144 
145   // Compute derived properties from the register classes.
146   computeRegisterProperties(STI.getRegisterInfo());
147 
148   setStackPointerRegisterToSaveRestore(RISCV::X2);
149 
150   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
151     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
152 
153   // TODO: add all necessary setOperationAction calls.
154   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
155 
156   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
157   setOperationAction(ISD::BR_CC, XLenVT, Expand);
158   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
159 
160   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
161   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
162 
163   setOperationAction(ISD::VASTART, MVT::Other, Custom);
164   setOperationAction(ISD::VAARG, MVT::Other, Expand);
165   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
166   setOperationAction(ISD::VAEND, MVT::Other, Expand);
167 
168   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
169   if (!Subtarget.hasStdExtZbb()) {
170     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
171     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
172   }
173 
174   if (Subtarget.is64Bit()) {
175     setOperationAction(ISD::ADD, MVT::i32, Custom);
176     setOperationAction(ISD::SUB, MVT::i32, Custom);
177     setOperationAction(ISD::SHL, MVT::i32, Custom);
178     setOperationAction(ISD::SRA, MVT::i32, Custom);
179     setOperationAction(ISD::SRL, MVT::i32, Custom);
180   }
181 
182   if (!Subtarget.hasStdExtM()) {
183     setOperationAction(ISD::MUL, XLenVT, Expand);
184     setOperationAction(ISD::MULHS, XLenVT, Expand);
185     setOperationAction(ISD::MULHU, XLenVT, Expand);
186     setOperationAction(ISD::SDIV, XLenVT, Expand);
187     setOperationAction(ISD::UDIV, XLenVT, Expand);
188     setOperationAction(ISD::SREM, XLenVT, Expand);
189     setOperationAction(ISD::UREM, XLenVT, Expand);
190   }
191 
192   if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) {
193     setOperationAction(ISD::MUL, MVT::i32, Custom);
194 
195     setOperationAction(ISD::SDIV, MVT::i8, Custom);
196     setOperationAction(ISD::UDIV, MVT::i8, Custom);
197     setOperationAction(ISD::UREM, MVT::i8, Custom);
198     setOperationAction(ISD::SDIV, MVT::i16, Custom);
199     setOperationAction(ISD::UDIV, MVT::i16, Custom);
200     setOperationAction(ISD::UREM, MVT::i16, Custom);
201     setOperationAction(ISD::SDIV, MVT::i32, Custom);
202     setOperationAction(ISD::UDIV, MVT::i32, Custom);
203     setOperationAction(ISD::UREM, MVT::i32, Custom);
204   }
205 
206   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
207   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
208   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
209   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
210 
211   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
212   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
213   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
214 
215   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
216     if (Subtarget.is64Bit()) {
217       setOperationAction(ISD::ROTL, MVT::i32, Custom);
218       setOperationAction(ISD::ROTR, MVT::i32, Custom);
219     }
220   } else {
221     setOperationAction(ISD::ROTL, XLenVT, Expand);
222     setOperationAction(ISD::ROTR, XLenVT, Expand);
223   }
224 
225   if (Subtarget.hasStdExtZbp()) {
226     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
227     // more combining.
228     setOperationAction(ISD::BITREVERSE, XLenVT, Custom);
229     setOperationAction(ISD::BSWAP, XLenVT, Custom);
230 
231     if (Subtarget.is64Bit()) {
232       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
233       setOperationAction(ISD::BSWAP, MVT::i32, Custom);
234     }
235   } else {
236     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
237     // pattern match it directly in isel.
238     setOperationAction(ISD::BSWAP, XLenVT,
239                        Subtarget.hasStdExtZbb() ? Legal : Expand);
240   }
241 
242   if (Subtarget.hasStdExtZbb()) {
243     setOperationAction(ISD::SMIN, XLenVT, Legal);
244     setOperationAction(ISD::SMAX, XLenVT, Legal);
245     setOperationAction(ISD::UMIN, XLenVT, Legal);
246     setOperationAction(ISD::UMAX, XLenVT, Legal);
247   } else {
248     setOperationAction(ISD::CTTZ, XLenVT, Expand);
249     setOperationAction(ISD::CTLZ, XLenVT, Expand);
250     setOperationAction(ISD::CTPOP, XLenVT, Expand);
251   }
252 
253   if (Subtarget.hasStdExtZbt()) {
254     setOperationAction(ISD::FSHL, XLenVT, Legal);
255     setOperationAction(ISD::FSHR, XLenVT, Legal);
256     setOperationAction(ISD::SELECT, XLenVT, Legal);
257 
258     if (Subtarget.is64Bit()) {
259       setOperationAction(ISD::FSHL, MVT::i32, Custom);
260       setOperationAction(ISD::FSHR, MVT::i32, Custom);
261     }
262   } else {
263     setOperationAction(ISD::SELECT, XLenVT, Custom);
264   }
265 
266   ISD::CondCode FPCCToExpand[] = {
267       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
268       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
269       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
270 
271   ISD::NodeType FPOpToExpand[] = {
272       ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP,
273       ISD::FP_TO_FP16};
274 
275   if (Subtarget.hasStdExtZfh())
276     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
277 
278   if (Subtarget.hasStdExtZfh()) {
279     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
280     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
281     for (auto CC : FPCCToExpand)
282       setCondCodeAction(CC, MVT::f16, Expand);
283     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
284     setOperationAction(ISD::SELECT, MVT::f16, Custom);
285     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
286     for (auto Op : FPOpToExpand)
287       setOperationAction(Op, MVT::f16, Expand);
288   }
289 
290   if (Subtarget.hasStdExtF()) {
291     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
292     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
293     for (auto CC : FPCCToExpand)
294       setCondCodeAction(CC, MVT::f32, Expand);
295     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
296     setOperationAction(ISD::SELECT, MVT::f32, Custom);
297     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
298     for (auto Op : FPOpToExpand)
299       setOperationAction(Op, MVT::f32, Expand);
300     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
301     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
302   }
303 
304   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
305     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
306 
307   if (Subtarget.hasStdExtD()) {
308     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
309     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
310     for (auto CC : FPCCToExpand)
311       setCondCodeAction(CC, MVT::f64, Expand);
312     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
313     setOperationAction(ISD::SELECT, MVT::f64, Custom);
314     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
315     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
316     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
317     for (auto Op : FPOpToExpand)
318       setOperationAction(Op, MVT::f64, Expand);
319     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
320     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
321   }
322 
323   if (Subtarget.is64Bit()) {
324     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
325     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
326     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
327     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
328   }
329 
330   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
331   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
332   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
333   setOperationAction(ISD::JumpTable, XLenVT, Custom);
334 
335   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
336 
337   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
338   // Unfortunately this can't be determined just from the ISA naming string.
339   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
340                      Subtarget.is64Bit() ? Legal : Custom);
341 
342   setOperationAction(ISD::TRAP, MVT::Other, Legal);
343   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
344   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
345 
346   if (Subtarget.hasStdExtA()) {
347     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
348     setMinCmpXchgSizeInBits(32);
349   } else {
350     setMaxAtomicSizeInBitsSupported(0);
351   }
352 
353   setBooleanContents(ZeroOrOneBooleanContent);
354 
355   if (Subtarget.hasStdExtV()) {
356     setBooleanVectorContents(ZeroOrOneBooleanContent);
357 
358     setOperationAction(ISD::VSCALE, XLenVT, Custom);
359 
360     // RVV intrinsics may have illegal operands.
361     // We also need to custom legalize vmv.x.s.
362     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
363     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
364     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
365     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
366     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
367     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
368 
369     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
370 
371     if (Subtarget.is64Bit()) {
372       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
373       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
374     } else {
375       // We must custom-lower certain vXi64 operations on RV32 due to the vector
376       // element type being illegal.
377       setOperationAction(ISD::SPLAT_VECTOR, MVT::i64, Custom);
378       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
379       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
380     }
381 
382     for (MVT VT : BoolVecVTs) {
383       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
384 
385       // Mask VTs are custom-expanded into a series of standard nodes
386       setOperationAction(ISD::TRUNCATE, VT, Custom);
387     }
388 
389     for (MVT VT : IntVecVTs) {
390       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
391 
392       setOperationAction(ISD::SMIN, VT, Legal);
393       setOperationAction(ISD::SMAX, VT, Legal);
394       setOperationAction(ISD::UMIN, VT, Legal);
395       setOperationAction(ISD::UMAX, VT, Legal);
396 
397       setOperationAction(ISD::ROTL, VT, Expand);
398       setOperationAction(ISD::ROTR, VT, Expand);
399 
400       // Custom-lower extensions and truncations from/to mask types.
401       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
402       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
403       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
404 
405       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR"
406       // nodes which truncate by one power of two at a time.
407       setOperationAction(ISD::TRUNCATE, VT, Custom);
408 
409       // Custom-lower insert/extract operations to simplify patterns.
410       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
411       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
412     }
413 
414     // Expand various CCs to best match the RVV ISA, which natively supports UNE
415     // but no other unordered comparisons, and supports all ordered comparisons
416     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
417     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
418     // and we pattern-match those back to the "original", swapping operands once
419     // more. This way we catch both operations and both "vf" and "fv" forms with
420     // fewer patterns.
421     ISD::CondCode VFPCCToExpand[] = {
422         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
423         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
424         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
425     };
426 
427     // Sets common operation actions on RVV floating-point vector types.
428     const auto SetCommonVFPActions = [&](MVT VT) {
429       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
430       // Custom-lower insert/extract operations to simplify patterns.
431       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
432       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
433       for (auto CC : VFPCCToExpand)
434         setCondCodeAction(CC, VT, Expand);
435     };
436 
437     if (Subtarget.hasStdExtZfh())
438       for (MVT VT : F16VecVTs)
439         SetCommonVFPActions(VT);
440 
441     if (Subtarget.hasStdExtF())
442       for (MVT VT : F32VecVTs)
443         SetCommonVFPActions(VT);
444 
445     if (Subtarget.hasStdExtD())
446       for (MVT VT : F64VecVTs)
447         SetCommonVFPActions(VT);
448   }
449 
450   // Function alignments.
451   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
452   setMinFunctionAlignment(FunctionAlignment);
453   setPrefFunctionAlignment(FunctionAlignment);
454 
455   setMinimumJumpTableEntries(5);
456 
457   // Jumps are expensive, compared to logic
458   setJumpIsExpensive();
459 
460   // We can use any register for comparisons
461   setHasMultipleConditionRegisters();
462 
463   setTargetDAGCombine(ISD::SETCC);
464   if (Subtarget.hasStdExtZbp()) {
465     setTargetDAGCombine(ISD::OR);
466   }
467 }
468 
469 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
470                                             LLVMContext &Context,
471                                             EVT VT) const {
472   if (!VT.isVector())
473     return getPointerTy(DL);
474   if (Subtarget.hasStdExtV() && VT.isScalableVector())
475     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
476   return VT.changeVectorElementTypeToInteger();
477 }
478 
479 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
480                                              const CallInst &I,
481                                              MachineFunction &MF,
482                                              unsigned Intrinsic) const {
483   switch (Intrinsic) {
484   default:
485     return false;
486   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
487   case Intrinsic::riscv_masked_atomicrmw_add_i32:
488   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
489   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
490   case Intrinsic::riscv_masked_atomicrmw_max_i32:
491   case Intrinsic::riscv_masked_atomicrmw_min_i32:
492   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
493   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
494   case Intrinsic::riscv_masked_cmpxchg_i32:
495     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
496     Info.opc = ISD::INTRINSIC_W_CHAIN;
497     Info.memVT = MVT::getVT(PtrTy->getElementType());
498     Info.ptrVal = I.getArgOperand(0);
499     Info.offset = 0;
500     Info.align = Align(4);
501     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
502                  MachineMemOperand::MOVolatile;
503     return true;
504   }
505 }
506 
507 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
508                                                 const AddrMode &AM, Type *Ty,
509                                                 unsigned AS,
510                                                 Instruction *I) const {
511   // No global is ever allowed as a base.
512   if (AM.BaseGV)
513     return false;
514 
515   // Require a 12-bit signed offset.
516   if (!isInt<12>(AM.BaseOffs))
517     return false;
518 
519   switch (AM.Scale) {
520   case 0: // "r+i" or just "i", depending on HasBaseReg.
521     break;
522   case 1:
523     if (!AM.HasBaseReg) // allow "r+i".
524       break;
525     return false; // disallow "r+r" or "r+r+i".
526   default:
527     return false;
528   }
529 
530   return true;
531 }
532 
533 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
534   return isInt<12>(Imm);
535 }
536 
537 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
538   return isInt<12>(Imm);
539 }
540 
541 // On RV32, 64-bit integers are split into their high and low parts and held
542 // in two different registers, so the trunc is free since the low register can
543 // just be used.
544 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
545   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
546     return false;
547   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
548   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
549   return (SrcBits == 64 && DestBits == 32);
550 }
551 
552 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
553   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
554       !SrcVT.isInteger() || !DstVT.isInteger())
555     return false;
556   unsigned SrcBits = SrcVT.getSizeInBits();
557   unsigned DestBits = DstVT.getSizeInBits();
558   return (SrcBits == 64 && DestBits == 32);
559 }
560 
561 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
562   // Zexts are free if they can be combined with a load.
563   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
564     EVT MemVT = LD->getMemoryVT();
565     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
566          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
567         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
568          LD->getExtensionType() == ISD::ZEXTLOAD))
569       return true;
570   }
571 
572   return TargetLowering::isZExtFree(Val, VT2);
573 }
574 
575 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
576   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
577 }
578 
579 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
580   return Subtarget.hasStdExtZbb();
581 }
582 
583 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
584   return Subtarget.hasStdExtZbb();
585 }
586 
587 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
588                                        bool ForCodeSize) const {
589   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
590     return false;
591   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
592     return false;
593   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
594     return false;
595   if (Imm.isNegZero())
596     return false;
597   return Imm.isZero();
598 }
599 
600 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
601   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
602          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
603          (VT == MVT::f64 && Subtarget.hasStdExtD());
604 }
605 
606 // Changes the condition code and swaps operands if necessary, so the SetCC
607 // operation matches one of the comparisons supported directly in the RISC-V
608 // ISA.
609 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
610   switch (CC) {
611   default:
612     break;
613   case ISD::SETGT:
614   case ISD::SETLE:
615   case ISD::SETUGT:
616   case ISD::SETULE:
617     CC = ISD::getSetCCSwappedOperands(CC);
618     std::swap(LHS, RHS);
619     break;
620   }
621 }
622 
623 // Return the RISC-V branch opcode that matches the given DAG integer
624 // condition code. The CondCode must be one of those supported by the RISC-V
625 // ISA (see normaliseSetCC).
626 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
627   switch (CC) {
628   default:
629     llvm_unreachable("Unsupported CondCode");
630   case ISD::SETEQ:
631     return RISCV::BEQ;
632   case ISD::SETNE:
633     return RISCV::BNE;
634   case ISD::SETLT:
635     return RISCV::BLT;
636   case ISD::SETGE:
637     return RISCV::BGE;
638   case ISD::SETULT:
639     return RISCV::BLTU;
640   case ISD::SETUGE:
641     return RISCV::BGEU;
642   }
643 }
644 
645 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
646                                             SelectionDAG &DAG) const {
647   switch (Op.getOpcode()) {
648   default:
649     report_fatal_error("unimplemented operand");
650   case ISD::GlobalAddress:
651     return lowerGlobalAddress(Op, DAG);
652   case ISD::BlockAddress:
653     return lowerBlockAddress(Op, DAG);
654   case ISD::ConstantPool:
655     return lowerConstantPool(Op, DAG);
656   case ISD::JumpTable:
657     return lowerJumpTable(Op, DAG);
658   case ISD::GlobalTLSAddress:
659     return lowerGlobalTLSAddress(Op, DAG);
660   case ISD::SELECT:
661     return lowerSELECT(Op, DAG);
662   case ISD::VASTART:
663     return lowerVASTART(Op, DAG);
664   case ISD::FRAMEADDR:
665     return lowerFRAMEADDR(Op, DAG);
666   case ISD::RETURNADDR:
667     return lowerRETURNADDR(Op, DAG);
668   case ISD::SHL_PARTS:
669     return lowerShiftLeftParts(Op, DAG);
670   case ISD::SRA_PARTS:
671     return lowerShiftRightParts(Op, DAG, true);
672   case ISD::SRL_PARTS:
673     return lowerShiftRightParts(Op, DAG, false);
674   case ISD::BITCAST: {
675     assert(((Subtarget.is64Bit() && Subtarget.hasStdExtF()) ||
676             Subtarget.hasStdExtZfh()) &&
677            "Unexpected custom legalisation");
678     SDLoc DL(Op);
679     SDValue Op0 = Op.getOperand(0);
680     if (Op.getValueType() == MVT::f16 && Subtarget.hasStdExtZfh()) {
681       if (Op0.getValueType() != MVT::i16)
682         return SDValue();
683       SDValue NewOp0 =
684           DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), Op0);
685       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
686       return FPConv;
687     } else if (Op.getValueType() == MVT::f32 && Subtarget.is64Bit() &&
688                Subtarget.hasStdExtF()) {
689       if (Op0.getValueType() != MVT::i32)
690         return SDValue();
691       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
692       SDValue FPConv =
693           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
694       return FPConv;
695     }
696     return SDValue();
697   }
698   case ISD::INTRINSIC_WO_CHAIN:
699     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
700   case ISD::INTRINSIC_W_CHAIN:
701     return LowerINTRINSIC_W_CHAIN(Op, DAG);
702   case ISD::BSWAP:
703   case ISD::BITREVERSE: {
704     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
705     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
706     MVT VT = Op.getSimpleValueType();
707     SDLoc DL(Op);
708     // Start with the maximum immediate value which is the bitwidth - 1.
709     unsigned Imm = VT.getSizeInBits() - 1;
710     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
711     if (Op.getOpcode() == ISD::BSWAP)
712       Imm &= ~0x7U;
713     return DAG.getNode(RISCVISD::GREVI, DL, VT, Op.getOperand(0),
714                        DAG.getTargetConstant(Imm, DL, Subtarget.getXLenVT()));
715   }
716   case ISD::TRUNCATE: {
717     SDLoc DL(Op);
718     EVT VT = Op.getValueType();
719     // Only custom-lower vector truncates
720     if (!VT.isVector())
721       return Op;
722 
723     // Truncates to mask types are handled differently
724     if (VT.getVectorElementType() == MVT::i1)
725       return lowerVectorMaskTrunc(Op, DAG);
726 
727     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
728     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR" nodes which
729     // truncate by one power of two at a time.
730     EVT DstEltVT = VT.getVectorElementType();
731 
732     SDValue Src = Op.getOperand(0);
733     EVT SrcVT = Src.getValueType();
734     EVT SrcEltVT = SrcVT.getVectorElementType();
735 
736     assert(DstEltVT.bitsLT(SrcEltVT) &&
737            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
738            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
739            "Unexpected vector truncate lowering");
740 
741     SDValue Result = Src;
742     LLVMContext &Context = *DAG.getContext();
743     const ElementCount Count = SrcVT.getVectorElementCount();
744     do {
745       SrcEltVT = EVT::getIntegerVT(Context, SrcEltVT.getSizeInBits() / 2);
746       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
747       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR, DL, ResultVT, Result);
748     } while (SrcEltVT != DstEltVT);
749 
750     return Result;
751   }
752   case ISD::ANY_EXTEND:
753   case ISD::ZERO_EXTEND:
754     return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
755   case ISD::SIGN_EXTEND:
756     return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
757   case ISD::SPLAT_VECTOR:
758     return lowerSPLATVECTOR(Op, DAG);
759   case ISD::INSERT_VECTOR_ELT:
760     return lowerINSERT_VECTOR_ELT(Op, DAG);
761   case ISD::EXTRACT_VECTOR_ELT:
762     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
763   case ISD::VSCALE: {
764     MVT VT = Op.getSimpleValueType();
765     SDLoc DL(Op);
766     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
767     // We define our scalable vector types for lmul=1 to use a 64 bit known
768     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
769     // vscale as VLENB / 8.
770     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
771                                  DAG.getConstant(3, DL, VT));
772     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
773   }
774   }
775 }
776 
777 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
778                              SelectionDAG &DAG, unsigned Flags) {
779   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
780 }
781 
782 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
783                              SelectionDAG &DAG, unsigned Flags) {
784   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
785                                    Flags);
786 }
787 
788 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
789                              SelectionDAG &DAG, unsigned Flags) {
790   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
791                                    N->getOffset(), Flags);
792 }
793 
794 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
795                              SelectionDAG &DAG, unsigned Flags) {
796   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
797 }
798 
799 template <class NodeTy>
800 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
801                                      bool IsLocal) const {
802   SDLoc DL(N);
803   EVT Ty = getPointerTy(DAG.getDataLayout());
804 
805   if (isPositionIndependent()) {
806     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
807     if (IsLocal)
808       // Use PC-relative addressing to access the symbol. This generates the
809       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
810       // %pcrel_lo(auipc)).
811       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
812 
813     // Use PC-relative addressing to access the GOT for this symbol, then load
814     // the address from the GOT. This generates the pattern (PseudoLA sym),
815     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
816     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
817   }
818 
819   switch (getTargetMachine().getCodeModel()) {
820   default:
821     report_fatal_error("Unsupported code model for lowering");
822   case CodeModel::Small: {
823     // Generate a sequence for accessing addresses within the first 2 GiB of
824     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
825     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
826     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
827     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
828     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
829   }
830   case CodeModel::Medium: {
831     // Generate a sequence for accessing addresses within any 2GiB range within
832     // the address space. This generates the pattern (PseudoLLA sym), which
833     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
834     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
835     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
836   }
837   }
838 }
839 
840 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
841                                                 SelectionDAG &DAG) const {
842   SDLoc DL(Op);
843   EVT Ty = Op.getValueType();
844   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
845   int64_t Offset = N->getOffset();
846   MVT XLenVT = Subtarget.getXLenVT();
847 
848   const GlobalValue *GV = N->getGlobal();
849   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
850   SDValue Addr = getAddr(N, DAG, IsLocal);
851 
852   // In order to maximise the opportunity for common subexpression elimination,
853   // emit a separate ADD node for the global address offset instead of folding
854   // it in the global address node. Later peephole optimisations may choose to
855   // fold it back in when profitable.
856   if (Offset != 0)
857     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
858                        DAG.getConstant(Offset, DL, XLenVT));
859   return Addr;
860 }
861 
862 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
863                                                SelectionDAG &DAG) const {
864   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
865 
866   return getAddr(N, DAG);
867 }
868 
869 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
870                                                SelectionDAG &DAG) const {
871   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
872 
873   return getAddr(N, DAG);
874 }
875 
876 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
877                                             SelectionDAG &DAG) const {
878   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
879 
880   return getAddr(N, DAG);
881 }
882 
883 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
884                                               SelectionDAG &DAG,
885                                               bool UseGOT) const {
886   SDLoc DL(N);
887   EVT Ty = getPointerTy(DAG.getDataLayout());
888   const GlobalValue *GV = N->getGlobal();
889   MVT XLenVT = Subtarget.getXLenVT();
890 
891   if (UseGOT) {
892     // Use PC-relative addressing to access the GOT for this TLS symbol, then
893     // load the address from the GOT and add the thread pointer. This generates
894     // the pattern (PseudoLA_TLS_IE sym), which expands to
895     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
896     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
897     SDValue Load =
898         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
899 
900     // Add the thread pointer.
901     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
902     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
903   }
904 
905   // Generate a sequence for accessing the address relative to the thread
906   // pointer, with the appropriate adjustment for the thread pointer offset.
907   // This generates the pattern
908   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
909   SDValue AddrHi =
910       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
911   SDValue AddrAdd =
912       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
913   SDValue AddrLo =
914       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
915 
916   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
917   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
918   SDValue MNAdd = SDValue(
919       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
920       0);
921   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
922 }
923 
924 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
925                                                SelectionDAG &DAG) const {
926   SDLoc DL(N);
927   EVT Ty = getPointerTy(DAG.getDataLayout());
928   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
929   const GlobalValue *GV = N->getGlobal();
930 
931   // Use a PC-relative addressing mode to access the global dynamic GOT address.
932   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
933   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
934   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
935   SDValue Load =
936       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
937 
938   // Prepare argument list to generate call.
939   ArgListTy Args;
940   ArgListEntry Entry;
941   Entry.Node = Load;
942   Entry.Ty = CallTy;
943   Args.push_back(Entry);
944 
945   // Setup call to __tls_get_addr.
946   TargetLowering::CallLoweringInfo CLI(DAG);
947   CLI.setDebugLoc(DL)
948       .setChain(DAG.getEntryNode())
949       .setLibCallee(CallingConv::C, CallTy,
950                     DAG.getExternalSymbol("__tls_get_addr", Ty),
951                     std::move(Args));
952 
953   return LowerCallTo(CLI).first;
954 }
955 
956 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
957                                                    SelectionDAG &DAG) const {
958   SDLoc DL(Op);
959   EVT Ty = Op.getValueType();
960   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
961   int64_t Offset = N->getOffset();
962   MVT XLenVT = Subtarget.getXLenVT();
963 
964   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
965 
966   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
967       CallingConv::GHC)
968     report_fatal_error("In GHC calling convention TLS is not supported");
969 
970   SDValue Addr;
971   switch (Model) {
972   case TLSModel::LocalExec:
973     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
974     break;
975   case TLSModel::InitialExec:
976     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
977     break;
978   case TLSModel::LocalDynamic:
979   case TLSModel::GeneralDynamic:
980     Addr = getDynamicTLSAddr(N, DAG);
981     break;
982   }
983 
984   // In order to maximise the opportunity for common subexpression elimination,
985   // emit a separate ADD node for the global address offset instead of folding
986   // it in the global address node. Later peephole optimisations may choose to
987   // fold it back in when profitable.
988   if (Offset != 0)
989     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
990                        DAG.getConstant(Offset, DL, XLenVT));
991   return Addr;
992 }
993 
994 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
995   SDValue CondV = Op.getOperand(0);
996   SDValue TrueV = Op.getOperand(1);
997   SDValue FalseV = Op.getOperand(2);
998   SDLoc DL(Op);
999   MVT XLenVT = Subtarget.getXLenVT();
1000 
1001   // If the result type is XLenVT and CondV is the output of a SETCC node
1002   // which also operated on XLenVT inputs, then merge the SETCC node into the
1003   // lowered RISCVISD::SELECT_CC to take advantage of the integer
1004   // compare+branch instructions. i.e.:
1005   // (select (setcc lhs, rhs, cc), truev, falsev)
1006   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
1007   if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
1008       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
1009     SDValue LHS = CondV.getOperand(0);
1010     SDValue RHS = CondV.getOperand(1);
1011     auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
1012     ISD::CondCode CCVal = CC->get();
1013 
1014     normaliseSetCC(LHS, RHS, CCVal);
1015 
1016     SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
1017     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
1018     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
1019   }
1020 
1021   // Otherwise:
1022   // (select condv, truev, falsev)
1023   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
1024   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
1025   SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
1026 
1027   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
1028 
1029   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
1030 }
1031 
1032 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1033   MachineFunction &MF = DAG.getMachineFunction();
1034   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
1035 
1036   SDLoc DL(Op);
1037   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1038                                  getPointerTy(MF.getDataLayout()));
1039 
1040   // vastart just stores the address of the VarArgsFrameIndex slot into the
1041   // memory location argument.
1042   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1043   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1044                       MachinePointerInfo(SV));
1045 }
1046 
1047 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
1048                                             SelectionDAG &DAG) const {
1049   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
1050   MachineFunction &MF = DAG.getMachineFunction();
1051   MachineFrameInfo &MFI = MF.getFrameInfo();
1052   MFI.setFrameAddressIsTaken(true);
1053   Register FrameReg = RI.getFrameRegister(MF);
1054   int XLenInBytes = Subtarget.getXLen() / 8;
1055 
1056   EVT VT = Op.getValueType();
1057   SDLoc DL(Op);
1058   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
1059   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1060   while (Depth--) {
1061     int Offset = -(XLenInBytes * 2);
1062     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
1063                               DAG.getIntPtrConstant(Offset, DL));
1064     FrameAddr =
1065         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
1066   }
1067   return FrameAddr;
1068 }
1069 
1070 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
1071                                              SelectionDAG &DAG) const {
1072   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
1073   MachineFunction &MF = DAG.getMachineFunction();
1074   MachineFrameInfo &MFI = MF.getFrameInfo();
1075   MFI.setReturnAddressIsTaken(true);
1076   MVT XLenVT = Subtarget.getXLenVT();
1077   int XLenInBytes = Subtarget.getXLen() / 8;
1078 
1079   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1080     return SDValue();
1081 
1082   EVT VT = Op.getValueType();
1083   SDLoc DL(Op);
1084   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1085   if (Depth) {
1086     int Off = -XLenInBytes;
1087     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
1088     SDValue Offset = DAG.getConstant(Off, DL, VT);
1089     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
1090                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
1091                        MachinePointerInfo());
1092   }
1093 
1094   // Return the value of the return address register, marking it an implicit
1095   // live-in.
1096   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
1097   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
1098 }
1099 
1100 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
1101                                                  SelectionDAG &DAG) const {
1102   SDLoc DL(Op);
1103   SDValue Lo = Op.getOperand(0);
1104   SDValue Hi = Op.getOperand(1);
1105   SDValue Shamt = Op.getOperand(2);
1106   EVT VT = Lo.getValueType();
1107 
1108   // if Shamt-XLEN < 0: // Shamt < XLEN
1109   //   Lo = Lo << Shamt
1110   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
1111   // else:
1112   //   Lo = 0
1113   //   Hi = Lo << (Shamt-XLEN)
1114 
1115   SDValue Zero = DAG.getConstant(0, DL, VT);
1116   SDValue One = DAG.getConstant(1, DL, VT);
1117   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
1118   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
1119   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
1120   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
1121 
1122   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
1123   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
1124   SDValue ShiftRightLo =
1125       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
1126   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
1127   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
1128   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
1129 
1130   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
1131 
1132   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
1133   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
1134 
1135   SDValue Parts[2] = {Lo, Hi};
1136   return DAG.getMergeValues(Parts, DL);
1137 }
1138 
1139 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1140                                                   bool IsSRA) const {
1141   SDLoc DL(Op);
1142   SDValue Lo = Op.getOperand(0);
1143   SDValue Hi = Op.getOperand(1);
1144   SDValue Shamt = Op.getOperand(2);
1145   EVT VT = Lo.getValueType();
1146 
1147   // SRA expansion:
1148   //   if Shamt-XLEN < 0: // Shamt < XLEN
1149   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
1150   //     Hi = Hi >>s Shamt
1151   //   else:
1152   //     Lo = Hi >>s (Shamt-XLEN);
1153   //     Hi = Hi >>s (XLEN-1)
1154   //
1155   // SRL expansion:
1156   //   if Shamt-XLEN < 0: // Shamt < XLEN
1157   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
1158   //     Hi = Hi >>u Shamt
1159   //   else:
1160   //     Lo = Hi >>u (Shamt-XLEN);
1161   //     Hi = 0;
1162 
1163   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
1164 
1165   SDValue Zero = DAG.getConstant(0, DL, VT);
1166   SDValue One = DAG.getConstant(1, DL, VT);
1167   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
1168   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
1169   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
1170   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
1171 
1172   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
1173   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
1174   SDValue ShiftLeftHi =
1175       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
1176   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
1177   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
1178   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
1179   SDValue HiFalse =
1180       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
1181 
1182   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
1183 
1184   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
1185   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
1186 
1187   SDValue Parts[2] = {Lo, Hi};
1188   return DAG.getMergeValues(Parts, DL);
1189 }
1190 
1191 // Custom-lower a SPLAT_VECTOR where XLEN<SEW, as the SEW element type is
1192 // illegal (currently only vXi64 RV32).
1193 // FIXME: We could also catch non-constant sign-extended i32 values and lower
1194 // them to SPLAT_VECTOR_I64
1195 SDValue RISCVTargetLowering::lowerSPLATVECTOR(SDValue Op,
1196                                               SelectionDAG &DAG) const {
1197   SDLoc DL(Op);
1198   EVT VecVT = Op.getValueType();
1199   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
1200          "Unexpected SPLAT_VECTOR lowering");
1201   SDValue SplatVal = Op.getOperand(0);
1202 
1203   // If we can prove that the value is a sign-extended 32-bit value, lower this
1204   // as a custom node in order to try and match RVV vector/scalar instructions.
1205   if (auto *CVal = dyn_cast<ConstantSDNode>(SplatVal)) {
1206     if (isInt<32>(CVal->getSExtValue()))
1207       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT,
1208                          DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32));
1209   }
1210 
1211   if (SplatVal.getOpcode() == ISD::SIGN_EXTEND &&
1212       SplatVal.getOperand(0).getValueType() == MVT::i32) {
1213     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT,
1214                        SplatVal.getOperand(0));
1215   }
1216 
1217   // Else, on RV32 we lower an i64-element SPLAT_VECTOR thus, being careful not
1218   // to accidentally sign-extend the 32-bit halves to the e64 SEW:
1219   // vmv.v.x vX, hi
1220   // vsll.vx vX, vX, /*32*/
1221   // vmv.v.x vY, lo
1222   // vsll.vx vY, vY, /*32*/
1223   // vsrl.vx vY, vY, /*32*/
1224   // vor.vv vX, vX, vY
1225   SDValue One = DAG.getConstant(1, DL, MVT::i32);
1226   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1227   SDValue ThirtyTwoV = DAG.getConstant(32, DL, VecVT);
1228   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, SplatVal, Zero);
1229   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, SplatVal, One);
1230 
1231   Lo = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
1232   Lo = DAG.getNode(ISD::SHL, DL, VecVT, Lo, ThirtyTwoV);
1233   Lo = DAG.getNode(ISD::SRL, DL, VecVT, Lo, ThirtyTwoV);
1234 
1235   if (isNullConstant(Hi))
1236     return Lo;
1237 
1238   Hi = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Hi);
1239   Hi = DAG.getNode(ISD::SHL, DL, VecVT, Hi, ThirtyTwoV);
1240 
1241   return DAG.getNode(ISD::OR, DL, VecVT, Lo, Hi);
1242 }
1243 
1244 // Custom-lower extensions from mask vectors by using a vselect either with 1
1245 // for zero/any-extension or -1 for sign-extension:
1246 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
1247 // Note that any-extension is lowered identically to zero-extension.
1248 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
1249                                                 int64_t ExtTrueVal) const {
1250   SDLoc DL(Op);
1251   EVT VecVT = Op.getValueType();
1252   SDValue Src = Op.getOperand(0);
1253   // Only custom-lower extensions from mask types
1254   if (!Src.getValueType().isVector() ||
1255       Src.getValueType().getVectorElementType() != MVT::i1)
1256     return Op;
1257 
1258   // Be careful not to introduce illegal scalar types at this stage, and be
1259   // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
1260   // illegal and must be expanded. Since we know that the constants are
1261   // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
1262   bool IsRV32E64 =
1263       !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
1264   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1265   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, Subtarget.getXLenVT());
1266 
1267   if (!IsRV32E64) {
1268     SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
1269     SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
1270   } else {
1271     SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
1272     SplatTrueVal =
1273         DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
1274   }
1275 
1276   return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
1277 }
1278 
1279 // Custom-lower truncations from vectors to mask vectors by using a mask and a
1280 // setcc operation:
1281 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
1282 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
1283                                                   SelectionDAG &DAG) const {
1284   SDLoc DL(Op);
1285   EVT MaskVT = Op.getValueType();
1286   // Only expect to custom-lower truncations to mask types
1287   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
1288          "Unexpected type for vector mask lowering");
1289   SDValue Src = Op.getOperand(0);
1290   EVT VecVT = Src.getValueType();
1291 
1292   // Be careful not to introduce illegal scalar types at this stage, and be
1293   // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
1294   // illegal and must be expanded. Since we know that the constants are
1295   // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
1296   bool IsRV32E64 =
1297       !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
1298   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
1299   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1300 
1301   if (!IsRV32E64) {
1302     SplatOne = DAG.getSplatVector(VecVT, DL, SplatOne);
1303     SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
1304   } else {
1305     SplatOne = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatOne);
1306     SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
1307   }
1308 
1309   SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
1310 
1311   return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
1312 }
1313 
1314 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
1315                                                     SelectionDAG &DAG) const {
1316   SDLoc DL(Op);
1317   EVT VecVT = Op.getValueType();
1318   SDValue Vec = Op.getOperand(0);
1319   SDValue Val = Op.getOperand(1);
1320   SDValue Idx = Op.getOperand(2);
1321 
1322   // Custom-legalize INSERT_VECTOR_ELT where XLEN>=SEW, so that the vector is
1323   // first slid down into position, the value is inserted into the first
1324   // position, and the vector is slid back up. We do this to simplify patterns.
1325   //   (slideup vec, (insertelt (slidedown impdef, vec, idx), val, 0), idx),
1326   if (Subtarget.is64Bit() || VecVT.getVectorElementType() != MVT::i64) {
1327     if (isNullConstant(Idx))
1328       return Op;
1329     SDValue Slidedown = DAG.getNode(RISCVISD::VSLIDEDOWN, DL, VecVT,
1330                                     DAG.getUNDEF(VecVT), Vec, Idx);
1331     SDValue InsertElt0 =
1332         DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecVT, Slidedown, Val,
1333                     DAG.getConstant(0, DL, Subtarget.getXLenVT()));
1334 
1335     return DAG.getNode(RISCVISD::VSLIDEUP, DL, VecVT, Vec, InsertElt0, Idx);
1336   }
1337 
1338   // Custom-legalize INSERT_VECTOR_ELT where XLEN<SEW, as the SEW element type
1339   // is illegal (currently only vXi64 RV32).
1340   // Since there is no easy way of getting a single element into a vector when
1341   // XLEN<SEW, we lower the operation to the following sequence:
1342   //   splat      vVal, rVal
1343   //   vid.v      vVid
1344   //   vmseq.vx   mMask, vVid, rIdx
1345   //   vmerge.vvm vDest, vSrc, vVal, mMask
1346   // This essentially merges the original vector with the inserted element by
1347   // using a mask whose only set bit is that corresponding to the insert
1348   // index.
1349   SDValue SplattedVal = DAG.getSplatVector(VecVT, DL, Val);
1350   SDValue SplattedIdx = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Idx);
1351 
1352   SDValue VID = DAG.getNode(RISCVISD::VID, DL, VecVT);
1353   auto SetCCVT =
1354       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VecVT);
1355   SDValue Mask = DAG.getSetCC(DL, SetCCVT, VID, SplattedIdx, ISD::SETEQ);
1356 
1357   return DAG.getNode(ISD::VSELECT, DL, VecVT, Mask, SplattedVal, Vec);
1358 }
1359 
1360 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
1361 // extract the first element: (extractelt (slidedown vec, idx), 0). This is
1362 // done to maintain partity with the legalization of RV32 vXi64 legalization.
1363 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
1364                                                      SelectionDAG &DAG) const {
1365   SDLoc DL(Op);
1366   SDValue Idx = Op.getOperand(1);
1367   if (isNullConstant(Idx))
1368     return Op;
1369 
1370   SDValue Vec = Op.getOperand(0);
1371   EVT EltVT = Op.getValueType();
1372   EVT VecVT = Vec.getValueType();
1373   SDValue Slidedown = DAG.getNode(RISCVISD::VSLIDEDOWN, DL, VecVT,
1374                                   DAG.getUNDEF(VecVT), Vec, Idx);
1375 
1376   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Slidedown,
1377                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
1378 }
1379 
1380 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1381                                                      SelectionDAG &DAG) const {
1382   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1383   SDLoc DL(Op);
1384 
1385   if (Subtarget.hasStdExtV()) {
1386     // Some RVV intrinsics may claim that they want an integer operand to be
1387     // extended.
1388     if (const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1389             RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo)) {
1390       if (II->ExtendedOperand) {
1391         assert(II->ExtendedOperand < Op.getNumOperands());
1392         SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
1393         SDValue &ScalarOp = Operands[II->ExtendedOperand];
1394         EVT OpVT = ScalarOp.getValueType();
1395         if (OpVT == MVT::i8 || OpVT == MVT::i16 ||
1396             (OpVT == MVT::i32 && Subtarget.is64Bit())) {
1397           // If the operand is a constant, sign extend to increase our chances
1398           // of being able to use a .vi instruction. ANY_EXTEND would become a
1399           // a zero extend and the simm5 check in isel would fail.
1400           // FIXME: Should we ignore the upper bits in isel instead?
1401           unsigned ExtOpc = isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND
1402                                                           : ISD::ANY_EXTEND;
1403           ScalarOp = DAG.getNode(ExtOpc, DL, Subtarget.getXLenVT(), ScalarOp);
1404           return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
1405                              Operands);
1406         }
1407       }
1408     }
1409   }
1410 
1411   switch (IntNo) {
1412   default:
1413     return SDValue();    // Don't custom lower most intrinsics.
1414   case Intrinsic::thread_pointer: {
1415     EVT PtrVT = getPointerTy(DAG.getDataLayout());
1416     return DAG.getRegister(RISCV::X4, PtrVT);
1417   }
1418   case Intrinsic::riscv_vmv_x_s:
1419     assert(Op.getValueType() == Subtarget.getXLenVT() && "Unexpected VT!");
1420     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
1421                        Op.getOperand(1));
1422   }
1423 }
1424 
1425 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
1426                                                     SelectionDAG &DAG) const {
1427   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1428   SDLoc DL(Op);
1429 
1430   if (Subtarget.hasStdExtV()) {
1431     // Some RVV intrinsics may claim that they want an integer operand to be
1432     // extended.
1433     if (const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1434             RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo)) {
1435       if (II->ExtendedOperand) {
1436         // The operands start from the second argument in INTRINSIC_W_CHAIN.
1437         unsigned ExtendOp = II->ExtendedOperand + 1;
1438         assert(ExtendOp < Op.getNumOperands());
1439         SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
1440         SDValue &ScalarOp = Operands[ExtendOp];
1441         EVT OpVT = ScalarOp.getValueType();
1442         if (OpVT == MVT::i8 || OpVT == MVT::i16 ||
1443             (OpVT == MVT::i32 && Subtarget.is64Bit())) {
1444           // If the operand is a constant, sign extend to increase our chances
1445           // of being able to use a .vi instruction. ANY_EXTEND would become a
1446           // a zero extend and the simm5 check in isel would fail.
1447           // FIXME: Should we ignore the upper bits in isel instead?
1448           unsigned ExtOpc = isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND
1449                                                           : ISD::ANY_EXTEND;
1450           ScalarOp = DAG.getNode(ExtOpc, DL, Subtarget.getXLenVT(), ScalarOp);
1451           return DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, Op->getVTList(),
1452                              Operands);
1453         }
1454       }
1455     }
1456   }
1457 
1458   switch (IntNo) {
1459   default:
1460     return SDValue(); // Don't custom lower most intrinsics.
1461   case Intrinsic::riscv_vleff: {
1462     SDLoc DL(Op);
1463     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other, MVT::Glue);
1464     SDValue Load = DAG.getNode(RISCVISD::VLEFF, DL, VTs, Op.getOperand(0),
1465                                Op.getOperand(2), Op.getOperand(3));
1466     SDValue ReadVL =
1467         SDValue(DAG.getMachineNode(RISCV::PseudoReadVL, DL, Op->getValueType(1),
1468                                    Load.getValue(2)),
1469                 0);
1470     return DAG.getMergeValues({Load, ReadVL, Load.getValue(1)}, DL);
1471   }
1472   case Intrinsic::riscv_vleff_mask: {
1473     SDLoc DL(Op);
1474     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other, MVT::Glue);
1475     SDValue Load = DAG.getNode(RISCVISD::VLEFF_MASK, DL, VTs, Op.getOperand(0),
1476                                Op.getOperand(2), Op.getOperand(3),
1477                                Op.getOperand(4), Op.getOperand(5));
1478     SDValue ReadVL =
1479         SDValue(DAG.getMachineNode(RISCV::PseudoReadVL, DL, Op->getValueType(1),
1480                                    Load.getValue(2)),
1481                 0);
1482     return DAG.getMergeValues({Load, ReadVL, Load.getValue(1)}, DL);
1483   }
1484   }
1485 }
1486 
1487 // Returns the opcode of the target-specific SDNode that implements the 32-bit
1488 // form of the given Opcode.
1489 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
1490   switch (Opcode) {
1491   default:
1492     llvm_unreachable("Unexpected opcode");
1493   case ISD::SHL:
1494     return RISCVISD::SLLW;
1495   case ISD::SRA:
1496     return RISCVISD::SRAW;
1497   case ISD::SRL:
1498     return RISCVISD::SRLW;
1499   case ISD::SDIV:
1500     return RISCVISD::DIVW;
1501   case ISD::UDIV:
1502     return RISCVISD::DIVUW;
1503   case ISD::UREM:
1504     return RISCVISD::REMUW;
1505   case ISD::ROTL:
1506     return RISCVISD::ROLW;
1507   case ISD::ROTR:
1508     return RISCVISD::RORW;
1509   case RISCVISD::GREVI:
1510     return RISCVISD::GREVIW;
1511   case RISCVISD::GORCI:
1512     return RISCVISD::GORCIW;
1513   }
1514 }
1515 
1516 // Converts the given 32-bit operation to a target-specific SelectionDAG node.
1517 // Because i32 isn't a legal type for RV64, these operations would otherwise
1518 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W
1519 // later one because the fact the operation was originally of type i32 is
1520 // lost.
1521 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
1522                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
1523   SDLoc DL(N);
1524   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
1525   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
1526   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
1527   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
1528   // ReplaceNodeResults requires we maintain the same type for the return value.
1529   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
1530 }
1531 
1532 // Converts the given 32-bit operation to a i64 operation with signed extension
1533 // semantic to reduce the signed extension instructions.
1534 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
1535   SDLoc DL(N);
1536   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
1537   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
1538   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
1539   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
1540                                DAG.getValueType(MVT::i32));
1541   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
1542 }
1543 
1544 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
1545                                              SmallVectorImpl<SDValue> &Results,
1546                                              SelectionDAG &DAG) const {
1547   SDLoc DL(N);
1548   switch (N->getOpcode()) {
1549   default:
1550     llvm_unreachable("Don't know how to custom type legalize this operation!");
1551   case ISD::STRICT_FP_TO_SINT:
1552   case ISD::STRICT_FP_TO_UINT:
1553   case ISD::FP_TO_SINT:
1554   case ISD::FP_TO_UINT: {
1555     bool IsStrict = N->isStrictFPOpcode();
1556     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1557            "Unexpected custom legalisation");
1558     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
1559     // If the FP type needs to be softened, emit a library call using the 'si'
1560     // version. If we left it to default legalization we'd end up with 'di'. If
1561     // the FP type doesn't need to be softened just let generic type
1562     // legalization promote the result type.
1563     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
1564         TargetLowering::TypeSoftenFloat)
1565       return;
1566     RTLIB::Libcall LC;
1567     if (N->getOpcode() == ISD::FP_TO_SINT ||
1568         N->getOpcode() == ISD::STRICT_FP_TO_SINT)
1569       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
1570     else
1571       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
1572     MakeLibCallOptions CallOptions;
1573     EVT OpVT = Op0.getValueType();
1574     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
1575     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
1576     SDValue Result;
1577     std::tie(Result, Chain) =
1578         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
1579     Results.push_back(Result);
1580     if (IsStrict)
1581       Results.push_back(Chain);
1582     break;
1583   }
1584   case ISD::READCYCLECOUNTER: {
1585     assert(!Subtarget.is64Bit() &&
1586            "READCYCLECOUNTER only has custom type legalization on riscv32");
1587 
1588     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
1589     SDValue RCW =
1590         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
1591 
1592     Results.push_back(
1593         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
1594     Results.push_back(RCW.getValue(2));
1595     break;
1596   }
1597   case ISD::ADD:
1598   case ISD::SUB:
1599   case ISD::MUL:
1600     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1601            "Unexpected custom legalisation");
1602     if (N->getOperand(1).getOpcode() == ISD::Constant)
1603       return;
1604     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
1605     break;
1606   case ISD::SHL:
1607   case ISD::SRA:
1608   case ISD::SRL:
1609     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1610            "Unexpected custom legalisation");
1611     if (N->getOperand(1).getOpcode() == ISD::Constant)
1612       return;
1613     Results.push_back(customLegalizeToWOp(N, DAG));
1614     break;
1615   case ISD::ROTL:
1616   case ISD::ROTR:
1617     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1618            "Unexpected custom legalisation");
1619     Results.push_back(customLegalizeToWOp(N, DAG));
1620     break;
1621   case ISD::SDIV:
1622   case ISD::UDIV:
1623   case ISD::UREM: {
1624     MVT VT = N->getSimpleValueType(0);
1625     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
1626            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
1627            "Unexpected custom legalisation");
1628     if (N->getOperand(0).getOpcode() == ISD::Constant ||
1629         N->getOperand(1).getOpcode() == ISD::Constant)
1630       return;
1631 
1632     // If the input is i32, use ANY_EXTEND since the W instructions don't read
1633     // the upper 32 bits. For other types we need to sign or zero extend
1634     // based on the opcode.
1635     unsigned ExtOpc = ISD::ANY_EXTEND;
1636     if (VT != MVT::i32)
1637       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
1638                                            : ISD::ZERO_EXTEND;
1639 
1640     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
1641     break;
1642   }
1643   case ISD::BITCAST: {
1644     assert(((N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1645              Subtarget.hasStdExtF()) ||
1646             (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh())) &&
1647            "Unexpected custom legalisation");
1648     SDValue Op0 = N->getOperand(0);
1649     if (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh()) {
1650       if (Op0.getValueType() != MVT::f16)
1651         return;
1652       SDValue FPConv =
1653           DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, Subtarget.getXLenVT(), Op0);
1654       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
1655     } else if (N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1656                Subtarget.hasStdExtF()) {
1657       if (Op0.getValueType() != MVT::f32)
1658         return;
1659       SDValue FPConv =
1660           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
1661       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
1662     }
1663     break;
1664   }
1665   case RISCVISD::GREVI:
1666   case RISCVISD::GORCI: {
1667     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1668            "Unexpected custom legalisation");
1669     // This is similar to customLegalizeToWOp, except that we pass the second
1670     // operand (a TargetConstant) straight through: it is already of type
1671     // XLenVT.
1672     SDLoc DL(N);
1673     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
1674     SDValue NewOp0 =
1675         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
1676     SDValue NewRes =
1677         DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, N->getOperand(1));
1678     // ReplaceNodeResults requires we maintain the same type for the return
1679     // value.
1680     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
1681     break;
1682   }
1683   case ISD::BSWAP:
1684   case ISD::BITREVERSE: {
1685     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1686            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
1687     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
1688                                  N->getOperand(0));
1689     unsigned Imm = N->getOpcode() == ISD::BITREVERSE ? 31 : 24;
1690     SDValue GREVIW = DAG.getNode(RISCVISD::GREVIW, DL, MVT::i64, NewOp0,
1691                                  DAG.getTargetConstant(Imm, DL,
1692                                                        Subtarget.getXLenVT()));
1693     // ReplaceNodeResults requires we maintain the same type for the return
1694     // value.
1695     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, GREVIW));
1696     break;
1697   }
1698   case ISD::FSHL:
1699   case ISD::FSHR: {
1700     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
1701            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
1702     SDValue NewOp0 =
1703         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
1704     SDValue NewOp1 =
1705         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
1706     SDValue NewOp2 =
1707         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
1708     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
1709     // Mask the shift amount to 5 bits.
1710     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
1711                          DAG.getConstant(0x1f, DL, MVT::i64));
1712     unsigned Opc =
1713         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
1714     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
1715     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
1716     break;
1717   }
1718   case ISD::EXTRACT_VECTOR_ELT: {
1719     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
1720     // type is illegal (currently only vXi64 RV32).
1721     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
1722     // transferred to the destination register. We issue two of these from the
1723     // upper- and lower- halves of the SEW-bit vector element, slid down to the
1724     // first element.
1725     SDLoc DL(N);
1726     SDValue Vec = N->getOperand(0);
1727     SDValue Idx = N->getOperand(1);
1728     EVT VecVT = Vec.getValueType();
1729     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
1730            VecVT.getVectorElementType() == MVT::i64 &&
1731            "Unexpected EXTRACT_VECTOR_ELT legalization");
1732 
1733     SDValue Slidedown = Vec;
1734     // Unless the index is known to be 0, we must slide the vector down to get
1735     // the desired element into index 0.
1736     if (!isNullConstant(Idx))
1737       Slidedown = DAG.getNode(RISCVISD::VSLIDEDOWN, DL, VecVT,
1738                               DAG.getUNDEF(VecVT), Vec, Idx);
1739 
1740     MVT XLenVT = Subtarget.getXLenVT();
1741     // Extract the lower XLEN bits of the correct vector element.
1742     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Slidedown, Idx);
1743 
1744     // To extract the upper XLEN bits of the vector element, shift the first
1745     // element right by 32 bits and re-extract the lower XLEN bits.
1746     SDValue ThirtyTwoV =
1747         DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT,
1748                     DAG.getConstant(32, DL, Subtarget.getXLenVT()));
1749     SDValue LShr32 = DAG.getNode(ISD::SRL, DL, VecVT, Slidedown, ThirtyTwoV);
1750 
1751     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32, Idx);
1752 
1753     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
1754     break;
1755   }
1756   case ISD::INTRINSIC_WO_CHAIN: {
1757     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
1758     switch (IntNo) {
1759     default:
1760       llvm_unreachable(
1761           "Don't know how to custom type legalize this intrinsic!");
1762     case Intrinsic::riscv_vmv_x_s: {
1763       EVT VT = N->getValueType(0);
1764       assert((VT == MVT::i8 || VT == MVT::i16 ||
1765               (Subtarget.is64Bit() && VT == MVT::i32)) &&
1766              "Unexpected custom legalisation!");
1767       SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
1768                                     Subtarget.getXLenVT(), N->getOperand(1));
1769       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
1770       break;
1771     }
1772     }
1773     break;
1774   }
1775   }
1776 }
1777 
1778 // A structure to hold one of the bit-manipulation patterns below. Together, a
1779 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
1780 //   (or (and (shl x, 1), 0xAAAAAAAA),
1781 //       (and (srl x, 1), 0x55555555))
1782 struct RISCVBitmanipPat {
1783   SDValue Op;
1784   unsigned ShAmt;
1785   bool IsSHL;
1786 
1787   bool formsPairWith(const RISCVBitmanipPat &Other) const {
1788     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
1789   }
1790 };
1791 
1792 // Matches any of the following bit-manipulation patterns:
1793 //   (and (shl x, 1), (0x55555555 << 1))
1794 //   (and (srl x, 1), 0x55555555)
1795 //   (shl (and x, 0x55555555), 1)
1796 //   (srl (and x, (0x55555555 << 1)), 1)
1797 // where the shift amount and mask may vary thus:
1798 //   [1]  = 0x55555555 / 0xAAAAAAAA
1799 //   [2]  = 0x33333333 / 0xCCCCCCCC
1800 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
1801 //   [8]  = 0x00FF00FF / 0xFF00FF00
1802 //   [16] = 0x0000FFFF / 0xFFFFFFFF
1803 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
1804 static Optional<RISCVBitmanipPat> matchRISCVBitmanipPat(SDValue Op) {
1805   Optional<uint64_t> Mask;
1806   // Optionally consume a mask around the shift operation.
1807   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
1808     Mask = Op.getConstantOperandVal(1);
1809     Op = Op.getOperand(0);
1810   }
1811   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
1812     return None;
1813   bool IsSHL = Op.getOpcode() == ISD::SHL;
1814 
1815   if (!isa<ConstantSDNode>(Op.getOperand(1)))
1816     return None;
1817   auto ShAmt = Op.getConstantOperandVal(1);
1818 
1819   if (!isPowerOf2_64(ShAmt))
1820     return None;
1821 
1822   // These are the unshifted masks which we use to match bit-manipulation
1823   // patterns. They may be shifted left in certain circumstances.
1824   static const uint64_t BitmanipMasks[] = {
1825       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
1826       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL,
1827   };
1828 
1829   unsigned MaskIdx = Log2_64(ShAmt);
1830   if (MaskIdx >= array_lengthof(BitmanipMasks))
1831     return None;
1832 
1833   auto Src = Op.getOperand(0);
1834 
1835   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
1836   auto ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
1837 
1838   // The expected mask is shifted left when the AND is found around SHL
1839   // patterns.
1840   //   ((x >> 1) & 0x55555555)
1841   //   ((x << 1) & 0xAAAAAAAA)
1842   bool SHLExpMask = IsSHL;
1843 
1844   if (!Mask) {
1845     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
1846     // the mask is all ones: consume that now.
1847     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
1848       Mask = Src.getConstantOperandVal(1);
1849       Src = Src.getOperand(0);
1850       // The expected mask is now in fact shifted left for SRL, so reverse the
1851       // decision.
1852       //   ((x & 0xAAAAAAAA) >> 1)
1853       //   ((x & 0x55555555) << 1)
1854       SHLExpMask = !SHLExpMask;
1855     } else {
1856       // Use a default shifted mask of all-ones if there's no AND, truncated
1857       // down to the expected width. This simplifies the logic later on.
1858       Mask = maskTrailingOnes<uint64_t>(Width);
1859       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
1860     }
1861   }
1862 
1863   if (SHLExpMask)
1864     ExpMask <<= ShAmt;
1865 
1866   if (Mask != ExpMask)
1867     return None;
1868 
1869   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
1870 }
1871 
1872 // Match the following pattern as a GREVI(W) operation
1873 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
1874 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
1875                                const RISCVSubtarget &Subtarget) {
1876   EVT VT = Op.getValueType();
1877 
1878   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
1879     auto LHS = matchRISCVBitmanipPat(Op.getOperand(0));
1880     auto RHS = matchRISCVBitmanipPat(Op.getOperand(1));
1881     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
1882       SDLoc DL(Op);
1883       return DAG.getNode(
1884           RISCVISD::GREVI, DL, VT, LHS->Op,
1885           DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT()));
1886     }
1887   }
1888   return SDValue();
1889 }
1890 
1891 // Matches any the following pattern as a GORCI(W) operation
1892 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
1893 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
1894 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
1895 // Note that with the variant of 3.,
1896 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
1897 // the inner pattern will first be matched as GREVI and then the outer
1898 // pattern will be matched to GORC via the first rule above.
1899 // 4.  (or (rotl/rotr x, bitwidth/2), x)
1900 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
1901                                const RISCVSubtarget &Subtarget) {
1902   EVT VT = Op.getValueType();
1903 
1904   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
1905     SDLoc DL(Op);
1906     SDValue Op0 = Op.getOperand(0);
1907     SDValue Op1 = Op.getOperand(1);
1908 
1909     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
1910       if (Reverse.getOpcode() == RISCVISD::GREVI && Reverse.getOperand(0) == X &&
1911           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
1912         return DAG.getNode(RISCVISD::GORCI, DL, VT, X, Reverse.getOperand(1));
1913       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
1914       if ((Reverse.getOpcode() == ISD::ROTL ||
1915            Reverse.getOpcode() == ISD::ROTR) &&
1916           Reverse.getOperand(0) == X &&
1917           isa<ConstantSDNode>(Reverse.getOperand(1))) {
1918         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
1919         if (RotAmt == (VT.getSizeInBits() / 2))
1920           return DAG.getNode(
1921               RISCVISD::GORCI, DL, VT, X,
1922               DAG.getTargetConstant(RotAmt, DL, Subtarget.getXLenVT()));
1923       }
1924       return SDValue();
1925     };
1926 
1927     // Check for either commutable permutation of (or (GREVI x, shamt), x)
1928     if (SDValue V = MatchOROfReverse(Op0, Op1))
1929       return V;
1930     if (SDValue V = MatchOROfReverse(Op1, Op0))
1931       return V;
1932 
1933     // OR is commutable so canonicalize its OR operand to the left
1934     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
1935       std::swap(Op0, Op1);
1936     if (Op0.getOpcode() != ISD::OR)
1937       return SDValue();
1938     SDValue OrOp0 = Op0.getOperand(0);
1939     SDValue OrOp1 = Op0.getOperand(1);
1940     auto LHS = matchRISCVBitmanipPat(OrOp0);
1941     // OR is commutable so swap the operands and try again: x might have been
1942     // on the left
1943     if (!LHS) {
1944       std::swap(OrOp0, OrOp1);
1945       LHS = matchRISCVBitmanipPat(OrOp0);
1946     }
1947     auto RHS = matchRISCVBitmanipPat(Op1);
1948     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
1949       return DAG.getNode(
1950           RISCVISD::GORCI, DL, VT, LHS->Op,
1951           DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT()));
1952     }
1953   }
1954   return SDValue();
1955 }
1956 
1957 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
1958 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
1959 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
1960 // not undo itself, but they are redundant.
1961 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
1962   unsigned ShAmt1 = N->getConstantOperandVal(1);
1963   SDValue Src = N->getOperand(0);
1964 
1965   if (Src.getOpcode() != N->getOpcode())
1966     return SDValue();
1967 
1968   unsigned ShAmt2 = Src.getConstantOperandVal(1);
1969   Src = Src.getOperand(0);
1970 
1971   unsigned CombinedShAmt;
1972   if (N->getOpcode() == RISCVISD::GORCI || N->getOpcode() == RISCVISD::GORCIW)
1973     CombinedShAmt = ShAmt1 | ShAmt2;
1974   else
1975     CombinedShAmt = ShAmt1 ^ ShAmt2;
1976 
1977   if (CombinedShAmt == 0)
1978     return Src;
1979 
1980   SDLoc DL(N);
1981   return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), Src,
1982                      DAG.getTargetConstant(CombinedShAmt, DL,
1983                                            N->getOperand(1).getValueType()));
1984 }
1985 
1986 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
1987                                                DAGCombinerInfo &DCI) const {
1988   SelectionDAG &DAG = DCI.DAG;
1989 
1990   switch (N->getOpcode()) {
1991   default:
1992     break;
1993   case RISCVISD::SplitF64: {
1994     SDValue Op0 = N->getOperand(0);
1995     // If the input to SplitF64 is just BuildPairF64 then the operation is
1996     // redundant. Instead, use BuildPairF64's operands directly.
1997     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
1998       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
1999 
2000     SDLoc DL(N);
2001 
2002     // It's cheaper to materialise two 32-bit integers than to load a double
2003     // from the constant pool and transfer it to integer registers through the
2004     // stack.
2005     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
2006       APInt V = C->getValueAPF().bitcastToAPInt();
2007       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
2008       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
2009       return DCI.CombineTo(N, Lo, Hi);
2010     }
2011 
2012     // This is a target-specific version of a DAGCombine performed in
2013     // DAGCombiner::visitBITCAST. It performs the equivalent of:
2014     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
2015     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
2016     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
2017         !Op0.getNode()->hasOneUse())
2018       break;
2019     SDValue NewSplitF64 =
2020         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
2021                     Op0.getOperand(0));
2022     SDValue Lo = NewSplitF64.getValue(0);
2023     SDValue Hi = NewSplitF64.getValue(1);
2024     APInt SignBit = APInt::getSignMask(32);
2025     if (Op0.getOpcode() == ISD::FNEG) {
2026       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
2027                                   DAG.getConstant(SignBit, DL, MVT::i32));
2028       return DCI.CombineTo(N, Lo, NewHi);
2029     }
2030     assert(Op0.getOpcode() == ISD::FABS);
2031     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
2032                                 DAG.getConstant(~SignBit, DL, MVT::i32));
2033     return DCI.CombineTo(N, Lo, NewHi);
2034   }
2035   case RISCVISD::SLLW:
2036   case RISCVISD::SRAW:
2037   case RISCVISD::SRLW:
2038   case RISCVISD::ROLW:
2039   case RISCVISD::RORW: {
2040     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
2041     SDValue LHS = N->getOperand(0);
2042     SDValue RHS = N->getOperand(1);
2043     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
2044     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
2045     if (SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI) ||
2046         SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)) {
2047       if (N->getOpcode() != ISD::DELETED_NODE)
2048         DCI.AddToWorklist(N);
2049       return SDValue(N, 0);
2050     }
2051     break;
2052   }
2053   case RISCVISD::FSLW:
2054   case RISCVISD::FSRW: {
2055     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
2056     // read.
2057     SDValue Op0 = N->getOperand(0);
2058     SDValue Op1 = N->getOperand(1);
2059     SDValue ShAmt = N->getOperand(2);
2060     APInt OpMask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
2061     APInt ShAmtMask = APInt::getLowBitsSet(ShAmt.getValueSizeInBits(), 6);
2062     if (SimplifyDemandedBits(Op0, OpMask, DCI) ||
2063         SimplifyDemandedBits(Op1, OpMask, DCI) ||
2064         SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) {
2065       if (N->getOpcode() != ISD::DELETED_NODE)
2066         DCI.AddToWorklist(N);
2067       return SDValue(N, 0);
2068     }
2069     break;
2070   }
2071   case RISCVISD::GREVIW:
2072   case RISCVISD::GORCIW: {
2073     // Only the lower 32 bits of the first operand are read
2074     SDValue Op0 = N->getOperand(0);
2075     APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
2076     if (SimplifyDemandedBits(Op0, Mask, DCI)) {
2077       if (N->getOpcode() != ISD::DELETED_NODE)
2078         DCI.AddToWorklist(N);
2079       return SDValue(N, 0);
2080     }
2081 
2082     return combineGREVI_GORCI(N, DCI.DAG);
2083   }
2084   case RISCVISD::FMV_X_ANYEXTW_RV64: {
2085     SDLoc DL(N);
2086     SDValue Op0 = N->getOperand(0);
2087     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
2088     // conversion is unnecessary and can be replaced with an ANY_EXTEND
2089     // of the FMV_W_X_RV64 operand.
2090     if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) {
2091       assert(Op0.getOperand(0).getValueType() == MVT::i64 &&
2092              "Unexpected value type!");
2093       return Op0.getOperand(0);
2094     }
2095 
2096     // This is a target-specific version of a DAGCombine performed in
2097     // DAGCombiner::visitBITCAST. It performs the equivalent of:
2098     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
2099     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
2100     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
2101         !Op0.getNode()->hasOneUse())
2102       break;
2103     SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64,
2104                                  Op0.getOperand(0));
2105     APInt SignBit = APInt::getSignMask(32).sext(64);
2106     if (Op0.getOpcode() == ISD::FNEG)
2107       return DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV,
2108                          DAG.getConstant(SignBit, DL, MVT::i64));
2109 
2110     assert(Op0.getOpcode() == ISD::FABS);
2111     return DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV,
2112                        DAG.getConstant(~SignBit, DL, MVT::i64));
2113   }
2114   case RISCVISD::GREVI:
2115   case RISCVISD::GORCI:
2116     return combineGREVI_GORCI(N, DCI.DAG);
2117   case ISD::OR:
2118     if (auto GREV = combineORToGREV(SDValue(N, 0), DCI.DAG, Subtarget))
2119       return GREV;
2120     if (auto GORC = combineORToGORC(SDValue(N, 0), DCI.DAG, Subtarget))
2121       return GORC;
2122     break;
2123   case RISCVISD::SELECT_CC: {
2124     // Transform
2125     // (select_cc (xor X, 1), 0, setne, trueV, falseV) ->
2126     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
2127     // This can occur when legalizing some floating point comparisons.
2128     SDValue LHS = N->getOperand(0);
2129     SDValue RHS = N->getOperand(1);
2130     auto CCVal = static_cast<ISD::CondCode>(N->getConstantOperandVal(2));
2131     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
2132     if (ISD::isIntEqualitySetCC(CCVal) && isNullConstant(RHS) &&
2133         LHS.getOpcode() == ISD::XOR && isOneConstant(LHS.getOperand(1)) &&
2134         DAG.MaskedValueIsZero(LHS.getOperand(0), Mask)) {
2135       SDLoc DL(N);
2136       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
2137       SDValue TargetCC = DAG.getConstant(CCVal, DL, Subtarget.getXLenVT());
2138       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
2139                          {LHS.getOperand(0), RHS, TargetCC, N->getOperand(3),
2140                           N->getOperand(4)});
2141     }
2142     break;
2143   }
2144   case ISD::SETCC: {
2145     // (setcc X, 1, setne) -> (setcc X, 0, seteq) if we can prove X is 0/1.
2146     // Comparing with 0 may allow us to fold into bnez/beqz.
2147     SDValue LHS = N->getOperand(0);
2148     SDValue RHS = N->getOperand(1);
2149     if (LHS.getValueType().isScalableVector())
2150       break;
2151     auto CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2152     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
2153     if (isOneConstant(RHS) && ISD::isIntEqualitySetCC(CC) &&
2154         DAG.MaskedValueIsZero(LHS, Mask)) {
2155       SDLoc DL(N);
2156       SDValue Zero = DAG.getConstant(0, DL, LHS.getValueType());
2157       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2158       return DAG.getSetCC(DL, N->getValueType(0), LHS, Zero, CC);
2159     }
2160     break;
2161   }
2162   }
2163 
2164   return SDValue();
2165 }
2166 
2167 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
2168     const SDNode *N, CombineLevel Level) const {
2169   // The following folds are only desirable if `(OP _, c1 << c2)` can be
2170   // materialised in fewer instructions than `(OP _, c1)`:
2171   //
2172   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
2173   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
2174   SDValue N0 = N->getOperand(0);
2175   EVT Ty = N0.getValueType();
2176   if (Ty.isScalarInteger() &&
2177       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
2178     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2179     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
2180     if (C1 && C2) {
2181       const APInt &C1Int = C1->getAPIntValue();
2182       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
2183 
2184       // We can materialise `c1 << c2` into an add immediate, so it's "free",
2185       // and the combine should happen, to potentially allow further combines
2186       // later.
2187       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
2188           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
2189         return true;
2190 
2191       // We can materialise `c1` in an add immediate, so it's "free", and the
2192       // combine should be prevented.
2193       if (C1Int.getMinSignedBits() <= 64 &&
2194           isLegalAddImmediate(C1Int.getSExtValue()))
2195         return false;
2196 
2197       // Neither constant will fit into an immediate, so find materialisation
2198       // costs.
2199       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
2200                                               Subtarget.is64Bit());
2201       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
2202           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit());
2203 
2204       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
2205       // combine should be prevented.
2206       if (C1Cost < ShiftedC1Cost)
2207         return false;
2208     }
2209   }
2210   return true;
2211 }
2212 
2213 bool RISCVTargetLowering::targetShrinkDemandedConstant(
2214     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
2215     TargetLoweringOpt &TLO) const {
2216   // Delay this optimization as late as possible.
2217   if (!TLO.LegalOps)
2218     return false;
2219 
2220   EVT VT = Op.getValueType();
2221   if (VT.isVector())
2222     return false;
2223 
2224   // Only handle AND for now.
2225   if (Op.getOpcode() != ISD::AND)
2226     return false;
2227 
2228   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2229   if (!C)
2230     return false;
2231 
2232   const APInt &Mask = C->getAPIntValue();
2233 
2234   // Clear all non-demanded bits initially.
2235   APInt ShrunkMask = Mask & DemandedBits;
2236 
2237   // If the shrunk mask fits in sign extended 12 bits, let the target
2238   // independent code apply it.
2239   if (ShrunkMask.isSignedIntN(12))
2240     return false;
2241 
2242   // Try to make a smaller immediate by setting undemanded bits.
2243 
2244   // We need to be able to make a negative number through a combination of mask
2245   // and undemanded bits.
2246   APInt ExpandedMask = Mask | ~DemandedBits;
2247   if (!ExpandedMask.isNegative())
2248     return false;
2249 
2250   // What is the fewest number of bits we need to represent the negative number.
2251   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
2252 
2253   // Try to make a 12 bit negative immediate. If that fails try to make a 32
2254   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
2255   APInt NewMask = ShrunkMask;
2256   if (MinSignedBits <= 12)
2257     NewMask.setBitsFrom(11);
2258   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
2259     NewMask.setBitsFrom(31);
2260   else
2261     return false;
2262 
2263   // Sanity check that our new mask is a subset of the demanded mask.
2264   assert(NewMask.isSubsetOf(ExpandedMask));
2265 
2266   // If we aren't changing the mask, just return true to keep it and prevent
2267   // the caller from optimizing.
2268   if (NewMask == Mask)
2269     return true;
2270 
2271   // Replace the constant with the new mask.
2272   SDLoc DL(Op);
2273   SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
2274   SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
2275   return TLO.CombineTo(Op, NewOp);
2276 }
2277 
2278 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
2279                                                         KnownBits &Known,
2280                                                         const APInt &DemandedElts,
2281                                                         const SelectionDAG &DAG,
2282                                                         unsigned Depth) const {
2283   unsigned BitWidth = Known.getBitWidth();
2284   unsigned Opc = Op.getOpcode();
2285   assert((Opc >= ISD::BUILTIN_OP_END ||
2286           Opc == ISD::INTRINSIC_WO_CHAIN ||
2287           Opc == ISD::INTRINSIC_W_CHAIN ||
2288           Opc == ISD::INTRINSIC_VOID) &&
2289          "Should use MaskedValueIsZero if you don't know whether Op"
2290          " is a target node!");
2291 
2292   Known.resetAll();
2293   switch (Opc) {
2294   default: break;
2295   case RISCVISD::REMUW: {
2296     KnownBits Known2;
2297     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2298     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2299     // We only care about the lower 32 bits.
2300     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
2301     // Restore the original width by sign extending.
2302     Known = Known.sext(BitWidth);
2303     break;
2304   }
2305   case RISCVISD::DIVUW: {
2306     KnownBits Known2;
2307     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2308     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2309     // We only care about the lower 32 bits.
2310     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
2311     // Restore the original width by sign extending.
2312     Known = Known.sext(BitWidth);
2313     break;
2314   }
2315   case RISCVISD::READ_VLENB:
2316     // We assume VLENB is at least 8 bytes.
2317     // FIXME: The 1.0 draft spec defines minimum VLEN as 128 bits.
2318     Known.Zero.setLowBits(3);
2319     break;
2320   }
2321 }
2322 
2323 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
2324     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
2325     unsigned Depth) const {
2326   switch (Op.getOpcode()) {
2327   default:
2328     break;
2329   case RISCVISD::SLLW:
2330   case RISCVISD::SRAW:
2331   case RISCVISD::SRLW:
2332   case RISCVISD::DIVW:
2333   case RISCVISD::DIVUW:
2334   case RISCVISD::REMUW:
2335   case RISCVISD::ROLW:
2336   case RISCVISD::RORW:
2337   case RISCVISD::GREVIW:
2338   case RISCVISD::GORCIW:
2339   case RISCVISD::FSLW:
2340   case RISCVISD::FSRW:
2341     // TODO: As the result is sign-extended, this is conservatively correct. A
2342     // more precise answer could be calculated for SRAW depending on known
2343     // bits in the shift amount.
2344     return 33;
2345   case RISCVISD::VMV_X_S:
2346     // The number of sign bits of the scalar result is computed by obtaining the
2347     // element type of the input vector operand, subtracting its width from the
2348     // XLEN, and then adding one (sign bit within the element type). If the
2349     // element type is wider than XLen, the least-significant XLEN bits are
2350     // taken.
2351     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
2352       return 1;
2353     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
2354   }
2355 
2356   return 1;
2357 }
2358 
2359 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
2360                                                   MachineBasicBlock *BB) {
2361   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
2362 
2363   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
2364   // Should the count have wrapped while it was being read, we need to try
2365   // again.
2366   // ...
2367   // read:
2368   // rdcycleh x3 # load high word of cycle
2369   // rdcycle  x2 # load low word of cycle
2370   // rdcycleh x4 # load high word of cycle
2371   // bne x3, x4, read # check if high word reads match, otherwise try again
2372   // ...
2373 
2374   MachineFunction &MF = *BB->getParent();
2375   const BasicBlock *LLVM_BB = BB->getBasicBlock();
2376   MachineFunction::iterator It = ++BB->getIterator();
2377 
2378   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
2379   MF.insert(It, LoopMBB);
2380 
2381   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
2382   MF.insert(It, DoneMBB);
2383 
2384   // Transfer the remainder of BB and its successor edges to DoneMBB.
2385   DoneMBB->splice(DoneMBB->begin(), BB,
2386                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
2387   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
2388 
2389   BB->addSuccessor(LoopMBB);
2390 
2391   MachineRegisterInfo &RegInfo = MF.getRegInfo();
2392   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
2393   Register LoReg = MI.getOperand(0).getReg();
2394   Register HiReg = MI.getOperand(1).getReg();
2395   DebugLoc DL = MI.getDebugLoc();
2396 
2397   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
2398   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
2399       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
2400       .addReg(RISCV::X0);
2401   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
2402       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
2403       .addReg(RISCV::X0);
2404   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
2405       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
2406       .addReg(RISCV::X0);
2407 
2408   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
2409       .addReg(HiReg)
2410       .addReg(ReadAgainReg)
2411       .addMBB(LoopMBB);
2412 
2413   LoopMBB->addSuccessor(LoopMBB);
2414   LoopMBB->addSuccessor(DoneMBB);
2415 
2416   MI.eraseFromParent();
2417 
2418   return DoneMBB;
2419 }
2420 
2421 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
2422                                              MachineBasicBlock *BB) {
2423   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
2424 
2425   MachineFunction &MF = *BB->getParent();
2426   DebugLoc DL = MI.getDebugLoc();
2427   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2428   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
2429   Register LoReg = MI.getOperand(0).getReg();
2430   Register HiReg = MI.getOperand(1).getReg();
2431   Register SrcReg = MI.getOperand(2).getReg();
2432   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
2433   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
2434 
2435   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
2436                           RI);
2437   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
2438   MachineMemOperand *MMOLo =
2439       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
2440   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
2441       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
2442   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
2443       .addFrameIndex(FI)
2444       .addImm(0)
2445       .addMemOperand(MMOLo);
2446   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
2447       .addFrameIndex(FI)
2448       .addImm(4)
2449       .addMemOperand(MMOHi);
2450   MI.eraseFromParent(); // The pseudo instruction is gone now.
2451   return BB;
2452 }
2453 
2454 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
2455                                                  MachineBasicBlock *BB) {
2456   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
2457          "Unexpected instruction");
2458 
2459   MachineFunction &MF = *BB->getParent();
2460   DebugLoc DL = MI.getDebugLoc();
2461   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2462   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
2463   Register DstReg = MI.getOperand(0).getReg();
2464   Register LoReg = MI.getOperand(1).getReg();
2465   Register HiReg = MI.getOperand(2).getReg();
2466   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
2467   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
2468 
2469   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
2470   MachineMemOperand *MMOLo =
2471       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
2472   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
2473       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
2474   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
2475       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
2476       .addFrameIndex(FI)
2477       .addImm(0)
2478       .addMemOperand(MMOLo);
2479   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
2480       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
2481       .addFrameIndex(FI)
2482       .addImm(4)
2483       .addMemOperand(MMOHi);
2484   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
2485   MI.eraseFromParent(); // The pseudo instruction is gone now.
2486   return BB;
2487 }
2488 
2489 static bool isSelectPseudo(MachineInstr &MI) {
2490   switch (MI.getOpcode()) {
2491   default:
2492     return false;
2493   case RISCV::Select_GPR_Using_CC_GPR:
2494   case RISCV::Select_FPR16_Using_CC_GPR:
2495   case RISCV::Select_FPR32_Using_CC_GPR:
2496   case RISCV::Select_FPR64_Using_CC_GPR:
2497     return true;
2498   }
2499 }
2500 
2501 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
2502                                            MachineBasicBlock *BB) {
2503   // To "insert" Select_* instructions, we actually have to insert the triangle
2504   // control-flow pattern.  The incoming instructions know the destination vreg
2505   // to set, the condition code register to branch on, the true/false values to
2506   // select between, and the condcode to use to select the appropriate branch.
2507   //
2508   // We produce the following control flow:
2509   //     HeadMBB
2510   //     |  \
2511   //     |  IfFalseMBB
2512   //     | /
2513   //    TailMBB
2514   //
2515   // When we find a sequence of selects we attempt to optimize their emission
2516   // by sharing the control flow. Currently we only handle cases where we have
2517   // multiple selects with the exact same condition (same LHS, RHS and CC).
2518   // The selects may be interleaved with other instructions if the other
2519   // instructions meet some requirements we deem safe:
2520   // - They are debug instructions. Otherwise,
2521   // - They do not have side-effects, do not access memory and their inputs do
2522   //   not depend on the results of the select pseudo-instructions.
2523   // The TrueV/FalseV operands of the selects cannot depend on the result of
2524   // previous selects in the sequence.
2525   // These conditions could be further relaxed. See the X86 target for a
2526   // related approach and more information.
2527   Register LHS = MI.getOperand(1).getReg();
2528   Register RHS = MI.getOperand(2).getReg();
2529   auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
2530 
2531   SmallVector<MachineInstr *, 4> SelectDebugValues;
2532   SmallSet<Register, 4> SelectDests;
2533   SelectDests.insert(MI.getOperand(0).getReg());
2534 
2535   MachineInstr *LastSelectPseudo = &MI;
2536 
2537   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
2538        SequenceMBBI != E; ++SequenceMBBI) {
2539     if (SequenceMBBI->isDebugInstr())
2540       continue;
2541     else if (isSelectPseudo(*SequenceMBBI)) {
2542       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
2543           SequenceMBBI->getOperand(2).getReg() != RHS ||
2544           SequenceMBBI->getOperand(3).getImm() != CC ||
2545           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
2546           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
2547         break;
2548       LastSelectPseudo = &*SequenceMBBI;
2549       SequenceMBBI->collectDebugValues(SelectDebugValues);
2550       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
2551     } else {
2552       if (SequenceMBBI->hasUnmodeledSideEffects() ||
2553           SequenceMBBI->mayLoadOrStore())
2554         break;
2555       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
2556             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
2557           }))
2558         break;
2559     }
2560   }
2561 
2562   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
2563   const BasicBlock *LLVM_BB = BB->getBasicBlock();
2564   DebugLoc DL = MI.getDebugLoc();
2565   MachineFunction::iterator I = ++BB->getIterator();
2566 
2567   MachineBasicBlock *HeadMBB = BB;
2568   MachineFunction *F = BB->getParent();
2569   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
2570   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
2571 
2572   F->insert(I, IfFalseMBB);
2573   F->insert(I, TailMBB);
2574 
2575   // Transfer debug instructions associated with the selects to TailMBB.
2576   for (MachineInstr *DebugInstr : SelectDebugValues) {
2577     TailMBB->push_back(DebugInstr->removeFromParent());
2578   }
2579 
2580   // Move all instructions after the sequence to TailMBB.
2581   TailMBB->splice(TailMBB->end(), HeadMBB,
2582                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
2583   // Update machine-CFG edges by transferring all successors of the current
2584   // block to the new block which will contain the Phi nodes for the selects.
2585   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
2586   // Set the successors for HeadMBB.
2587   HeadMBB->addSuccessor(IfFalseMBB);
2588   HeadMBB->addSuccessor(TailMBB);
2589 
2590   // Insert appropriate branch.
2591   unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
2592 
2593   BuildMI(HeadMBB, DL, TII.get(Opcode))
2594     .addReg(LHS)
2595     .addReg(RHS)
2596     .addMBB(TailMBB);
2597 
2598   // IfFalseMBB just falls through to TailMBB.
2599   IfFalseMBB->addSuccessor(TailMBB);
2600 
2601   // Create PHIs for all of the select pseudo-instructions.
2602   auto SelectMBBI = MI.getIterator();
2603   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
2604   auto InsertionPoint = TailMBB->begin();
2605   while (SelectMBBI != SelectEnd) {
2606     auto Next = std::next(SelectMBBI);
2607     if (isSelectPseudo(*SelectMBBI)) {
2608       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
2609       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
2610               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
2611           .addReg(SelectMBBI->getOperand(4).getReg())
2612           .addMBB(HeadMBB)
2613           .addReg(SelectMBBI->getOperand(5).getReg())
2614           .addMBB(IfFalseMBB);
2615       SelectMBBI->eraseFromParent();
2616     }
2617     SelectMBBI = Next;
2618   }
2619 
2620   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
2621   return TailMBB;
2622 }
2623 
2624 static MachineBasicBlock *addVSetVL(MachineInstr &MI, MachineBasicBlock *BB,
2625                                     int VLIndex, unsigned SEWIndex,
2626                                     RISCVVLMUL VLMul, bool WritesElement0) {
2627   MachineFunction &MF = *BB->getParent();
2628   DebugLoc DL = MI.getDebugLoc();
2629   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2630 
2631   unsigned SEW = MI.getOperand(SEWIndex).getImm();
2632   assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
2633   RISCVVSEW ElementWidth = static_cast<RISCVVSEW>(Log2_32(SEW / 8));
2634 
2635   MachineRegisterInfo &MRI = MF.getRegInfo();
2636 
2637   // VL and VTYPE are alive here.
2638   MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI));
2639 
2640   if (VLIndex >= 0) {
2641     // Set VL (rs1 != X0).
2642     Register DestReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
2643     MIB.addReg(DestReg, RegState::Define | RegState::Dead)
2644         .addReg(MI.getOperand(VLIndex).getReg());
2645   } else
2646     // With no VL operator in the pseudo, do not modify VL (rd = X0, rs1 = X0).
2647     MIB.addReg(RISCV::X0, RegState::Define | RegState::Dead)
2648         .addReg(RISCV::X0, RegState::Kill);
2649 
2650   // Default to tail agnostic unless the destination is tied to a source. In
2651   // that case the user would have some control over the tail values. The tail
2652   // policy is also ignored on instructions that only update element 0 like
2653   // vmv.s.x or reductions so use agnostic there to match the common case.
2654   // FIXME: This is conservatively correct, but we might want to detect that
2655   // the input is undefined.
2656   bool TailAgnostic = true;
2657   unsigned UseOpIdx;
2658   if (MI.isRegTiedToUseOperand(0, &UseOpIdx) && !WritesElement0) {
2659     TailAgnostic = false;
2660     // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic.
2661     const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
2662     MachineInstr *UseMI = MRI.getVRegDef(UseMO.getReg());
2663     if (UseMI && UseMI->isImplicitDef())
2664       TailAgnostic = true;
2665   }
2666 
2667   // For simplicity we reuse the vtype representation here.
2668   MIB.addImm(RISCVVType::encodeVTYPE(VLMul, ElementWidth,
2669                                      /*TailAgnostic*/ TailAgnostic,
2670                                      /*MaskAgnostic*/ false));
2671 
2672   // Remove (now) redundant operands from pseudo
2673   MI.getOperand(SEWIndex).setImm(-1);
2674   if (VLIndex >= 0) {
2675     MI.getOperand(VLIndex).setReg(RISCV::NoRegister);
2676     MI.getOperand(VLIndex).setIsKill(false);
2677   }
2678 
2679   return BB;
2680 }
2681 
2682 MachineBasicBlock *
2683 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
2684                                                  MachineBasicBlock *BB) const {
2685   uint64_t TSFlags = MI.getDesc().TSFlags;
2686 
2687   if (TSFlags & RISCVII::HasSEWOpMask) {
2688     unsigned NumOperands = MI.getNumExplicitOperands();
2689     int VLIndex = (TSFlags & RISCVII::HasVLOpMask) ? NumOperands - 2 : -1;
2690     unsigned SEWIndex = NumOperands - 1;
2691     bool WritesElement0 = TSFlags & RISCVII::WritesElement0Mask;
2692 
2693     RISCVVLMUL VLMul = static_cast<RISCVVLMUL>((TSFlags & RISCVII::VLMulMask) >>
2694                                                RISCVII::VLMulShift);
2695     return addVSetVL(MI, BB, VLIndex, SEWIndex, VLMul, WritesElement0);
2696   }
2697 
2698   switch (MI.getOpcode()) {
2699   default:
2700     llvm_unreachable("Unexpected instr type to insert");
2701   case RISCV::ReadCycleWide:
2702     assert(!Subtarget.is64Bit() &&
2703            "ReadCycleWrite is only to be used on riscv32");
2704     return emitReadCycleWidePseudo(MI, BB);
2705   case RISCV::Select_GPR_Using_CC_GPR:
2706   case RISCV::Select_FPR16_Using_CC_GPR:
2707   case RISCV::Select_FPR32_Using_CC_GPR:
2708   case RISCV::Select_FPR64_Using_CC_GPR:
2709     return emitSelectPseudo(MI, BB);
2710   case RISCV::BuildPairF64Pseudo:
2711     return emitBuildPairF64Pseudo(MI, BB);
2712   case RISCV::SplitF64Pseudo:
2713     return emitSplitF64Pseudo(MI, BB);
2714   }
2715 }
2716 
2717 // Calling Convention Implementation.
2718 // The expectations for frontend ABI lowering vary from target to target.
2719 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
2720 // details, but this is a longer term goal. For now, we simply try to keep the
2721 // role of the frontend as simple and well-defined as possible. The rules can
2722 // be summarised as:
2723 // * Never split up large scalar arguments. We handle them here.
2724 // * If a hardfloat calling convention is being used, and the struct may be
2725 // passed in a pair of registers (fp+fp, int+fp), and both registers are
2726 // available, then pass as two separate arguments. If either the GPRs or FPRs
2727 // are exhausted, then pass according to the rule below.
2728 // * If a struct could never be passed in registers or directly in a stack
2729 // slot (as it is larger than 2*XLEN and the floating point rules don't
2730 // apply), then pass it using a pointer with the byval attribute.
2731 // * If a struct is less than 2*XLEN, then coerce to either a two-element
2732 // word-sized array or a 2*XLEN scalar (depending on alignment).
2733 // * The frontend can determine whether a struct is returned by reference or
2734 // not based on its size and fields. If it will be returned by reference, the
2735 // frontend must modify the prototype so a pointer with the sret annotation is
2736 // passed as the first argument. This is not necessary for large scalar
2737 // returns.
2738 // * Struct return values and varargs should be coerced to structs containing
2739 // register-size fields in the same situations they would be for fixed
2740 // arguments.
2741 
2742 static const MCPhysReg ArgGPRs[] = {
2743   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
2744   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
2745 };
2746 static const MCPhysReg ArgFPR16s[] = {
2747   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
2748   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
2749 };
2750 static const MCPhysReg ArgFPR32s[] = {
2751   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
2752   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
2753 };
2754 static const MCPhysReg ArgFPR64s[] = {
2755   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
2756   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
2757 };
2758 // This is an interim calling convention and it may be changed in the future.
2759 static const MCPhysReg ArgVRs[] = {
2760     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
2761     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
2762     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
2763 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
2764                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
2765                                      RISCV::V20M2, RISCV::V22M2};
2766 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
2767                                      RISCV::V20M4};
2768 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
2769 
2770 // Pass a 2*XLEN argument that has been split into two XLEN values through
2771 // registers or the stack as necessary.
2772 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
2773                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
2774                                 MVT ValVT2, MVT LocVT2,
2775                                 ISD::ArgFlagsTy ArgFlags2) {
2776   unsigned XLenInBytes = XLen / 8;
2777   if (Register Reg = State.AllocateReg(ArgGPRs)) {
2778     // At least one half can be passed via register.
2779     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
2780                                      VA1.getLocVT(), CCValAssign::Full));
2781   } else {
2782     // Both halves must be passed on the stack, with proper alignment.
2783     Align StackAlign =
2784         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
2785     State.addLoc(
2786         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
2787                             State.AllocateStack(XLenInBytes, StackAlign),
2788                             VA1.getLocVT(), CCValAssign::Full));
2789     State.addLoc(CCValAssign::getMem(
2790         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
2791         LocVT2, CCValAssign::Full));
2792     return false;
2793   }
2794 
2795   if (Register Reg = State.AllocateReg(ArgGPRs)) {
2796     // The second half can also be passed via register.
2797     State.addLoc(
2798         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
2799   } else {
2800     // The second half is passed via the stack, without additional alignment.
2801     State.addLoc(CCValAssign::getMem(
2802         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
2803         LocVT2, CCValAssign::Full));
2804   }
2805 
2806   return false;
2807 }
2808 
2809 // Implements the RISC-V calling convention. Returns true upon failure.
2810 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
2811                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
2812                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
2813                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
2814                      Optional<unsigned> FirstMaskArgument) {
2815   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
2816   assert(XLen == 32 || XLen == 64);
2817   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
2818 
2819   // Any return value split in to more than two values can't be returned
2820   // directly.
2821   if (IsRet && ValNo > 1)
2822     return true;
2823 
2824   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
2825   // variadic argument, or if no F16/F32 argument registers are available.
2826   bool UseGPRForF16_F32 = true;
2827   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
2828   // variadic argument, or if no F64 argument registers are available.
2829   bool UseGPRForF64 = true;
2830 
2831   switch (ABI) {
2832   default:
2833     llvm_unreachable("Unexpected ABI");
2834   case RISCVABI::ABI_ILP32:
2835   case RISCVABI::ABI_LP64:
2836     break;
2837   case RISCVABI::ABI_ILP32F:
2838   case RISCVABI::ABI_LP64F:
2839     UseGPRForF16_F32 = !IsFixed;
2840     break;
2841   case RISCVABI::ABI_ILP32D:
2842   case RISCVABI::ABI_LP64D:
2843     UseGPRForF16_F32 = !IsFixed;
2844     UseGPRForF64 = !IsFixed;
2845     break;
2846   }
2847 
2848   // FPR16, FPR32, and FPR64 alias each other.
2849   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
2850     UseGPRForF16_F32 = true;
2851     UseGPRForF64 = true;
2852   }
2853 
2854   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
2855   // similar local variables rather than directly checking against the target
2856   // ABI.
2857 
2858   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
2859     LocVT = XLenVT;
2860     LocInfo = CCValAssign::BCvt;
2861   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
2862     LocVT = MVT::i64;
2863     LocInfo = CCValAssign::BCvt;
2864   }
2865 
2866   // If this is a variadic argument, the RISC-V calling convention requires
2867   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
2868   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
2869   // be used regardless of whether the original argument was split during
2870   // legalisation or not. The argument will not be passed by registers if the
2871   // original type is larger than 2*XLEN, so the register alignment rule does
2872   // not apply.
2873   unsigned TwoXLenInBytes = (2 * XLen) / 8;
2874   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
2875       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
2876     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
2877     // Skip 'odd' register if necessary.
2878     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
2879       State.AllocateReg(ArgGPRs);
2880   }
2881 
2882   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
2883   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
2884       State.getPendingArgFlags();
2885 
2886   assert(PendingLocs.size() == PendingArgFlags.size() &&
2887          "PendingLocs and PendingArgFlags out of sync");
2888 
2889   // Handle passing f64 on RV32D with a soft float ABI or when floating point
2890   // registers are exhausted.
2891   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
2892     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
2893            "Can't lower f64 if it is split");
2894     // Depending on available argument GPRS, f64 may be passed in a pair of
2895     // GPRs, split between a GPR and the stack, or passed completely on the
2896     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
2897     // cases.
2898     Register Reg = State.AllocateReg(ArgGPRs);
2899     LocVT = MVT::i32;
2900     if (!Reg) {
2901       unsigned StackOffset = State.AllocateStack(8, Align(8));
2902       State.addLoc(
2903           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
2904       return false;
2905     }
2906     if (!State.AllocateReg(ArgGPRs))
2907       State.AllocateStack(4, Align(4));
2908     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2909     return false;
2910   }
2911 
2912   // Split arguments might be passed indirectly, so keep track of the pending
2913   // values.
2914   if (ArgFlags.isSplit() || !PendingLocs.empty()) {
2915     LocVT = XLenVT;
2916     LocInfo = CCValAssign::Indirect;
2917     PendingLocs.push_back(
2918         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
2919     PendingArgFlags.push_back(ArgFlags);
2920     if (!ArgFlags.isSplitEnd()) {
2921       return false;
2922     }
2923   }
2924 
2925   // If the split argument only had two elements, it should be passed directly
2926   // in registers or on the stack.
2927   if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
2928     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
2929     // Apply the normal calling convention rules to the first half of the
2930     // split argument.
2931     CCValAssign VA = PendingLocs[0];
2932     ISD::ArgFlagsTy AF = PendingArgFlags[0];
2933     PendingLocs.clear();
2934     PendingArgFlags.clear();
2935     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
2936                                ArgFlags);
2937   }
2938 
2939   // Allocate to a register if possible, or else a stack slot.
2940   Register Reg;
2941   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
2942     Reg = State.AllocateReg(ArgFPR16s);
2943   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
2944     Reg = State.AllocateReg(ArgFPR32s);
2945   else if (ValVT == MVT::f64 && !UseGPRForF64)
2946     Reg = State.AllocateReg(ArgFPR64s);
2947   else if (ValVT.isScalableVector()) {
2948     const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
2949     if (RC == &RISCV::VRRegClass) {
2950       // Assign the first mask argument to V0.
2951       // This is an interim calling convention and it may be changed in the
2952       // future.
2953       if (FirstMaskArgument.hasValue() &&
2954           ValNo == FirstMaskArgument.getValue()) {
2955         Reg = State.AllocateReg(RISCV::V0);
2956       } else {
2957         Reg = State.AllocateReg(ArgVRs);
2958       }
2959     } else if (RC == &RISCV::VRM2RegClass) {
2960       Reg = State.AllocateReg(ArgVRM2s);
2961     } else if (RC == &RISCV::VRM4RegClass) {
2962       Reg = State.AllocateReg(ArgVRM4s);
2963     } else if (RC == &RISCV::VRM8RegClass) {
2964       Reg = State.AllocateReg(ArgVRM8s);
2965     } else {
2966       llvm_unreachable("Unhandled class register for ValueType");
2967     }
2968     if (!Reg) {
2969       LocInfo = CCValAssign::Indirect;
2970       // Try using a GPR to pass the address
2971       Reg = State.AllocateReg(ArgGPRs);
2972       LocVT = XLenVT;
2973     }
2974   } else
2975     Reg = State.AllocateReg(ArgGPRs);
2976   unsigned StackOffset =
2977       Reg ? 0 : State.AllocateStack(XLen / 8, Align(XLen / 8));
2978 
2979   // If we reach this point and PendingLocs is non-empty, we must be at the
2980   // end of a split argument that must be passed indirectly.
2981   if (!PendingLocs.empty()) {
2982     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
2983     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
2984 
2985     for (auto &It : PendingLocs) {
2986       if (Reg)
2987         It.convertToReg(Reg);
2988       else
2989         It.convertToMem(StackOffset);
2990       State.addLoc(It);
2991     }
2992     PendingLocs.clear();
2993     PendingArgFlags.clear();
2994     return false;
2995   }
2996 
2997   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
2998           (TLI.getSubtarget().hasStdExtV() && ValVT.isScalableVector())) &&
2999          "Expected an XLenVT or scalable vector types at this stage");
3000 
3001   if (Reg) {
3002     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3003     return false;
3004   }
3005 
3006   // When a floating-point value is passed on the stack, no bit-conversion is
3007   // needed.
3008   if (ValVT.isFloatingPoint()) {
3009     LocVT = ValVT;
3010     LocInfo = CCValAssign::Full;
3011   }
3012   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
3013   return false;
3014 }
3015 
3016 template <typename ArgTy>
3017 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
3018   for (const auto &ArgIdx : enumerate(Args)) {
3019     MVT ArgVT = ArgIdx.value().VT;
3020     if (ArgVT.isScalableVector() &&
3021         ArgVT.getVectorElementType().SimpleTy == MVT::i1)
3022       return ArgIdx.index();
3023   }
3024   return None;
3025 }
3026 
3027 void RISCVTargetLowering::analyzeInputArgs(
3028     MachineFunction &MF, CCState &CCInfo,
3029     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
3030   unsigned NumArgs = Ins.size();
3031   FunctionType *FType = MF.getFunction().getFunctionType();
3032 
3033   Optional<unsigned> FirstMaskArgument;
3034   if (Subtarget.hasStdExtV())
3035     FirstMaskArgument = preAssignMask(Ins);
3036 
3037   for (unsigned i = 0; i != NumArgs; ++i) {
3038     MVT ArgVT = Ins[i].VT;
3039     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
3040 
3041     Type *ArgTy = nullptr;
3042     if (IsRet)
3043       ArgTy = FType->getReturnType();
3044     else if (Ins[i].isOrigArg())
3045       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
3046 
3047     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
3048     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
3049                  ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
3050                  FirstMaskArgument)) {
3051       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
3052                         << EVT(ArgVT).getEVTString() << '\n');
3053       llvm_unreachable(nullptr);
3054     }
3055   }
3056 }
3057 
3058 void RISCVTargetLowering::analyzeOutputArgs(
3059     MachineFunction &MF, CCState &CCInfo,
3060     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
3061     CallLoweringInfo *CLI) const {
3062   unsigned NumArgs = Outs.size();
3063 
3064   Optional<unsigned> FirstMaskArgument;
3065   if (Subtarget.hasStdExtV())
3066     FirstMaskArgument = preAssignMask(Outs);
3067 
3068   for (unsigned i = 0; i != NumArgs; i++) {
3069     MVT ArgVT = Outs[i].VT;
3070     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3071     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
3072 
3073     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
3074     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
3075                  ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
3076                  FirstMaskArgument)) {
3077       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
3078                         << EVT(ArgVT).getEVTString() << "\n");
3079       llvm_unreachable(nullptr);
3080     }
3081   }
3082 }
3083 
3084 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
3085 // values.
3086 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
3087                                    const CCValAssign &VA, const SDLoc &DL) {
3088   switch (VA.getLocInfo()) {
3089   default:
3090     llvm_unreachable("Unexpected CCValAssign::LocInfo");
3091   case CCValAssign::Full:
3092     break;
3093   case CCValAssign::BCvt:
3094     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
3095       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
3096     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
3097       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
3098     else
3099       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3100     break;
3101   }
3102   return Val;
3103 }
3104 
3105 // The caller is responsible for loading the full value if the argument is
3106 // passed with CCValAssign::Indirect.
3107 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
3108                                 const CCValAssign &VA, const SDLoc &DL,
3109                                 const RISCVTargetLowering &TLI) {
3110   MachineFunction &MF = DAG.getMachineFunction();
3111   MachineRegisterInfo &RegInfo = MF.getRegInfo();
3112   EVT LocVT = VA.getLocVT();
3113   SDValue Val;
3114   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
3115   Register VReg = RegInfo.createVirtualRegister(RC);
3116   RegInfo.addLiveIn(VA.getLocReg(), VReg);
3117   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
3118 
3119   if (VA.getLocInfo() == CCValAssign::Indirect)
3120     return Val;
3121 
3122   return convertLocVTToValVT(DAG, Val, VA, DL);
3123 }
3124 
3125 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
3126                                    const CCValAssign &VA, const SDLoc &DL) {
3127   EVT LocVT = VA.getLocVT();
3128 
3129   switch (VA.getLocInfo()) {
3130   default:
3131     llvm_unreachable("Unexpected CCValAssign::LocInfo");
3132   case CCValAssign::Full:
3133     break;
3134   case CCValAssign::BCvt:
3135     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
3136       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
3137     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
3138       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
3139     else
3140       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
3141     break;
3142   }
3143   return Val;
3144 }
3145 
3146 // The caller is responsible for loading the full value if the argument is
3147 // passed with CCValAssign::Indirect.
3148 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
3149                                 const CCValAssign &VA, const SDLoc &DL) {
3150   MachineFunction &MF = DAG.getMachineFunction();
3151   MachineFrameInfo &MFI = MF.getFrameInfo();
3152   EVT LocVT = VA.getLocVT();
3153   EVT ValVT = VA.getValVT();
3154   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
3155   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3156                                  VA.getLocMemOffset(), /*Immutable=*/true);
3157   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3158   SDValue Val;
3159 
3160   ISD::LoadExtType ExtType;
3161   switch (VA.getLocInfo()) {
3162   default:
3163     llvm_unreachable("Unexpected CCValAssign::LocInfo");
3164   case CCValAssign::Full:
3165   case CCValAssign::Indirect:
3166   case CCValAssign::BCvt:
3167     ExtType = ISD::NON_EXTLOAD;
3168     break;
3169   }
3170   Val = DAG.getExtLoad(
3171       ExtType, DL, LocVT, Chain, FIN,
3172       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
3173   return Val;
3174 }
3175 
3176 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
3177                                        const CCValAssign &VA, const SDLoc &DL) {
3178   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
3179          "Unexpected VA");
3180   MachineFunction &MF = DAG.getMachineFunction();
3181   MachineFrameInfo &MFI = MF.getFrameInfo();
3182   MachineRegisterInfo &RegInfo = MF.getRegInfo();
3183 
3184   if (VA.isMemLoc()) {
3185     // f64 is passed on the stack.
3186     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
3187     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
3188     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
3189                        MachinePointerInfo::getFixedStack(MF, FI));
3190   }
3191 
3192   assert(VA.isRegLoc() && "Expected register VA assignment");
3193 
3194   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
3195   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
3196   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
3197   SDValue Hi;
3198   if (VA.getLocReg() == RISCV::X17) {
3199     // Second half of f64 is passed on the stack.
3200     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
3201     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
3202     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
3203                      MachinePointerInfo::getFixedStack(MF, FI));
3204   } else {
3205     // Second half of f64 is passed in another GPR.
3206     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
3207     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
3208     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
3209   }
3210   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
3211 }
3212 
3213 // FastCC has less than 1% performance improvement for some particular
3214 // benchmark. But theoretically, it may has benenfit for some cases.
3215 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT,
3216                             CCValAssign::LocInfo LocInfo,
3217                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
3218 
3219   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
3220     // X5 and X6 might be used for save-restore libcall.
3221     static const MCPhysReg GPRList[] = {
3222         RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
3223         RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
3224         RISCV::X29, RISCV::X30, RISCV::X31};
3225     if (unsigned Reg = State.AllocateReg(GPRList)) {
3226       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3227       return false;
3228     }
3229   }
3230 
3231   if (LocVT == MVT::f16) {
3232     static const MCPhysReg FPR16List[] = {
3233         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
3234         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
3235         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
3236         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
3237     if (unsigned Reg = State.AllocateReg(FPR16List)) {
3238       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3239       return false;
3240     }
3241   }
3242 
3243   if (LocVT == MVT::f32) {
3244     static const MCPhysReg FPR32List[] = {
3245         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
3246         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
3247         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
3248         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
3249     if (unsigned Reg = State.AllocateReg(FPR32List)) {
3250       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3251       return false;
3252     }
3253   }
3254 
3255   if (LocVT == MVT::f64) {
3256     static const MCPhysReg FPR64List[] = {
3257         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
3258         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
3259         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
3260         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
3261     if (unsigned Reg = State.AllocateReg(FPR64List)) {
3262       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3263       return false;
3264     }
3265   }
3266 
3267   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
3268     unsigned Offset4 = State.AllocateStack(4, Align(4));
3269     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
3270     return false;
3271   }
3272 
3273   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
3274     unsigned Offset5 = State.AllocateStack(8, Align(8));
3275     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
3276     return false;
3277   }
3278 
3279   return true; // CC didn't match.
3280 }
3281 
3282 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
3283                          CCValAssign::LocInfo LocInfo,
3284                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
3285 
3286   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
3287     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
3288     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
3289     static const MCPhysReg GPRList[] = {
3290         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
3291         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
3292     if (unsigned Reg = State.AllocateReg(GPRList)) {
3293       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3294       return false;
3295     }
3296   }
3297 
3298   if (LocVT == MVT::f32) {
3299     // Pass in STG registers: F1, ..., F6
3300     //                        fs0 ... fs5
3301     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
3302                                           RISCV::F18_F, RISCV::F19_F,
3303                                           RISCV::F20_F, RISCV::F21_F};
3304     if (unsigned Reg = State.AllocateReg(FPR32List)) {
3305       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3306       return false;
3307     }
3308   }
3309 
3310   if (LocVT == MVT::f64) {
3311     // Pass in STG registers: D1, ..., D6
3312     //                        fs6 ... fs11
3313     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
3314                                           RISCV::F24_D, RISCV::F25_D,
3315                                           RISCV::F26_D, RISCV::F27_D};
3316     if (unsigned Reg = State.AllocateReg(FPR64List)) {
3317       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3318       return false;
3319     }
3320   }
3321 
3322   report_fatal_error("No registers left in GHC calling convention");
3323   return true;
3324 }
3325 
3326 // Transform physical registers into virtual registers.
3327 SDValue RISCVTargetLowering::LowerFormalArguments(
3328     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3329     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3330     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3331 
3332   MachineFunction &MF = DAG.getMachineFunction();
3333 
3334   switch (CallConv) {
3335   default:
3336     report_fatal_error("Unsupported calling convention");
3337   case CallingConv::C:
3338   case CallingConv::Fast:
3339     break;
3340   case CallingConv::GHC:
3341     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
3342         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
3343       report_fatal_error(
3344         "GHC calling convention requires the F and D instruction set extensions");
3345   }
3346 
3347   const Function &Func = MF.getFunction();
3348   if (Func.hasFnAttribute("interrupt")) {
3349     if (!Func.arg_empty())
3350       report_fatal_error(
3351         "Functions with the interrupt attribute cannot have arguments!");
3352 
3353     StringRef Kind =
3354       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
3355 
3356     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
3357       report_fatal_error(
3358         "Function interrupt attribute argument not supported!");
3359   }
3360 
3361   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3362   MVT XLenVT = Subtarget.getXLenVT();
3363   unsigned XLenInBytes = Subtarget.getXLen() / 8;
3364   // Used with vargs to acumulate store chains.
3365   std::vector<SDValue> OutChains;
3366 
3367   // Assign locations to all of the incoming arguments.
3368   SmallVector<CCValAssign, 16> ArgLocs;
3369   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3370 
3371   if (CallConv == CallingConv::Fast)
3372     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC);
3373   else if (CallConv == CallingConv::GHC)
3374     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
3375   else
3376     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
3377 
3378   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3379     CCValAssign &VA = ArgLocs[i];
3380     SDValue ArgValue;
3381     // Passing f64 on RV32D with a soft float ABI must be handled as a special
3382     // case.
3383     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
3384       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
3385     else if (VA.isRegLoc())
3386       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
3387     else
3388       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
3389 
3390     if (VA.getLocInfo() == CCValAssign::Indirect) {
3391       // If the original argument was split and passed by reference (e.g. i128
3392       // on RV32), we need to load all parts of it here (using the same
3393       // address).
3394       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
3395                                    MachinePointerInfo()));
3396       unsigned ArgIndex = Ins[i].OrigArgIndex;
3397       assert(Ins[i].PartOffset == 0);
3398       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
3399         CCValAssign &PartVA = ArgLocs[i + 1];
3400         unsigned PartOffset = Ins[i + 1].PartOffset;
3401         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
3402                                       DAG.getIntPtrConstant(PartOffset, DL));
3403         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
3404                                      MachinePointerInfo()));
3405         ++i;
3406       }
3407       continue;
3408     }
3409     InVals.push_back(ArgValue);
3410   }
3411 
3412   if (IsVarArg) {
3413     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
3414     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
3415     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
3416     MachineFrameInfo &MFI = MF.getFrameInfo();
3417     MachineRegisterInfo &RegInfo = MF.getRegInfo();
3418     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
3419 
3420     // Offset of the first variable argument from stack pointer, and size of
3421     // the vararg save area. For now, the varargs save area is either zero or
3422     // large enough to hold a0-a7.
3423     int VaArgOffset, VarArgsSaveSize;
3424 
3425     // If all registers are allocated, then all varargs must be passed on the
3426     // stack and we don't need to save any argregs.
3427     if (ArgRegs.size() == Idx) {
3428       VaArgOffset = CCInfo.getNextStackOffset();
3429       VarArgsSaveSize = 0;
3430     } else {
3431       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
3432       VaArgOffset = -VarArgsSaveSize;
3433     }
3434 
3435     // Record the frame index of the first variable argument
3436     // which is a value necessary to VASTART.
3437     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
3438     RVFI->setVarArgsFrameIndex(FI);
3439 
3440     // If saving an odd number of registers then create an extra stack slot to
3441     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
3442     // offsets to even-numbered registered remain 2*XLEN-aligned.
3443     if (Idx % 2) {
3444       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
3445       VarArgsSaveSize += XLenInBytes;
3446     }
3447 
3448     // Copy the integer registers that may have been used for passing varargs
3449     // to the vararg save area.
3450     for (unsigned I = Idx; I < ArgRegs.size();
3451          ++I, VaArgOffset += XLenInBytes) {
3452       const Register Reg = RegInfo.createVirtualRegister(RC);
3453       RegInfo.addLiveIn(ArgRegs[I], Reg);
3454       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
3455       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
3456       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3457       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3458                                    MachinePointerInfo::getFixedStack(MF, FI));
3459       cast<StoreSDNode>(Store.getNode())
3460           ->getMemOperand()
3461           ->setValue((Value *)nullptr);
3462       OutChains.push_back(Store);
3463     }
3464     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
3465   }
3466 
3467   // All stores are grouped in one node to allow the matching between
3468   // the size of Ins and InVals. This only happens for vararg functions.
3469   if (!OutChains.empty()) {
3470     OutChains.push_back(Chain);
3471     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3472   }
3473 
3474   return Chain;
3475 }
3476 
3477 /// isEligibleForTailCallOptimization - Check whether the call is eligible
3478 /// for tail call optimization.
3479 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
3480 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
3481     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
3482     const SmallVector<CCValAssign, 16> &ArgLocs) const {
3483 
3484   auto &Callee = CLI.Callee;
3485   auto CalleeCC = CLI.CallConv;
3486   auto &Outs = CLI.Outs;
3487   auto &Caller = MF.getFunction();
3488   auto CallerCC = Caller.getCallingConv();
3489 
3490   // Exception-handling functions need a special set of instructions to
3491   // indicate a return to the hardware. Tail-calling another function would
3492   // probably break this.
3493   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
3494   // should be expanded as new function attributes are introduced.
3495   if (Caller.hasFnAttribute("interrupt"))
3496     return false;
3497 
3498   // Do not tail call opt if the stack is used to pass parameters.
3499   if (CCInfo.getNextStackOffset() != 0)
3500     return false;
3501 
3502   // Do not tail call opt if any parameters need to be passed indirectly.
3503   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
3504   // passed indirectly. So the address of the value will be passed in a
3505   // register, or if not available, then the address is put on the stack. In
3506   // order to pass indirectly, space on the stack often needs to be allocated
3507   // in order to store the value. In this case the CCInfo.getNextStackOffset()
3508   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
3509   // are passed CCValAssign::Indirect.
3510   for (auto &VA : ArgLocs)
3511     if (VA.getLocInfo() == CCValAssign::Indirect)
3512       return false;
3513 
3514   // Do not tail call opt if either caller or callee uses struct return
3515   // semantics.
3516   auto IsCallerStructRet = Caller.hasStructRetAttr();
3517   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
3518   if (IsCallerStructRet || IsCalleeStructRet)
3519     return false;
3520 
3521   // Externally-defined functions with weak linkage should not be
3522   // tail-called. The behaviour of branch instructions in this situation (as
3523   // used for tail calls) is implementation-defined, so we cannot rely on the
3524   // linker replacing the tail call with a return.
3525   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3526     const GlobalValue *GV = G->getGlobal();
3527     if (GV->hasExternalWeakLinkage())
3528       return false;
3529   }
3530 
3531   // The callee has to preserve all registers the caller needs to preserve.
3532   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
3533   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3534   if (CalleeCC != CallerCC) {
3535     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3536     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3537       return false;
3538   }
3539 
3540   // Byval parameters hand the function a pointer directly into the stack area
3541   // we want to reuse during a tail call. Working around this *is* possible
3542   // but less efficient and uglier in LowerCall.
3543   for (auto &Arg : Outs)
3544     if (Arg.Flags.isByVal())
3545       return false;
3546 
3547   return true;
3548 }
3549 
3550 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
3551 // and output parameter nodes.
3552 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
3553                                        SmallVectorImpl<SDValue> &InVals) const {
3554   SelectionDAG &DAG = CLI.DAG;
3555   SDLoc &DL = CLI.DL;
3556   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3557   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3558   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3559   SDValue Chain = CLI.Chain;
3560   SDValue Callee = CLI.Callee;
3561   bool &IsTailCall = CLI.IsTailCall;
3562   CallingConv::ID CallConv = CLI.CallConv;
3563   bool IsVarArg = CLI.IsVarArg;
3564   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3565   MVT XLenVT = Subtarget.getXLenVT();
3566 
3567   MachineFunction &MF = DAG.getMachineFunction();
3568 
3569   // Analyze the operands of the call, assigning locations to each operand.
3570   SmallVector<CCValAssign, 16> ArgLocs;
3571   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3572 
3573   if (CallConv == CallingConv::Fast)
3574     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC);
3575   else if (CallConv == CallingConv::GHC)
3576     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
3577   else
3578     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
3579 
3580   // Check if it's really possible to do a tail call.
3581   if (IsTailCall)
3582     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
3583 
3584   if (IsTailCall)
3585     ++NumTailCalls;
3586   else if (CLI.CB && CLI.CB->isMustTailCall())
3587     report_fatal_error("failed to perform tail call elimination on a call "
3588                        "site marked musttail");
3589 
3590   // Get a count of how many bytes are to be pushed on the stack.
3591   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
3592 
3593   // Create local copies for byval args
3594   SmallVector<SDValue, 8> ByValArgs;
3595   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
3596     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3597     if (!Flags.isByVal())
3598       continue;
3599 
3600     SDValue Arg = OutVals[i];
3601     unsigned Size = Flags.getByValSize();
3602     Align Alignment = Flags.getNonZeroByValAlign();
3603 
3604     int FI =
3605         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
3606     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3607     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
3608 
3609     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
3610                           /*IsVolatile=*/false,
3611                           /*AlwaysInline=*/false, IsTailCall,
3612                           MachinePointerInfo(), MachinePointerInfo());
3613     ByValArgs.push_back(FIPtr);
3614   }
3615 
3616   if (!IsTailCall)
3617     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
3618 
3619   // Copy argument values to their designated locations.
3620   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
3621   SmallVector<SDValue, 8> MemOpChains;
3622   SDValue StackPtr;
3623   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
3624     CCValAssign &VA = ArgLocs[i];
3625     SDValue ArgValue = OutVals[i];
3626     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3627 
3628     // Handle passing f64 on RV32D with a soft float ABI as a special case.
3629     bool IsF64OnRV32DSoftABI =
3630         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
3631     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
3632       SDValue SplitF64 = DAG.getNode(
3633           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
3634       SDValue Lo = SplitF64.getValue(0);
3635       SDValue Hi = SplitF64.getValue(1);
3636 
3637       Register RegLo = VA.getLocReg();
3638       RegsToPass.push_back(std::make_pair(RegLo, Lo));
3639 
3640       if (RegLo == RISCV::X17) {
3641         // Second half of f64 is passed on the stack.
3642         // Work out the address of the stack slot.
3643         if (!StackPtr.getNode())
3644           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
3645         // Emit the store.
3646         MemOpChains.push_back(
3647             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
3648       } else {
3649         // Second half of f64 is passed in another GPR.
3650         assert(RegLo < RISCV::X31 && "Invalid register pair");
3651         Register RegHigh = RegLo + 1;
3652         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
3653       }
3654       continue;
3655     }
3656 
3657     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
3658     // as any other MemLoc.
3659 
3660     // Promote the value if needed.
3661     // For now, only handle fully promoted and indirect arguments.
3662     if (VA.getLocInfo() == CCValAssign::Indirect) {
3663       // Store the argument in a stack slot and pass its address.
3664       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
3665       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3666       MemOpChains.push_back(
3667           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
3668                        MachinePointerInfo::getFixedStack(MF, FI)));
3669       // If the original argument was split (e.g. i128), we need
3670       // to store all parts of it here (and pass just one address).
3671       unsigned ArgIndex = Outs[i].OrigArgIndex;
3672       assert(Outs[i].PartOffset == 0);
3673       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
3674         SDValue PartValue = OutVals[i + 1];
3675         unsigned PartOffset = Outs[i + 1].PartOffset;
3676         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
3677                                       DAG.getIntPtrConstant(PartOffset, DL));
3678         MemOpChains.push_back(
3679             DAG.getStore(Chain, DL, PartValue, Address,
3680                          MachinePointerInfo::getFixedStack(MF, FI)));
3681         ++i;
3682       }
3683       ArgValue = SpillSlot;
3684     } else {
3685       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
3686     }
3687 
3688     // Use local copy if it is a byval arg.
3689     if (Flags.isByVal())
3690       ArgValue = ByValArgs[j++];
3691 
3692     if (VA.isRegLoc()) {
3693       // Queue up the argument copies and emit them at the end.
3694       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
3695     } else {
3696       assert(VA.isMemLoc() && "Argument not register or memory");
3697       assert(!IsTailCall && "Tail call not allowed if stack is used "
3698                             "for passing parameters");
3699 
3700       // Work out the address of the stack slot.
3701       if (!StackPtr.getNode())
3702         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
3703       SDValue Address =
3704           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
3705                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
3706 
3707       // Emit the store.
3708       MemOpChains.push_back(
3709           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
3710     }
3711   }
3712 
3713   // Join the stores, which are independent of one another.
3714   if (!MemOpChains.empty())
3715     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3716 
3717   SDValue Glue;
3718 
3719   // Build a sequence of copy-to-reg nodes, chained and glued together.
3720   for (auto &Reg : RegsToPass) {
3721     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
3722     Glue = Chain.getValue(1);
3723   }
3724 
3725   // Validate that none of the argument registers have been marked as
3726   // reserved, if so report an error. Do the same for the return address if this
3727   // is not a tailcall.
3728   validateCCReservedRegs(RegsToPass, MF);
3729   if (!IsTailCall &&
3730       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
3731     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
3732         MF.getFunction(),
3733         "Return address register required, but has been reserved."});
3734 
3735   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
3736   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
3737   // split it and then direct call can be matched by PseudoCALL.
3738   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
3739     const GlobalValue *GV = S->getGlobal();
3740 
3741     unsigned OpFlags = RISCVII::MO_CALL;
3742     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
3743       OpFlags = RISCVII::MO_PLT;
3744 
3745     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3746   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3747     unsigned OpFlags = RISCVII::MO_CALL;
3748 
3749     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
3750                                                  nullptr))
3751       OpFlags = RISCVII::MO_PLT;
3752 
3753     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
3754   }
3755 
3756   // The first call operand is the chain and the second is the target address.
3757   SmallVector<SDValue, 8> Ops;
3758   Ops.push_back(Chain);
3759   Ops.push_back(Callee);
3760 
3761   // Add argument registers to the end of the list so that they are
3762   // known live into the call.
3763   for (auto &Reg : RegsToPass)
3764     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
3765 
3766   if (!IsTailCall) {
3767     // Add a register mask operand representing the call-preserved registers.
3768     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3769     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3770     assert(Mask && "Missing call preserved mask for calling convention");
3771     Ops.push_back(DAG.getRegisterMask(Mask));
3772   }
3773 
3774   // Glue the call to the argument copies, if any.
3775   if (Glue.getNode())
3776     Ops.push_back(Glue);
3777 
3778   // Emit the call.
3779   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3780 
3781   if (IsTailCall) {
3782     MF.getFrameInfo().setHasTailCall();
3783     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
3784   }
3785 
3786   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
3787   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
3788   Glue = Chain.getValue(1);
3789 
3790   // Mark the end of the call, which is glued to the call itself.
3791   Chain = DAG.getCALLSEQ_END(Chain,
3792                              DAG.getConstant(NumBytes, DL, PtrVT, true),
3793                              DAG.getConstant(0, DL, PtrVT, true),
3794                              Glue, DL);
3795   Glue = Chain.getValue(1);
3796 
3797   // Assign locations to each value returned by this call.
3798   SmallVector<CCValAssign, 16> RVLocs;
3799   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3800   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
3801 
3802   // Copy all of the result registers out of their specified physreg.
3803   for (auto &VA : RVLocs) {
3804     // Copy the value out
3805     SDValue RetValue =
3806         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
3807     // Glue the RetValue to the end of the call sequence
3808     Chain = RetValue.getValue(1);
3809     Glue = RetValue.getValue(2);
3810 
3811     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
3812       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
3813       SDValue RetValue2 =
3814           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
3815       Chain = RetValue2.getValue(1);
3816       Glue = RetValue2.getValue(2);
3817       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
3818                              RetValue2);
3819     }
3820 
3821     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
3822 
3823     InVals.push_back(RetValue);
3824   }
3825 
3826   return Chain;
3827 }
3828 
3829 bool RISCVTargetLowering::CanLowerReturn(
3830     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
3831     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3832   SmallVector<CCValAssign, 16> RVLocs;
3833   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3834 
3835   Optional<unsigned> FirstMaskArgument;
3836   if (Subtarget.hasStdExtV())
3837     FirstMaskArgument = preAssignMask(Outs);
3838 
3839   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
3840     MVT VT = Outs[i].VT;
3841     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3842     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
3843     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
3844                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
3845                  *this, FirstMaskArgument))
3846       return false;
3847   }
3848   return true;
3849 }
3850 
3851 SDValue
3852 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3853                                  bool IsVarArg,
3854                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
3855                                  const SmallVectorImpl<SDValue> &OutVals,
3856                                  const SDLoc &DL, SelectionDAG &DAG) const {
3857   const MachineFunction &MF = DAG.getMachineFunction();
3858   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
3859 
3860   // Stores the assignment of the return value to a location.
3861   SmallVector<CCValAssign, 16> RVLocs;
3862 
3863   // Info about the registers and stack slot.
3864   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3865                  *DAG.getContext());
3866 
3867   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
3868                     nullptr);
3869 
3870   if (CallConv == CallingConv::GHC && !RVLocs.empty())
3871     report_fatal_error("GHC functions return void only");
3872 
3873   SDValue Glue;
3874   SmallVector<SDValue, 4> RetOps(1, Chain);
3875 
3876   // Copy the result values into the output registers.
3877   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
3878     SDValue Val = OutVals[i];
3879     CCValAssign &VA = RVLocs[i];
3880     assert(VA.isRegLoc() && "Can only return in registers!");
3881 
3882     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
3883       // Handle returning f64 on RV32D with a soft float ABI.
3884       assert(VA.isRegLoc() && "Expected return via registers");
3885       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
3886                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
3887       SDValue Lo = SplitF64.getValue(0);
3888       SDValue Hi = SplitF64.getValue(1);
3889       Register RegLo = VA.getLocReg();
3890       assert(RegLo < RISCV::X31 && "Invalid register pair");
3891       Register RegHi = RegLo + 1;
3892 
3893       if (STI.isRegisterReservedByUser(RegLo) ||
3894           STI.isRegisterReservedByUser(RegHi))
3895         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
3896             MF.getFunction(),
3897             "Return value register required, but has been reserved."});
3898 
3899       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
3900       Glue = Chain.getValue(1);
3901       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
3902       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
3903       Glue = Chain.getValue(1);
3904       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
3905     } else {
3906       // Handle a 'normal' return.
3907       Val = convertValVTToLocVT(DAG, Val, VA, DL);
3908       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
3909 
3910       if (STI.isRegisterReservedByUser(VA.getLocReg()))
3911         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
3912             MF.getFunction(),
3913             "Return value register required, but has been reserved."});
3914 
3915       // Guarantee that all emitted copies are stuck together.
3916       Glue = Chain.getValue(1);
3917       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3918     }
3919   }
3920 
3921   RetOps[0] = Chain; // Update chain.
3922 
3923   // Add the glue node if we have it.
3924   if (Glue.getNode()) {
3925     RetOps.push_back(Glue);
3926   }
3927 
3928   // Interrupt service routines use different return instructions.
3929   const Function &Func = DAG.getMachineFunction().getFunction();
3930   if (Func.hasFnAttribute("interrupt")) {
3931     if (!Func.getReturnType()->isVoidTy())
3932       report_fatal_error(
3933           "Functions with the interrupt attribute must have void return type!");
3934 
3935     MachineFunction &MF = DAG.getMachineFunction();
3936     StringRef Kind =
3937       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
3938 
3939     unsigned RetOpc;
3940     if (Kind == "user")
3941       RetOpc = RISCVISD::URET_FLAG;
3942     else if (Kind == "supervisor")
3943       RetOpc = RISCVISD::SRET_FLAG;
3944     else
3945       RetOpc = RISCVISD::MRET_FLAG;
3946 
3947     return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
3948   }
3949 
3950   return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
3951 }
3952 
3953 void RISCVTargetLowering::validateCCReservedRegs(
3954     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
3955     MachineFunction &MF) const {
3956   const Function &F = MF.getFunction();
3957   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
3958 
3959   if (llvm::any_of(Regs, [&STI](auto Reg) {
3960         return STI.isRegisterReservedByUser(Reg.first);
3961       }))
3962     F.getContext().diagnose(DiagnosticInfoUnsupported{
3963         F, "Argument register required, but has been reserved."});
3964 }
3965 
3966 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3967   return CI->isTailCall();
3968 }
3969 
3970 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
3971 #define NODE_NAME_CASE(NODE)                                                   \
3972   case RISCVISD::NODE:                                                         \
3973     return "RISCVISD::" #NODE;
3974   // clang-format off
3975   switch ((RISCVISD::NodeType)Opcode) {
3976   case RISCVISD::FIRST_NUMBER:
3977     break;
3978   NODE_NAME_CASE(RET_FLAG)
3979   NODE_NAME_CASE(URET_FLAG)
3980   NODE_NAME_CASE(SRET_FLAG)
3981   NODE_NAME_CASE(MRET_FLAG)
3982   NODE_NAME_CASE(CALL)
3983   NODE_NAME_CASE(SELECT_CC)
3984   NODE_NAME_CASE(BuildPairF64)
3985   NODE_NAME_CASE(SplitF64)
3986   NODE_NAME_CASE(TAIL)
3987   NODE_NAME_CASE(SLLW)
3988   NODE_NAME_CASE(SRAW)
3989   NODE_NAME_CASE(SRLW)
3990   NODE_NAME_CASE(DIVW)
3991   NODE_NAME_CASE(DIVUW)
3992   NODE_NAME_CASE(REMUW)
3993   NODE_NAME_CASE(ROLW)
3994   NODE_NAME_CASE(RORW)
3995   NODE_NAME_CASE(FSLW)
3996   NODE_NAME_CASE(FSRW)
3997   NODE_NAME_CASE(FMV_H_X)
3998   NODE_NAME_CASE(FMV_X_ANYEXTH)
3999   NODE_NAME_CASE(FMV_W_X_RV64)
4000   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
4001   NODE_NAME_CASE(READ_CYCLE_WIDE)
4002   NODE_NAME_CASE(GREVI)
4003   NODE_NAME_CASE(GREVIW)
4004   NODE_NAME_CASE(GORCI)
4005   NODE_NAME_CASE(GORCIW)
4006   NODE_NAME_CASE(VMV_X_S)
4007   NODE_NAME_CASE(SPLAT_VECTOR_I64)
4008   NODE_NAME_CASE(READ_VLENB)
4009   NODE_NAME_CASE(TRUNCATE_VECTOR)
4010   NODE_NAME_CASE(VLEFF)
4011   NODE_NAME_CASE(VLEFF_MASK)
4012   NODE_NAME_CASE(VSLIDEUP)
4013   NODE_NAME_CASE(VSLIDEDOWN)
4014   NODE_NAME_CASE(VID)
4015   }
4016   // clang-format on
4017   return nullptr;
4018 #undef NODE_NAME_CASE
4019 }
4020 
4021 /// getConstraintType - Given a constraint letter, return the type of
4022 /// constraint it is for this target.
4023 RISCVTargetLowering::ConstraintType
4024 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
4025   if (Constraint.size() == 1) {
4026     switch (Constraint[0]) {
4027     default:
4028       break;
4029     case 'f':
4030       return C_RegisterClass;
4031     case 'I':
4032     case 'J':
4033     case 'K':
4034       return C_Immediate;
4035     case 'A':
4036       return C_Memory;
4037     }
4038   }
4039   return TargetLowering::getConstraintType(Constraint);
4040 }
4041 
4042 std::pair<unsigned, const TargetRegisterClass *>
4043 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4044                                                   StringRef Constraint,
4045                                                   MVT VT) const {
4046   // First, see if this is a constraint that directly corresponds to a
4047   // RISCV register class.
4048   if (Constraint.size() == 1) {
4049     switch (Constraint[0]) {
4050     case 'r':
4051       return std::make_pair(0U, &RISCV::GPRRegClass);
4052     case 'f':
4053       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
4054         return std::make_pair(0U, &RISCV::FPR16RegClass);
4055       if (Subtarget.hasStdExtF() && VT == MVT::f32)
4056         return std::make_pair(0U, &RISCV::FPR32RegClass);
4057       if (Subtarget.hasStdExtD() && VT == MVT::f64)
4058         return std::make_pair(0U, &RISCV::FPR64RegClass);
4059       break;
4060     default:
4061       break;
4062     }
4063   }
4064 
4065   // Clang will correctly decode the usage of register name aliases into their
4066   // official names. However, other frontends like `rustc` do not. This allows
4067   // users of these frontends to use the ABI names for registers in LLVM-style
4068   // register constraints.
4069   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
4070                                .Case("{zero}", RISCV::X0)
4071                                .Case("{ra}", RISCV::X1)
4072                                .Case("{sp}", RISCV::X2)
4073                                .Case("{gp}", RISCV::X3)
4074                                .Case("{tp}", RISCV::X4)
4075                                .Case("{t0}", RISCV::X5)
4076                                .Case("{t1}", RISCV::X6)
4077                                .Case("{t2}", RISCV::X7)
4078                                .Cases("{s0}", "{fp}", RISCV::X8)
4079                                .Case("{s1}", RISCV::X9)
4080                                .Case("{a0}", RISCV::X10)
4081                                .Case("{a1}", RISCV::X11)
4082                                .Case("{a2}", RISCV::X12)
4083                                .Case("{a3}", RISCV::X13)
4084                                .Case("{a4}", RISCV::X14)
4085                                .Case("{a5}", RISCV::X15)
4086                                .Case("{a6}", RISCV::X16)
4087                                .Case("{a7}", RISCV::X17)
4088                                .Case("{s2}", RISCV::X18)
4089                                .Case("{s3}", RISCV::X19)
4090                                .Case("{s4}", RISCV::X20)
4091                                .Case("{s5}", RISCV::X21)
4092                                .Case("{s6}", RISCV::X22)
4093                                .Case("{s7}", RISCV::X23)
4094                                .Case("{s8}", RISCV::X24)
4095                                .Case("{s9}", RISCV::X25)
4096                                .Case("{s10}", RISCV::X26)
4097                                .Case("{s11}", RISCV::X27)
4098                                .Case("{t3}", RISCV::X28)
4099                                .Case("{t4}", RISCV::X29)
4100                                .Case("{t5}", RISCV::X30)
4101                                .Case("{t6}", RISCV::X31)
4102                                .Default(RISCV::NoRegister);
4103   if (XRegFromAlias != RISCV::NoRegister)
4104     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
4105 
4106   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
4107   // TableGen record rather than the AsmName to choose registers for InlineAsm
4108   // constraints, plus we want to match those names to the widest floating point
4109   // register type available, manually select floating point registers here.
4110   //
4111   // The second case is the ABI name of the register, so that frontends can also
4112   // use the ABI names in register constraint lists.
4113   if (Subtarget.hasStdExtF()) {
4114     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
4115                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
4116                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
4117                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
4118                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
4119                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
4120                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
4121                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
4122                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
4123                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
4124                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
4125                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
4126                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
4127                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
4128                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
4129                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
4130                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
4131                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
4132                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
4133                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
4134                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
4135                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
4136                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
4137                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
4138                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
4139                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
4140                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
4141                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
4142                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
4143                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
4144                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
4145                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
4146                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
4147                         .Default(RISCV::NoRegister);
4148     if (FReg != RISCV::NoRegister) {
4149       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
4150       if (Subtarget.hasStdExtD()) {
4151         unsigned RegNo = FReg - RISCV::F0_F;
4152         unsigned DReg = RISCV::F0_D + RegNo;
4153         return std::make_pair(DReg, &RISCV::FPR64RegClass);
4154       }
4155       return std::make_pair(FReg, &RISCV::FPR32RegClass);
4156     }
4157   }
4158 
4159   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4160 }
4161 
4162 unsigned
4163 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
4164   // Currently only support length 1 constraints.
4165   if (ConstraintCode.size() == 1) {
4166     switch (ConstraintCode[0]) {
4167     case 'A':
4168       return InlineAsm::Constraint_A;
4169     default:
4170       break;
4171     }
4172   }
4173 
4174   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
4175 }
4176 
4177 void RISCVTargetLowering::LowerAsmOperandForConstraint(
4178     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4179     SelectionDAG &DAG) const {
4180   // Currently only support length 1 constraints.
4181   if (Constraint.length() == 1) {
4182     switch (Constraint[0]) {
4183     case 'I':
4184       // Validate & create a 12-bit signed immediate operand.
4185       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4186         uint64_t CVal = C->getSExtValue();
4187         if (isInt<12>(CVal))
4188           Ops.push_back(
4189               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
4190       }
4191       return;
4192     case 'J':
4193       // Validate & create an integer zero operand.
4194       if (auto *C = dyn_cast<ConstantSDNode>(Op))
4195         if (C->getZExtValue() == 0)
4196           Ops.push_back(
4197               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
4198       return;
4199     case 'K':
4200       // Validate & create a 5-bit unsigned immediate operand.
4201       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4202         uint64_t CVal = C->getZExtValue();
4203         if (isUInt<5>(CVal))
4204           Ops.push_back(
4205               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
4206       }
4207       return;
4208     default:
4209       break;
4210     }
4211   }
4212   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4213 }
4214 
4215 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
4216                                                    Instruction *Inst,
4217                                                    AtomicOrdering Ord) const {
4218   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
4219     return Builder.CreateFence(Ord);
4220   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
4221     return Builder.CreateFence(AtomicOrdering::Release);
4222   return nullptr;
4223 }
4224 
4225 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
4226                                                     Instruction *Inst,
4227                                                     AtomicOrdering Ord) const {
4228   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
4229     return Builder.CreateFence(AtomicOrdering::Acquire);
4230   return nullptr;
4231 }
4232 
4233 TargetLowering::AtomicExpansionKind
4234 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
4235   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
4236   // point operations can't be used in an lr/sc sequence without breaking the
4237   // forward-progress guarantee.
4238   if (AI->isFloatingPointOperation())
4239     return AtomicExpansionKind::CmpXChg;
4240 
4241   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
4242   if (Size == 8 || Size == 16)
4243     return AtomicExpansionKind::MaskedIntrinsic;
4244   return AtomicExpansionKind::None;
4245 }
4246 
4247 static Intrinsic::ID
4248 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
4249   if (XLen == 32) {
4250     switch (BinOp) {
4251     default:
4252       llvm_unreachable("Unexpected AtomicRMW BinOp");
4253     case AtomicRMWInst::Xchg:
4254       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
4255     case AtomicRMWInst::Add:
4256       return Intrinsic::riscv_masked_atomicrmw_add_i32;
4257     case AtomicRMWInst::Sub:
4258       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
4259     case AtomicRMWInst::Nand:
4260       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
4261     case AtomicRMWInst::Max:
4262       return Intrinsic::riscv_masked_atomicrmw_max_i32;
4263     case AtomicRMWInst::Min:
4264       return Intrinsic::riscv_masked_atomicrmw_min_i32;
4265     case AtomicRMWInst::UMax:
4266       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
4267     case AtomicRMWInst::UMin:
4268       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
4269     }
4270   }
4271 
4272   if (XLen == 64) {
4273     switch (BinOp) {
4274     default:
4275       llvm_unreachable("Unexpected AtomicRMW BinOp");
4276     case AtomicRMWInst::Xchg:
4277       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
4278     case AtomicRMWInst::Add:
4279       return Intrinsic::riscv_masked_atomicrmw_add_i64;
4280     case AtomicRMWInst::Sub:
4281       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
4282     case AtomicRMWInst::Nand:
4283       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
4284     case AtomicRMWInst::Max:
4285       return Intrinsic::riscv_masked_atomicrmw_max_i64;
4286     case AtomicRMWInst::Min:
4287       return Intrinsic::riscv_masked_atomicrmw_min_i64;
4288     case AtomicRMWInst::UMax:
4289       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
4290     case AtomicRMWInst::UMin:
4291       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
4292     }
4293   }
4294 
4295   llvm_unreachable("Unexpected XLen\n");
4296 }
4297 
4298 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
4299     IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
4300     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
4301   unsigned XLen = Subtarget.getXLen();
4302   Value *Ordering =
4303       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
4304   Type *Tys[] = {AlignedAddr->getType()};
4305   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
4306       AI->getModule(),
4307       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
4308 
4309   if (XLen == 64) {
4310     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
4311     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
4312     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
4313   }
4314 
4315   Value *Result;
4316 
4317   // Must pass the shift amount needed to sign extend the loaded value prior
4318   // to performing a signed comparison for min/max. ShiftAmt is the number of
4319   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
4320   // is the number of bits to left+right shift the value in order to
4321   // sign-extend.
4322   if (AI->getOperation() == AtomicRMWInst::Min ||
4323       AI->getOperation() == AtomicRMWInst::Max) {
4324     const DataLayout &DL = AI->getModule()->getDataLayout();
4325     unsigned ValWidth =
4326         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
4327     Value *SextShamt =
4328         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
4329     Result = Builder.CreateCall(LrwOpScwLoop,
4330                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
4331   } else {
4332     Result =
4333         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
4334   }
4335 
4336   if (XLen == 64)
4337     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
4338   return Result;
4339 }
4340 
4341 TargetLowering::AtomicExpansionKind
4342 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
4343     AtomicCmpXchgInst *CI) const {
4344   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
4345   if (Size == 8 || Size == 16)
4346     return AtomicExpansionKind::MaskedIntrinsic;
4347   return AtomicExpansionKind::None;
4348 }
4349 
4350 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
4351     IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
4352     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
4353   unsigned XLen = Subtarget.getXLen();
4354   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
4355   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
4356   if (XLen == 64) {
4357     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
4358     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
4359     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
4360     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
4361   }
4362   Type *Tys[] = {AlignedAddr->getType()};
4363   Function *MaskedCmpXchg =
4364       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
4365   Value *Result = Builder.CreateCall(
4366       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
4367   if (XLen == 64)
4368     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
4369   return Result;
4370 }
4371 
4372 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4373                                                      EVT VT) const {
4374   VT = VT.getScalarType();
4375 
4376   if (!VT.isSimple())
4377     return false;
4378 
4379   switch (VT.getSimpleVT().SimpleTy) {
4380   case MVT::f16:
4381     return Subtarget.hasStdExtZfh();
4382   case MVT::f32:
4383     return Subtarget.hasStdExtF();
4384   case MVT::f64:
4385     return Subtarget.hasStdExtD();
4386   default:
4387     break;
4388   }
4389 
4390   return false;
4391 }
4392 
4393 Register RISCVTargetLowering::getExceptionPointerRegister(
4394     const Constant *PersonalityFn) const {
4395   return RISCV::X10;
4396 }
4397 
4398 Register RISCVTargetLowering::getExceptionSelectorRegister(
4399     const Constant *PersonalityFn) const {
4400   return RISCV::X11;
4401 }
4402 
4403 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
4404   // Return false to suppress the unnecessary extensions if the LibCall
4405   // arguments or return value is f32 type for LP64 ABI.
4406   RISCVABI::ABI ABI = Subtarget.getTargetABI();
4407   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
4408     return false;
4409 
4410   return true;
4411 }
4412 
4413 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
4414   if (Subtarget.is64Bit() && Type == MVT::i32)
4415     return true;
4416 
4417   return IsSigned;
4418 }
4419 
4420 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
4421                                                  SDValue C) const {
4422   // Check integral scalar types.
4423   if (VT.isScalarInteger()) {
4424     // Omit the optimization if the sub target has the M extension and the data
4425     // size exceeds XLen.
4426     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
4427       return false;
4428     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
4429       // Break the MUL to a SLLI and an ADD/SUB.
4430       const APInt &Imm = ConstNode->getAPIntValue();
4431       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
4432           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
4433         return true;
4434       // Omit the following optimization if the sub target has the M extension
4435       // and the data size >= XLen.
4436       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
4437         return false;
4438       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
4439       // a pair of LUI/ADDI.
4440       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
4441         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
4442         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
4443             (1 - ImmS).isPowerOf2())
4444         return true;
4445       }
4446     }
4447   }
4448 
4449   return false;
4450 }
4451 
4452 #define GET_REGISTER_MATCHER
4453 #include "RISCVGenAsmMatcher.inc"
4454 
4455 Register
4456 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
4457                                        const MachineFunction &MF) const {
4458   Register Reg = MatchRegisterAltName(RegName);
4459   if (Reg == RISCV::NoRegister)
4460     Reg = MatchRegisterName(RegName);
4461   if (Reg == RISCV::NoRegister)
4462     report_fatal_error(
4463         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
4464   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
4465   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
4466     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
4467                              StringRef(RegName) + "\"."));
4468   return Reg;
4469 }
4470 
4471 namespace llvm {
4472 namespace RISCVVIntrinsicsTable {
4473 
4474 #define GET_RISCVVIntrinsicsTable_IMPL
4475 #include "RISCVGenSearchableTables.inc"
4476 
4477 } // namespace RISCVVIntrinsicsTable
4478 
4479 namespace RISCVZvlssegTable {
4480 
4481 #define GET_RISCVZvlssegTable_IMPL
4482 #include "RISCVGenSearchableTables.inc"
4483 
4484 } // namespace RISCVZvlssegTable
4485 } // namespace llvm
4486