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