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     if (Subtarget.useRVVForFixedLengthVectors()) {
145       auto addRegClassForFixedVectors = [this](MVT VT) {
146         unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT);
147         const TargetRegisterClass *RC;
148         if (LMul == 1 || VT.getVectorElementType() == MVT::i1)
149           RC = &RISCV::VRRegClass;
150         else if (LMul == 2)
151           RC = &RISCV::VRM2RegClass;
152         else if (LMul == 4)
153           RC = &RISCV::VRM4RegClass;
154         else if (LMul == 8)
155           RC = &RISCV::VRM8RegClass;
156         else
157           llvm_unreachable("Unexpected LMul!");
158 
159         addRegisterClass(VT, RC);
160       };
161       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
162         if (useRVVForFixedLengthVectorVT(VT))
163           addRegClassForFixedVectors(VT);
164 
165       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
166         if (useRVVForFixedLengthVectorVT(VT))
167           addRegClassForFixedVectors(VT);
168     }
169   }
170 
171   // Compute derived properties from the register classes.
172   computeRegisterProperties(STI.getRegisterInfo());
173 
174   setStackPointerRegisterToSaveRestore(RISCV::X2);
175 
176   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
177     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
178 
179   // TODO: add all necessary setOperationAction calls.
180   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
181 
182   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
183   setOperationAction(ISD::BR_CC, XLenVT, Expand);
184   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
185   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
186 
187   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
188   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
189 
190   setOperationAction(ISD::VASTART, MVT::Other, Custom);
191   setOperationAction(ISD::VAARG, MVT::Other, Expand);
192   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
193   setOperationAction(ISD::VAEND, MVT::Other, Expand);
194 
195   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
196   if (!Subtarget.hasStdExtZbb()) {
197     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
198     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
199   }
200 
201   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit())
202     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
203 
204   if (Subtarget.is64Bit()) {
205     setOperationAction(ISD::ADD, MVT::i32, Custom);
206     setOperationAction(ISD::SUB, MVT::i32, Custom);
207     setOperationAction(ISD::SHL, MVT::i32, Custom);
208     setOperationAction(ISD::SRA, MVT::i32, Custom);
209     setOperationAction(ISD::SRL, MVT::i32, Custom);
210 
211     setOperationAction(ISD::UADDO, MVT::i32, Custom);
212     setOperationAction(ISD::USUBO, MVT::i32, Custom);
213     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
214     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
215   }
216 
217   if (!Subtarget.hasStdExtM()) {
218     setOperationAction(ISD::MUL, XLenVT, Expand);
219     setOperationAction(ISD::MULHS, XLenVT, Expand);
220     setOperationAction(ISD::MULHU, XLenVT, Expand);
221     setOperationAction(ISD::SDIV, XLenVT, Expand);
222     setOperationAction(ISD::UDIV, XLenVT, Expand);
223     setOperationAction(ISD::SREM, XLenVT, Expand);
224     setOperationAction(ISD::UREM, XLenVT, Expand);
225   } else {
226     if (Subtarget.is64Bit()) {
227       setOperationAction(ISD::MUL, MVT::i32, Custom);
228       setOperationAction(ISD::MUL, MVT::i128, Custom);
229 
230       setOperationAction(ISD::SDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UDIV, MVT::i8, Custom);
232       setOperationAction(ISD::UREM, MVT::i8, Custom);
233       setOperationAction(ISD::SDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UDIV, MVT::i16, Custom);
235       setOperationAction(ISD::UREM, MVT::i16, Custom);
236       setOperationAction(ISD::SDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UDIV, MVT::i32, Custom);
238       setOperationAction(ISD::UREM, MVT::i32, Custom);
239     } else {
240       setOperationAction(ISD::MUL, MVT::i64, Custom);
241     }
242   }
243 
244   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
246   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
247   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
248 
249   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
251   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
252 
253   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
254     if (Subtarget.is64Bit()) {
255       setOperationAction(ISD::ROTL, MVT::i32, Custom);
256       setOperationAction(ISD::ROTR, MVT::i32, Custom);
257     }
258   } else {
259     setOperationAction(ISD::ROTL, XLenVT, Expand);
260     setOperationAction(ISD::ROTR, XLenVT, Expand);
261   }
262 
263   if (Subtarget.hasStdExtZbp()) {
264     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
265     // more combining.
266     setOperationAction(ISD::BITREVERSE, XLenVT, Custom);
267     setOperationAction(ISD::BSWAP, XLenVT, Custom);
268 
269     if (Subtarget.is64Bit()) {
270       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
271       setOperationAction(ISD::BSWAP, MVT::i32, Custom);
272     }
273   } else {
274     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
275     // pattern match it directly in isel.
276     setOperationAction(ISD::BSWAP, XLenVT,
277                        Subtarget.hasStdExtZbb() ? Legal : Expand);
278   }
279 
280   if (Subtarget.hasStdExtZbb()) {
281     setOperationAction(ISD::SMIN, XLenVT, Legal);
282     setOperationAction(ISD::SMAX, XLenVT, Legal);
283     setOperationAction(ISD::UMIN, XLenVT, Legal);
284     setOperationAction(ISD::UMAX, XLenVT, Legal);
285 
286     if (Subtarget.is64Bit()) {
287       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
288       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
289       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
290       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
291     }
292   } else {
293     setOperationAction(ISD::CTTZ, XLenVT, Expand);
294     setOperationAction(ISD::CTLZ, XLenVT, Expand);
295     setOperationAction(ISD::CTPOP, XLenVT, Expand);
296   }
297 
298   if (Subtarget.hasStdExtZbt()) {
299     setOperationAction(ISD::FSHL, XLenVT, Custom);
300     setOperationAction(ISD::FSHR, XLenVT, Custom);
301     setOperationAction(ISD::SELECT, XLenVT, Legal);
302 
303     if (Subtarget.is64Bit()) {
304       setOperationAction(ISD::FSHL, MVT::i32, Custom);
305       setOperationAction(ISD::FSHR, MVT::i32, Custom);
306     }
307   } else {
308     setOperationAction(ISD::SELECT, XLenVT, Custom);
309   }
310 
311   ISD::CondCode FPCCToExpand[] = {
312       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
313       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
314       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
315 
316   ISD::NodeType FPOpToExpand[] = {
317       ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP,
318       ISD::FP_TO_FP16};
319 
320   if (Subtarget.hasStdExtZfh())
321     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
322 
323   if (Subtarget.hasStdExtZfh()) {
324     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
325     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
326     for (auto CC : FPCCToExpand)
327       setCondCodeAction(CC, MVT::f16, Expand);
328     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
329     setOperationAction(ISD::SELECT, MVT::f16, Custom);
330     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
331     for (auto Op : FPOpToExpand)
332       setOperationAction(Op, MVT::f16, Expand);
333   }
334 
335   if (Subtarget.hasStdExtF()) {
336     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
337     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
338     for (auto CC : FPCCToExpand)
339       setCondCodeAction(CC, MVT::f32, Expand);
340     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
341     setOperationAction(ISD::SELECT, MVT::f32, Custom);
342     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
343     for (auto Op : FPOpToExpand)
344       setOperationAction(Op, MVT::f32, Expand);
345     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
346     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
347   }
348 
349   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
350     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
351 
352   if (Subtarget.hasStdExtD()) {
353     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
354     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
355     for (auto CC : FPCCToExpand)
356       setCondCodeAction(CC, MVT::f64, Expand);
357     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
358     setOperationAction(ISD::SELECT, MVT::f64, Custom);
359     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
360     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
361     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
362     for (auto Op : FPOpToExpand)
363       setOperationAction(Op, MVT::f64, Expand);
364     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
365     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
366   }
367 
368   if (Subtarget.is64Bit()) {
369     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
370     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
371     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
372     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
373   }
374 
375   if (Subtarget.hasStdExtF()) {
376     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
377     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
378   }
379 
380   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
381   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
382   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
383   setOperationAction(ISD::JumpTable, XLenVT, Custom);
384 
385   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
386 
387   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
388   // Unfortunately this can't be determined just from the ISA naming string.
389   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
390                      Subtarget.is64Bit() ? Legal : Custom);
391 
392   setOperationAction(ISD::TRAP, MVT::Other, Legal);
393   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
394   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
395 
396   if (Subtarget.hasStdExtA()) {
397     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
398     setMinCmpXchgSizeInBits(32);
399   } else {
400     setMaxAtomicSizeInBitsSupported(0);
401   }
402 
403   setBooleanContents(ZeroOrOneBooleanContent);
404 
405   if (Subtarget.hasStdExtV()) {
406     setBooleanVectorContents(ZeroOrOneBooleanContent);
407 
408     setOperationAction(ISD::VSCALE, XLenVT, Custom);
409 
410     // RVV intrinsics may have illegal operands.
411     // We also need to custom legalize vmv.x.s.
412     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
413     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
414     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
415     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
416     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
417     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
418     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
419     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
420 
421     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
422 
423     if (!Subtarget.is64Bit()) {
424       // We must custom-lower certain vXi64 operations on RV32 due to the vector
425       // element type being illegal.
426       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
427       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
428 
429       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
430       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
431       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
432       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
433       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
434       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
435       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
436       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
437     }
438 
439     for (MVT VT : BoolVecVTs) {
440       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
441 
442       // Mask VTs are custom-expanded into a series of standard nodes
443       setOperationAction(ISD::TRUNCATE, VT, Custom);
444       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
445       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
446 
447       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
448 
449       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
450       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
451       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
452 
453       // Expand all extending loads to types larger than this, and truncating
454       // stores from types larger than this.
455       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
456         setTruncStoreAction(OtherVT, VT, Expand);
457         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
458         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
459         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
460       }
461     }
462 
463     for (MVT VT : IntVecVTs) {
464       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
465       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
466 
467       setOperationAction(ISD::SMIN, VT, Legal);
468       setOperationAction(ISD::SMAX, VT, Legal);
469       setOperationAction(ISD::UMIN, VT, Legal);
470       setOperationAction(ISD::UMAX, VT, Legal);
471 
472       setOperationAction(ISD::ROTL, VT, Expand);
473       setOperationAction(ISD::ROTR, VT, Expand);
474 
475       // Custom-lower extensions and truncations from/to mask types.
476       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
477       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
478       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
479 
480       // RVV has native int->float & float->int conversions where the
481       // element type sizes are within one power-of-two of each other. Any
482       // wider distances between type sizes have to be lowered as sequences
483       // which progressively narrow the gap in stages.
484       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
485       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
486       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
487       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
488 
489       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
490       // nodes which truncate by one power of two at a time.
491       setOperationAction(ISD::TRUNCATE, VT, Custom);
492 
493       // Custom-lower insert/extract operations to simplify patterns.
494       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
495       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
496 
497       // Custom-lower reduction operations to set up the corresponding custom
498       // nodes' operands.
499       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
500       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
501       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
502       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
503       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
504       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
505       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
506       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
507 
508       setOperationAction(ISD::MLOAD, VT, Custom);
509       setOperationAction(ISD::MSTORE, VT, Custom);
510       setOperationAction(ISD::MGATHER, VT, Custom);
511       setOperationAction(ISD::MSCATTER, VT, Custom);
512 
513       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
514       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
515       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
516 
517       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
518       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
519 
520       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
521         setTruncStoreAction(VT, OtherVT, Expand);
522         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
523         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
524         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
525       }
526     }
527 
528     // Expand various CCs to best match the RVV ISA, which natively supports UNE
529     // but no other unordered comparisons, and supports all ordered comparisons
530     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
531     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
532     // and we pattern-match those back to the "original", swapping operands once
533     // more. This way we catch both operations and both "vf" and "fv" forms with
534     // fewer patterns.
535     ISD::CondCode VFPCCToExpand[] = {
536         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
537         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
538         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
539     };
540 
541     // Sets common operation actions on RVV floating-point vector types.
542     const auto SetCommonVFPActions = [&](MVT VT) {
543       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
544       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
545       // sizes are within one power-of-two of each other. Therefore conversions
546       // between vXf16 and vXf64 must be lowered as sequences which convert via
547       // vXf32.
548       setOperationAction(ISD::FP_ROUND, VT, Custom);
549       setOperationAction(ISD::FP_EXTEND, VT, Custom);
550       // Custom-lower insert/extract operations to simplify patterns.
551       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
552       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
553       // Expand various condition codes (explained above).
554       for (auto CC : VFPCCToExpand)
555         setCondCodeAction(CC, VT, Expand);
556 
557       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
558       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
559       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
560 
561       setOperationAction(ISD::MLOAD, VT, Custom);
562       setOperationAction(ISD::MSTORE, VT, Custom);
563       setOperationAction(ISD::MGATHER, VT, Custom);
564       setOperationAction(ISD::MSCATTER, VT, Custom);
565 
566       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
567       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
568       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
569 
570       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
571     };
572 
573     // Sets common extload/truncstore actions on RVV floating-point vector
574     // types.
575     const auto SetCommonVFPExtLoadTruncStoreActions =
576         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
577           for (auto SmallVT : SmallerVTs) {
578             setTruncStoreAction(VT, SmallVT, Expand);
579             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
580           }
581         };
582 
583     if (Subtarget.hasStdExtZfh())
584       for (MVT VT : F16VecVTs)
585         SetCommonVFPActions(VT);
586 
587     for (MVT VT : F32VecVTs) {
588       if (Subtarget.hasStdExtF())
589         SetCommonVFPActions(VT);
590       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
591     }
592 
593     for (MVT VT : F64VecVTs) {
594       if (Subtarget.hasStdExtD())
595         SetCommonVFPActions(VT);
596       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
597       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
598     }
599 
600     if (Subtarget.useRVVForFixedLengthVectors()) {
601       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
602         if (!useRVVForFixedLengthVectorVT(VT))
603           continue;
604 
605         // By default everything must be expanded.
606         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
607           setOperationAction(Op, VT, Expand);
608         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
609           setTruncStoreAction(VT, OtherVT, Expand);
610           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
611           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
612           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
613         }
614 
615         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
616         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
617         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
618 
619         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
620         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
621 
622         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
623 
624         setOperationAction(ISD::LOAD, VT, Custom);
625         setOperationAction(ISD::STORE, VT, Custom);
626 
627         setOperationAction(ISD::SETCC, VT, Custom);
628 
629         setOperationAction(ISD::TRUNCATE, VT, Custom);
630 
631         setOperationAction(ISD::BITCAST, VT, Custom);
632 
633         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
634         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
635         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
636 
637         // Operations below are different for between masks and other vectors.
638         if (VT.getVectorElementType() == MVT::i1) {
639           setOperationAction(ISD::AND, VT, Custom);
640           setOperationAction(ISD::OR, VT, Custom);
641           setOperationAction(ISD::XOR, VT, Custom);
642           continue;
643         }
644 
645         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
646         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
647 
648         setOperationAction(ISD::MLOAD, VT, Custom);
649         setOperationAction(ISD::MSTORE, VT, Custom);
650         setOperationAction(ISD::MGATHER, VT, Custom);
651         setOperationAction(ISD::MSCATTER, VT, Custom);
652         setOperationAction(ISD::ADD, VT, Custom);
653         setOperationAction(ISD::MUL, VT, Custom);
654         setOperationAction(ISD::SUB, VT, Custom);
655         setOperationAction(ISD::AND, VT, Custom);
656         setOperationAction(ISD::OR, VT, Custom);
657         setOperationAction(ISD::XOR, VT, Custom);
658         setOperationAction(ISD::SDIV, VT, Custom);
659         setOperationAction(ISD::SREM, VT, Custom);
660         setOperationAction(ISD::UDIV, VT, Custom);
661         setOperationAction(ISD::UREM, VT, Custom);
662         setOperationAction(ISD::SHL, VT, Custom);
663         setOperationAction(ISD::SRA, VT, Custom);
664         setOperationAction(ISD::SRL, VT, Custom);
665 
666         setOperationAction(ISD::SMIN, VT, Custom);
667         setOperationAction(ISD::SMAX, VT, Custom);
668         setOperationAction(ISD::UMIN, VT, Custom);
669         setOperationAction(ISD::UMAX, VT, Custom);
670         setOperationAction(ISD::ABS,  VT, Custom);
671 
672         setOperationAction(ISD::MULHS, VT, Custom);
673         setOperationAction(ISD::MULHU, VT, Custom);
674 
675         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
676         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
677         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
678         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
679 
680         setOperationAction(ISD::VSELECT, VT, Custom);
681 
682         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
683         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
684         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
685 
686         // Custom-lower reduction operations to set up the corresponding custom
687         // nodes' operands.
688         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
689         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
690         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
691         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
692         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
693       }
694 
695       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
696         if (!useRVVForFixedLengthVectorVT(VT))
697           continue;
698 
699         // By default everything must be expanded.
700         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
701           setOperationAction(Op, VT, Expand);
702         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
703           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
704           setTruncStoreAction(VT, OtherVT, Expand);
705         }
706 
707         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
708         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
709         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
710 
711         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
712         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
713         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
714         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
715 
716         setOperationAction(ISD::LOAD, VT, Custom);
717         setOperationAction(ISD::STORE, VT, Custom);
718         setOperationAction(ISD::MLOAD, VT, Custom);
719         setOperationAction(ISD::MSTORE, VT, Custom);
720         setOperationAction(ISD::MGATHER, VT, Custom);
721         setOperationAction(ISD::MSCATTER, VT, Custom);
722         setOperationAction(ISD::FADD, VT, Custom);
723         setOperationAction(ISD::FSUB, VT, Custom);
724         setOperationAction(ISD::FMUL, VT, Custom);
725         setOperationAction(ISD::FDIV, VT, Custom);
726         setOperationAction(ISD::FNEG, VT, Custom);
727         setOperationAction(ISD::FABS, VT, Custom);
728         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
729         setOperationAction(ISD::FSQRT, VT, Custom);
730         setOperationAction(ISD::FMA, VT, Custom);
731 
732         setOperationAction(ISD::FP_ROUND, VT, Custom);
733         setOperationAction(ISD::FP_EXTEND, VT, Custom);
734 
735         for (auto CC : VFPCCToExpand)
736           setCondCodeAction(CC, VT, Expand);
737 
738         setOperationAction(ISD::VSELECT, VT, Custom);
739 
740         setOperationAction(ISD::BITCAST, VT, Custom);
741 
742         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
743         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
744       }
745 
746       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
747       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
748       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
749       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
750       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
751       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
752       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
753       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
754     }
755   }
756 
757   // Function alignments.
758   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
759   setMinFunctionAlignment(FunctionAlignment);
760   setPrefFunctionAlignment(FunctionAlignment);
761 
762   setMinimumJumpTableEntries(5);
763 
764   // Jumps are expensive, compared to logic
765   setJumpIsExpensive();
766 
767   // We can use any register for comparisons
768   setHasMultipleConditionRegisters();
769 
770   if (Subtarget.hasStdExtZbp()) {
771     setTargetDAGCombine(ISD::OR);
772   }
773   if (Subtarget.hasStdExtV()) {
774     setTargetDAGCombine(ISD::FCOPYSIGN);
775     setTargetDAGCombine(ISD::MGATHER);
776     setTargetDAGCombine(ISD::MSCATTER);
777   }
778 }
779 
780 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
781                                             LLVMContext &Context,
782                                             EVT VT) const {
783   if (!VT.isVector())
784     return getPointerTy(DL);
785   if (Subtarget.hasStdExtV() &&
786       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
787     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
788   return VT.changeVectorElementTypeToInteger();
789 }
790 
791 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
792                                              const CallInst &I,
793                                              MachineFunction &MF,
794                                              unsigned Intrinsic) const {
795   switch (Intrinsic) {
796   default:
797     return false;
798   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
799   case Intrinsic::riscv_masked_atomicrmw_add_i32:
800   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
801   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
802   case Intrinsic::riscv_masked_atomicrmw_max_i32:
803   case Intrinsic::riscv_masked_atomicrmw_min_i32:
804   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
805   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
806   case Intrinsic::riscv_masked_cmpxchg_i32:
807     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
808     Info.opc = ISD::INTRINSIC_W_CHAIN;
809     Info.memVT = MVT::getVT(PtrTy->getElementType());
810     Info.ptrVal = I.getArgOperand(0);
811     Info.offset = 0;
812     Info.align = Align(4);
813     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
814                  MachineMemOperand::MOVolatile;
815     return true;
816   }
817 }
818 
819 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
820                                                 const AddrMode &AM, Type *Ty,
821                                                 unsigned AS,
822                                                 Instruction *I) const {
823   // No global is ever allowed as a base.
824   if (AM.BaseGV)
825     return false;
826 
827   // Require a 12-bit signed offset.
828   if (!isInt<12>(AM.BaseOffs))
829     return false;
830 
831   switch (AM.Scale) {
832   case 0: // "r+i" or just "i", depending on HasBaseReg.
833     break;
834   case 1:
835     if (!AM.HasBaseReg) // allow "r+i".
836       break;
837     return false; // disallow "r+r" or "r+r+i".
838   default:
839     return false;
840   }
841 
842   return true;
843 }
844 
845 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
846   return isInt<12>(Imm);
847 }
848 
849 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
850   return isInt<12>(Imm);
851 }
852 
853 // On RV32, 64-bit integers are split into their high and low parts and held
854 // in two different registers, so the trunc is free since the low register can
855 // just be used.
856 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
857   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
858     return false;
859   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
860   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
861   return (SrcBits == 64 && DestBits == 32);
862 }
863 
864 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
865   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
866       !SrcVT.isInteger() || !DstVT.isInteger())
867     return false;
868   unsigned SrcBits = SrcVT.getSizeInBits();
869   unsigned DestBits = DstVT.getSizeInBits();
870   return (SrcBits == 64 && DestBits == 32);
871 }
872 
873 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
874   // Zexts are free if they can be combined with a load.
875   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
876     EVT MemVT = LD->getMemoryVT();
877     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
878          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
879         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
880          LD->getExtensionType() == ISD::ZEXTLOAD))
881       return true;
882   }
883 
884   return TargetLowering::isZExtFree(Val, VT2);
885 }
886 
887 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
888   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
889 }
890 
891 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
892   return Subtarget.hasStdExtZbb();
893 }
894 
895 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
896   return Subtarget.hasStdExtZbb();
897 }
898 
899 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
900                                        bool ForCodeSize) const {
901   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
902     return false;
903   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
904     return false;
905   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
906     return false;
907   if (Imm.isNegZero())
908     return false;
909   return Imm.isZero();
910 }
911 
912 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
913   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
914          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
915          (VT == MVT::f64 && Subtarget.hasStdExtD());
916 }
917 
918 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
919                                                       CallingConv::ID CC,
920                                                       EVT VT) const {
921   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
922   // end up using a GPR but that will be decided based on ABI.
923   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
924     return MVT::f32;
925 
926   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
927 }
928 
929 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
930                                                            CallingConv::ID CC,
931                                                            EVT VT) const {
932   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
933   // end up using a GPR but that will be decided based on ABI.
934   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
935     return 1;
936 
937   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
938 }
939 
940 // Changes the condition code and swaps operands if necessary, so the SetCC
941 // operation matches one of the comparisons supported directly by branches
942 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
943 // with 1/-1.
944 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
945                                     ISD::CondCode &CC, SelectionDAG &DAG) {
946   // Convert X > -1 to X >= 0.
947   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
948     RHS = DAG.getConstant(0, DL, RHS.getValueType());
949     CC = ISD::SETGE;
950     return;
951   }
952   // Convert X < 1 to 0 >= X.
953   if (CC == ISD::SETLT && isOneConstant(RHS)) {
954     RHS = LHS;
955     LHS = DAG.getConstant(0, DL, RHS.getValueType());
956     CC = ISD::SETGE;
957     return;
958   }
959 
960   switch (CC) {
961   default:
962     break;
963   case ISD::SETGT:
964   case ISD::SETLE:
965   case ISD::SETUGT:
966   case ISD::SETULE:
967     CC = ISD::getSetCCSwappedOperands(CC);
968     std::swap(LHS, RHS);
969     break;
970   }
971 }
972 
973 // Return the RISC-V branch opcode that matches the given DAG integer
974 // condition code. The CondCode must be one of those supported by the RISC-V
975 // ISA (see translateSetCCForBranch).
976 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) {
977   switch (CC) {
978   default:
979     llvm_unreachable("Unsupported CondCode");
980   case ISD::SETEQ:
981     return RISCV::BEQ;
982   case ISD::SETNE:
983     return RISCV::BNE;
984   case ISD::SETLT:
985     return RISCV::BLT;
986   case ISD::SETGE:
987     return RISCV::BGE;
988   case ISD::SETULT:
989     return RISCV::BLTU;
990   case ISD::SETUGE:
991     return RISCV::BGEU;
992   }
993 }
994 
995 RISCVVLMUL RISCVTargetLowering::getLMUL(MVT VT) {
996   assert(VT.isScalableVector() && "Expecting a scalable vector type");
997   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
998   if (VT.getVectorElementType() == MVT::i1)
999     KnownSize *= 8;
1000 
1001   switch (KnownSize) {
1002   default:
1003     llvm_unreachable("Invalid LMUL.");
1004   case 8:
1005     return RISCVVLMUL::LMUL_F8;
1006   case 16:
1007     return RISCVVLMUL::LMUL_F4;
1008   case 32:
1009     return RISCVVLMUL::LMUL_F2;
1010   case 64:
1011     return RISCVVLMUL::LMUL_1;
1012   case 128:
1013     return RISCVVLMUL::LMUL_2;
1014   case 256:
1015     return RISCVVLMUL::LMUL_4;
1016   case 512:
1017     return RISCVVLMUL::LMUL_8;
1018   }
1019 }
1020 
1021 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVVLMUL LMul) {
1022   switch (LMul) {
1023   default:
1024     llvm_unreachable("Invalid LMUL.");
1025   case RISCVVLMUL::LMUL_F8:
1026   case RISCVVLMUL::LMUL_F4:
1027   case RISCVVLMUL::LMUL_F2:
1028   case RISCVVLMUL::LMUL_1:
1029     return RISCV::VRRegClassID;
1030   case RISCVVLMUL::LMUL_2:
1031     return RISCV::VRM2RegClassID;
1032   case RISCVVLMUL::LMUL_4:
1033     return RISCV::VRM4RegClassID;
1034   case RISCVVLMUL::LMUL_8:
1035     return RISCV::VRM8RegClassID;
1036   }
1037 }
1038 
1039 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1040   RISCVVLMUL LMUL = getLMUL(VT);
1041   if (LMUL == RISCVVLMUL::LMUL_F8 || LMUL == RISCVVLMUL::LMUL_F4 ||
1042       LMUL == RISCVVLMUL::LMUL_F2 || LMUL == RISCVVLMUL::LMUL_1) {
1043     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1044                   "Unexpected subreg numbering");
1045     return RISCV::sub_vrm1_0 + Index;
1046   }
1047   if (LMUL == RISCVVLMUL::LMUL_2) {
1048     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1049                   "Unexpected subreg numbering");
1050     return RISCV::sub_vrm2_0 + Index;
1051   }
1052   if (LMUL == RISCVVLMUL::LMUL_4) {
1053     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1054                   "Unexpected subreg numbering");
1055     return RISCV::sub_vrm4_0 + Index;
1056   }
1057   llvm_unreachable("Invalid vector type.");
1058 }
1059 
1060 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1061   if (VT.getVectorElementType() == MVT::i1)
1062     return RISCV::VRRegClassID;
1063   return getRegClassIDForLMUL(getLMUL(VT));
1064 }
1065 
1066 // Attempt to decompose a subvector insert/extract between VecVT and
1067 // SubVecVT via subregister indices. Returns the subregister index that
1068 // can perform the subvector insert/extract with the given element index, as
1069 // well as the index corresponding to any leftover subvectors that must be
1070 // further inserted/extracted within the register class for SubVecVT.
1071 std::pair<unsigned, unsigned>
1072 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1073     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1074     const RISCVRegisterInfo *TRI) {
1075   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1076                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1077                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1078                 "Register classes not ordered");
1079   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1080   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1081   // Try to compose a subregister index that takes us from the incoming
1082   // LMUL>1 register class down to the outgoing one. At each step we half
1083   // the LMUL:
1084   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1085   // Note that this is not guaranteed to find a subregister index, such as
1086   // when we are extracting from one VR type to another.
1087   unsigned SubRegIdx = RISCV::NoSubRegister;
1088   for (const unsigned RCID :
1089        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1090     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1091       VecVT = VecVT.getHalfNumVectorElementsVT();
1092       bool IsHi =
1093           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1094       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1095                                             getSubregIndexByMVT(VecVT, IsHi));
1096       if (IsHi)
1097         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1098     }
1099   return {SubRegIdx, InsertExtractIdx};
1100 }
1101 
1102 // Return the largest legal scalable vector type that matches VT's element type.
1103 MVT RISCVTargetLowering::getContainerForFixedLengthVector(
1104     const TargetLowering &TLI, MVT VT, const RISCVSubtarget &Subtarget) {
1105   assert(VT.isFixedLengthVector() && TLI.isTypeLegal(VT) &&
1106          "Expected legal fixed length vector!");
1107 
1108   unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT);
1109   assert(LMul <= 8 && isPowerOf2_32(LMul) && "Unexpected LMUL!");
1110 
1111   MVT EltVT = VT.getVectorElementType();
1112   switch (EltVT.SimpleTy) {
1113   default:
1114     llvm_unreachable("unexpected element type for RVV container");
1115   case MVT::i1: {
1116     // Masks are calculated assuming 8-bit elements since that's when we need
1117     // the most elements.
1118     unsigned EltsPerBlock = RISCV::RVVBitsPerBlock / 8;
1119     return MVT::getScalableVectorVT(MVT::i1, LMul * EltsPerBlock);
1120   }
1121   case MVT::i8:
1122   case MVT::i16:
1123   case MVT::i32:
1124   case MVT::i64:
1125   case MVT::f16:
1126   case MVT::f32:
1127   case MVT::f64: {
1128     unsigned EltsPerBlock = RISCV::RVVBitsPerBlock / EltVT.getSizeInBits();
1129     return MVT::getScalableVectorVT(EltVT, LMul * EltsPerBlock);
1130   }
1131   }
1132 }
1133 
1134 MVT RISCVTargetLowering::getContainerForFixedLengthVector(
1135     SelectionDAG &DAG, MVT VT, const RISCVSubtarget &Subtarget) {
1136   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1137                                           Subtarget);
1138 }
1139 
1140 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1141   return getContainerForFixedLengthVector(*this, VT, getSubtarget());
1142 }
1143 
1144 // Grow V to consume an entire RVV register.
1145 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1146                                        const RISCVSubtarget &Subtarget) {
1147   assert(VT.isScalableVector() &&
1148          "Expected to convert into a scalable vector!");
1149   assert(V.getValueType().isFixedLengthVector() &&
1150          "Expected a fixed length vector operand!");
1151   SDLoc DL(V);
1152   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1153   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1154 }
1155 
1156 // Shrink V so it's just big enough to maintain a VT's worth of data.
1157 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1158                                          const RISCVSubtarget &Subtarget) {
1159   assert(VT.isFixedLengthVector() &&
1160          "Expected to convert into a fixed length vector!");
1161   assert(V.getValueType().isScalableVector() &&
1162          "Expected a scalable vector operand!");
1163   SDLoc DL(V);
1164   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1165   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1166 }
1167 
1168 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1169 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1170 // the vector type that it is contained in.
1171 static std::pair<SDValue, SDValue>
1172 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1173                 const RISCVSubtarget &Subtarget) {
1174   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1175   MVT XLenVT = Subtarget.getXLenVT();
1176   SDValue VL = VecVT.isFixedLengthVector()
1177                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1178                    : DAG.getRegister(RISCV::X0, XLenVT);
1179   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1180   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1181   return {Mask, VL};
1182 }
1183 
1184 // As above but assuming the given type is a scalable vector type.
1185 static std::pair<SDValue, SDValue>
1186 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1187                         const RISCVSubtarget &Subtarget) {
1188   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1189   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1190 }
1191 
1192 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1193 // of either is (currently) supported. This can get us into an infinite loop
1194 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1195 // as a ..., etc.
1196 // Until either (or both) of these can reliably lower any node, reporting that
1197 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1198 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1199 // which is not desirable.
1200 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1201     EVT VT, unsigned DefinedValues) const {
1202   return false;
1203 }
1204 
1205 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1206   // Only splats are currently supported.
1207   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1208     return true;
1209 
1210   return false;
1211 }
1212 
1213 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1214                                  const RISCVSubtarget &Subtarget) {
1215   MVT VT = Op.getSimpleValueType();
1216   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1217 
1218   MVT ContainerVT =
1219       RISCVTargetLowering::getContainerForFixedLengthVector(DAG, VT, Subtarget);
1220 
1221   SDLoc DL(Op);
1222   SDValue Mask, VL;
1223   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1224 
1225   MVT XLenVT = Subtarget.getXLenVT();
1226   unsigned NumElts = Op.getNumOperands();
1227 
1228   if (VT.getVectorElementType() == MVT::i1) {
1229     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1230       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1231       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1232     }
1233 
1234     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1235       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1236       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1237     }
1238 
1239     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1240     // scalar integer chunks whose bit-width depends on the number of mask
1241     // bits and XLEN.
1242     // First, determine the most appropriate scalar integer type to use. This
1243     // is at most XLenVT, but may be shrunk to a smaller vector element type
1244     // according to the size of the final vector - use i8 chunks rather than
1245     // XLenVT if we're producing a v8i1. This results in more consistent
1246     // codegen across RV32 and RV64.
1247     // If we have to use more than one INSERT_VECTOR_ELT then this optimization
1248     // is likely to increase code size; avoid peforming it in such a case.
1249     unsigned NumViaIntegerBits =
1250         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1251     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
1252         (!DAG.shouldOptForSize() || NumElts <= NumViaIntegerBits)) {
1253       // Now we can create our integer vector type. Note that it may be larger
1254       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1255       MVT IntegerViaVecVT =
1256           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1257                            divideCeil(NumElts, NumViaIntegerBits));
1258 
1259       uint64_t Bits = 0;
1260       unsigned BitPos = 0, IntegerEltIdx = 0;
1261       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1262 
1263       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1264         // Once we accumulate enough bits to fill our scalar type, insert into
1265         // our vector and clear our accumulated data.
1266         if (I != 0 && I % NumViaIntegerBits == 0) {
1267           if (NumViaIntegerBits <= 32)
1268             Bits = SignExtend64(Bits, 32);
1269           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1270           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1271                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1272           Bits = 0;
1273           BitPos = 0;
1274           IntegerEltIdx++;
1275         }
1276         SDValue V = Op.getOperand(I);
1277         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1278         Bits |= ((uint64_t)BitValue << BitPos);
1279       }
1280 
1281       // Insert the (remaining) scalar value into position in our integer
1282       // vector type.
1283       if (NumViaIntegerBits <= 32)
1284         Bits = SignExtend64(Bits, 32);
1285       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1286       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1287                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1288 
1289       if (NumElts < NumViaIntegerBits) {
1290         // If we're producing a smaller vector than our minimum legal integer
1291         // type, bitcast to the equivalent (known-legal) mask type, and extract
1292         // our final mask.
1293         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1294         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1295         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1296                           DAG.getConstant(0, DL, XLenVT));
1297       } else {
1298         // Else we must have produced an integer type with the same size as the
1299         // mask type; bitcast for the final result.
1300         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1301         Vec = DAG.getBitcast(VT, Vec);
1302       }
1303 
1304       return Vec;
1305     }
1306 
1307     return SDValue();
1308   }
1309 
1310   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1311     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1312                                         : RISCVISD::VMV_V_X_VL;
1313     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1314     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1315   }
1316 
1317   // Try and match an index sequence, which we can lower directly to the vid
1318   // instruction. An all-undef vector is matched by getSplatValue, above.
1319   if (VT.isInteger()) {
1320     bool IsVID = true;
1321     for (unsigned I = 0; I < NumElts && IsVID; I++)
1322       IsVID &= Op.getOperand(I).isUndef() ||
1323                (isa<ConstantSDNode>(Op.getOperand(I)) &&
1324                 Op.getConstantOperandVal(I) == I);
1325 
1326     if (IsVID) {
1327       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1328       return convertFromScalableVector(VT, VID, DAG, Subtarget);
1329     }
1330   }
1331 
1332   // Attempt to detect "hidden" splats, which only reveal themselves as splats
1333   // when re-interpreted as a vector with a larger element type. For example,
1334   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
1335   // could be instead splat as
1336   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
1337   // TODO: This optimization could also work on non-constant splats, but it
1338   // would require bit-manipulation instructions to construct the splat value.
1339   SmallVector<SDValue> Sequence;
1340   unsigned EltBitSize = VT.getScalarSizeInBits();
1341   const auto *BV = cast<BuildVectorSDNode>(Op);
1342   if (VT.isInteger() && EltBitSize < 64 &&
1343       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
1344       BV->getRepeatedSequence(Sequence) &&
1345       (Sequence.size() * EltBitSize) <= 64) {
1346     unsigned SeqLen = Sequence.size();
1347     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
1348     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
1349     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
1350             ViaIntVT == MVT::i64) &&
1351            "Unexpected sequence type");
1352 
1353     unsigned EltIdx = 0;
1354     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
1355     uint64_t SplatValue = 0;
1356     // Construct the amalgamated value which can be splatted as this larger
1357     // vector type.
1358     for (const auto &SeqV : Sequence) {
1359       if (!SeqV.isUndef())
1360         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
1361                        << (EltIdx * EltBitSize));
1362       EltIdx++;
1363     }
1364 
1365     // On RV64, sign-extend from 32 to 64 bits where possible in order to
1366     // achieve better constant materializion.
1367     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
1368       SplatValue = SignExtend64(SplatValue, 32);
1369 
1370     // Since we can't introduce illegal i64 types at this stage, we can only
1371     // perform an i64 splat on RV32 if it is its own sign-extended value. That
1372     // way we can use RVV instructions to splat.
1373     assert((ViaIntVT.bitsLE(XLenVT) ||
1374             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
1375            "Unexpected bitcast sequence");
1376     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
1377       SDValue ViaVL =
1378           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
1379       MVT ViaContainerVT =
1380           RISCVTargetLowering::getContainerForFixedLengthVector(DAG, ViaVecVT,
1381                                                                 Subtarget);
1382       SDValue Splat =
1383           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
1384                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
1385       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
1386       return DAG.getBitcast(VT, Splat);
1387     }
1388   }
1389 
1390   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
1391   // which constitute a large proportion of the elements. In such cases we can
1392   // splat a vector with the dominant element and make up the shortfall with
1393   // INSERT_VECTOR_ELTs.
1394   // Note that this includes vectors of 2 elements by association. The
1395   // upper-most element is the "dominant" one, allowing us to use a splat to
1396   // "insert" the upper element, and an insert of the lower element at position
1397   // 0, which improves codegen.
1398   SDValue DominantValue;
1399   unsigned MostCommonCount = 0;
1400   DenseMap<SDValue, unsigned> ValueCounts;
1401   unsigned NumUndefElts =
1402       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
1403 
1404   for (SDValue V : Op->op_values()) {
1405     if (V.isUndef())
1406       continue;
1407 
1408     ValueCounts.insert(std::make_pair(V, 0));
1409     unsigned &Count = ValueCounts[V];
1410 
1411     // Is this value dominant? In case of a tie, prefer the highest element as
1412     // it's cheaper to insert near the beginning of a vector than it is at the
1413     // end.
1414     if (++Count >= MostCommonCount) {
1415       DominantValue = V;
1416       MostCommonCount = Count;
1417     }
1418   }
1419 
1420   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
1421   unsigned NumDefElts = NumElts - NumUndefElts;
1422   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
1423 
1424   // Don't perform this optimization when optimizing for size, since
1425   // materializing elements and inserting them tends to cause code bloat.
1426   if (!DAG.shouldOptForSize() &&
1427       ((MostCommonCount > DominantValueCountThreshold) ||
1428        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
1429     // Start by splatting the most common element.
1430     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
1431 
1432     DenseSet<SDValue> Processed{DominantValue};
1433     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
1434     for (const auto &OpIdx : enumerate(Op->ops())) {
1435       const SDValue &V = OpIdx.value();
1436       if (V.isUndef() || !Processed.insert(V).second)
1437         continue;
1438       if (ValueCounts[V] == 1) {
1439         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
1440                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
1441       } else {
1442         // Blend in all instances of this value using a VSELECT, using a
1443         // mask where each bit signals whether that element is the one
1444         // we're after.
1445         SmallVector<SDValue> Ops;
1446         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
1447           return DAG.getConstant(V == V1, DL, XLenVT);
1448         });
1449         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
1450                           DAG.getBuildVector(SelMaskTy, DL, Ops),
1451                           DAG.getSplatBuildVector(VT, DL, V), Vec);
1452       }
1453     }
1454 
1455     return Vec;
1456   }
1457 
1458   return SDValue();
1459 }
1460 
1461 // Called by type legalization to handle splat of i64 on RV32.
1462 // FIXME: We can optimize this when the type has sign or zero bits in one
1463 // of the halves.
1464 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
1465                                    SDValue VL, SelectionDAG &DAG) {
1466   SDValue ThirtyTwoV = DAG.getConstant(32, DL, VT);
1467   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
1468                            DAG.getConstant(0, DL, MVT::i32));
1469   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
1470                            DAG.getConstant(1, DL, MVT::i32));
1471 
1472   // vmv.v.x vX, hi
1473   // vsll.vx vX, vX, /*32*/
1474   // vmv.v.x vY, lo
1475   // vsll.vx vY, vY, /*32*/
1476   // vsrl.vx vY, vY, /*32*/
1477   // vor.vv vX, vX, vY
1478   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1479   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1480   Lo = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
1481   Lo = DAG.getNode(RISCVISD::SHL_VL, DL, VT, Lo, ThirtyTwoV, Mask, VL);
1482   Lo = DAG.getNode(RISCVISD::SRL_VL, DL, VT, Lo, ThirtyTwoV, Mask, VL);
1483 
1484   Hi = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Hi, VL);
1485   Hi = DAG.getNode(RISCVISD::SHL_VL, DL, VT, Hi, ThirtyTwoV, Mask, VL);
1486 
1487   return DAG.getNode(RISCVISD::OR_VL, DL, VT, Lo, Hi, Mask, VL);
1488 }
1489 
1490 // This function lowers a splat of a scalar operand Splat with the vector
1491 // length VL. It ensures the final sequence is type legal, which is useful when
1492 // lowering a splat after type legalization.
1493 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
1494                                 SelectionDAG &DAG,
1495                                 const RISCVSubtarget &Subtarget) {
1496   if (VT.isFloatingPoint())
1497     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
1498 
1499   MVT XLenVT = Subtarget.getXLenVT();
1500 
1501   // Simplest case is that the operand needs to be promoted to XLenVT.
1502   if (Scalar.getValueType().bitsLE(XLenVT)) {
1503     // If the operand is a constant, sign extend to increase our chances
1504     // of being able to use a .vi instruction. ANY_EXTEND would become a
1505     // a zero extend and the simm5 check in isel would fail.
1506     // FIXME: Should we ignore the upper bits in isel instead?
1507     unsigned ExtOpc =
1508         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
1509     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
1510     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
1511   }
1512 
1513   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
1514          "Unexpected scalar for splat lowering!");
1515 
1516   // If this is a sign-extended 32-bit constant, we can truncate it and rely
1517   // on the instruction to sign-extend since SEW>XLEN.
1518   if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) {
1519     if (isInt<32>(CVal->getSExtValue()))
1520       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
1521                          DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32),
1522                          VL);
1523   }
1524 
1525   // Otherwise use the more complicated splatting algorithm.
1526   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
1527 }
1528 
1529 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
1530                                    const RISCVSubtarget &Subtarget) {
1531   SDValue V1 = Op.getOperand(0);
1532   SDValue V2 = Op.getOperand(1);
1533   SDLoc DL(Op);
1534   MVT XLenVT = Subtarget.getXLenVT();
1535   MVT VT = Op.getSimpleValueType();
1536   unsigned NumElts = VT.getVectorNumElements();
1537   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
1538 
1539   MVT ContainerVT =
1540       RISCVTargetLowering::getContainerForFixedLengthVector(DAG, VT, Subtarget);
1541 
1542   SDValue TrueMask, VL;
1543   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1544 
1545   if (SVN->isSplat()) {
1546     int Lane = SVN->getSplatIndex();
1547     if (Lane >= 0) {
1548       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
1549       assert(Lane < (int)NumElts && "Unexpected lane!");
1550       SDValue Gather =
1551           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
1552                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
1553       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1554     }
1555   }
1556 
1557   // Detect shuffles which can be re-expressed as vector selects; these are
1558   // shuffles in which each element in the destination is taken from an element
1559   // at the corresponding index in either source vectors.
1560   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
1561     int MaskIndex = MaskIdx.value();
1562     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
1563   });
1564 
1565   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
1566 
1567   SmallVector<SDValue> MaskVals;
1568   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
1569   // merged with a second vrgather.
1570   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
1571 
1572   // By default we preserve the original operand order, and use a mask to
1573   // select LHS as true and RHS as false. However, since RVV vector selects may
1574   // feature splats but only on the LHS, we may choose to invert our mask and
1575   // instead select between RHS and LHS.
1576   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
1577   bool InvertMask = IsSelect == SwapOps;
1578 
1579   // Now construct the mask that will be used by the vselect or blended
1580   // vrgather operation. For vrgathers, construct the appropriate indices into
1581   // each vector.
1582   for (int MaskIndex : SVN->getMask()) {
1583     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
1584     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
1585     if (!IsSelect) {
1586       bool IsLHS = MaskIndex < (int)NumElts;
1587       // For "undef" elements of -1, shuffle in element 0 instead.
1588       GatherIndicesLHS.push_back(
1589           DAG.getConstant(IsLHS ? std::max(MaskIndex, 0) : 0, DL, XLenVT));
1590       // TODO: If we're masking out unused elements anyway, it might produce
1591       // better code if we use the most-common element index instead of 0.
1592       GatherIndicesRHS.push_back(
1593           DAG.getConstant(IsLHS ? 0 : MaskIndex - NumElts, DL, XLenVT));
1594     }
1595   }
1596 
1597   if (SwapOps) {
1598     std::swap(V1, V2);
1599     std::swap(GatherIndicesLHS, GatherIndicesRHS);
1600   }
1601 
1602   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
1603   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
1604   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
1605 
1606   if (IsSelect)
1607     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
1608 
1609   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
1610     // On such a large vector we're unable to use i8 as the index type.
1611     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
1612     // may involve vector splitting if we're already at LMUL=8, or our
1613     // user-supplied maximum fixed-length LMUL.
1614     return SDValue();
1615   }
1616 
1617   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
1618   MVT IndexVT = VT.changeTypeToInteger();
1619   // Since we can't introduce illegal index types at this stage, use i16 and
1620   // vrgatherei16 if the corresponding index type for plain vrgather is greater
1621   // than XLenVT.
1622   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
1623     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
1624     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
1625   }
1626 
1627   MVT IndexContainerVT =
1628       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
1629 
1630   SDValue Gather;
1631   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
1632   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
1633   if (SDValue SplatValue = DAG.getSplatValue(V1)) {
1634     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
1635   } else {
1636     SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
1637     LHSIndices =
1638         convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
1639 
1640     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
1641     Gather =
1642         DAG.getNode(GatherOpc, DL, ContainerVT, V1, LHSIndices, TrueMask, VL);
1643   }
1644 
1645   // If a second vector operand is used by this shuffle, blend it in with an
1646   // additional vrgather.
1647   if (!V2.isUndef()) {
1648     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
1649     SelectMask =
1650         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
1651 
1652     SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
1653     RHSIndices =
1654         convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
1655 
1656     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
1657     V2 = DAG.getNode(GatherOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, VL);
1658     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
1659                          Gather, VL);
1660   }
1661 
1662   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1663 }
1664 
1665 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
1666                                      SDLoc DL, SelectionDAG &DAG,
1667                                      const RISCVSubtarget &Subtarget) {
1668   if (VT.isScalableVector())
1669     return DAG.getFPExtendOrRound(Op, DL, VT);
1670   assert(VT.isFixedLengthVector() &&
1671          "Unexpected value type for RVV FP extend/round lowering");
1672   SDValue Mask, VL;
1673   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1674   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
1675                         ? RISCVISD::FP_EXTEND_VL
1676                         : RISCVISD::FP_ROUND_VL;
1677   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
1678 }
1679 
1680 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
1681                                             SelectionDAG &DAG) const {
1682   switch (Op.getOpcode()) {
1683   default:
1684     report_fatal_error("unimplemented operand");
1685   case ISD::GlobalAddress:
1686     return lowerGlobalAddress(Op, DAG);
1687   case ISD::BlockAddress:
1688     return lowerBlockAddress(Op, DAG);
1689   case ISD::ConstantPool:
1690     return lowerConstantPool(Op, DAG);
1691   case ISD::JumpTable:
1692     return lowerJumpTable(Op, DAG);
1693   case ISD::GlobalTLSAddress:
1694     return lowerGlobalTLSAddress(Op, DAG);
1695   case ISD::SELECT:
1696     return lowerSELECT(Op, DAG);
1697   case ISD::BRCOND:
1698     return lowerBRCOND(Op, DAG);
1699   case ISD::VASTART:
1700     return lowerVASTART(Op, DAG);
1701   case ISD::FRAMEADDR:
1702     return lowerFRAMEADDR(Op, DAG);
1703   case ISD::RETURNADDR:
1704     return lowerRETURNADDR(Op, DAG);
1705   case ISD::SHL_PARTS:
1706     return lowerShiftLeftParts(Op, DAG);
1707   case ISD::SRA_PARTS:
1708     return lowerShiftRightParts(Op, DAG, true);
1709   case ISD::SRL_PARTS:
1710     return lowerShiftRightParts(Op, DAG, false);
1711   case ISD::BITCAST: {
1712     SDLoc DL(Op);
1713     EVT VT = Op.getValueType();
1714     SDValue Op0 = Op.getOperand(0);
1715     EVT Op0VT = Op0.getValueType();
1716     MVT XLenVT = Subtarget.getXLenVT();
1717     if (VT.isFixedLengthVector()) {
1718       // We can handle fixed length vector bitcasts with a simple replacement
1719       // in isel.
1720       if (Op0VT.isFixedLengthVector())
1721         return Op;
1722       // When bitcasting from scalar to fixed-length vector, insert the scalar
1723       // into a one-element vector of the result type, and perform a vector
1724       // bitcast.
1725       if (!Op0VT.isVector()) {
1726         auto BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
1727         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
1728                                               DAG.getUNDEF(BVT), Op0,
1729                                               DAG.getConstant(0, DL, XLenVT)));
1730       }
1731       return SDValue();
1732     }
1733     // Custom-legalize bitcasts from fixed-length vector types to scalar types
1734     // thus: bitcast the vector to a one-element vector type whose element type
1735     // is the same as the result type, and extract the first element.
1736     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
1737       LLVMContext &Context = *DAG.getContext();
1738       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
1739       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
1740                          DAG.getConstant(0, DL, XLenVT));
1741     }
1742     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
1743       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
1744       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
1745       return FPConv;
1746     }
1747     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
1748         Subtarget.hasStdExtF()) {
1749       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
1750       SDValue FPConv =
1751           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
1752       return FPConv;
1753     }
1754     return SDValue();
1755   }
1756   case ISD::INTRINSIC_WO_CHAIN:
1757     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1758   case ISD::INTRINSIC_W_CHAIN:
1759     return LowerINTRINSIC_W_CHAIN(Op, DAG);
1760   case ISD::BSWAP:
1761   case ISD::BITREVERSE: {
1762     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
1763     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
1764     MVT VT = Op.getSimpleValueType();
1765     SDLoc DL(Op);
1766     // Start with the maximum immediate value which is the bitwidth - 1.
1767     unsigned Imm = VT.getSizeInBits() - 1;
1768     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
1769     if (Op.getOpcode() == ISD::BSWAP)
1770       Imm &= ~0x7U;
1771     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
1772                        DAG.getConstant(Imm, DL, VT));
1773   }
1774   case ISD::FSHL:
1775   case ISD::FSHR: {
1776     MVT VT = Op.getSimpleValueType();
1777     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
1778     SDLoc DL(Op);
1779     if (Op.getOperand(2).getOpcode() == ISD::Constant)
1780       return Op;
1781     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
1782     // use log(XLen) bits. Mask the shift amount accordingly.
1783     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
1784     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
1785                                 DAG.getConstant(ShAmtWidth, DL, VT));
1786     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
1787     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
1788   }
1789   case ISD::TRUNCATE: {
1790     SDLoc DL(Op);
1791     MVT VT = Op.getSimpleValueType();
1792     // Only custom-lower vector truncates
1793     if (!VT.isVector())
1794       return Op;
1795 
1796     // Truncates to mask types are handled differently
1797     if (VT.getVectorElementType() == MVT::i1)
1798       return lowerVectorMaskTrunc(Op, DAG);
1799 
1800     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
1801     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
1802     // truncate by one power of two at a time.
1803     MVT DstEltVT = VT.getVectorElementType();
1804 
1805     SDValue Src = Op.getOperand(0);
1806     MVT SrcVT = Src.getSimpleValueType();
1807     MVT SrcEltVT = SrcVT.getVectorElementType();
1808 
1809     assert(DstEltVT.bitsLT(SrcEltVT) &&
1810            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
1811            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
1812            "Unexpected vector truncate lowering");
1813 
1814     MVT ContainerVT = SrcVT;
1815     if (SrcVT.isFixedLengthVector()) {
1816       ContainerVT = getContainerForFixedLengthVector(SrcVT);
1817       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
1818     }
1819 
1820     SDValue Result = Src;
1821     SDValue Mask, VL;
1822     std::tie(Mask, VL) =
1823         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
1824     LLVMContext &Context = *DAG.getContext();
1825     const ElementCount Count = ContainerVT.getVectorElementCount();
1826     do {
1827       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
1828       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
1829       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
1830                            Mask, VL);
1831     } while (SrcEltVT != DstEltVT);
1832 
1833     if (SrcVT.isFixedLengthVector())
1834       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
1835 
1836     return Result;
1837   }
1838   case ISD::ANY_EXTEND:
1839   case ISD::ZERO_EXTEND:
1840     if (Op.getOperand(0).getValueType().isVector() &&
1841         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
1842       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
1843     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
1844   case ISD::SIGN_EXTEND:
1845     if (Op.getOperand(0).getValueType().isVector() &&
1846         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
1847       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
1848     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
1849   case ISD::SPLAT_VECTOR_PARTS:
1850     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
1851   case ISD::INSERT_VECTOR_ELT:
1852     return lowerINSERT_VECTOR_ELT(Op, DAG);
1853   case ISD::EXTRACT_VECTOR_ELT:
1854     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
1855   case ISD::VSCALE: {
1856     MVT VT = Op.getSimpleValueType();
1857     SDLoc DL(Op);
1858     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
1859     // We define our scalable vector types for lmul=1 to use a 64 bit known
1860     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
1861     // vscale as VLENB / 8.
1862     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
1863     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
1864                                  DAG.getConstant(3, DL, VT));
1865     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
1866   }
1867   case ISD::FP_EXTEND: {
1868     // RVV can only do fp_extend to types double the size as the source. We
1869     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
1870     // via f32.
1871     SDLoc DL(Op);
1872     MVT VT = Op.getSimpleValueType();
1873     SDValue Src = Op.getOperand(0);
1874     MVT SrcVT = Src.getSimpleValueType();
1875 
1876     // Prepare any fixed-length vector operands.
1877     MVT ContainerVT = VT;
1878     if (SrcVT.isFixedLengthVector()) {
1879       ContainerVT = getContainerForFixedLengthVector(VT);
1880       MVT SrcContainerVT =
1881           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
1882       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
1883     }
1884 
1885     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
1886         SrcVT.getVectorElementType() != MVT::f16) {
1887       // For scalable vectors, we only need to close the gap between
1888       // vXf16->vXf64.
1889       if (!VT.isFixedLengthVector())
1890         return Op;
1891       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
1892       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
1893       return convertFromScalableVector(VT, Src, DAG, Subtarget);
1894     }
1895 
1896     MVT InterVT = VT.changeVectorElementType(MVT::f32);
1897     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
1898     SDValue IntermediateExtend = getRVVFPExtendOrRound(
1899         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
1900 
1901     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
1902                                            DL, DAG, Subtarget);
1903     if (VT.isFixedLengthVector())
1904       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
1905     return Extend;
1906   }
1907   case ISD::FP_ROUND: {
1908     // RVV can only do fp_round to types half the size as the source. We
1909     // custom-lower f64->f16 rounds via RVV's round-to-odd float
1910     // conversion instruction.
1911     SDLoc DL(Op);
1912     MVT VT = Op.getSimpleValueType();
1913     SDValue Src = Op.getOperand(0);
1914     MVT SrcVT = Src.getSimpleValueType();
1915 
1916     // Prepare any fixed-length vector operands.
1917     MVT ContainerVT = VT;
1918     if (VT.isFixedLengthVector()) {
1919       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
1920       ContainerVT =
1921           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
1922       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
1923     }
1924 
1925     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
1926         SrcVT.getVectorElementType() != MVT::f64) {
1927       // For scalable vectors, we only need to close the gap between
1928       // vXf64<->vXf16.
1929       if (!VT.isFixedLengthVector())
1930         return Op;
1931       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
1932       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
1933       return convertFromScalableVector(VT, Src, DAG, Subtarget);
1934     }
1935 
1936     SDValue Mask, VL;
1937     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1938 
1939     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
1940     SDValue IntermediateRound =
1941         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
1942     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
1943                                           DL, DAG, Subtarget);
1944 
1945     if (VT.isFixedLengthVector())
1946       return convertFromScalableVector(VT, Round, DAG, Subtarget);
1947     return Round;
1948   }
1949   case ISD::FP_TO_SINT:
1950   case ISD::FP_TO_UINT:
1951   case ISD::SINT_TO_FP:
1952   case ISD::UINT_TO_FP: {
1953     // RVV can only do fp<->int conversions to types half/double the size as
1954     // the source. We custom-lower any conversions that do two hops into
1955     // sequences.
1956     MVT VT = Op.getSimpleValueType();
1957     if (!VT.isVector())
1958       return Op;
1959     SDLoc DL(Op);
1960     SDValue Src = Op.getOperand(0);
1961     MVT EltVT = VT.getVectorElementType();
1962     MVT SrcVT = Src.getSimpleValueType();
1963     MVT SrcEltVT = SrcVT.getVectorElementType();
1964     unsigned EltSize = EltVT.getSizeInBits();
1965     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
1966     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
1967            "Unexpected vector element types");
1968 
1969     bool IsInt2FP = SrcEltVT.isInteger();
1970     // Widening conversions
1971     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
1972       if (IsInt2FP) {
1973         // Do a regular integer sign/zero extension then convert to float.
1974         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
1975                                       VT.getVectorElementCount());
1976         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
1977                                  ? ISD::ZERO_EXTEND
1978                                  : ISD::SIGN_EXTEND;
1979         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
1980         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
1981       }
1982       // FP2Int
1983       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
1984       // Do one doubling fp_extend then complete the operation by converting
1985       // to int.
1986       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1987       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
1988       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
1989     }
1990 
1991     // Narrowing conversions
1992     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
1993       if (IsInt2FP) {
1994         // One narrowing int_to_fp, then an fp_round.
1995         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
1996         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1997         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
1998         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
1999       }
2000       // FP2Int
2001       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2002       // representable by the integer, the result is poison.
2003       MVT IVecVT =
2004           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2005                            VT.getVectorElementCount());
2006       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2007       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2008     }
2009 
2010     // Scalable vectors can exit here. Patterns will handle equally-sized
2011     // conversions halving/doubling ones.
2012     if (!VT.isFixedLengthVector())
2013       return Op;
2014 
2015     // For fixed-length vectors we lower to a custom "VL" node.
2016     unsigned RVVOpc = 0;
2017     switch (Op.getOpcode()) {
2018     default:
2019       llvm_unreachable("Impossible opcode");
2020     case ISD::FP_TO_SINT:
2021       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2022       break;
2023     case ISD::FP_TO_UINT:
2024       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2025       break;
2026     case ISD::SINT_TO_FP:
2027       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2028       break;
2029     case ISD::UINT_TO_FP:
2030       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2031       break;
2032     }
2033 
2034     MVT ContainerVT, SrcContainerVT;
2035     // Derive the reference container type from the larger vector type.
2036     if (SrcEltSize > EltSize) {
2037       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2038       ContainerVT =
2039           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2040     } else {
2041       ContainerVT = getContainerForFixedLengthVector(VT);
2042       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2043     }
2044 
2045     SDValue Mask, VL;
2046     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2047 
2048     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2049     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2050     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2051   }
2052   case ISD::VECREDUCE_ADD:
2053   case ISD::VECREDUCE_UMAX:
2054   case ISD::VECREDUCE_SMAX:
2055   case ISD::VECREDUCE_UMIN:
2056   case ISD::VECREDUCE_SMIN:
2057     return lowerVECREDUCE(Op, DAG);
2058   case ISD::VECREDUCE_AND:
2059   case ISD::VECREDUCE_OR:
2060   case ISD::VECREDUCE_XOR:
2061     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2062       return lowerVectorMaskVECREDUCE(Op, DAG);
2063     return lowerVECREDUCE(Op, DAG);
2064   case ISD::VECREDUCE_FADD:
2065   case ISD::VECREDUCE_SEQ_FADD:
2066     return lowerFPVECREDUCE(Op, DAG);
2067   case ISD::INSERT_SUBVECTOR:
2068     return lowerINSERT_SUBVECTOR(Op, DAG);
2069   case ISD::EXTRACT_SUBVECTOR:
2070     return lowerEXTRACT_SUBVECTOR(Op, DAG);
2071   case ISD::STEP_VECTOR:
2072     return lowerSTEP_VECTOR(Op, DAG);
2073   case ISD::VECTOR_REVERSE:
2074     return lowerVECTOR_REVERSE(Op, DAG);
2075   case ISD::BUILD_VECTOR:
2076     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
2077   case ISD::VECTOR_SHUFFLE:
2078     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
2079   case ISD::CONCAT_VECTORS: {
2080     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
2081     // better than going through the stack, as the default expansion does.
2082     SDLoc DL(Op);
2083     MVT VT = Op.getSimpleValueType();
2084     unsigned NumOpElts =
2085         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
2086     SDValue Vec = DAG.getUNDEF(VT);
2087     for (const auto &OpIdx : enumerate(Op->ops()))
2088       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
2089                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
2090     return Vec;
2091   }
2092   case ISD::LOAD:
2093     return lowerFixedLengthVectorLoadToRVV(Op, DAG);
2094   case ISD::STORE:
2095     return lowerFixedLengthVectorStoreToRVV(Op, DAG);
2096   case ISD::MLOAD:
2097     return lowerMLOAD(Op, DAG);
2098   case ISD::MSTORE:
2099     return lowerMSTORE(Op, DAG);
2100   case ISD::SETCC:
2101     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
2102   case ISD::ADD:
2103     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
2104   case ISD::SUB:
2105     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
2106   case ISD::MUL:
2107     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
2108   case ISD::MULHS:
2109     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
2110   case ISD::MULHU:
2111     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
2112   case ISD::AND:
2113     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
2114                                               RISCVISD::AND_VL);
2115   case ISD::OR:
2116     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
2117                                               RISCVISD::OR_VL);
2118   case ISD::XOR:
2119     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
2120                                               RISCVISD::XOR_VL);
2121   case ISD::SDIV:
2122     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
2123   case ISD::SREM:
2124     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
2125   case ISD::UDIV:
2126     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
2127   case ISD::UREM:
2128     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
2129   case ISD::SHL:
2130     return lowerToScalableOp(Op, DAG, RISCVISD::SHL_VL);
2131   case ISD::SRA:
2132     return lowerToScalableOp(Op, DAG, RISCVISD::SRA_VL);
2133   case ISD::SRL:
2134     return lowerToScalableOp(Op, DAG, RISCVISD::SRL_VL);
2135   case ISD::FADD:
2136     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
2137   case ISD::FSUB:
2138     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
2139   case ISD::FMUL:
2140     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
2141   case ISD::FDIV:
2142     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
2143   case ISD::FNEG:
2144     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
2145   case ISD::FABS:
2146     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
2147   case ISD::FSQRT:
2148     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
2149   case ISD::FMA:
2150     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
2151   case ISD::SMIN:
2152     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
2153   case ISD::SMAX:
2154     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
2155   case ISD::UMIN:
2156     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
2157   case ISD::UMAX:
2158     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
2159   case ISD::ABS:
2160     return lowerABS(Op, DAG);
2161   case ISD::VSELECT:
2162     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
2163   case ISD::FCOPYSIGN:
2164     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
2165   case ISD::MGATHER:
2166     return lowerMGATHER(Op, DAG);
2167   case ISD::MSCATTER:
2168     return lowerMSCATTER(Op, DAG);
2169   case ISD::FLT_ROUNDS_:
2170     return lowerGET_ROUNDING(Op, DAG);
2171   case ISD::SET_ROUNDING:
2172     return lowerSET_ROUNDING(Op, DAG);
2173   }
2174 }
2175 
2176 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
2177                              SelectionDAG &DAG, unsigned Flags) {
2178   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
2179 }
2180 
2181 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
2182                              SelectionDAG &DAG, unsigned Flags) {
2183   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
2184                                    Flags);
2185 }
2186 
2187 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
2188                              SelectionDAG &DAG, unsigned Flags) {
2189   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
2190                                    N->getOffset(), Flags);
2191 }
2192 
2193 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
2194                              SelectionDAG &DAG, unsigned Flags) {
2195   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
2196 }
2197 
2198 template <class NodeTy>
2199 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
2200                                      bool IsLocal) const {
2201   SDLoc DL(N);
2202   EVT Ty = getPointerTy(DAG.getDataLayout());
2203 
2204   if (isPositionIndependent()) {
2205     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
2206     if (IsLocal)
2207       // Use PC-relative addressing to access the symbol. This generates the
2208       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
2209       // %pcrel_lo(auipc)).
2210       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
2211 
2212     // Use PC-relative addressing to access the GOT for this symbol, then load
2213     // the address from the GOT. This generates the pattern (PseudoLA sym),
2214     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
2215     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
2216   }
2217 
2218   switch (getTargetMachine().getCodeModel()) {
2219   default:
2220     report_fatal_error("Unsupported code model for lowering");
2221   case CodeModel::Small: {
2222     // Generate a sequence for accessing addresses within the first 2 GiB of
2223     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
2224     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
2225     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
2226     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
2227     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
2228   }
2229   case CodeModel::Medium: {
2230     // Generate a sequence for accessing addresses within any 2GiB range within
2231     // the address space. This generates the pattern (PseudoLLA sym), which
2232     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
2233     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
2234     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
2235   }
2236   }
2237 }
2238 
2239 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
2240                                                 SelectionDAG &DAG) const {
2241   SDLoc DL(Op);
2242   EVT Ty = Op.getValueType();
2243   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2244   int64_t Offset = N->getOffset();
2245   MVT XLenVT = Subtarget.getXLenVT();
2246 
2247   const GlobalValue *GV = N->getGlobal();
2248   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2249   SDValue Addr = getAddr(N, DAG, IsLocal);
2250 
2251   // In order to maximise the opportunity for common subexpression elimination,
2252   // emit a separate ADD node for the global address offset instead of folding
2253   // it in the global address node. Later peephole optimisations may choose to
2254   // fold it back in when profitable.
2255   if (Offset != 0)
2256     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
2257                        DAG.getConstant(Offset, DL, XLenVT));
2258   return Addr;
2259 }
2260 
2261 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
2262                                                SelectionDAG &DAG) const {
2263   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2264 
2265   return getAddr(N, DAG);
2266 }
2267 
2268 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
2269                                                SelectionDAG &DAG) const {
2270   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2271 
2272   return getAddr(N, DAG);
2273 }
2274 
2275 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
2276                                             SelectionDAG &DAG) const {
2277   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2278 
2279   return getAddr(N, DAG);
2280 }
2281 
2282 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
2283                                               SelectionDAG &DAG,
2284                                               bool UseGOT) const {
2285   SDLoc DL(N);
2286   EVT Ty = getPointerTy(DAG.getDataLayout());
2287   const GlobalValue *GV = N->getGlobal();
2288   MVT XLenVT = Subtarget.getXLenVT();
2289 
2290   if (UseGOT) {
2291     // Use PC-relative addressing to access the GOT for this TLS symbol, then
2292     // load the address from the GOT and add the thread pointer. This generates
2293     // the pattern (PseudoLA_TLS_IE sym), which expands to
2294     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
2295     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
2296     SDValue Load =
2297         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
2298 
2299     // Add the thread pointer.
2300     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
2301     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
2302   }
2303 
2304   // Generate a sequence for accessing the address relative to the thread
2305   // pointer, with the appropriate adjustment for the thread pointer offset.
2306   // This generates the pattern
2307   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
2308   SDValue AddrHi =
2309       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
2310   SDValue AddrAdd =
2311       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
2312   SDValue AddrLo =
2313       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
2314 
2315   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
2316   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
2317   SDValue MNAdd = SDValue(
2318       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
2319       0);
2320   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
2321 }
2322 
2323 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
2324                                                SelectionDAG &DAG) const {
2325   SDLoc DL(N);
2326   EVT Ty = getPointerTy(DAG.getDataLayout());
2327   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
2328   const GlobalValue *GV = N->getGlobal();
2329 
2330   // Use a PC-relative addressing mode to access the global dynamic GOT address.
2331   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
2332   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
2333   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
2334   SDValue Load =
2335       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
2336 
2337   // Prepare argument list to generate call.
2338   ArgListTy Args;
2339   ArgListEntry Entry;
2340   Entry.Node = Load;
2341   Entry.Ty = CallTy;
2342   Args.push_back(Entry);
2343 
2344   // Setup call to __tls_get_addr.
2345   TargetLowering::CallLoweringInfo CLI(DAG);
2346   CLI.setDebugLoc(DL)
2347       .setChain(DAG.getEntryNode())
2348       .setLibCallee(CallingConv::C, CallTy,
2349                     DAG.getExternalSymbol("__tls_get_addr", Ty),
2350                     std::move(Args));
2351 
2352   return LowerCallTo(CLI).first;
2353 }
2354 
2355 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
2356                                                    SelectionDAG &DAG) const {
2357   SDLoc DL(Op);
2358   EVT Ty = Op.getValueType();
2359   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2360   int64_t Offset = N->getOffset();
2361   MVT XLenVT = Subtarget.getXLenVT();
2362 
2363   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
2364 
2365   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
2366       CallingConv::GHC)
2367     report_fatal_error("In GHC calling convention TLS is not supported");
2368 
2369   SDValue Addr;
2370   switch (Model) {
2371   case TLSModel::LocalExec:
2372     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
2373     break;
2374   case TLSModel::InitialExec:
2375     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
2376     break;
2377   case TLSModel::LocalDynamic:
2378   case TLSModel::GeneralDynamic:
2379     Addr = getDynamicTLSAddr(N, DAG);
2380     break;
2381   }
2382 
2383   // In order to maximise the opportunity for common subexpression elimination,
2384   // emit a separate ADD node for the global address offset instead of folding
2385   // it in the global address node. Later peephole optimisations may choose to
2386   // fold it back in when profitable.
2387   if (Offset != 0)
2388     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
2389                        DAG.getConstant(Offset, DL, XLenVT));
2390   return Addr;
2391 }
2392 
2393 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2394   SDValue CondV = Op.getOperand(0);
2395   SDValue TrueV = Op.getOperand(1);
2396   SDValue FalseV = Op.getOperand(2);
2397   SDLoc DL(Op);
2398   MVT XLenVT = Subtarget.getXLenVT();
2399 
2400   // If the result type is XLenVT and CondV is the output of a SETCC node
2401   // which also operated on XLenVT inputs, then merge the SETCC node into the
2402   // lowered RISCVISD::SELECT_CC to take advantage of the integer
2403   // compare+branch instructions. i.e.:
2404   // (select (setcc lhs, rhs, cc), truev, falsev)
2405   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
2406   if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
2407       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
2408     SDValue LHS = CondV.getOperand(0);
2409     SDValue RHS = CondV.getOperand(1);
2410     auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
2411     ISD::CondCode CCVal = CC->get();
2412 
2413     // Special case for a select of 2 constants that have a diffence of 1.
2414     // Normally this is done by DAGCombine, but if the select is introduced by
2415     // type legalization or op legalization, we miss it. Restricting to SETLT
2416     // case for now because that is what signed saturating add/sub need.
2417     // FIXME: We don't need the condition to be SETLT or even a SETCC,
2418     // but we would probably want to swap the true/false values if the condition
2419     // is SETGE/SETLE to avoid an XORI.
2420     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
2421         CCVal == ISD::SETLT) {
2422       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
2423       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
2424       if (TrueVal - 1 == FalseVal)
2425         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
2426       if (TrueVal + 1 == FalseVal)
2427         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
2428     }
2429 
2430     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
2431 
2432     SDValue TargetCC = DAG.getTargetConstant(CCVal, DL, XLenVT);
2433     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
2434     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
2435   }
2436 
2437   // Otherwise:
2438   // (select condv, truev, falsev)
2439   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
2440   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
2441   SDValue SetNE = DAG.getTargetConstant(ISD::SETNE, DL, XLenVT);
2442 
2443   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
2444 
2445   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
2446 }
2447 
2448 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2449   SDValue CondV = Op.getOperand(1);
2450   SDLoc DL(Op);
2451   MVT XLenVT = Subtarget.getXLenVT();
2452 
2453   if (CondV.getOpcode() == ISD::SETCC &&
2454       CondV.getOperand(0).getValueType() == XLenVT) {
2455     SDValue LHS = CondV.getOperand(0);
2456     SDValue RHS = CondV.getOperand(1);
2457     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
2458 
2459     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
2460 
2461     SDValue TargetCC = DAG.getCondCode(CCVal);
2462     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
2463                        LHS, RHS, TargetCC, Op.getOperand(2));
2464   }
2465 
2466   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
2467                      CondV, DAG.getConstant(0, DL, XLenVT),
2468                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
2469 }
2470 
2471 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2472   MachineFunction &MF = DAG.getMachineFunction();
2473   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
2474 
2475   SDLoc DL(Op);
2476   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2477                                  getPointerTy(MF.getDataLayout()));
2478 
2479   // vastart just stores the address of the VarArgsFrameIndex slot into the
2480   // memory location argument.
2481   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2482   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2483                       MachinePointerInfo(SV));
2484 }
2485 
2486 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
2487                                             SelectionDAG &DAG) const {
2488   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
2489   MachineFunction &MF = DAG.getMachineFunction();
2490   MachineFrameInfo &MFI = MF.getFrameInfo();
2491   MFI.setFrameAddressIsTaken(true);
2492   Register FrameReg = RI.getFrameRegister(MF);
2493   int XLenInBytes = Subtarget.getXLen() / 8;
2494 
2495   EVT VT = Op.getValueType();
2496   SDLoc DL(Op);
2497   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
2498   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2499   while (Depth--) {
2500     int Offset = -(XLenInBytes * 2);
2501     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
2502                               DAG.getIntPtrConstant(Offset, DL));
2503     FrameAddr =
2504         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2505   }
2506   return FrameAddr;
2507 }
2508 
2509 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
2510                                              SelectionDAG &DAG) const {
2511   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
2512   MachineFunction &MF = DAG.getMachineFunction();
2513   MachineFrameInfo &MFI = MF.getFrameInfo();
2514   MFI.setReturnAddressIsTaken(true);
2515   MVT XLenVT = Subtarget.getXLenVT();
2516   int XLenInBytes = Subtarget.getXLen() / 8;
2517 
2518   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2519     return SDValue();
2520 
2521   EVT VT = Op.getValueType();
2522   SDLoc DL(Op);
2523   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2524   if (Depth) {
2525     int Off = -XLenInBytes;
2526     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
2527     SDValue Offset = DAG.getConstant(Off, DL, VT);
2528     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
2529                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
2530                        MachinePointerInfo());
2531   }
2532 
2533   // Return the value of the return address register, marking it an implicit
2534   // live-in.
2535   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
2536   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
2537 }
2538 
2539 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
2540                                                  SelectionDAG &DAG) const {
2541   SDLoc DL(Op);
2542   SDValue Lo = Op.getOperand(0);
2543   SDValue Hi = Op.getOperand(1);
2544   SDValue Shamt = Op.getOperand(2);
2545   EVT VT = Lo.getValueType();
2546 
2547   // if Shamt-XLEN < 0: // Shamt < XLEN
2548   //   Lo = Lo << Shamt
2549   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
2550   // else:
2551   //   Lo = 0
2552   //   Hi = Lo << (Shamt-XLEN)
2553 
2554   SDValue Zero = DAG.getConstant(0, DL, VT);
2555   SDValue One = DAG.getConstant(1, DL, VT);
2556   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
2557   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
2558   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
2559   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
2560 
2561   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2562   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
2563   SDValue ShiftRightLo =
2564       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
2565   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2566   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2567   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
2568 
2569   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
2570 
2571   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
2572   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
2573 
2574   SDValue Parts[2] = {Lo, Hi};
2575   return DAG.getMergeValues(Parts, DL);
2576 }
2577 
2578 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2579                                                   bool IsSRA) const {
2580   SDLoc DL(Op);
2581   SDValue Lo = Op.getOperand(0);
2582   SDValue Hi = Op.getOperand(1);
2583   SDValue Shamt = Op.getOperand(2);
2584   EVT VT = Lo.getValueType();
2585 
2586   // SRA expansion:
2587   //   if Shamt-XLEN < 0: // Shamt < XLEN
2588   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
2589   //     Hi = Hi >>s Shamt
2590   //   else:
2591   //     Lo = Hi >>s (Shamt-XLEN);
2592   //     Hi = Hi >>s (XLEN-1)
2593   //
2594   // SRL expansion:
2595   //   if Shamt-XLEN < 0: // Shamt < XLEN
2596   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
2597   //     Hi = Hi >>u Shamt
2598   //   else:
2599   //     Lo = Hi >>u (Shamt-XLEN);
2600   //     Hi = 0;
2601 
2602   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
2603 
2604   SDValue Zero = DAG.getConstant(0, DL, VT);
2605   SDValue One = DAG.getConstant(1, DL, VT);
2606   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
2607   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
2608   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
2609   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
2610 
2611   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2612   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
2613   SDValue ShiftLeftHi =
2614       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
2615   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
2616   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
2617   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
2618   SDValue HiFalse =
2619       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
2620 
2621   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
2622 
2623   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
2624   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
2625 
2626   SDValue Parts[2] = {Lo, Hi};
2627   return DAG.getMergeValues(Parts, DL);
2628 }
2629 
2630 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
2631 // illegal (currently only vXi64 RV32).
2632 // FIXME: We could also catch non-constant sign-extended i32 values and lower
2633 // them to SPLAT_VECTOR_I64
2634 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
2635                                                      SelectionDAG &DAG) const {
2636   SDLoc DL(Op);
2637   EVT VecVT = Op.getValueType();
2638   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
2639          "Unexpected SPLAT_VECTOR_PARTS lowering");
2640 
2641   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
2642   SDValue Lo = Op.getOperand(0);
2643   SDValue Hi = Op.getOperand(1);
2644 
2645   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2646     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2647     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2648     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2649     // node in order to try and match RVV vector/scalar instructions.
2650     if ((LoC >> 31) == HiC)
2651       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
2652   }
2653 
2654   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
2655   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
2656       isa<ConstantSDNode>(Hi.getOperand(1)) &&
2657       Hi.getConstantOperandVal(1) == 31)
2658     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
2659 
2660   // Else, on RV32 we lower an i64-element SPLAT_VECTOR thus, being careful not
2661   // to accidentally sign-extend the 32-bit halves to the e64 SEW:
2662   // vmv.v.x vX, hi
2663   // vsll.vx vX, vX, /*32*/
2664   // vmv.v.x vY, lo
2665   // vsll.vx vY, vY, /*32*/
2666   // vsrl.vx vY, vY, /*32*/
2667   // vor.vv vX, vX, vY
2668   SDValue ThirtyTwoV = DAG.getConstant(32, DL, VecVT);
2669 
2670   Lo = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
2671   Lo = DAG.getNode(ISD::SHL, DL, VecVT, Lo, ThirtyTwoV);
2672   Lo = DAG.getNode(ISD::SRL, DL, VecVT, Lo, ThirtyTwoV);
2673 
2674   if (isNullConstant(Hi))
2675     return Lo;
2676 
2677   Hi = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Hi);
2678   Hi = DAG.getNode(ISD::SHL, DL, VecVT, Hi, ThirtyTwoV);
2679 
2680   return DAG.getNode(ISD::OR, DL, VecVT, Lo, Hi);
2681 }
2682 
2683 // Custom-lower extensions from mask vectors by using a vselect either with 1
2684 // for zero/any-extension or -1 for sign-extension:
2685 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
2686 // Note that any-extension is lowered identically to zero-extension.
2687 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
2688                                                 int64_t ExtTrueVal) const {
2689   SDLoc DL(Op);
2690   MVT VecVT = Op.getSimpleValueType();
2691   SDValue Src = Op.getOperand(0);
2692   // Only custom-lower extensions from mask types
2693   assert(Src.getValueType().isVector() &&
2694          Src.getValueType().getVectorElementType() == MVT::i1);
2695 
2696   MVT XLenVT = Subtarget.getXLenVT();
2697   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
2698   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
2699 
2700   if (VecVT.isScalableVector()) {
2701     // Be careful not to introduce illegal scalar types at this stage, and be
2702     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
2703     // illegal and must be expanded. Since we know that the constants are
2704     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
2705     bool IsRV32E64 =
2706         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
2707 
2708     if (!IsRV32E64) {
2709       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
2710       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
2711     } else {
2712       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
2713       SplatTrueVal =
2714           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
2715     }
2716 
2717     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
2718   }
2719 
2720   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
2721   MVT I1ContainerVT =
2722       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
2723 
2724   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
2725 
2726   SDValue Mask, VL;
2727   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
2728 
2729   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
2730   SplatTrueVal =
2731       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
2732   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
2733                                SplatTrueVal, SplatZero, VL);
2734 
2735   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
2736 }
2737 
2738 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
2739     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
2740   MVT ExtVT = Op.getSimpleValueType();
2741   // Only custom-lower extensions from fixed-length vector types.
2742   if (!ExtVT.isFixedLengthVector())
2743     return Op;
2744   MVT VT = Op.getOperand(0).getSimpleValueType();
2745   // Grab the canonical container type for the extended type. Infer the smaller
2746   // type from that to ensure the same number of vector elements, as we know
2747   // the LMUL will be sufficient to hold the smaller type.
2748   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
2749   // Get the extended container type manually to ensure the same number of
2750   // vector elements between source and dest.
2751   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
2752                                      ContainerExtVT.getVectorElementCount());
2753 
2754   SDValue Op1 =
2755       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
2756 
2757   SDLoc DL(Op);
2758   SDValue Mask, VL;
2759   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2760 
2761   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
2762 
2763   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
2764 }
2765 
2766 // Custom-lower truncations from vectors to mask vectors by using a mask and a
2767 // setcc operation:
2768 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
2769 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
2770                                                   SelectionDAG &DAG) const {
2771   SDLoc DL(Op);
2772   EVT MaskVT = Op.getValueType();
2773   // Only expect to custom-lower truncations to mask types
2774   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
2775          "Unexpected type for vector mask lowering");
2776   SDValue Src = Op.getOperand(0);
2777   MVT VecVT = Src.getSimpleValueType();
2778 
2779   // If this is a fixed vector, we need to convert it to a scalable vector.
2780   MVT ContainerVT = VecVT;
2781   if (VecVT.isFixedLengthVector()) {
2782     ContainerVT = getContainerForFixedLengthVector(VecVT);
2783     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2784   }
2785 
2786   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
2787   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
2788 
2789   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
2790   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
2791 
2792   if (VecVT.isScalableVector()) {
2793     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
2794     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
2795   }
2796 
2797   SDValue Mask, VL;
2798   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
2799 
2800   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2801   SDValue Trunc =
2802       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
2803   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
2804                       DAG.getCondCode(ISD::SETNE), Mask, VL);
2805   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
2806 }
2807 
2808 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
2809 // first position of a vector, and that vector is slid up to the insert index.
2810 // By limiting the active vector length to index+1 and merging with the
2811 // original vector (with an undisturbed tail policy for elements >= VL), we
2812 // achieve the desired result of leaving all elements untouched except the one
2813 // at VL-1, which is replaced with the desired value.
2814 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2815                                                     SelectionDAG &DAG) const {
2816   SDLoc DL(Op);
2817   MVT VecVT = Op.getSimpleValueType();
2818   SDValue Vec = Op.getOperand(0);
2819   SDValue Val = Op.getOperand(1);
2820   SDValue Idx = Op.getOperand(2);
2821 
2822   MVT ContainerVT = VecVT;
2823   // If the operand is a fixed-length vector, convert to a scalable one.
2824   if (VecVT.isFixedLengthVector()) {
2825     ContainerVT = getContainerForFixedLengthVector(VecVT);
2826     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2827   }
2828 
2829   MVT XLenVT = Subtarget.getXLenVT();
2830 
2831   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
2832   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
2833   // Even i64-element vectors on RV32 can be lowered without scalar
2834   // legalization if the most-significant 32 bits of the value are not affected
2835   // by the sign-extension of the lower 32 bits.
2836   // TODO: We could also catch sign extensions of a 32-bit value.
2837   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
2838     const auto *CVal = cast<ConstantSDNode>(Val);
2839     if (isInt<32>(CVal->getSExtValue())) {
2840       IsLegalInsert = true;
2841       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
2842     }
2843   }
2844 
2845   SDValue Mask, VL;
2846   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
2847 
2848   SDValue ValInVec;
2849 
2850   if (IsLegalInsert) {
2851     unsigned Opc =
2852         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
2853     if (isNullConstant(Idx)) {
2854       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
2855       if (!VecVT.isFixedLengthVector())
2856         return Vec;
2857       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
2858     }
2859     ValInVec =
2860         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
2861   } else {
2862     // On RV32, i64-element vectors must be specially handled to place the
2863     // value at element 0, by using two vslide1up instructions in sequence on
2864     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
2865     // this.
2866     SDValue One = DAG.getConstant(1, DL, XLenVT);
2867     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
2868     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
2869     MVT I32ContainerVT =
2870         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
2871     SDValue I32Mask =
2872         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
2873     // Limit the active VL to two.
2874     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
2875     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
2876     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
2877     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
2878                            InsertI64VL);
2879     // First slide in the hi value, then the lo in underneath it.
2880     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
2881                            ValHi, I32Mask, InsertI64VL);
2882     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
2883                            ValLo, I32Mask, InsertI64VL);
2884     // Bitcast back to the right container type.
2885     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
2886   }
2887 
2888   // Now that the value is in a vector, slide it into position.
2889   SDValue InsertVL =
2890       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
2891   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
2892                                 ValInVec, Idx, Mask, InsertVL);
2893   if (!VecVT.isFixedLengthVector())
2894     return Slideup;
2895   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
2896 }
2897 
2898 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
2899 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
2900 // types this is done using VMV_X_S to allow us to glean information about the
2901 // sign bits of the result.
2902 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2903                                                      SelectionDAG &DAG) const {
2904   SDLoc DL(Op);
2905   SDValue Idx = Op.getOperand(1);
2906   SDValue Vec = Op.getOperand(0);
2907   EVT EltVT = Op.getValueType();
2908   MVT VecVT = Vec.getSimpleValueType();
2909   MVT XLenVT = Subtarget.getXLenVT();
2910 
2911   if (VecVT.getVectorElementType() == MVT::i1) {
2912     // FIXME: For now we just promote to an i8 vector and extract from that,
2913     // but this is probably not optimal.
2914     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
2915     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
2916     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
2917   }
2918 
2919   // If this is a fixed vector, we need to convert it to a scalable vector.
2920   MVT ContainerVT = VecVT;
2921   if (VecVT.isFixedLengthVector()) {
2922     ContainerVT = getContainerForFixedLengthVector(VecVT);
2923     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2924   }
2925 
2926   // If the index is 0, the vector is already in the right position.
2927   if (!isNullConstant(Idx)) {
2928     // Use a VL of 1 to avoid processing more elements than we need.
2929     SDValue VL = DAG.getConstant(1, DL, XLenVT);
2930     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
2931     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2932     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2933                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
2934   }
2935 
2936   if (!EltVT.isInteger()) {
2937     // Floating-point extracts are handled in TableGen.
2938     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
2939                        DAG.getConstant(0, DL, XLenVT));
2940   }
2941 
2942   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
2943   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
2944 }
2945 
2946 // Some RVV intrinsics may claim that they want an integer operand to be
2947 // promoted or expanded.
2948 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
2949                                           const RISCVSubtarget &Subtarget) {
2950   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2951           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
2952          "Unexpected opcode");
2953 
2954   if (!Subtarget.hasStdExtV())
2955     return SDValue();
2956 
2957   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
2958   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
2959   SDLoc DL(Op);
2960 
2961   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
2962       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
2963   if (!II || !II->SplatOperand)
2964     return SDValue();
2965 
2966   unsigned SplatOp = II->SplatOperand + HasChain;
2967   assert(SplatOp < Op.getNumOperands());
2968 
2969   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
2970   SDValue &ScalarOp = Operands[SplatOp];
2971   MVT OpVT = ScalarOp.getSimpleValueType();
2972   MVT XLenVT = Subtarget.getXLenVT();
2973 
2974   // If this isn't a scalar, or its type is XLenVT we're done.
2975   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
2976     return SDValue();
2977 
2978   // Simplest case is that the operand needs to be promoted to XLenVT.
2979   if (OpVT.bitsLT(XLenVT)) {
2980     // If the operand is a constant, sign extend to increase our chances
2981     // of being able to use a .vi instruction. ANY_EXTEND would become a
2982     // a zero extend and the simm5 check in isel would fail.
2983     // FIXME: Should we ignore the upper bits in isel instead?
2984     unsigned ExtOpc =
2985         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2986     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
2987     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
2988   }
2989 
2990   // Use the previous operand to get the vXi64 VT. The result might be a mask
2991   // VT for compares. Using the previous operand assumes that the previous
2992   // operand will never have a smaller element size than a scalar operand and
2993   // that a widening operation never uses SEW=64.
2994   // NOTE: If this fails the below assert, we can probably just find the
2995   // element count from any operand or result and use it to construct the VT.
2996   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
2997   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
2998 
2999   // The more complex case is when the scalar is larger than XLenVT.
3000   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
3001          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
3002 
3003   // If this is a sign-extended 32-bit constant, we can truncate it and rely
3004   // on the instruction to sign-extend since SEW>XLEN.
3005   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
3006     if (isInt<32>(CVal->getSExtValue())) {
3007       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3008       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3009     }
3010   }
3011 
3012   // We need to convert the scalar to a splat vector.
3013   // FIXME: Can we implicitly truncate the scalar if it is known to
3014   // be sign extended?
3015   // VL should be the last operand.
3016   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
3017   assert(VL.getValueType() == XLenVT);
3018   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
3019   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3020 }
3021 
3022 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3023                                                      SelectionDAG &DAG) const {
3024   unsigned IntNo = Op.getConstantOperandVal(0);
3025   SDLoc DL(Op);
3026   MVT XLenVT = Subtarget.getXLenVT();
3027 
3028   switch (IntNo) {
3029   default:
3030     break; // Don't custom lower most intrinsics.
3031   case Intrinsic::thread_pointer: {
3032     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3033     return DAG.getRegister(RISCV::X4, PtrVT);
3034   }
3035   case Intrinsic::riscv_orc_b:
3036     // Lower to the GORCI encoding for orc.b.
3037     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
3038                        DAG.getConstant(7, DL, XLenVT));
3039   case Intrinsic::riscv_vmv_x_s:
3040     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
3041     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
3042                        Op.getOperand(1));
3043   case Intrinsic::riscv_vmv_v_x:
3044     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
3045                             Op.getSimpleValueType(), DL, DAG, Subtarget);
3046   case Intrinsic::riscv_vfmv_v_f:
3047     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
3048                        Op.getOperand(1), Op.getOperand(2));
3049   case Intrinsic::riscv_vmv_s_x: {
3050     SDValue Scalar = Op.getOperand(2);
3051 
3052     if (Scalar.getValueType().bitsLE(XLenVT)) {
3053       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
3054       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
3055                          Op.getOperand(1), Scalar, Op.getOperand(3));
3056     }
3057 
3058     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
3059 
3060     // This is an i64 value that lives in two scalar registers. We have to
3061     // insert this in a convoluted way. First we build vXi64 splat containing
3062     // the/ two values that we assemble using some bit math. Next we'll use
3063     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
3064     // to merge element 0 from our splat into the source vector.
3065     // FIXME: This is probably not the best way to do this, but it is
3066     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
3067     // point.
3068     //   vmv.v.x vX, hi
3069     //   vsll.vx vX, vX, /*32*/
3070     //   vmv.v.x vY, lo
3071     //   vsll.vx vY, vY, /*32*/
3072     //   vsrl.vx vY, vY, /*32*/
3073     //   vor.vv vX, vX, vY
3074     //
3075     //   vid.v      vVid
3076     //   vmseq.vx   mMask, vVid, 0
3077     //   vmerge.vvm vDest, vSrc, vVal, mMask
3078     MVT VT = Op.getSimpleValueType();
3079     SDValue Vec = Op.getOperand(1);
3080     SDValue VL = Op.getOperand(3);
3081 
3082     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
3083     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
3084                                       DAG.getConstant(0, DL, MVT::i32), VL);
3085 
3086     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
3087     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3088     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
3089     SDValue SelectCond =
3090         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
3091                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
3092     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
3093                        Vec, VL);
3094   }
3095   case Intrinsic::riscv_vslide1up:
3096   case Intrinsic::riscv_vslide1down:
3097   case Intrinsic::riscv_vslide1up_mask:
3098   case Intrinsic::riscv_vslide1down_mask: {
3099     // We need to special case these when the scalar is larger than XLen.
3100     unsigned NumOps = Op.getNumOperands();
3101     bool IsMasked = NumOps == 6;
3102     unsigned OpOffset = IsMasked ? 1 : 0;
3103     SDValue Scalar = Op.getOperand(2 + OpOffset);
3104     if (Scalar.getValueType().bitsLE(XLenVT))
3105       break;
3106 
3107     // Splatting a sign extended constant is fine.
3108     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
3109       if (isInt<32>(CVal->getSExtValue()))
3110         break;
3111 
3112     MVT VT = Op.getSimpleValueType();
3113     assert(VT.getVectorElementType() == MVT::i64 &&
3114            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
3115 
3116     // Convert the vector source to the equivalent nxvXi32 vector.
3117     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
3118     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
3119 
3120     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3121                                    DAG.getConstant(0, DL, XLenVT));
3122     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3123                                    DAG.getConstant(1, DL, XLenVT));
3124 
3125     // Double the VL since we halved SEW.
3126     SDValue VL = Op.getOperand(NumOps - 1);
3127     SDValue I32VL =
3128         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
3129 
3130     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
3131     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
3132 
3133     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
3134     // instructions.
3135     if (IntNo == Intrinsic::riscv_vslide1up ||
3136         IntNo == Intrinsic::riscv_vslide1up_mask) {
3137       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
3138                         I32Mask, I32VL);
3139       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
3140                         I32Mask, I32VL);
3141     } else {
3142       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
3143                         I32Mask, I32VL);
3144       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
3145                         I32Mask, I32VL);
3146     }
3147 
3148     // Convert back to nxvXi64.
3149     Vec = DAG.getBitcast(VT, Vec);
3150 
3151     if (!IsMasked)
3152       return Vec;
3153 
3154     // Apply mask after the operation.
3155     SDValue Mask = Op.getOperand(NumOps - 2);
3156     SDValue MaskedOff = Op.getOperand(1);
3157     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
3158   }
3159   }
3160 
3161   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
3162 }
3163 
3164 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3165                                                     SelectionDAG &DAG) const {
3166   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
3167 }
3168 
3169 static MVT getLMUL1VT(MVT VT) {
3170   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
3171          "Unexpected vector MVT");
3172   return MVT::getScalableVectorVT(
3173       VT.getVectorElementType(),
3174       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
3175 }
3176 
3177 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
3178   switch (ISDOpcode) {
3179   default:
3180     llvm_unreachable("Unhandled reduction");
3181   case ISD::VECREDUCE_ADD:
3182     return RISCVISD::VECREDUCE_ADD_VL;
3183   case ISD::VECREDUCE_UMAX:
3184     return RISCVISD::VECREDUCE_UMAX_VL;
3185   case ISD::VECREDUCE_SMAX:
3186     return RISCVISD::VECREDUCE_SMAX_VL;
3187   case ISD::VECREDUCE_UMIN:
3188     return RISCVISD::VECREDUCE_UMIN_VL;
3189   case ISD::VECREDUCE_SMIN:
3190     return RISCVISD::VECREDUCE_SMIN_VL;
3191   case ISD::VECREDUCE_AND:
3192     return RISCVISD::VECREDUCE_AND_VL;
3193   case ISD::VECREDUCE_OR:
3194     return RISCVISD::VECREDUCE_OR_VL;
3195   case ISD::VECREDUCE_XOR:
3196     return RISCVISD::VECREDUCE_XOR_VL;
3197   }
3198 }
3199 
3200 SDValue RISCVTargetLowering::lowerVectorMaskVECREDUCE(SDValue Op,
3201                                                       SelectionDAG &DAG) const {
3202   SDLoc DL(Op);
3203   SDValue Vec = Op.getOperand(0);
3204   MVT VecVT = Vec.getSimpleValueType();
3205   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
3206           Op.getOpcode() == ISD::VECREDUCE_OR ||
3207           Op.getOpcode() == ISD::VECREDUCE_XOR) &&
3208          "Unexpected reduction lowering");
3209 
3210   MVT XLenVT = Subtarget.getXLenVT();
3211   assert(Op.getValueType() == XLenVT &&
3212          "Expected reduction output to be legalized to XLenVT");
3213 
3214   MVT ContainerVT = VecVT;
3215   if (VecVT.isFixedLengthVector()) {
3216     ContainerVT = getContainerForFixedLengthVector(VecVT);
3217     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3218   }
3219 
3220   SDValue Mask, VL;
3221   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3222   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3223 
3224   switch (Op.getOpcode()) {
3225   default:
3226     llvm_unreachable("Unhandled reduction");
3227   case ISD::VECREDUCE_AND:
3228     // vpopc ~x == 0
3229     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, Mask, VL);
3230     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
3231     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETEQ);
3232   case ISD::VECREDUCE_OR:
3233     // vpopc x != 0
3234     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
3235     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETNE);
3236   case ISD::VECREDUCE_XOR: {
3237     // ((vpopc x) & 1) != 0
3238     SDValue One = DAG.getConstant(1, DL, XLenVT);
3239     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
3240     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
3241     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETNE);
3242   }
3243   }
3244 }
3245 
3246 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
3247                                             SelectionDAG &DAG) const {
3248   SDLoc DL(Op);
3249   SDValue Vec = Op.getOperand(0);
3250   EVT VecEVT = Vec.getValueType();
3251 
3252   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
3253 
3254   // Due to ordering in legalize types we may have a vector type that needs to
3255   // be split. Do that manually so we can get down to a legal type.
3256   while (getTypeAction(*DAG.getContext(), VecEVT) ==
3257          TargetLowering::TypeSplitVector) {
3258     SDValue Lo, Hi;
3259     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
3260     VecEVT = Lo.getValueType();
3261     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
3262   }
3263 
3264   // TODO: The type may need to be widened rather than split. Or widened before
3265   // it can be split.
3266   if (!isTypeLegal(VecEVT))
3267     return SDValue();
3268 
3269   MVT VecVT = VecEVT.getSimpleVT();
3270   MVT VecEltVT = VecVT.getVectorElementType();
3271   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
3272 
3273   MVT ContainerVT = VecVT;
3274   if (VecVT.isFixedLengthVector()) {
3275     ContainerVT = getContainerForFixedLengthVector(VecVT);
3276     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3277   }
3278 
3279   MVT M1VT = getLMUL1VT(ContainerVT);
3280 
3281   SDValue Mask, VL;
3282   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3283 
3284   // FIXME: This is a VLMAX splat which might be too large and can prevent
3285   // vsetvli removal.
3286   SDValue NeutralElem =
3287       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
3288   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
3289   SDValue Reduction =
3290       DAG.getNode(RVVOpcode, DL, M1VT, Vec, IdentitySplat, Mask, VL);
3291   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
3292                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
3293   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
3294 }
3295 
3296 // Given a reduction op, this function returns the matching reduction opcode,
3297 // the vector SDValue and the scalar SDValue required to lower this to a
3298 // RISCVISD node.
3299 static std::tuple<unsigned, SDValue, SDValue>
3300 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
3301   SDLoc DL(Op);
3302   switch (Op.getOpcode()) {
3303   default:
3304     llvm_unreachable("Unhandled reduction");
3305   case ISD::VECREDUCE_FADD:
3306     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
3307                            DAG.getConstantFP(0.0, DL, EltVT));
3308   case ISD::VECREDUCE_SEQ_FADD:
3309     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
3310                            Op.getOperand(0));
3311   }
3312 }
3313 
3314 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
3315                                               SelectionDAG &DAG) const {
3316   SDLoc DL(Op);
3317   MVT VecEltVT = Op.getSimpleValueType();
3318 
3319   unsigned RVVOpcode;
3320   SDValue VectorVal, ScalarVal;
3321   std::tie(RVVOpcode, VectorVal, ScalarVal) =
3322       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
3323   MVT VecVT = VectorVal.getSimpleValueType();
3324 
3325   MVT ContainerVT = VecVT;
3326   if (VecVT.isFixedLengthVector()) {
3327     ContainerVT = getContainerForFixedLengthVector(VecVT);
3328     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
3329   }
3330 
3331   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
3332 
3333   SDValue Mask, VL;
3334   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3335 
3336   // FIXME: This is a VLMAX splat which might be too large and can prevent
3337   // vsetvli removal.
3338   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
3339   SDValue Reduction =
3340       DAG.getNode(RVVOpcode, DL, M1VT, VectorVal, ScalarSplat, Mask, VL);
3341   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
3342                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
3343 }
3344 
3345 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
3346                                                    SelectionDAG &DAG) const {
3347   SDValue Vec = Op.getOperand(0);
3348   SDValue SubVec = Op.getOperand(1);
3349   MVT VecVT = Vec.getSimpleValueType();
3350   MVT SubVecVT = SubVec.getSimpleValueType();
3351 
3352   SDLoc DL(Op);
3353   MVT XLenVT = Subtarget.getXLenVT();
3354   unsigned OrigIdx = Op.getConstantOperandVal(2);
3355   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
3356 
3357   // We don't have the ability to slide mask vectors up indexed by their i1
3358   // elements; the smallest we can do is i8. Often we are able to bitcast to
3359   // equivalent i8 vectors. Note that when inserting a fixed-length vector
3360   // into a scalable one, we might not necessarily have enough scalable
3361   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
3362   if (SubVecVT.getVectorElementType() == MVT::i1 &&
3363       (OrigIdx != 0 || !Vec.isUndef())) {
3364     if (VecVT.getVectorMinNumElements() >= 8 &&
3365         SubVecVT.getVectorMinNumElements() >= 8) {
3366       assert(OrigIdx % 8 == 0 && "Invalid index");
3367       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
3368              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
3369              "Unexpected mask vector lowering");
3370       OrigIdx /= 8;
3371       SubVecVT =
3372           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
3373                            SubVecVT.isScalableVector());
3374       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
3375                                VecVT.isScalableVector());
3376       Vec = DAG.getBitcast(VecVT, Vec);
3377       SubVec = DAG.getBitcast(SubVecVT, SubVec);
3378     } else {
3379       // We can't slide this mask vector up indexed by its i1 elements.
3380       // This poses a problem when we wish to insert a scalable vector which
3381       // can't be re-expressed as a larger type. Just choose the slow path and
3382       // extend to a larger type, then truncate back down.
3383       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
3384       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
3385       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
3386       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
3387       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
3388                         Op.getOperand(2));
3389       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
3390       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
3391     }
3392   }
3393 
3394   // If the subvector vector is a fixed-length type, we cannot use subregister
3395   // manipulation to simplify the codegen; we don't know which register of a
3396   // LMUL group contains the specific subvector as we only know the minimum
3397   // register size. Therefore we must slide the vector group up the full
3398   // amount.
3399   if (SubVecVT.isFixedLengthVector()) {
3400     if (OrigIdx == 0 && Vec.isUndef())
3401       return Op;
3402     MVT ContainerVT = VecVT;
3403     if (VecVT.isFixedLengthVector()) {
3404       ContainerVT = getContainerForFixedLengthVector(VecVT);
3405       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3406     }
3407     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
3408                          DAG.getUNDEF(ContainerVT), SubVec,
3409                          DAG.getConstant(0, DL, XLenVT));
3410     SDValue Mask =
3411         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
3412     // Set the vector length to only the number of elements we care about. Note
3413     // that for slideup this includes the offset.
3414     SDValue VL =
3415         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
3416     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
3417     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3418                                   SubVec, SlideupAmt, Mask, VL);
3419     if (VecVT.isFixedLengthVector())
3420       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3421     return DAG.getBitcast(Op.getValueType(), Slideup);
3422   }
3423 
3424   unsigned SubRegIdx, RemIdx;
3425   std::tie(SubRegIdx, RemIdx) =
3426       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
3427           VecVT, SubVecVT, OrigIdx, TRI);
3428 
3429   RISCVVLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
3430   bool IsSubVecPartReg = SubVecLMUL == RISCVVLMUL::LMUL_F2 ||
3431                          SubVecLMUL == RISCVVLMUL::LMUL_F4 ||
3432                          SubVecLMUL == RISCVVLMUL::LMUL_F8;
3433 
3434   // 1. If the Idx has been completely eliminated and this subvector's size is
3435   // a vector register or a multiple thereof, or the surrounding elements are
3436   // undef, then this is a subvector insert which naturally aligns to a vector
3437   // register. These can easily be handled using subregister manipulation.
3438   // 2. If the subvector is smaller than a vector register, then the insertion
3439   // must preserve the undisturbed elements of the register. We do this by
3440   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
3441   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
3442   // subvector within the vector register, and an INSERT_SUBVECTOR of that
3443   // LMUL=1 type back into the larger vector (resolving to another subregister
3444   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
3445   // to avoid allocating a large register group to hold our subvector.
3446   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
3447     return Op;
3448 
3449   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
3450   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
3451   // (in our case undisturbed). This means we can set up a subvector insertion
3452   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
3453   // size of the subvector.
3454   MVT InterSubVT = VecVT;
3455   SDValue AlignedExtract = Vec;
3456   unsigned AlignedIdx = OrigIdx - RemIdx;
3457   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
3458     InterSubVT = getLMUL1VT(VecVT);
3459     // Extract a subvector equal to the nearest full vector register type. This
3460     // should resolve to a EXTRACT_SUBREG instruction.
3461     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
3462                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
3463   }
3464 
3465   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
3466   // For scalable vectors this must be further multiplied by vscale.
3467   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
3468 
3469   SDValue Mask, VL;
3470   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
3471 
3472   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
3473   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
3474   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
3475   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
3476 
3477   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
3478                        DAG.getUNDEF(InterSubVT), SubVec,
3479                        DAG.getConstant(0, DL, XLenVT));
3480 
3481   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
3482                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
3483 
3484   // If required, insert this subvector back into the correct vector register.
3485   // This should resolve to an INSERT_SUBREG instruction.
3486   if (VecVT.bitsGT(InterSubVT))
3487     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
3488                           DAG.getConstant(AlignedIdx, DL, XLenVT));
3489 
3490   // We might have bitcast from a mask type: cast back to the original type if
3491   // required.
3492   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
3493 }
3494 
3495 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
3496                                                     SelectionDAG &DAG) const {
3497   SDValue Vec = Op.getOperand(0);
3498   MVT SubVecVT = Op.getSimpleValueType();
3499   MVT VecVT = Vec.getSimpleValueType();
3500 
3501   SDLoc DL(Op);
3502   MVT XLenVT = Subtarget.getXLenVT();
3503   unsigned OrigIdx = Op.getConstantOperandVal(1);
3504   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
3505 
3506   // We don't have the ability to slide mask vectors down indexed by their i1
3507   // elements; the smallest we can do is i8. Often we are able to bitcast to
3508   // equivalent i8 vectors. Note that when extracting a fixed-length vector
3509   // from a scalable one, we might not necessarily have enough scalable
3510   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
3511   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
3512     if (VecVT.getVectorMinNumElements() >= 8 &&
3513         SubVecVT.getVectorMinNumElements() >= 8) {
3514       assert(OrigIdx % 8 == 0 && "Invalid index");
3515       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
3516              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
3517              "Unexpected mask vector lowering");
3518       OrigIdx /= 8;
3519       SubVecVT =
3520           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
3521                            SubVecVT.isScalableVector());
3522       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
3523                                VecVT.isScalableVector());
3524       Vec = DAG.getBitcast(VecVT, Vec);
3525     } else {
3526       // We can't slide this mask vector down, indexed by its i1 elements.
3527       // This poses a problem when we wish to extract a scalable vector which
3528       // can't be re-expressed as a larger type. Just choose the slow path and
3529       // extend to a larger type, then truncate back down.
3530       // TODO: We could probably improve this when extracting certain fixed
3531       // from fixed, where we can extract as i8 and shift the correct element
3532       // right to reach the desired subvector?
3533       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
3534       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
3535       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
3536       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
3537                         Op.getOperand(1));
3538       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
3539       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
3540     }
3541   }
3542 
3543   // If the subvector vector is a fixed-length type, we cannot use subregister
3544   // manipulation to simplify the codegen; we don't know which register of a
3545   // LMUL group contains the specific subvector as we only know the minimum
3546   // register size. Therefore we must slide the vector group down the full
3547   // amount.
3548   if (SubVecVT.isFixedLengthVector()) {
3549     // With an index of 0 this is a cast-like subvector, which can be performed
3550     // with subregister operations.
3551     if (OrigIdx == 0)
3552       return Op;
3553     MVT ContainerVT = VecVT;
3554     if (VecVT.isFixedLengthVector()) {
3555       ContainerVT = getContainerForFixedLengthVector(VecVT);
3556       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3557     }
3558     SDValue Mask =
3559         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
3560     // Set the vector length to only the number of elements we care about. This
3561     // avoids sliding down elements we're going to discard straight away.
3562     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
3563     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
3564     SDValue Slidedown =
3565         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3566                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
3567     // Now we can use a cast-like subvector extract to get the result.
3568     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
3569                             DAG.getConstant(0, DL, XLenVT));
3570     return DAG.getBitcast(Op.getValueType(), Slidedown);
3571   }
3572 
3573   unsigned SubRegIdx, RemIdx;
3574   std::tie(SubRegIdx, RemIdx) =
3575       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
3576           VecVT, SubVecVT, OrigIdx, TRI);
3577 
3578   // If the Idx has been completely eliminated then this is a subvector extract
3579   // which naturally aligns to a vector register. These can easily be handled
3580   // using subregister manipulation.
3581   if (RemIdx == 0)
3582     return Op;
3583 
3584   // Else we must shift our vector register directly to extract the subvector.
3585   // Do this using VSLIDEDOWN.
3586 
3587   // If the vector type is an LMUL-group type, extract a subvector equal to the
3588   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
3589   // instruction.
3590   MVT InterSubVT = VecVT;
3591   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
3592     InterSubVT = getLMUL1VT(VecVT);
3593     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
3594                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
3595   }
3596 
3597   // Slide this vector register down by the desired number of elements in order
3598   // to place the desired subvector starting at element 0.
3599   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
3600   // For scalable vectors this must be further multiplied by vscale.
3601   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
3602 
3603   SDValue Mask, VL;
3604   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
3605   SDValue Slidedown =
3606       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
3607                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
3608 
3609   // Now the vector is in the right position, extract our final subvector. This
3610   // should resolve to a COPY.
3611   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
3612                           DAG.getConstant(0, DL, XLenVT));
3613 
3614   // We might have bitcast from a mask type: cast back to the original type if
3615   // required.
3616   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
3617 }
3618 
3619 // Implement step_vector to the vid instruction.
3620 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
3621                                               SelectionDAG &DAG) const {
3622   SDLoc DL(Op);
3623   assert(Op.getConstantOperandAPInt(0) == 1 && "Unexpected step value");
3624   MVT VT = Op.getSimpleValueType();
3625   SDValue Mask, VL;
3626   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
3627   return DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
3628 }
3629 
3630 // Implement vector_reverse using vrgather.vv with indices determined by
3631 // subtracting the id of each element from (VLMAX-1). This will convert
3632 // the indices like so:
3633 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
3634 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
3635 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
3636                                                  SelectionDAG &DAG) const {
3637   SDLoc DL(Op);
3638   MVT VecVT = Op.getSimpleValueType();
3639   unsigned EltSize = VecVT.getScalarSizeInBits();
3640   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
3641 
3642   unsigned MaxVLMAX = 0;
3643   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
3644   if (VectorBitsMax != 0)
3645     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
3646 
3647   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
3648   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
3649 
3650   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
3651   // to use vrgatherei16.vv.
3652   // TODO: It's also possible to use vrgatherei16.vv for other types to
3653   // decrease register width for the index calculation.
3654   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
3655     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
3656     // Reverse each half, then reassemble them in reverse order.
3657     // NOTE: It's also possible that after splitting that VLMAX no longer
3658     // requires vrgatherei16.vv.
3659     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
3660       SDValue Lo, Hi;
3661       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3662       EVT LoVT, HiVT;
3663       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
3664       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
3665       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
3666       // Reassemble the low and high pieces reversed.
3667       // FIXME: This is a CONCAT_VECTORS.
3668       SDValue Res =
3669           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
3670                       DAG.getIntPtrConstant(0, DL));
3671       return DAG.getNode(
3672           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
3673           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
3674     }
3675 
3676     // Just promote the int type to i16 which will double the LMUL.
3677     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
3678     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
3679   }
3680 
3681   MVT XLenVT = Subtarget.getXLenVT();
3682   SDValue Mask, VL;
3683   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
3684 
3685   // Calculate VLMAX-1 for the desired SEW.
3686   unsigned MinElts = VecVT.getVectorMinNumElements();
3687   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
3688                               DAG.getConstant(MinElts, DL, XLenVT));
3689   SDValue VLMinus1 =
3690       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
3691 
3692   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
3693   bool IsRV32E64 =
3694       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
3695   SDValue SplatVL;
3696   if (!IsRV32E64)
3697     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
3698   else
3699     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
3700 
3701   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
3702   SDValue Indices =
3703       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
3704 
3705   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
3706 }
3707 
3708 SDValue
3709 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
3710                                                      SelectionDAG &DAG) const {
3711   auto *Load = cast<LoadSDNode>(Op);
3712 
3713   SDLoc DL(Op);
3714   MVT VT = Op.getSimpleValueType();
3715   MVT ContainerVT = getContainerForFixedLengthVector(VT);
3716 
3717   SDValue VL =
3718       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
3719 
3720   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
3721   SDValue NewLoad = DAG.getMemIntrinsicNode(
3722       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
3723       Load->getMemoryVT(), Load->getMemOperand());
3724 
3725   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
3726   return DAG.getMergeValues({Result, Load->getChain()}, DL);
3727 }
3728 
3729 SDValue
3730 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
3731                                                       SelectionDAG &DAG) const {
3732   auto *Store = cast<StoreSDNode>(Op);
3733 
3734   SDLoc DL(Op);
3735   SDValue StoreVal = Store->getValue();
3736   MVT VT = StoreVal.getSimpleValueType();
3737 
3738   // If the size less than a byte, we need to pad with zeros to make a byte.
3739   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
3740     VT = MVT::v8i1;
3741     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3742                            DAG.getConstant(0, DL, VT), StoreVal,
3743                            DAG.getIntPtrConstant(0, DL));
3744   }
3745 
3746   MVT ContainerVT = getContainerForFixedLengthVector(VT);
3747 
3748   SDValue VL =
3749       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
3750 
3751   SDValue NewValue =
3752       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
3753   return DAG.getMemIntrinsicNode(
3754       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
3755       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
3756       Store->getMemoryVT(), Store->getMemOperand());
3757 }
3758 
3759 SDValue RISCVTargetLowering::lowerMLOAD(SDValue Op, SelectionDAG &DAG) const {
3760   auto *Load = cast<MaskedLoadSDNode>(Op);
3761 
3762   SDLoc DL(Op);
3763   MVT VT = Op.getSimpleValueType();
3764   MVT XLenVT = Subtarget.getXLenVT();
3765 
3766   SDValue Mask = Load->getMask();
3767   SDValue PassThru = Load->getPassThru();
3768   SDValue VL;
3769 
3770   MVT ContainerVT = VT;
3771   if (VT.isFixedLengthVector()) {
3772     ContainerVT = getContainerForFixedLengthVector(VT);
3773     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3774 
3775     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
3776     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
3777     VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
3778   } else
3779     VL = DAG.getRegister(RISCV::X0, XLenVT);
3780 
3781   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
3782   SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vle_mask, DL, XLenVT);
3783   SDValue Ops[] = {Load->getChain(),   IntID, PassThru,
3784                    Load->getBasePtr(), Mask,  VL};
3785   SDValue Result =
3786       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
3787                               Load->getMemoryVT(), Load->getMemOperand());
3788   SDValue Chain = Result.getValue(1);
3789 
3790   if (VT.isFixedLengthVector())
3791     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3792 
3793   return DAG.getMergeValues({Result, Chain}, DL);
3794 }
3795 
3796 SDValue RISCVTargetLowering::lowerMSTORE(SDValue Op, SelectionDAG &DAG) const {
3797   auto *Store = cast<MaskedStoreSDNode>(Op);
3798 
3799   SDLoc DL(Op);
3800   SDValue Val = Store->getValue();
3801   SDValue Mask = Store->getMask();
3802   MVT VT = Val.getSimpleValueType();
3803   MVT XLenVT = Subtarget.getXLenVT();
3804   SDValue VL;
3805 
3806   MVT ContainerVT = VT;
3807   if (VT.isFixedLengthVector()) {
3808     ContainerVT = getContainerForFixedLengthVector(VT);
3809     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3810 
3811     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
3812     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
3813     VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
3814   } else
3815     VL = DAG.getRegister(RISCV::X0, XLenVT);
3816 
3817   SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vse_mask, DL, XLenVT);
3818   return DAG.getMemIntrinsicNode(
3819       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
3820       {Store->getChain(), IntID, Val, Store->getBasePtr(), Mask, VL},
3821       Store->getMemoryVT(), Store->getMemOperand());
3822 }
3823 
3824 SDValue
3825 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
3826                                                       SelectionDAG &DAG) const {
3827   MVT InVT = Op.getOperand(0).getSimpleValueType();
3828   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
3829 
3830   MVT VT = Op.getSimpleValueType();
3831 
3832   SDValue Op1 =
3833       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3834   SDValue Op2 =
3835       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
3836 
3837   SDLoc DL(Op);
3838   SDValue VL =
3839       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
3840 
3841   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3842   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3843 
3844   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
3845                             Op.getOperand(2), Mask, VL);
3846 
3847   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
3848 }
3849 
3850 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
3851     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
3852   MVT VT = Op.getSimpleValueType();
3853 
3854   if (VT.getVectorElementType() == MVT::i1)
3855     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
3856 
3857   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
3858 }
3859 
3860 // Lower vector ABS to smax(X, sub(0, X)).
3861 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
3862   SDLoc DL(Op);
3863   MVT VT = Op.getSimpleValueType();
3864   SDValue X = Op.getOperand(0);
3865 
3866   assert(VT.isFixedLengthVector() && "Unexpected type");
3867 
3868   MVT ContainerVT = getContainerForFixedLengthVector(VT);
3869   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
3870 
3871   SDValue Mask, VL;
3872   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3873 
3874   SDValue SplatZero =
3875       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
3876                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
3877   SDValue NegX =
3878       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
3879   SDValue Max =
3880       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
3881 
3882   return convertFromScalableVector(VT, Max, DAG, Subtarget);
3883 }
3884 
3885 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
3886     SDValue Op, SelectionDAG &DAG) const {
3887   SDLoc DL(Op);
3888   MVT VT = Op.getSimpleValueType();
3889   SDValue Mag = Op.getOperand(0);
3890   SDValue Sign = Op.getOperand(1);
3891   assert(Mag.getValueType() == Sign.getValueType() &&
3892          "Can only handle COPYSIGN with matching types.");
3893 
3894   MVT ContainerVT = getContainerForFixedLengthVector(VT);
3895   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
3896   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
3897 
3898   SDValue Mask, VL;
3899   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3900 
3901   SDValue CopySign =
3902       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
3903 
3904   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
3905 }
3906 
3907 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
3908     SDValue Op, SelectionDAG &DAG) const {
3909   MVT VT = Op.getSimpleValueType();
3910   MVT ContainerVT = getContainerForFixedLengthVector(VT);
3911 
3912   MVT I1ContainerVT =
3913       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3914 
3915   SDValue CC =
3916       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
3917   SDValue Op1 =
3918       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
3919   SDValue Op2 =
3920       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
3921 
3922   SDLoc DL(Op);
3923   SDValue Mask, VL;
3924   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3925 
3926   SDValue Select =
3927       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
3928 
3929   return convertFromScalableVector(VT, Select, DAG, Subtarget);
3930 }
3931 
3932 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
3933                                                unsigned NewOpc,
3934                                                bool HasMask) const {
3935   MVT VT = Op.getSimpleValueType();
3936   assert(useRVVForFixedLengthVectorVT(VT) &&
3937          "Only expected to lower fixed length vector operation!");
3938   MVT ContainerVT = getContainerForFixedLengthVector(VT);
3939 
3940   // Create list of operands by converting existing ones to scalable types.
3941   SmallVector<SDValue, 6> Ops;
3942   for (const SDValue &V : Op->op_values()) {
3943     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
3944 
3945     // Pass through non-vector operands.
3946     if (!V.getValueType().isVector()) {
3947       Ops.push_back(V);
3948       continue;
3949     }
3950 
3951     // "cast" fixed length vector to a scalable vector.
3952     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
3953            "Only fixed length vectors are supported!");
3954     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
3955   }
3956 
3957   SDLoc DL(Op);
3958   SDValue Mask, VL;
3959   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3960   if (HasMask)
3961     Ops.push_back(Mask);
3962   Ops.push_back(VL);
3963 
3964   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
3965   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
3966 }
3967 
3968 // Custom lower MGATHER to a legalized form for RVV. It will then be matched to
3969 // a RVV indexed load. The RVV indexed load instructions only support the
3970 // "unsigned unscaled" addressing mode; indices are implicitly zero-extended or
3971 // truncated to XLEN and are treated as byte offsets. Any signed or scaled
3972 // indexing is extended to the XLEN value type and scaled accordingly.
3973 SDValue RISCVTargetLowering::lowerMGATHER(SDValue Op, SelectionDAG &DAG) const {
3974   auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
3975   SDLoc DL(Op);
3976 
3977   SDValue Index = MGN->getIndex();
3978   SDValue Mask = MGN->getMask();
3979   SDValue PassThru = MGN->getPassThru();
3980 
3981   MVT VT = Op.getSimpleValueType();
3982   MVT IndexVT = Index.getSimpleValueType();
3983   MVT XLenVT = Subtarget.getXLenVT();
3984 
3985   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
3986          "Unexpected VTs!");
3987   assert(MGN->getBasePtr().getSimpleValueType() == XLenVT &&
3988          "Unexpected pointer type");
3989   // Targets have to explicitly opt-in for extending vector loads.
3990   assert(MGN->getExtensionType() == ISD::NON_EXTLOAD &&
3991          "Unexpected extending MGATHER");
3992 
3993   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
3994   // the selection of the masked intrinsics doesn't do this for us.
3995   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
3996 
3997   SDValue VL;
3998   MVT ContainerVT = VT;
3999   if (VT.isFixedLengthVector()) {
4000     // We need to use the larger of the result and index type to determine the
4001     // scalable type to use so we don't increase LMUL for any operand/result.
4002     if (VT.bitsGE(IndexVT)) {
4003       ContainerVT = getContainerForFixedLengthVector(VT);
4004       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
4005                                  ContainerVT.getVectorElementCount());
4006     } else {
4007       IndexVT = getContainerForFixedLengthVector(IndexVT);
4008       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
4009                                      IndexVT.getVectorElementCount());
4010     }
4011 
4012     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
4013 
4014     if (!IsUnmasked) {
4015       MVT MaskVT =
4016           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4017       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4018       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4019     }
4020 
4021     VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4022   } else
4023     VL = DAG.getRegister(RISCV::X0, XLenVT);
4024 
4025   unsigned IntID =
4026       IsUnmasked ? Intrinsic::riscv_vloxei : Intrinsic::riscv_vloxei_mask;
4027   SmallVector<SDValue, 8> Ops{MGN->getChain(),
4028                               DAG.getTargetConstant(IntID, DL, XLenVT)};
4029   if (!IsUnmasked)
4030     Ops.push_back(PassThru);
4031   Ops.push_back(MGN->getBasePtr());
4032   Ops.push_back(Index);
4033   if (!IsUnmasked)
4034     Ops.push_back(Mask);
4035   Ops.push_back(VL);
4036 
4037   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4038   SDValue Result =
4039       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4040                               MGN->getMemoryVT(), MGN->getMemOperand());
4041   SDValue Chain = Result.getValue(1);
4042 
4043   if (VT.isFixedLengthVector())
4044     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4045 
4046   return DAG.getMergeValues({Result, Chain}, DL);
4047 }
4048 
4049 // Custom lower MSCATTER to a legalized form for RVV. It will then be matched to
4050 // a RVV indexed store. The RVV indexed store instructions only support the
4051 // "unsigned unscaled" addressing mode; indices are implicitly zero-extended or
4052 // truncated to XLEN and are treated as byte offsets. Any signed or scaled
4053 // indexing is extended to the XLEN value type and scaled accordingly.
4054 SDValue RISCVTargetLowering::lowerMSCATTER(SDValue Op,
4055                                            SelectionDAG &DAG) const {
4056   auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
4057   SDLoc DL(Op);
4058   SDValue Index = MSN->getIndex();
4059   SDValue Mask = MSN->getMask();
4060   SDValue Val = MSN->getValue();
4061 
4062   MVT VT = Val.getSimpleValueType();
4063   MVT IndexVT = Index.getSimpleValueType();
4064   MVT XLenVT = Subtarget.getXLenVT();
4065 
4066   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
4067          "Unexpected VTs!");
4068   assert(MSN->getBasePtr().getSimpleValueType() == XLenVT &&
4069          "Unexpected pointer type");
4070   // Targets have to explicitly opt-in for extending vector loads and
4071   // truncating vector stores.
4072   assert(!MSN->isTruncatingStore() && "Unexpected extending MSCATTER");
4073 
4074   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4075   // the selection of the masked intrinsics doesn't do this for us.
4076   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4077 
4078   SDValue VL;
4079   if (VT.isFixedLengthVector()) {
4080     // We need to use the larger of the value and index type to determine the
4081     // scalable type to use so we don't increase LMUL for any operand/result.
4082     if (VT.bitsGE(IndexVT)) {
4083       VT = getContainerForFixedLengthVector(VT);
4084       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
4085                                  VT.getVectorElementCount());
4086     } else {
4087       IndexVT = getContainerForFixedLengthVector(IndexVT);
4088       VT = MVT::getVectorVT(VT.getVectorElementType(),
4089                             IndexVT.getVectorElementCount());
4090     }
4091 
4092     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
4093     Val = convertToScalableVector(VT, Val, DAG, Subtarget);
4094 
4095     if (!IsUnmasked) {
4096       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4097       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4098     }
4099 
4100     VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4101   } else
4102     VL = DAG.getRegister(RISCV::X0, XLenVT);
4103 
4104   unsigned IntID =
4105       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
4106   SmallVector<SDValue, 8> Ops{MSN->getChain(),
4107                               DAG.getTargetConstant(IntID, DL, XLenVT)};
4108   Ops.push_back(Val);
4109   Ops.push_back(MSN->getBasePtr());
4110   Ops.push_back(Index);
4111   if (!IsUnmasked)
4112     Ops.push_back(Mask);
4113   Ops.push_back(VL);
4114 
4115   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, MSN->getVTList(), Ops,
4116                                  MSN->getMemoryVT(), MSN->getMemOperand());
4117 }
4118 
4119 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
4120                                                SelectionDAG &DAG) const {
4121   const MVT XLenVT = Subtarget.getXLenVT();
4122   SDLoc DL(Op);
4123   SDValue Chain = Op->getOperand(0);
4124   SDValue SysRegNo = DAG.getConstant(
4125       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
4126   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
4127   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
4128 
4129   // Encoding used for rounding mode in RISCV differs from that used in
4130   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
4131   // table, which consists of a sequence of 4-bit fields, each representing
4132   // corresponding FLT_ROUNDS mode.
4133   static const int Table =
4134       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
4135       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
4136       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
4137       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
4138       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
4139 
4140   SDValue Shift =
4141       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
4142   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
4143                                 DAG.getConstant(Table, DL, XLenVT), Shift);
4144   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
4145                                DAG.getConstant(7, DL, XLenVT));
4146 
4147   return DAG.getMergeValues({Masked, Chain}, DL);
4148 }
4149 
4150 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
4151                                                SelectionDAG &DAG) const {
4152   const MVT XLenVT = Subtarget.getXLenVT();
4153   SDLoc DL(Op);
4154   SDValue Chain = Op->getOperand(0);
4155   SDValue RMValue = Op->getOperand(1);
4156   SDValue SysRegNo = DAG.getConstant(
4157       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
4158 
4159   // Encoding used for rounding mode in RISCV differs from that used in
4160   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
4161   // a table, which consists of a sequence of 4-bit fields, each representing
4162   // corresponding RISCV mode.
4163   static const unsigned Table =
4164       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
4165       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
4166       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
4167       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
4168       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
4169 
4170   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
4171                               DAG.getConstant(2, DL, XLenVT));
4172   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
4173                                 DAG.getConstant(Table, DL, XLenVT), Shift);
4174   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
4175                         DAG.getConstant(0x7, DL, XLenVT));
4176   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
4177                      RMValue);
4178 }
4179 
4180 // Returns the opcode of the target-specific SDNode that implements the 32-bit
4181 // form of the given Opcode.
4182 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
4183   switch (Opcode) {
4184   default:
4185     llvm_unreachable("Unexpected opcode");
4186   case ISD::SHL:
4187     return RISCVISD::SLLW;
4188   case ISD::SRA:
4189     return RISCVISD::SRAW;
4190   case ISD::SRL:
4191     return RISCVISD::SRLW;
4192   case ISD::SDIV:
4193     return RISCVISD::DIVW;
4194   case ISD::UDIV:
4195     return RISCVISD::DIVUW;
4196   case ISD::UREM:
4197     return RISCVISD::REMUW;
4198   case ISD::ROTL:
4199     return RISCVISD::ROLW;
4200   case ISD::ROTR:
4201     return RISCVISD::RORW;
4202   case RISCVISD::GREV:
4203     return RISCVISD::GREVW;
4204   case RISCVISD::GORC:
4205     return RISCVISD::GORCW;
4206   }
4207 }
4208 
4209 // Converts the given 32-bit operation to a target-specific SelectionDAG node.
4210 // Because i32 isn't a legal type for RV64, these operations would otherwise
4211 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W
4212 // later one because the fact the operation was originally of type i32 is
4213 // lost.
4214 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
4215                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
4216   SDLoc DL(N);
4217   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
4218   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
4219   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
4220   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
4221   // ReplaceNodeResults requires we maintain the same type for the return value.
4222   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
4223 }
4224 
4225 // Converts the given 32-bit operation to a i64 operation with signed extension
4226 // semantic to reduce the signed extension instructions.
4227 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
4228   SDLoc DL(N);
4229   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
4230   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
4231   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
4232   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
4233                                DAG.getValueType(MVT::i32));
4234   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
4235 }
4236 
4237 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
4238                                              SmallVectorImpl<SDValue> &Results,
4239                                              SelectionDAG &DAG) const {
4240   SDLoc DL(N);
4241   switch (N->getOpcode()) {
4242   default:
4243     llvm_unreachable("Don't know how to custom type legalize this operation!");
4244   case ISD::STRICT_FP_TO_SINT:
4245   case ISD::STRICT_FP_TO_UINT:
4246   case ISD::FP_TO_SINT:
4247   case ISD::FP_TO_UINT: {
4248     bool IsStrict = N->isStrictFPOpcode();
4249     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4250            "Unexpected custom legalisation");
4251     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
4252     // If the FP type needs to be softened, emit a library call using the 'si'
4253     // version. If we left it to default legalization we'd end up with 'di'. If
4254     // the FP type doesn't need to be softened just let generic type
4255     // legalization promote the result type.
4256     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
4257         TargetLowering::TypeSoftenFloat)
4258       return;
4259     RTLIB::Libcall LC;
4260     if (N->getOpcode() == ISD::FP_TO_SINT ||
4261         N->getOpcode() == ISD::STRICT_FP_TO_SINT)
4262       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
4263     else
4264       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
4265     MakeLibCallOptions CallOptions;
4266     EVT OpVT = Op0.getValueType();
4267     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
4268     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
4269     SDValue Result;
4270     std::tie(Result, Chain) =
4271         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
4272     Results.push_back(Result);
4273     if (IsStrict)
4274       Results.push_back(Chain);
4275     break;
4276   }
4277   case ISD::READCYCLECOUNTER: {
4278     assert(!Subtarget.is64Bit() &&
4279            "READCYCLECOUNTER only has custom type legalization on riscv32");
4280 
4281     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
4282     SDValue RCW =
4283         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
4284 
4285     Results.push_back(
4286         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
4287     Results.push_back(RCW.getValue(2));
4288     break;
4289   }
4290   case ISD::MUL: {
4291     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
4292     unsigned XLen = Subtarget.getXLen();
4293     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
4294     if (Size > XLen) {
4295       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
4296       SDValue LHS = N->getOperand(0);
4297       SDValue RHS = N->getOperand(1);
4298       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
4299 
4300       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
4301       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
4302       // We need exactly one side to be unsigned.
4303       if (LHSIsU == RHSIsU)
4304         return;
4305 
4306       auto MakeMULPair = [&](SDValue S, SDValue U) {
4307         MVT XLenVT = Subtarget.getXLenVT();
4308         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
4309         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
4310         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
4311         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
4312         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
4313       };
4314 
4315       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
4316       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
4317 
4318       // The other operand should be signed, but still prefer MULH when
4319       // possible.
4320       if (RHSIsU && LHSIsS && !RHSIsS)
4321         Results.push_back(MakeMULPair(LHS, RHS));
4322       else if (LHSIsU && RHSIsS && !LHSIsS)
4323         Results.push_back(MakeMULPair(RHS, LHS));
4324 
4325       return;
4326     }
4327     LLVM_FALLTHROUGH;
4328   }
4329   case ISD::ADD:
4330   case ISD::SUB:
4331     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4332            "Unexpected custom legalisation");
4333     if (N->getOperand(1).getOpcode() == ISD::Constant)
4334       return;
4335     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
4336     break;
4337   case ISD::SHL:
4338   case ISD::SRA:
4339   case ISD::SRL:
4340     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4341            "Unexpected custom legalisation");
4342     if (N->getOperand(1).getOpcode() == ISD::Constant)
4343       return;
4344     Results.push_back(customLegalizeToWOp(N, DAG));
4345     break;
4346   case ISD::ROTL:
4347   case ISD::ROTR:
4348     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4349            "Unexpected custom legalisation");
4350     Results.push_back(customLegalizeToWOp(N, DAG));
4351     break;
4352   case ISD::CTTZ:
4353   case ISD::CTTZ_ZERO_UNDEF:
4354   case ISD::CTLZ:
4355   case ISD::CTLZ_ZERO_UNDEF: {
4356     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4357            "Unexpected custom legalisation");
4358 
4359     SDValue NewOp0 =
4360         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
4361     bool IsCTZ =
4362         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
4363     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
4364     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
4365     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
4366     return;
4367   }
4368   case ISD::SDIV:
4369   case ISD::UDIV:
4370   case ISD::UREM: {
4371     MVT VT = N->getSimpleValueType(0);
4372     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
4373            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
4374            "Unexpected custom legalisation");
4375     if (N->getOperand(0).getOpcode() == ISD::Constant ||
4376         N->getOperand(1).getOpcode() == ISD::Constant)
4377       return;
4378 
4379     // If the input is i32, use ANY_EXTEND since the W instructions don't read
4380     // the upper 32 bits. For other types we need to sign or zero extend
4381     // based on the opcode.
4382     unsigned ExtOpc = ISD::ANY_EXTEND;
4383     if (VT != MVT::i32)
4384       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
4385                                            : ISD::ZERO_EXTEND;
4386 
4387     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
4388     break;
4389   }
4390   case ISD::UADDO:
4391   case ISD::USUBO: {
4392     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4393            "Unexpected custom legalisation");
4394     bool IsAdd = N->getOpcode() == ISD::UADDO;
4395     // Create an ADDW or SUBW.
4396     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
4397     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
4398     SDValue Res =
4399         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
4400     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
4401                       DAG.getValueType(MVT::i32));
4402 
4403     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
4404     // Since the inputs are sign extended from i32, this is equivalent to
4405     // comparing the lower 32 bits.
4406     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
4407     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
4408                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
4409 
4410     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
4411     Results.push_back(Overflow);
4412     return;
4413   }
4414   case ISD::UADDSAT:
4415   case ISD::USUBSAT: {
4416     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4417            "Unexpected custom legalisation");
4418     if (Subtarget.hasStdExtZbb()) {
4419       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
4420       // sign extend allows overflow of the lower 32 bits to be detected on
4421       // the promoted size.
4422       SDValue LHS =
4423           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
4424       SDValue RHS =
4425           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
4426       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
4427       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
4428       return;
4429     }
4430 
4431     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
4432     // promotion for UADDO/USUBO.
4433     Results.push_back(expandAddSubSat(N, DAG));
4434     return;
4435   }
4436   case ISD::BITCAST: {
4437     EVT VT = N->getValueType(0);
4438     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
4439     SDValue Op0 = N->getOperand(0);
4440     EVT Op0VT = Op0.getValueType();
4441     MVT XLenVT = Subtarget.getXLenVT();
4442     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
4443       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
4444       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
4445     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
4446                Subtarget.hasStdExtF()) {
4447       SDValue FPConv =
4448           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
4449       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
4450     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
4451                isTypeLegal(Op0VT)) {
4452       // Custom-legalize bitcasts from fixed-length vector types to illegal
4453       // scalar types in order to improve codegen. Bitcast the vector to a
4454       // one-element vector type whose element type is the same as the result
4455       // type, and extract the first element.
4456       LLVMContext &Context = *DAG.getContext();
4457       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
4458       Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
4459                                     DAG.getConstant(0, DL, XLenVT)));
4460     }
4461     break;
4462   }
4463   case RISCVISD::GREV:
4464   case RISCVISD::GORC: {
4465     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4466            "Unexpected custom legalisation");
4467     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
4468     // This is similar to customLegalizeToWOp, except that we pass the second
4469     // operand (a TargetConstant) straight through: it is already of type
4470     // XLenVT.
4471     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
4472     SDValue NewOp0 =
4473         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
4474     SDValue NewOp1 =
4475         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
4476     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
4477     // ReplaceNodeResults requires we maintain the same type for the return
4478     // value.
4479     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
4480     break;
4481   }
4482   case RISCVISD::SHFL: {
4483     // There is no SHFLIW instruction, but we can just promote the operation.
4484     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4485            "Unexpected custom legalisation");
4486     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
4487     SDValue NewOp0 =
4488         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
4489     SDValue NewOp1 =
4490         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
4491     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
4492     // ReplaceNodeResults requires we maintain the same type for the return
4493     // value.
4494     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
4495     break;
4496   }
4497   case ISD::BSWAP:
4498   case ISD::BITREVERSE: {
4499     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4500            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
4501     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
4502                                  N->getOperand(0));
4503     unsigned Imm = N->getOpcode() == ISD::BITREVERSE ? 31 : 24;
4504     SDValue GREVIW = DAG.getNode(RISCVISD::GREVW, DL, MVT::i64, NewOp0,
4505                                  DAG.getConstant(Imm, DL, MVT::i64));
4506     // ReplaceNodeResults requires we maintain the same type for the return
4507     // value.
4508     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, GREVIW));
4509     break;
4510   }
4511   case ISD::FSHL:
4512   case ISD::FSHR: {
4513     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4514            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
4515     SDValue NewOp0 =
4516         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
4517     SDValue NewOp1 =
4518         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
4519     SDValue NewOp2 =
4520         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
4521     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
4522     // Mask the shift amount to 5 bits.
4523     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
4524                          DAG.getConstant(0x1f, DL, MVT::i64));
4525     unsigned Opc =
4526         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
4527     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
4528     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
4529     break;
4530   }
4531   case ISD::EXTRACT_VECTOR_ELT: {
4532     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
4533     // type is illegal (currently only vXi64 RV32).
4534     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
4535     // transferred to the destination register. We issue two of these from the
4536     // upper- and lower- halves of the SEW-bit vector element, slid down to the
4537     // first element.
4538     SDValue Vec = N->getOperand(0);
4539     SDValue Idx = N->getOperand(1);
4540 
4541     // The vector type hasn't been legalized yet so we can't issue target
4542     // specific nodes if it needs legalization.
4543     // FIXME: We would manually legalize if it's important.
4544     if (!isTypeLegal(Vec.getValueType()))
4545       return;
4546 
4547     MVT VecVT = Vec.getSimpleValueType();
4548 
4549     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
4550            VecVT.getVectorElementType() == MVT::i64 &&
4551            "Unexpected EXTRACT_VECTOR_ELT legalization");
4552 
4553     // If this is a fixed vector, we need to convert it to a scalable vector.
4554     MVT ContainerVT = VecVT;
4555     if (VecVT.isFixedLengthVector()) {
4556       ContainerVT = getContainerForFixedLengthVector(VecVT);
4557       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4558     }
4559 
4560     MVT XLenVT = Subtarget.getXLenVT();
4561 
4562     // Use a VL of 1 to avoid processing more elements than we need.
4563     MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
4564     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4565     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4566 
4567     // Unless the index is known to be 0, we must slide the vector down to get
4568     // the desired element into index 0.
4569     if (!isNullConstant(Idx)) {
4570       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4571                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4572     }
4573 
4574     // Extract the lower XLEN bits of the correct vector element.
4575     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4576 
4577     // To extract the upper XLEN bits of the vector element, shift the first
4578     // element right by 32 bits and re-extract the lower XLEN bits.
4579     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4580                                      DAG.getConstant(32, DL, XLenVT), VL);
4581     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
4582                                  ThirtyTwoV, Mask, VL);
4583 
4584     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
4585 
4586     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
4587     break;
4588   }
4589   case ISD::INTRINSIC_WO_CHAIN: {
4590     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4591     switch (IntNo) {
4592     default:
4593       llvm_unreachable(
4594           "Don't know how to custom type legalize this intrinsic!");
4595     case Intrinsic::riscv_orc_b: {
4596       // Lower to the GORCI encoding for orc.b with the operand extended.
4597       SDValue NewOp =
4598           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
4599       // If Zbp is enabled, use GORCIW which will sign extend the result.
4600       unsigned Opc =
4601           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
4602       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
4603                                 DAG.getConstant(7, DL, MVT::i64));
4604       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
4605       return;
4606     }
4607     case Intrinsic::riscv_vmv_x_s: {
4608       EVT VT = N->getValueType(0);
4609       MVT XLenVT = Subtarget.getXLenVT();
4610       if (VT.bitsLT(XLenVT)) {
4611         // Simple case just extract using vmv.x.s and truncate.
4612         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
4613                                       Subtarget.getXLenVT(), N->getOperand(1));
4614         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
4615         return;
4616       }
4617 
4618       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
4619              "Unexpected custom legalization");
4620 
4621       // We need to do the move in two steps.
4622       SDValue Vec = N->getOperand(1);
4623       MVT VecVT = Vec.getSimpleValueType();
4624 
4625       // First extract the lower XLEN bits of the element.
4626       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4627 
4628       // To extract the upper XLEN bits of the vector element, shift the first
4629       // element right by 32 bits and re-extract the lower XLEN bits.
4630       SDValue VL = DAG.getConstant(1, DL, XLenVT);
4631       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
4632       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4633       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
4634                                        DAG.getConstant(32, DL, XLenVT), VL);
4635       SDValue LShr32 =
4636           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
4637       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
4638 
4639       Results.push_back(
4640           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
4641       break;
4642     }
4643     }
4644     break;
4645   }
4646   case ISD::VECREDUCE_ADD:
4647   case ISD::VECREDUCE_AND:
4648   case ISD::VECREDUCE_OR:
4649   case ISD::VECREDUCE_XOR:
4650   case ISD::VECREDUCE_SMAX:
4651   case ISD::VECREDUCE_UMAX:
4652   case ISD::VECREDUCE_SMIN:
4653   case ISD::VECREDUCE_UMIN:
4654     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
4655       Results.push_back(V);
4656     break;
4657   case ISD::FLT_ROUNDS_: {
4658     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
4659     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
4660     Results.push_back(Res.getValue(0));
4661     Results.push_back(Res.getValue(1));
4662     break;
4663   }
4664   }
4665 }
4666 
4667 // A structure to hold one of the bit-manipulation patterns below. Together, a
4668 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
4669 //   (or (and (shl x, 1), 0xAAAAAAAA),
4670 //       (and (srl x, 1), 0x55555555))
4671 struct RISCVBitmanipPat {
4672   SDValue Op;
4673   unsigned ShAmt;
4674   bool IsSHL;
4675 
4676   bool formsPairWith(const RISCVBitmanipPat &Other) const {
4677     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
4678   }
4679 };
4680 
4681 // Matches patterns of the form
4682 //   (and (shl x, C2), (C1 << C2))
4683 //   (and (srl x, C2), C1)
4684 //   (shl (and x, C1), C2)
4685 //   (srl (and x, (C1 << C2)), C2)
4686 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
4687 // The expected masks for each shift amount are specified in BitmanipMasks where
4688 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
4689 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
4690 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
4691 // XLen is 64.
4692 static Optional<RISCVBitmanipPat>
4693 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
4694   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
4695          "Unexpected number of masks");
4696   Optional<uint64_t> Mask;
4697   // Optionally consume a mask around the shift operation.
4698   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
4699     Mask = Op.getConstantOperandVal(1);
4700     Op = Op.getOperand(0);
4701   }
4702   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
4703     return None;
4704   bool IsSHL = Op.getOpcode() == ISD::SHL;
4705 
4706   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4707     return None;
4708   uint64_t ShAmt = Op.getConstantOperandVal(1);
4709 
4710   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
4711   if (ShAmt >= Width && !isPowerOf2_64(ShAmt))
4712     return None;
4713   // If we don't have enough masks for 64 bit, then we must be trying to
4714   // match SHFL so we're only allowed to shift 1/4 of the width.
4715   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
4716     return None;
4717 
4718   SDValue Src = Op.getOperand(0);
4719 
4720   // The expected mask is shifted left when the AND is found around SHL
4721   // patterns.
4722   //   ((x >> 1) & 0x55555555)
4723   //   ((x << 1) & 0xAAAAAAAA)
4724   bool SHLExpMask = IsSHL;
4725 
4726   if (!Mask) {
4727     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
4728     // the mask is all ones: consume that now.
4729     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
4730       Mask = Src.getConstantOperandVal(1);
4731       Src = Src.getOperand(0);
4732       // The expected mask is now in fact shifted left for SRL, so reverse the
4733       // decision.
4734       //   ((x & 0xAAAAAAAA) >> 1)
4735       //   ((x & 0x55555555) << 1)
4736       SHLExpMask = !SHLExpMask;
4737     } else {
4738       // Use a default shifted mask of all-ones if there's no AND, truncated
4739       // down to the expected width. This simplifies the logic later on.
4740       Mask = maskTrailingOnes<uint64_t>(Width);
4741       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
4742     }
4743   }
4744 
4745   unsigned MaskIdx = Log2_32(ShAmt);
4746   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
4747 
4748   if (SHLExpMask)
4749     ExpMask <<= ShAmt;
4750 
4751   if (Mask != ExpMask)
4752     return None;
4753 
4754   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
4755 }
4756 
4757 // Matches any of the following bit-manipulation patterns:
4758 //   (and (shl x, 1), (0x55555555 << 1))
4759 //   (and (srl x, 1), 0x55555555)
4760 //   (shl (and x, 0x55555555), 1)
4761 //   (srl (and x, (0x55555555 << 1)), 1)
4762 // where the shift amount and mask may vary thus:
4763 //   [1]  = 0x55555555 / 0xAAAAAAAA
4764 //   [2]  = 0x33333333 / 0xCCCCCCCC
4765 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
4766 //   [8]  = 0x00FF00FF / 0xFF00FF00
4767 //   [16] = 0x0000FFFF / 0xFFFFFFFF
4768 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
4769 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
4770   // These are the unshifted masks which we use to match bit-manipulation
4771   // patterns. They may be shifted left in certain circumstances.
4772   static const uint64_t BitmanipMasks[] = {
4773       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
4774       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
4775 
4776   return matchRISCVBitmanipPat(Op, BitmanipMasks);
4777 }
4778 
4779 // Match the following pattern as a GREVI(W) operation
4780 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
4781 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
4782                                const RISCVSubtarget &Subtarget) {
4783   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
4784   EVT VT = Op.getValueType();
4785 
4786   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
4787     auto LHS = matchGREVIPat(Op.getOperand(0));
4788     auto RHS = matchGREVIPat(Op.getOperand(1));
4789     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
4790       SDLoc DL(Op);
4791       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
4792                          DAG.getConstant(LHS->ShAmt, DL, VT));
4793     }
4794   }
4795   return SDValue();
4796 }
4797 
4798 // Matches any the following pattern as a GORCI(W) operation
4799 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
4800 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
4801 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
4802 // Note that with the variant of 3.,
4803 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
4804 // the inner pattern will first be matched as GREVI and then the outer
4805 // pattern will be matched to GORC via the first rule above.
4806 // 4.  (or (rotl/rotr x, bitwidth/2), x)
4807 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
4808                                const RISCVSubtarget &Subtarget) {
4809   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
4810   EVT VT = Op.getValueType();
4811 
4812   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
4813     SDLoc DL(Op);
4814     SDValue Op0 = Op.getOperand(0);
4815     SDValue Op1 = Op.getOperand(1);
4816 
4817     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
4818       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
4819           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
4820           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
4821         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
4822       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
4823       if ((Reverse.getOpcode() == ISD::ROTL ||
4824            Reverse.getOpcode() == ISD::ROTR) &&
4825           Reverse.getOperand(0) == X &&
4826           isa<ConstantSDNode>(Reverse.getOperand(1))) {
4827         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
4828         if (RotAmt == (VT.getSizeInBits() / 2))
4829           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
4830                              DAG.getConstant(RotAmt, DL, VT));
4831       }
4832       return SDValue();
4833     };
4834 
4835     // Check for either commutable permutation of (or (GREVI x, shamt), x)
4836     if (SDValue V = MatchOROfReverse(Op0, Op1))
4837       return V;
4838     if (SDValue V = MatchOROfReverse(Op1, Op0))
4839       return V;
4840 
4841     // OR is commutable so canonicalize its OR operand to the left
4842     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
4843       std::swap(Op0, Op1);
4844     if (Op0.getOpcode() != ISD::OR)
4845       return SDValue();
4846     SDValue OrOp0 = Op0.getOperand(0);
4847     SDValue OrOp1 = Op0.getOperand(1);
4848     auto LHS = matchGREVIPat(OrOp0);
4849     // OR is commutable so swap the operands and try again: x might have been
4850     // on the left
4851     if (!LHS) {
4852       std::swap(OrOp0, OrOp1);
4853       LHS = matchGREVIPat(OrOp0);
4854     }
4855     auto RHS = matchGREVIPat(Op1);
4856     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
4857       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
4858                          DAG.getConstant(LHS->ShAmt, DL, VT));
4859     }
4860   }
4861   return SDValue();
4862 }
4863 
4864 // Matches any of the following bit-manipulation patterns:
4865 //   (and (shl x, 1), (0x22222222 << 1))
4866 //   (and (srl x, 1), 0x22222222)
4867 //   (shl (and x, 0x22222222), 1)
4868 //   (srl (and x, (0x22222222 << 1)), 1)
4869 // where the shift amount and mask may vary thus:
4870 //   [1]  = 0x22222222 / 0x44444444
4871 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
4872 //   [4]  = 0x00F000F0 / 0x0F000F00
4873 //   [8]  = 0x0000FF00 / 0x00FF0000
4874 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
4875 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
4876   // These are the unshifted masks which we use to match bit-manipulation
4877   // patterns. They may be shifted left in certain circumstances.
4878   static const uint64_t BitmanipMasks[] = {
4879       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
4880       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
4881 
4882   return matchRISCVBitmanipPat(Op, BitmanipMasks);
4883 }
4884 
4885 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
4886 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
4887                                const RISCVSubtarget &Subtarget) {
4888   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
4889   EVT VT = Op.getValueType();
4890 
4891   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
4892     return SDValue();
4893 
4894   SDValue Op0 = Op.getOperand(0);
4895   SDValue Op1 = Op.getOperand(1);
4896 
4897   // Or is commutable so canonicalize the second OR to the LHS.
4898   if (Op0.getOpcode() != ISD::OR)
4899     std::swap(Op0, Op1);
4900   if (Op0.getOpcode() != ISD::OR)
4901     return SDValue();
4902 
4903   // We found an inner OR, so our operands are the operands of the inner OR
4904   // and the other operand of the outer OR.
4905   SDValue A = Op0.getOperand(0);
4906   SDValue B = Op0.getOperand(1);
4907   SDValue C = Op1;
4908 
4909   auto Match1 = matchSHFLPat(A);
4910   auto Match2 = matchSHFLPat(B);
4911 
4912   // If neither matched, we failed.
4913   if (!Match1 && !Match2)
4914     return SDValue();
4915 
4916   // We had at least one match. if one failed, try the remaining C operand.
4917   if (!Match1) {
4918     std::swap(A, C);
4919     Match1 = matchSHFLPat(A);
4920     if (!Match1)
4921       return SDValue();
4922   } else if (!Match2) {
4923     std::swap(B, C);
4924     Match2 = matchSHFLPat(B);
4925     if (!Match2)
4926       return SDValue();
4927   }
4928   assert(Match1 && Match2);
4929 
4930   // Make sure our matches pair up.
4931   if (!Match1->formsPairWith(*Match2))
4932     return SDValue();
4933 
4934   // All the remains is to make sure C is an AND with the same input, that masks
4935   // out the bits that are being shuffled.
4936   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
4937       C.getOperand(0) != Match1->Op)
4938     return SDValue();
4939 
4940   uint64_t Mask = C.getConstantOperandVal(1);
4941 
4942   static const uint64_t BitmanipMasks[] = {
4943       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
4944       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
4945   };
4946 
4947   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
4948   unsigned MaskIdx = Log2_32(Match1->ShAmt);
4949   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
4950 
4951   if (Mask != ExpMask)
4952     return SDValue();
4953 
4954   SDLoc DL(Op);
4955   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
4956                      DAG.getConstant(Match1->ShAmt, DL, VT));
4957 }
4958 
4959 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
4960 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
4961 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
4962 // not undo itself, but they are redundant.
4963 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
4964   SDValue Src = N->getOperand(0);
4965 
4966   if (Src.getOpcode() != N->getOpcode())
4967     return SDValue();
4968 
4969   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4970       !isa<ConstantSDNode>(Src.getOperand(1)))
4971     return SDValue();
4972 
4973   unsigned ShAmt1 = N->getConstantOperandVal(1);
4974   unsigned ShAmt2 = Src.getConstantOperandVal(1);
4975   Src = Src.getOperand(0);
4976 
4977   unsigned CombinedShAmt;
4978   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
4979     CombinedShAmt = ShAmt1 | ShAmt2;
4980   else
4981     CombinedShAmt = ShAmt1 ^ ShAmt2;
4982 
4983   if (CombinedShAmt == 0)
4984     return Src;
4985 
4986   SDLoc DL(N);
4987   return DAG.getNode(
4988       N->getOpcode(), DL, N->getValueType(0), Src,
4989       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
4990 }
4991 
4992 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
4993                                                DAGCombinerInfo &DCI) const {
4994   SelectionDAG &DAG = DCI.DAG;
4995 
4996   switch (N->getOpcode()) {
4997   default:
4998     break;
4999   case RISCVISD::SplitF64: {
5000     SDValue Op0 = N->getOperand(0);
5001     // If the input to SplitF64 is just BuildPairF64 then the operation is
5002     // redundant. Instead, use BuildPairF64's operands directly.
5003     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
5004       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
5005 
5006     SDLoc DL(N);
5007 
5008     // It's cheaper to materialise two 32-bit integers than to load a double
5009     // from the constant pool and transfer it to integer registers through the
5010     // stack.
5011     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
5012       APInt V = C->getValueAPF().bitcastToAPInt();
5013       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
5014       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
5015       return DCI.CombineTo(N, Lo, Hi);
5016     }
5017 
5018     // This is a target-specific version of a DAGCombine performed in
5019     // DAGCombiner::visitBITCAST. It performs the equivalent of:
5020     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5021     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5022     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
5023         !Op0.getNode()->hasOneUse())
5024       break;
5025     SDValue NewSplitF64 =
5026         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
5027                     Op0.getOperand(0));
5028     SDValue Lo = NewSplitF64.getValue(0);
5029     SDValue Hi = NewSplitF64.getValue(1);
5030     APInt SignBit = APInt::getSignMask(32);
5031     if (Op0.getOpcode() == ISD::FNEG) {
5032       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
5033                                   DAG.getConstant(SignBit, DL, MVT::i32));
5034       return DCI.CombineTo(N, Lo, NewHi);
5035     }
5036     assert(Op0.getOpcode() == ISD::FABS);
5037     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
5038                                 DAG.getConstant(~SignBit, DL, MVT::i32));
5039     return DCI.CombineTo(N, Lo, NewHi);
5040   }
5041   case RISCVISD::SLLW:
5042   case RISCVISD::SRAW:
5043   case RISCVISD::SRLW:
5044   case RISCVISD::ROLW:
5045   case RISCVISD::RORW: {
5046     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
5047     SDValue LHS = N->getOperand(0);
5048     SDValue RHS = N->getOperand(1);
5049     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
5050     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
5051     if (SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI) ||
5052         SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)) {
5053       if (N->getOpcode() != ISD::DELETED_NODE)
5054         DCI.AddToWorklist(N);
5055       return SDValue(N, 0);
5056     }
5057     break;
5058   }
5059   case RISCVISD::CLZW:
5060   case RISCVISD::CTZW: {
5061     // Only the lower 32 bits of the first operand are read
5062     SDValue Op0 = N->getOperand(0);
5063     APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
5064     if (SimplifyDemandedBits(Op0, Mask, DCI)) {
5065       if (N->getOpcode() != ISD::DELETED_NODE)
5066         DCI.AddToWorklist(N);
5067       return SDValue(N, 0);
5068     }
5069     break;
5070   }
5071   case RISCVISD::FSL:
5072   case RISCVISD::FSR: {
5073     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
5074     SDValue ShAmt = N->getOperand(2);
5075     unsigned BitWidth = ShAmt.getValueSizeInBits();
5076     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
5077     APInt ShAmtMask(BitWidth, (BitWidth * 2) - 1);
5078     if (SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) {
5079       if (N->getOpcode() != ISD::DELETED_NODE)
5080         DCI.AddToWorklist(N);
5081       return SDValue(N, 0);
5082     }
5083     break;
5084   }
5085   case RISCVISD::FSLW:
5086   case RISCVISD::FSRW: {
5087     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
5088     // read.
5089     SDValue Op0 = N->getOperand(0);
5090     SDValue Op1 = N->getOperand(1);
5091     SDValue ShAmt = N->getOperand(2);
5092     APInt OpMask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
5093     APInt ShAmtMask = APInt::getLowBitsSet(ShAmt.getValueSizeInBits(), 6);
5094     if (SimplifyDemandedBits(Op0, OpMask, DCI) ||
5095         SimplifyDemandedBits(Op1, OpMask, DCI) ||
5096         SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) {
5097       if (N->getOpcode() != ISD::DELETED_NODE)
5098         DCI.AddToWorklist(N);
5099       return SDValue(N, 0);
5100     }
5101     break;
5102   }
5103   case RISCVISD::GREVW:
5104   case RISCVISD::GORCW: {
5105     // Only the lower 32 bits of the first operand are read
5106     SDValue Op0 = N->getOperand(0);
5107     APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
5108     if (SimplifyDemandedBits(Op0, Mask, DCI)) {
5109       if (N->getOpcode() != ISD::DELETED_NODE)
5110         DCI.AddToWorklist(N);
5111       return SDValue(N, 0);
5112     }
5113 
5114     return combineGREVI_GORCI(N, DCI.DAG);
5115   }
5116   case RISCVISD::FMV_X_ANYEXTW_RV64: {
5117     SDLoc DL(N);
5118     SDValue Op0 = N->getOperand(0);
5119     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
5120     // conversion is unnecessary and can be replaced with an ANY_EXTEND
5121     // of the FMV_W_X_RV64 operand.
5122     if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) {
5123       assert(Op0.getOperand(0).getValueType() == MVT::i64 &&
5124              "Unexpected value type!");
5125       return Op0.getOperand(0);
5126     }
5127 
5128     // This is a target-specific version of a DAGCombine performed in
5129     // DAGCombiner::visitBITCAST. It performs the equivalent of:
5130     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5131     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5132     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
5133         !Op0.getNode()->hasOneUse())
5134       break;
5135     SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64,
5136                                  Op0.getOperand(0));
5137     APInt SignBit = APInt::getSignMask(32).sext(64);
5138     if (Op0.getOpcode() == ISD::FNEG)
5139       return DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV,
5140                          DAG.getConstant(SignBit, DL, MVT::i64));
5141 
5142     assert(Op0.getOpcode() == ISD::FABS);
5143     return DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV,
5144                        DAG.getConstant(~SignBit, DL, MVT::i64));
5145   }
5146   case RISCVISD::GREV:
5147   case RISCVISD::GORC:
5148     return combineGREVI_GORCI(N, DCI.DAG);
5149   case ISD::OR:
5150     if (auto GREV = combineORToGREV(SDValue(N, 0), DCI.DAG, Subtarget))
5151       return GREV;
5152     if (auto GORC = combineORToGORC(SDValue(N, 0), DCI.DAG, Subtarget))
5153       return GORC;
5154     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DCI.DAG, Subtarget))
5155       return SHFL;
5156     break;
5157   case RISCVISD::SELECT_CC: {
5158     // Transform
5159     SDValue LHS = N->getOperand(0);
5160     SDValue RHS = N->getOperand(1);
5161     auto CCVal = static_cast<ISD::CondCode>(N->getConstantOperandVal(2));
5162     if (!ISD::isIntEqualitySetCC(CCVal))
5163       break;
5164 
5165     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
5166     //      (select_cc X, Y, lt, trueV, falseV)
5167     // Sometimes the setcc is introduced after select_cc has been formed.
5168     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
5169         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
5170       // If we're looking for eq 0 instead of ne 0, we need to invert the
5171       // condition.
5172       bool Invert = CCVal == ISD::SETEQ;
5173       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
5174       if (Invert)
5175         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
5176 
5177       SDLoc DL(N);
5178       RHS = LHS.getOperand(1);
5179       LHS = LHS.getOperand(0);
5180       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
5181 
5182       SDValue TargetCC =
5183           DAG.getTargetConstant(CCVal, DL, Subtarget.getXLenVT());
5184       return DAG.getNode(
5185           RISCVISD::SELECT_CC, DL, N->getValueType(0),
5186           {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)});
5187     }
5188 
5189     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
5190     //      (select_cc X, Y, eq/ne, trueV, falseV)
5191     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
5192       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
5193                          {LHS.getOperand(0), LHS.getOperand(1),
5194                           N->getOperand(2), N->getOperand(3),
5195                           N->getOperand(4)});
5196     // (select_cc X, 1, setne, trueV, falseV) ->
5197     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
5198     // This can occur when legalizing some floating point comparisons.
5199     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
5200     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
5201       SDLoc DL(N);
5202       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
5203       SDValue TargetCC =
5204           DAG.getTargetConstant(CCVal, DL, Subtarget.getXLenVT());
5205       RHS = DAG.getConstant(0, DL, LHS.getValueType());
5206       return DAG.getNode(
5207           RISCVISD::SELECT_CC, DL, N->getValueType(0),
5208           {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)});
5209     }
5210 
5211     break;
5212   }
5213   case RISCVISD::BR_CC: {
5214     SDValue LHS = N->getOperand(1);
5215     SDValue RHS = N->getOperand(2);
5216     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
5217     if (!ISD::isIntEqualitySetCC(CCVal))
5218       break;
5219 
5220     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
5221     //      (br_cc X, Y, lt, dest)
5222     // Sometimes the setcc is introduced after br_cc has been formed.
5223     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
5224         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
5225       // If we're looking for eq 0 instead of ne 0, we need to invert the
5226       // condition.
5227       bool Invert = CCVal == ISD::SETEQ;
5228       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
5229       if (Invert)
5230         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
5231 
5232       SDLoc DL(N);
5233       RHS = LHS.getOperand(1);
5234       LHS = LHS.getOperand(0);
5235       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
5236 
5237       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
5238                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
5239                          N->getOperand(4));
5240     }
5241 
5242     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
5243     //      (br_cc X, Y, eq/ne, trueV, falseV)
5244     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
5245       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
5246                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
5247                          N->getOperand(3), N->getOperand(4));
5248 
5249     // (br_cc X, 1, setne, br_cc) ->
5250     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
5251     // This can occur when legalizing some floating point comparisons.
5252     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
5253     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
5254       SDLoc DL(N);
5255       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
5256       SDValue TargetCC = DAG.getCondCode(CCVal);
5257       RHS = DAG.getConstant(0, DL, LHS.getValueType());
5258       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
5259                          N->getOperand(0), LHS, RHS, TargetCC,
5260                          N->getOperand(4));
5261     }
5262     break;
5263   }
5264   case ISD::FCOPYSIGN: {
5265     EVT VT = N->getValueType(0);
5266     if (!VT.isVector())
5267       break;
5268     // There is a form of VFSGNJ which injects the negated sign of its second
5269     // operand. Try and bubble any FNEG up after the extend/round to produce
5270     // this optimized pattern. Avoid modifying cases where FP_ROUND and
5271     // TRUNC=1.
5272     SDValue In2 = N->getOperand(1);
5273     // Avoid cases where the extend/round has multiple uses, as duplicating
5274     // those is typically more expensive than removing a fneg.
5275     if (!In2.hasOneUse())
5276       break;
5277     if (In2.getOpcode() != ISD::FP_EXTEND &&
5278         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
5279       break;
5280     In2 = In2.getOperand(0);
5281     if (In2.getOpcode() != ISD::FNEG)
5282       break;
5283     SDLoc DL(N);
5284     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
5285     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
5286                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
5287   }
5288   case ISD::MGATHER:
5289   case ISD::MSCATTER: {
5290     if (!DCI.isBeforeLegalize())
5291       break;
5292     MaskedGatherScatterSDNode *MGSN = cast<MaskedGatherScatterSDNode>(N);
5293     SDValue Index = MGSN->getIndex();
5294     EVT IndexVT = Index.getValueType();
5295     MVT XLenVT = Subtarget.getXLenVT();
5296     // RISCV indexed loads only support the "unsigned unscaled" addressing
5297     // mode, so anything else must be manually legalized.
5298     bool NeedsIdxLegalization = MGSN->isIndexScaled() ||
5299                                 (MGSN->isIndexSigned() &&
5300                                  IndexVT.getVectorElementType().bitsLT(XLenVT));
5301     if (!NeedsIdxLegalization)
5302       break;
5303 
5304     SDLoc DL(N);
5305 
5306     // Any index legalization should first promote to XLenVT, so we don't lose
5307     // bits when scaling. This may create an illegal index type so we let
5308     // LLVM's legalization take care of the splitting.
5309     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
5310       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5311       Index = DAG.getNode(MGSN->isIndexSigned() ? ISD::SIGN_EXTEND
5312                                                 : ISD::ZERO_EXTEND,
5313                           DL, IndexVT, Index);
5314     }
5315 
5316     unsigned Scale = N->getConstantOperandVal(5);
5317     if (MGSN->isIndexScaled() && Scale != 1) {
5318       // Manually scale the indices by the element size.
5319       // TODO: Sanitize the scale operand here?
5320       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
5321       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
5322       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
5323     }
5324 
5325     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
5326     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) {
5327       return DAG.getMaskedGather(
5328           N->getVTList(), MGSN->getMemoryVT(), DL,
5329           {MGSN->getChain(), MGN->getPassThru(), MGSN->getMask(),
5330            MGSN->getBasePtr(), Index, MGN->getScale()},
5331           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
5332     }
5333     const auto *MSN = cast<MaskedScatterSDNode>(N);
5334     return DAG.getMaskedScatter(
5335         N->getVTList(), MGSN->getMemoryVT(), DL,
5336         {MGSN->getChain(), MSN->getValue(), MGSN->getMask(), MGSN->getBasePtr(),
5337          Index, MGSN->getScale()},
5338         MGSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
5339   }
5340   }
5341 
5342   return SDValue();
5343 }
5344 
5345 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
5346     const SDNode *N, CombineLevel Level) const {
5347   // The following folds are only desirable if `(OP _, c1 << c2)` can be
5348   // materialised in fewer instructions than `(OP _, c1)`:
5349   //
5350   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5351   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
5352   SDValue N0 = N->getOperand(0);
5353   EVT Ty = N0.getValueType();
5354   if (Ty.isScalarInteger() &&
5355       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
5356     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
5357     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
5358     if (C1 && C2) {
5359       const APInt &C1Int = C1->getAPIntValue();
5360       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
5361 
5362       // We can materialise `c1 << c2` into an add immediate, so it's "free",
5363       // and the combine should happen, to potentially allow further combines
5364       // later.
5365       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
5366           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
5367         return true;
5368 
5369       // We can materialise `c1` in an add immediate, so it's "free", and the
5370       // combine should be prevented.
5371       if (C1Int.getMinSignedBits() <= 64 &&
5372           isLegalAddImmediate(C1Int.getSExtValue()))
5373         return false;
5374 
5375       // Neither constant will fit into an immediate, so find materialisation
5376       // costs.
5377       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
5378                                               Subtarget.is64Bit());
5379       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
5380           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit());
5381 
5382       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
5383       // combine should be prevented.
5384       if (C1Cost < ShiftedC1Cost)
5385         return false;
5386     }
5387   }
5388   return true;
5389 }
5390 
5391 bool RISCVTargetLowering::targetShrinkDemandedConstant(
5392     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
5393     TargetLoweringOpt &TLO) const {
5394   // Delay this optimization as late as possible.
5395   if (!TLO.LegalOps)
5396     return false;
5397 
5398   EVT VT = Op.getValueType();
5399   if (VT.isVector())
5400     return false;
5401 
5402   // Only handle AND for now.
5403   if (Op.getOpcode() != ISD::AND)
5404     return false;
5405 
5406   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5407   if (!C)
5408     return false;
5409 
5410   const APInt &Mask = C->getAPIntValue();
5411 
5412   // Clear all non-demanded bits initially.
5413   APInt ShrunkMask = Mask & DemandedBits;
5414 
5415   // Try to make a smaller immediate by setting undemanded bits.
5416 
5417   APInt ExpandedMask = Mask | ~DemandedBits;
5418 
5419   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
5420     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
5421   };
5422   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
5423     if (NewMask == Mask)
5424       return true;
5425     SDLoc DL(Op);
5426     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
5427     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
5428     return TLO.CombineTo(Op, NewOp);
5429   };
5430 
5431   // If the shrunk mask fits in sign extended 12 bits, let the target
5432   // independent code apply it.
5433   if (ShrunkMask.isSignedIntN(12))
5434     return false;
5435 
5436   // Preserve (and X, 0xffff) when zext.h is supported.
5437   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
5438     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
5439     if (IsLegalMask(NewMask))
5440       return UseMask(NewMask);
5441   }
5442 
5443   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
5444   if (VT == MVT::i64) {
5445     APInt NewMask = APInt(64, 0xffffffff);
5446     if (IsLegalMask(NewMask))
5447       return UseMask(NewMask);
5448   }
5449 
5450   // For the remaining optimizations, we need to be able to make a negative
5451   // number through a combination of mask and undemanded bits.
5452   if (!ExpandedMask.isNegative())
5453     return false;
5454 
5455   // What is the fewest number of bits we need to represent the negative number.
5456   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
5457 
5458   // Try to make a 12 bit negative immediate. If that fails try to make a 32
5459   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
5460   APInt NewMask = ShrunkMask;
5461   if (MinSignedBits <= 12)
5462     NewMask.setBitsFrom(11);
5463   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
5464     NewMask.setBitsFrom(31);
5465   else
5466     return false;
5467 
5468   // Sanity check that our new mask is a subset of the demanded mask.
5469   assert(IsLegalMask(NewMask));
5470   return UseMask(NewMask);
5471 }
5472 
5473 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
5474                                                         KnownBits &Known,
5475                                                         const APInt &DemandedElts,
5476                                                         const SelectionDAG &DAG,
5477                                                         unsigned Depth) const {
5478   unsigned BitWidth = Known.getBitWidth();
5479   unsigned Opc = Op.getOpcode();
5480   assert((Opc >= ISD::BUILTIN_OP_END ||
5481           Opc == ISD::INTRINSIC_WO_CHAIN ||
5482           Opc == ISD::INTRINSIC_W_CHAIN ||
5483           Opc == ISD::INTRINSIC_VOID) &&
5484          "Should use MaskedValueIsZero if you don't know whether Op"
5485          " is a target node!");
5486 
5487   Known.resetAll();
5488   switch (Opc) {
5489   default: break;
5490   case RISCVISD::SELECT_CC: {
5491     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
5492     // If we don't know any bits, early out.
5493     if (Known.isUnknown())
5494       break;
5495     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
5496 
5497     // Only known if known in both the LHS and RHS.
5498     Known = KnownBits::commonBits(Known, Known2);
5499     break;
5500   }
5501   case RISCVISD::REMUW: {
5502     KnownBits Known2;
5503     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5504     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5505     // We only care about the lower 32 bits.
5506     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
5507     // Restore the original width by sign extending.
5508     Known = Known.sext(BitWidth);
5509     break;
5510   }
5511   case RISCVISD::DIVUW: {
5512     KnownBits Known2;
5513     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5514     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5515     // We only care about the lower 32 bits.
5516     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
5517     // Restore the original width by sign extending.
5518     Known = Known.sext(BitWidth);
5519     break;
5520   }
5521   case RISCVISD::CTZW: {
5522     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
5523     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
5524     unsigned LowBits = Log2_32(PossibleTZ) + 1;
5525     Known.Zero.setBitsFrom(LowBits);
5526     break;
5527   }
5528   case RISCVISD::CLZW: {
5529     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
5530     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
5531     unsigned LowBits = Log2_32(PossibleLZ) + 1;
5532     Known.Zero.setBitsFrom(LowBits);
5533     break;
5534   }
5535   case RISCVISD::READ_VLENB:
5536     // We assume VLENB is at least 16 bytes.
5537     Known.Zero.setLowBits(4);
5538     break;
5539   }
5540 }
5541 
5542 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
5543     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
5544     unsigned Depth) const {
5545   switch (Op.getOpcode()) {
5546   default:
5547     break;
5548   case RISCVISD::SLLW:
5549   case RISCVISD::SRAW:
5550   case RISCVISD::SRLW:
5551   case RISCVISD::DIVW:
5552   case RISCVISD::DIVUW:
5553   case RISCVISD::REMUW:
5554   case RISCVISD::ROLW:
5555   case RISCVISD::RORW:
5556   case RISCVISD::GREVW:
5557   case RISCVISD::GORCW:
5558   case RISCVISD::FSLW:
5559   case RISCVISD::FSRW:
5560     // TODO: As the result is sign-extended, this is conservatively correct. A
5561     // more precise answer could be calculated for SRAW depending on known
5562     // bits in the shift amount.
5563     return 33;
5564   case RISCVISD::SHFL: {
5565     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
5566     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
5567     // will stay within the upper 32 bits. If there were more than 32 sign bits
5568     // before there will be at least 33 sign bits after.
5569     if (Op.getValueType() == MVT::i64 &&
5570         isa<ConstantSDNode>(Op.getOperand(1)) &&
5571         (Op.getConstantOperandVal(1) & 0x10) == 0) {
5572       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5573       if (Tmp > 32)
5574         return 33;
5575     }
5576     break;
5577   }
5578   case RISCVISD::VMV_X_S:
5579     // The number of sign bits of the scalar result is computed by obtaining the
5580     // element type of the input vector operand, subtracting its width from the
5581     // XLEN, and then adding one (sign bit within the element type). If the
5582     // element type is wider than XLen, the least-significant XLEN bits are
5583     // taken.
5584     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
5585       return 1;
5586     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
5587   }
5588 
5589   return 1;
5590 }
5591 
5592 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
5593                                                   MachineBasicBlock *BB) {
5594   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
5595 
5596   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
5597   // Should the count have wrapped while it was being read, we need to try
5598   // again.
5599   // ...
5600   // read:
5601   // rdcycleh x3 # load high word of cycle
5602   // rdcycle  x2 # load low word of cycle
5603   // rdcycleh x4 # load high word of cycle
5604   // bne x3, x4, read # check if high word reads match, otherwise try again
5605   // ...
5606 
5607   MachineFunction &MF = *BB->getParent();
5608   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5609   MachineFunction::iterator It = ++BB->getIterator();
5610 
5611   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
5612   MF.insert(It, LoopMBB);
5613 
5614   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
5615   MF.insert(It, DoneMBB);
5616 
5617   // Transfer the remainder of BB and its successor edges to DoneMBB.
5618   DoneMBB->splice(DoneMBB->begin(), BB,
5619                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
5620   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
5621 
5622   BB->addSuccessor(LoopMBB);
5623 
5624   MachineRegisterInfo &RegInfo = MF.getRegInfo();
5625   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
5626   Register LoReg = MI.getOperand(0).getReg();
5627   Register HiReg = MI.getOperand(1).getReg();
5628   DebugLoc DL = MI.getDebugLoc();
5629 
5630   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
5631   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
5632       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
5633       .addReg(RISCV::X0);
5634   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
5635       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
5636       .addReg(RISCV::X0);
5637   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
5638       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
5639       .addReg(RISCV::X0);
5640 
5641   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
5642       .addReg(HiReg)
5643       .addReg(ReadAgainReg)
5644       .addMBB(LoopMBB);
5645 
5646   LoopMBB->addSuccessor(LoopMBB);
5647   LoopMBB->addSuccessor(DoneMBB);
5648 
5649   MI.eraseFromParent();
5650 
5651   return DoneMBB;
5652 }
5653 
5654 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
5655                                              MachineBasicBlock *BB) {
5656   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
5657 
5658   MachineFunction &MF = *BB->getParent();
5659   DebugLoc DL = MI.getDebugLoc();
5660   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
5661   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
5662   Register LoReg = MI.getOperand(0).getReg();
5663   Register HiReg = MI.getOperand(1).getReg();
5664   Register SrcReg = MI.getOperand(2).getReg();
5665   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
5666   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
5667 
5668   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
5669                           RI);
5670   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
5671   MachineMemOperand *MMOLo =
5672       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
5673   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
5674       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
5675   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
5676       .addFrameIndex(FI)
5677       .addImm(0)
5678       .addMemOperand(MMOLo);
5679   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
5680       .addFrameIndex(FI)
5681       .addImm(4)
5682       .addMemOperand(MMOHi);
5683   MI.eraseFromParent(); // The pseudo instruction is gone now.
5684   return BB;
5685 }
5686 
5687 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
5688                                                  MachineBasicBlock *BB) {
5689   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
5690          "Unexpected instruction");
5691 
5692   MachineFunction &MF = *BB->getParent();
5693   DebugLoc DL = MI.getDebugLoc();
5694   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
5695   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
5696   Register DstReg = MI.getOperand(0).getReg();
5697   Register LoReg = MI.getOperand(1).getReg();
5698   Register HiReg = MI.getOperand(2).getReg();
5699   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
5700   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
5701 
5702   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
5703   MachineMemOperand *MMOLo =
5704       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
5705   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
5706       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
5707   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
5708       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
5709       .addFrameIndex(FI)
5710       .addImm(0)
5711       .addMemOperand(MMOLo);
5712   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
5713       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
5714       .addFrameIndex(FI)
5715       .addImm(4)
5716       .addMemOperand(MMOHi);
5717   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
5718   MI.eraseFromParent(); // The pseudo instruction is gone now.
5719   return BB;
5720 }
5721 
5722 static bool isSelectPseudo(MachineInstr &MI) {
5723   switch (MI.getOpcode()) {
5724   default:
5725     return false;
5726   case RISCV::Select_GPR_Using_CC_GPR:
5727   case RISCV::Select_FPR16_Using_CC_GPR:
5728   case RISCV::Select_FPR32_Using_CC_GPR:
5729   case RISCV::Select_FPR64_Using_CC_GPR:
5730     return true;
5731   }
5732 }
5733 
5734 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
5735                                            MachineBasicBlock *BB) {
5736   // To "insert" Select_* instructions, we actually have to insert the triangle
5737   // control-flow pattern.  The incoming instructions know the destination vreg
5738   // to set, the condition code register to branch on, the true/false values to
5739   // select between, and the condcode to use to select the appropriate branch.
5740   //
5741   // We produce the following control flow:
5742   //     HeadMBB
5743   //     |  \
5744   //     |  IfFalseMBB
5745   //     | /
5746   //    TailMBB
5747   //
5748   // When we find a sequence of selects we attempt to optimize their emission
5749   // by sharing the control flow. Currently we only handle cases where we have
5750   // multiple selects with the exact same condition (same LHS, RHS and CC).
5751   // The selects may be interleaved with other instructions if the other
5752   // instructions meet some requirements we deem safe:
5753   // - They are debug instructions. Otherwise,
5754   // - They do not have side-effects, do not access memory and their inputs do
5755   //   not depend on the results of the select pseudo-instructions.
5756   // The TrueV/FalseV operands of the selects cannot depend on the result of
5757   // previous selects in the sequence.
5758   // These conditions could be further relaxed. See the X86 target for a
5759   // related approach and more information.
5760   Register LHS = MI.getOperand(1).getReg();
5761   Register RHS = MI.getOperand(2).getReg();
5762   auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
5763 
5764   SmallVector<MachineInstr *, 4> SelectDebugValues;
5765   SmallSet<Register, 4> SelectDests;
5766   SelectDests.insert(MI.getOperand(0).getReg());
5767 
5768   MachineInstr *LastSelectPseudo = &MI;
5769 
5770   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
5771        SequenceMBBI != E; ++SequenceMBBI) {
5772     if (SequenceMBBI->isDebugInstr())
5773       continue;
5774     else if (isSelectPseudo(*SequenceMBBI)) {
5775       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
5776           SequenceMBBI->getOperand(2).getReg() != RHS ||
5777           SequenceMBBI->getOperand(3).getImm() != CC ||
5778           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
5779           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
5780         break;
5781       LastSelectPseudo = &*SequenceMBBI;
5782       SequenceMBBI->collectDebugValues(SelectDebugValues);
5783       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
5784     } else {
5785       if (SequenceMBBI->hasUnmodeledSideEffects() ||
5786           SequenceMBBI->mayLoadOrStore())
5787         break;
5788       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
5789             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
5790           }))
5791         break;
5792     }
5793   }
5794 
5795   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
5796   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5797   DebugLoc DL = MI.getDebugLoc();
5798   MachineFunction::iterator I = ++BB->getIterator();
5799 
5800   MachineBasicBlock *HeadMBB = BB;
5801   MachineFunction *F = BB->getParent();
5802   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
5803   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
5804 
5805   F->insert(I, IfFalseMBB);
5806   F->insert(I, TailMBB);
5807 
5808   // Transfer debug instructions associated with the selects to TailMBB.
5809   for (MachineInstr *DebugInstr : SelectDebugValues) {
5810     TailMBB->push_back(DebugInstr->removeFromParent());
5811   }
5812 
5813   // Move all instructions after the sequence to TailMBB.
5814   TailMBB->splice(TailMBB->end(), HeadMBB,
5815                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
5816   // Update machine-CFG edges by transferring all successors of the current
5817   // block to the new block which will contain the Phi nodes for the selects.
5818   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
5819   // Set the successors for HeadMBB.
5820   HeadMBB->addSuccessor(IfFalseMBB);
5821   HeadMBB->addSuccessor(TailMBB);
5822 
5823   // Insert appropriate branch.
5824   unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
5825 
5826   BuildMI(HeadMBB, DL, TII.get(Opcode))
5827     .addReg(LHS)
5828     .addReg(RHS)
5829     .addMBB(TailMBB);
5830 
5831   // IfFalseMBB just falls through to TailMBB.
5832   IfFalseMBB->addSuccessor(TailMBB);
5833 
5834   // Create PHIs for all of the select pseudo-instructions.
5835   auto SelectMBBI = MI.getIterator();
5836   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
5837   auto InsertionPoint = TailMBB->begin();
5838   while (SelectMBBI != SelectEnd) {
5839     auto Next = std::next(SelectMBBI);
5840     if (isSelectPseudo(*SelectMBBI)) {
5841       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
5842       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
5843               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
5844           .addReg(SelectMBBI->getOperand(4).getReg())
5845           .addMBB(HeadMBB)
5846           .addReg(SelectMBBI->getOperand(5).getReg())
5847           .addMBB(IfFalseMBB);
5848       SelectMBBI->eraseFromParent();
5849     }
5850     SelectMBBI = Next;
5851   }
5852 
5853   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
5854   return TailMBB;
5855 }
5856 
5857 static MachineInstr *elideCopies(MachineInstr *MI,
5858                                  const MachineRegisterInfo &MRI) {
5859   while (true) {
5860     if (!MI->isFullCopy())
5861       return MI;
5862     if (!Register::isVirtualRegister(MI->getOperand(1).getReg()))
5863       return nullptr;
5864     MI = MRI.getVRegDef(MI->getOperand(1).getReg());
5865     if (!MI)
5866       return nullptr;
5867   }
5868 }
5869 
5870 static MachineBasicBlock *addVSetVL(MachineInstr &MI, MachineBasicBlock *BB,
5871                                     int VLIndex, unsigned SEWIndex,
5872                                     RISCVVLMUL VLMul, bool ForceTailAgnostic) {
5873   MachineFunction &MF = *BB->getParent();
5874   DebugLoc DL = MI.getDebugLoc();
5875   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
5876 
5877   unsigned SEW = MI.getOperand(SEWIndex).getImm();
5878   assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW");
5879   RISCVVSEW ElementWidth = static_cast<RISCVVSEW>(Log2_32(SEW / 8));
5880 
5881   MachineRegisterInfo &MRI = MF.getRegInfo();
5882 
5883   auto BuildVSETVLI = [&]() {
5884     if (VLIndex >= 0) {
5885       Register DestReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
5886       Register VLReg = MI.getOperand(VLIndex).getReg();
5887 
5888       // VL might be a compile time constant, but isel would have to put it
5889       // in a register. See if VL comes from an ADDI X0, imm.
5890       if (VLReg.isVirtual()) {
5891         MachineInstr *Def = MRI.getVRegDef(VLReg);
5892         if (Def && Def->getOpcode() == RISCV::ADDI &&
5893             Def->getOperand(1).getReg() == RISCV::X0 &&
5894             Def->getOperand(2).isImm()) {
5895           uint64_t Imm = Def->getOperand(2).getImm();
5896           // VSETIVLI allows a 5-bit zero extended immediate.
5897           if (isUInt<5>(Imm))
5898             return BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETIVLI))
5899                 .addReg(DestReg, RegState::Define | RegState::Dead)
5900                 .addImm(Imm);
5901         }
5902       }
5903 
5904       return BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI))
5905           .addReg(DestReg, RegState::Define | RegState::Dead)
5906           .addReg(VLReg);
5907     }
5908 
5909     // With no VL operator in the pseudo, do not modify VL (rd = X0, rs1 = X0).
5910     return BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI))
5911         .addReg(RISCV::X0, RegState::Define | RegState::Dead)
5912         .addReg(RISCV::X0, RegState::Kill);
5913   };
5914 
5915   MachineInstrBuilder MIB = BuildVSETVLI();
5916 
5917   // Default to tail agnostic unless the destination is tied to a source. In
5918   // that case the user would have some control over the tail values. The tail
5919   // policy is also ignored on instructions that only update element 0 like
5920   // vmv.s.x or reductions so use agnostic there to match the common case.
5921   // FIXME: This is conservatively correct, but we might want to detect that
5922   // the input is undefined.
5923   bool TailAgnostic = true;
5924   unsigned UseOpIdx;
5925   if (!ForceTailAgnostic && MI.isRegTiedToUseOperand(0, &UseOpIdx)) {
5926     TailAgnostic = false;
5927     // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic.
5928     const MachineOperand &UseMO = MI.getOperand(UseOpIdx);
5929     MachineInstr *UseMI = MRI.getVRegDef(UseMO.getReg());
5930     if (UseMI) {
5931       UseMI = elideCopies(UseMI, MRI);
5932       if (UseMI && UseMI->isImplicitDef())
5933         TailAgnostic = true;
5934     }
5935   }
5936 
5937   // For simplicity we reuse the vtype representation here.
5938   MIB.addImm(RISCVVType::encodeVTYPE(VLMul, ElementWidth,
5939                                      /*TailAgnostic*/ TailAgnostic,
5940                                      /*MaskAgnostic*/ false));
5941 
5942   // Remove (now) redundant operands from pseudo
5943   if (VLIndex >= 0) {
5944     MI.getOperand(VLIndex).setReg(RISCV::NoRegister);
5945     MI.getOperand(VLIndex).setIsKill(false);
5946   }
5947 
5948   return BB;
5949 }
5950 
5951 MachineBasicBlock *
5952 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
5953                                                  MachineBasicBlock *BB) const {
5954   uint64_t TSFlags = MI.getDesc().TSFlags;
5955 
5956   if (TSFlags & RISCVII::HasSEWOpMask) {
5957     unsigned NumOperands = MI.getNumExplicitOperands();
5958     int VLIndex = (TSFlags & RISCVII::HasVLOpMask) ? NumOperands - 2 : -1;
5959     unsigned SEWIndex = NumOperands - 1;
5960     bool ForceTailAgnostic = TSFlags & RISCVII::ForceTailAgnosticMask;
5961 
5962     RISCVVLMUL VLMul = static_cast<RISCVVLMUL>((TSFlags & RISCVII::VLMulMask) >>
5963                                                RISCVII::VLMulShift);
5964     return addVSetVL(MI, BB, VLIndex, SEWIndex, VLMul, ForceTailAgnostic);
5965   }
5966 
5967   switch (MI.getOpcode()) {
5968   default:
5969     llvm_unreachable("Unexpected instr type to insert");
5970   case RISCV::ReadCycleWide:
5971     assert(!Subtarget.is64Bit() &&
5972            "ReadCycleWrite is only to be used on riscv32");
5973     return emitReadCycleWidePseudo(MI, BB);
5974   case RISCV::Select_GPR_Using_CC_GPR:
5975   case RISCV::Select_FPR16_Using_CC_GPR:
5976   case RISCV::Select_FPR32_Using_CC_GPR:
5977   case RISCV::Select_FPR64_Using_CC_GPR:
5978     return emitSelectPseudo(MI, BB);
5979   case RISCV::BuildPairF64Pseudo:
5980     return emitBuildPairF64Pseudo(MI, BB);
5981   case RISCV::SplitF64Pseudo:
5982     return emitSplitF64Pseudo(MI, BB);
5983   }
5984 }
5985 
5986 // Calling Convention Implementation.
5987 // The expectations for frontend ABI lowering vary from target to target.
5988 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
5989 // details, but this is a longer term goal. For now, we simply try to keep the
5990 // role of the frontend as simple and well-defined as possible. The rules can
5991 // be summarised as:
5992 // * Never split up large scalar arguments. We handle them here.
5993 // * If a hardfloat calling convention is being used, and the struct may be
5994 // passed in a pair of registers (fp+fp, int+fp), and both registers are
5995 // available, then pass as two separate arguments. If either the GPRs or FPRs
5996 // are exhausted, then pass according to the rule below.
5997 // * If a struct could never be passed in registers or directly in a stack
5998 // slot (as it is larger than 2*XLEN and the floating point rules don't
5999 // apply), then pass it using a pointer with the byval attribute.
6000 // * If a struct is less than 2*XLEN, then coerce to either a two-element
6001 // word-sized array or a 2*XLEN scalar (depending on alignment).
6002 // * The frontend can determine whether a struct is returned by reference or
6003 // not based on its size and fields. If it will be returned by reference, the
6004 // frontend must modify the prototype so a pointer with the sret annotation is
6005 // passed as the first argument. This is not necessary for large scalar
6006 // returns.
6007 // * Struct return values and varargs should be coerced to structs containing
6008 // register-size fields in the same situations they would be for fixed
6009 // arguments.
6010 
6011 static const MCPhysReg ArgGPRs[] = {
6012   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
6013   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
6014 };
6015 static const MCPhysReg ArgFPR16s[] = {
6016   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
6017   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
6018 };
6019 static const MCPhysReg ArgFPR32s[] = {
6020   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
6021   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
6022 };
6023 static const MCPhysReg ArgFPR64s[] = {
6024   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
6025   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
6026 };
6027 // This is an interim calling convention and it may be changed in the future.
6028 static const MCPhysReg ArgVRs[] = {
6029     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
6030     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
6031     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
6032 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
6033                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
6034                                      RISCV::V20M2, RISCV::V22M2};
6035 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
6036                                      RISCV::V20M4};
6037 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
6038 
6039 // Pass a 2*XLEN argument that has been split into two XLEN values through
6040 // registers or the stack as necessary.
6041 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
6042                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
6043                                 MVT ValVT2, MVT LocVT2,
6044                                 ISD::ArgFlagsTy ArgFlags2) {
6045   unsigned XLenInBytes = XLen / 8;
6046   if (Register Reg = State.AllocateReg(ArgGPRs)) {
6047     // At least one half can be passed via register.
6048     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
6049                                      VA1.getLocVT(), CCValAssign::Full));
6050   } else {
6051     // Both halves must be passed on the stack, with proper alignment.
6052     Align StackAlign =
6053         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
6054     State.addLoc(
6055         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
6056                             State.AllocateStack(XLenInBytes, StackAlign),
6057                             VA1.getLocVT(), CCValAssign::Full));
6058     State.addLoc(CCValAssign::getMem(
6059         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
6060         LocVT2, CCValAssign::Full));
6061     return false;
6062   }
6063 
6064   if (Register Reg = State.AllocateReg(ArgGPRs)) {
6065     // The second half can also be passed via register.
6066     State.addLoc(
6067         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
6068   } else {
6069     // The second half is passed via the stack, without additional alignment.
6070     State.addLoc(CCValAssign::getMem(
6071         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
6072         LocVT2, CCValAssign::Full));
6073   }
6074 
6075   return false;
6076 }
6077 
6078 // Implements the RISC-V calling convention. Returns true upon failure.
6079 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
6080                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
6081                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
6082                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
6083                      Optional<unsigned> FirstMaskArgument) {
6084   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
6085   assert(XLen == 32 || XLen == 64);
6086   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
6087 
6088   // Any return value split in to more than two values can't be returned
6089   // directly. Vectors are returned via the available vector registers.
6090   if (!LocVT.isVector() && IsRet && ValNo > 1)
6091     return true;
6092 
6093   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
6094   // variadic argument, or if no F16/F32 argument registers are available.
6095   bool UseGPRForF16_F32 = true;
6096   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
6097   // variadic argument, or if no F64 argument registers are available.
6098   bool UseGPRForF64 = true;
6099 
6100   switch (ABI) {
6101   default:
6102     llvm_unreachable("Unexpected ABI");
6103   case RISCVABI::ABI_ILP32:
6104   case RISCVABI::ABI_LP64:
6105     break;
6106   case RISCVABI::ABI_ILP32F:
6107   case RISCVABI::ABI_LP64F:
6108     UseGPRForF16_F32 = !IsFixed;
6109     break;
6110   case RISCVABI::ABI_ILP32D:
6111   case RISCVABI::ABI_LP64D:
6112     UseGPRForF16_F32 = !IsFixed;
6113     UseGPRForF64 = !IsFixed;
6114     break;
6115   }
6116 
6117   // FPR16, FPR32, and FPR64 alias each other.
6118   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
6119     UseGPRForF16_F32 = true;
6120     UseGPRForF64 = true;
6121   }
6122 
6123   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
6124   // similar local variables rather than directly checking against the target
6125   // ABI.
6126 
6127   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
6128     LocVT = XLenVT;
6129     LocInfo = CCValAssign::BCvt;
6130   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
6131     LocVT = MVT::i64;
6132     LocInfo = CCValAssign::BCvt;
6133   }
6134 
6135   // If this is a variadic argument, the RISC-V calling convention requires
6136   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
6137   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
6138   // be used regardless of whether the original argument was split during
6139   // legalisation or not. The argument will not be passed by registers if the
6140   // original type is larger than 2*XLEN, so the register alignment rule does
6141   // not apply.
6142   unsigned TwoXLenInBytes = (2 * XLen) / 8;
6143   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
6144       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
6145     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
6146     // Skip 'odd' register if necessary.
6147     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
6148       State.AllocateReg(ArgGPRs);
6149   }
6150 
6151   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
6152   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
6153       State.getPendingArgFlags();
6154 
6155   assert(PendingLocs.size() == PendingArgFlags.size() &&
6156          "PendingLocs and PendingArgFlags out of sync");
6157 
6158   // Handle passing f64 on RV32D with a soft float ABI or when floating point
6159   // registers are exhausted.
6160   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
6161     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
6162            "Can't lower f64 if it is split");
6163     // Depending on available argument GPRS, f64 may be passed in a pair of
6164     // GPRs, split between a GPR and the stack, or passed completely on the
6165     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
6166     // cases.
6167     Register Reg = State.AllocateReg(ArgGPRs);
6168     LocVT = MVT::i32;
6169     if (!Reg) {
6170       unsigned StackOffset = State.AllocateStack(8, Align(8));
6171       State.addLoc(
6172           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
6173       return false;
6174     }
6175     if (!State.AllocateReg(ArgGPRs))
6176       State.AllocateStack(4, Align(4));
6177     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6178     return false;
6179   }
6180 
6181   // Fixed-length vectors are located in the corresponding scalable-vector
6182   // container types.
6183   if (ValVT.isFixedLengthVector())
6184     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
6185 
6186   // Split arguments might be passed indirectly, so keep track of the pending
6187   // values. Split vectors are passed via a mix of registers and indirectly, so
6188   // treat them as we would any other argument.
6189   if (!LocVT.isVector() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
6190     LocVT = XLenVT;
6191     LocInfo = CCValAssign::Indirect;
6192     PendingLocs.push_back(
6193         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
6194     PendingArgFlags.push_back(ArgFlags);
6195     if (!ArgFlags.isSplitEnd()) {
6196       return false;
6197     }
6198   }
6199 
6200   // If the split argument only had two elements, it should be passed directly
6201   // in registers or on the stack.
6202   if (!LocVT.isVector() && ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
6203     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
6204     // Apply the normal calling convention rules to the first half of the
6205     // split argument.
6206     CCValAssign VA = PendingLocs[0];
6207     ISD::ArgFlagsTy AF = PendingArgFlags[0];
6208     PendingLocs.clear();
6209     PendingArgFlags.clear();
6210     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
6211                                ArgFlags);
6212   }
6213 
6214   // Allocate to a register if possible, or else a stack slot.
6215   Register Reg;
6216   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
6217     Reg = State.AllocateReg(ArgFPR16s);
6218   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
6219     Reg = State.AllocateReg(ArgFPR32s);
6220   else if (ValVT == MVT::f64 && !UseGPRForF64)
6221     Reg = State.AllocateReg(ArgFPR64s);
6222   else if (ValVT.isVector()) {
6223     const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
6224     if (RC == &RISCV::VRRegClass) {
6225       // Assign the first mask argument to V0.
6226       // This is an interim calling convention and it may be changed in the
6227       // future.
6228       if (FirstMaskArgument.hasValue() &&
6229           ValNo == FirstMaskArgument.getValue()) {
6230         Reg = State.AllocateReg(RISCV::V0);
6231       } else {
6232         Reg = State.AllocateReg(ArgVRs);
6233       }
6234     } else if (RC == &RISCV::VRM2RegClass) {
6235       Reg = State.AllocateReg(ArgVRM2s);
6236     } else if (RC == &RISCV::VRM4RegClass) {
6237       Reg = State.AllocateReg(ArgVRM4s);
6238     } else if (RC == &RISCV::VRM8RegClass) {
6239       Reg = State.AllocateReg(ArgVRM8s);
6240     } else {
6241       llvm_unreachable("Unhandled class register for ValueType");
6242     }
6243     if (!Reg) {
6244       // For return values, the vector must be passed fully via registers or
6245       // via the stack.
6246       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
6247       // but we're using all of them.
6248       if (IsRet)
6249         return true;
6250       LocInfo = CCValAssign::Indirect;
6251       // Try using a GPR to pass the address
6252       Reg = State.AllocateReg(ArgGPRs);
6253       LocVT = XLenVT;
6254     }
6255   } else
6256     Reg = State.AllocateReg(ArgGPRs);
6257   unsigned StackOffset =
6258       Reg ? 0 : State.AllocateStack(XLen / 8, Align(XLen / 8));
6259 
6260   // If we reach this point and PendingLocs is non-empty, we must be at the
6261   // end of a split argument that must be passed indirectly.
6262   if (!PendingLocs.empty()) {
6263     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
6264     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
6265 
6266     for (auto &It : PendingLocs) {
6267       if (Reg)
6268         It.convertToReg(Reg);
6269       else
6270         It.convertToMem(StackOffset);
6271       State.addLoc(It);
6272     }
6273     PendingLocs.clear();
6274     PendingArgFlags.clear();
6275     return false;
6276   }
6277 
6278   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
6279           (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) &&
6280          "Expected an XLenVT or vector types at this stage");
6281 
6282   if (Reg) {
6283     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6284     return false;
6285   }
6286 
6287   // When a floating-point value is passed on the stack, no bit-conversion is
6288   // needed.
6289   if (ValVT.isFloatingPoint()) {
6290     LocVT = ValVT;
6291     LocInfo = CCValAssign::Full;
6292   }
6293   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
6294   return false;
6295 }
6296 
6297 template <typename ArgTy>
6298 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
6299   for (const auto &ArgIdx : enumerate(Args)) {
6300     MVT ArgVT = ArgIdx.value().VT;
6301     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
6302       return ArgIdx.index();
6303   }
6304   return None;
6305 }
6306 
6307 void RISCVTargetLowering::analyzeInputArgs(
6308     MachineFunction &MF, CCState &CCInfo,
6309     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
6310   unsigned NumArgs = Ins.size();
6311   FunctionType *FType = MF.getFunction().getFunctionType();
6312 
6313   Optional<unsigned> FirstMaskArgument;
6314   if (Subtarget.hasStdExtV())
6315     FirstMaskArgument = preAssignMask(Ins);
6316 
6317   for (unsigned i = 0; i != NumArgs; ++i) {
6318     MVT ArgVT = Ins[i].VT;
6319     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
6320 
6321     Type *ArgTy = nullptr;
6322     if (IsRet)
6323       ArgTy = FType->getReturnType();
6324     else if (Ins[i].isOrigArg())
6325       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
6326 
6327     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
6328     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
6329                  ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
6330                  FirstMaskArgument)) {
6331       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
6332                         << EVT(ArgVT).getEVTString() << '\n');
6333       llvm_unreachable(nullptr);
6334     }
6335   }
6336 }
6337 
6338 void RISCVTargetLowering::analyzeOutputArgs(
6339     MachineFunction &MF, CCState &CCInfo,
6340     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
6341     CallLoweringInfo *CLI) const {
6342   unsigned NumArgs = Outs.size();
6343 
6344   Optional<unsigned> FirstMaskArgument;
6345   if (Subtarget.hasStdExtV())
6346     FirstMaskArgument = preAssignMask(Outs);
6347 
6348   for (unsigned i = 0; i != NumArgs; i++) {
6349     MVT ArgVT = Outs[i].VT;
6350     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
6351     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
6352 
6353     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
6354     if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
6355                  ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
6356                  FirstMaskArgument)) {
6357       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
6358                         << EVT(ArgVT).getEVTString() << "\n");
6359       llvm_unreachable(nullptr);
6360     }
6361   }
6362 }
6363 
6364 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
6365 // values.
6366 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
6367                                    const CCValAssign &VA, const SDLoc &DL,
6368                                    const RISCVSubtarget &Subtarget) {
6369   switch (VA.getLocInfo()) {
6370   default:
6371     llvm_unreachable("Unexpected CCValAssign::LocInfo");
6372   case CCValAssign::Full:
6373     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
6374       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
6375     break;
6376   case CCValAssign::BCvt:
6377     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
6378       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
6379     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
6380       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
6381     else
6382       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
6383     break;
6384   }
6385   return Val;
6386 }
6387 
6388 // The caller is responsible for loading the full value if the argument is
6389 // passed with CCValAssign::Indirect.
6390 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
6391                                 const CCValAssign &VA, const SDLoc &DL,
6392                                 const RISCVTargetLowering &TLI) {
6393   MachineFunction &MF = DAG.getMachineFunction();
6394   MachineRegisterInfo &RegInfo = MF.getRegInfo();
6395   EVT LocVT = VA.getLocVT();
6396   SDValue Val;
6397   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
6398   Register VReg = RegInfo.createVirtualRegister(RC);
6399   RegInfo.addLiveIn(VA.getLocReg(), VReg);
6400   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
6401 
6402   if (VA.getLocInfo() == CCValAssign::Indirect)
6403     return Val;
6404 
6405   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
6406 }
6407 
6408 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
6409                                    const CCValAssign &VA, const SDLoc &DL,
6410                                    const RISCVSubtarget &Subtarget) {
6411   EVT LocVT = VA.getLocVT();
6412 
6413   switch (VA.getLocInfo()) {
6414   default:
6415     llvm_unreachable("Unexpected CCValAssign::LocInfo");
6416   case CCValAssign::Full:
6417     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
6418       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
6419     break;
6420   case CCValAssign::BCvt:
6421     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
6422       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
6423     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
6424       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
6425     else
6426       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
6427     break;
6428   }
6429   return Val;
6430 }
6431 
6432 // The caller is responsible for loading the full value if the argument is
6433 // passed with CCValAssign::Indirect.
6434 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
6435                                 const CCValAssign &VA, const SDLoc &DL) {
6436   MachineFunction &MF = DAG.getMachineFunction();
6437   MachineFrameInfo &MFI = MF.getFrameInfo();
6438   EVT LocVT = VA.getLocVT();
6439   EVT ValVT = VA.getValVT();
6440   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
6441   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
6442                                  VA.getLocMemOffset(), /*Immutable=*/true);
6443   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6444   SDValue Val;
6445 
6446   ISD::LoadExtType ExtType;
6447   switch (VA.getLocInfo()) {
6448   default:
6449     llvm_unreachable("Unexpected CCValAssign::LocInfo");
6450   case CCValAssign::Full:
6451   case CCValAssign::Indirect:
6452   case CCValAssign::BCvt:
6453     ExtType = ISD::NON_EXTLOAD;
6454     break;
6455   }
6456   Val = DAG.getExtLoad(
6457       ExtType, DL, LocVT, Chain, FIN,
6458       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
6459   return Val;
6460 }
6461 
6462 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
6463                                        const CCValAssign &VA, const SDLoc &DL) {
6464   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
6465          "Unexpected VA");
6466   MachineFunction &MF = DAG.getMachineFunction();
6467   MachineFrameInfo &MFI = MF.getFrameInfo();
6468   MachineRegisterInfo &RegInfo = MF.getRegInfo();
6469 
6470   if (VA.isMemLoc()) {
6471     // f64 is passed on the stack.
6472     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
6473     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
6474     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
6475                        MachinePointerInfo::getFixedStack(MF, FI));
6476   }
6477 
6478   assert(VA.isRegLoc() && "Expected register VA assignment");
6479 
6480   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
6481   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
6482   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
6483   SDValue Hi;
6484   if (VA.getLocReg() == RISCV::X17) {
6485     // Second half of f64 is passed on the stack.
6486     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
6487     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
6488     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
6489                      MachinePointerInfo::getFixedStack(MF, FI));
6490   } else {
6491     // Second half of f64 is passed in another GPR.
6492     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
6493     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
6494     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
6495   }
6496   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
6497 }
6498 
6499 // FastCC has less than 1% performance improvement for some particular
6500 // benchmark. But theoretically, it may has benenfit for some cases.
6501 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT,
6502                             CCValAssign::LocInfo LocInfo,
6503                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
6504 
6505   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
6506     // X5 and X6 might be used for save-restore libcall.
6507     static const MCPhysReg GPRList[] = {
6508         RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
6509         RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
6510         RISCV::X29, RISCV::X30, RISCV::X31};
6511     if (unsigned Reg = State.AllocateReg(GPRList)) {
6512       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6513       return false;
6514     }
6515   }
6516 
6517   if (LocVT == MVT::f16) {
6518     static const MCPhysReg FPR16List[] = {
6519         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
6520         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
6521         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
6522         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
6523     if (unsigned Reg = State.AllocateReg(FPR16List)) {
6524       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6525       return false;
6526     }
6527   }
6528 
6529   if (LocVT == MVT::f32) {
6530     static const MCPhysReg FPR32List[] = {
6531         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
6532         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
6533         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
6534         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
6535     if (unsigned Reg = State.AllocateReg(FPR32List)) {
6536       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6537       return false;
6538     }
6539   }
6540 
6541   if (LocVT == MVT::f64) {
6542     static const MCPhysReg FPR64List[] = {
6543         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
6544         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
6545         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
6546         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
6547     if (unsigned Reg = State.AllocateReg(FPR64List)) {
6548       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6549       return false;
6550     }
6551   }
6552 
6553   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
6554     unsigned Offset4 = State.AllocateStack(4, Align(4));
6555     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
6556     return false;
6557   }
6558 
6559   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
6560     unsigned Offset5 = State.AllocateStack(8, Align(8));
6561     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
6562     return false;
6563   }
6564 
6565   return true; // CC didn't match.
6566 }
6567 
6568 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
6569                          CCValAssign::LocInfo LocInfo,
6570                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
6571 
6572   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
6573     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
6574     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
6575     static const MCPhysReg GPRList[] = {
6576         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
6577         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
6578     if (unsigned Reg = State.AllocateReg(GPRList)) {
6579       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6580       return false;
6581     }
6582   }
6583 
6584   if (LocVT == MVT::f32) {
6585     // Pass in STG registers: F1, ..., F6
6586     //                        fs0 ... fs5
6587     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
6588                                           RISCV::F18_F, RISCV::F19_F,
6589                                           RISCV::F20_F, RISCV::F21_F};
6590     if (unsigned Reg = State.AllocateReg(FPR32List)) {
6591       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6592       return false;
6593     }
6594   }
6595 
6596   if (LocVT == MVT::f64) {
6597     // Pass in STG registers: D1, ..., D6
6598     //                        fs6 ... fs11
6599     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
6600                                           RISCV::F24_D, RISCV::F25_D,
6601                                           RISCV::F26_D, RISCV::F27_D};
6602     if (unsigned Reg = State.AllocateReg(FPR64List)) {
6603       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6604       return false;
6605     }
6606   }
6607 
6608   report_fatal_error("No registers left in GHC calling convention");
6609   return true;
6610 }
6611 
6612 // Transform physical registers into virtual registers.
6613 SDValue RISCVTargetLowering::LowerFormalArguments(
6614     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
6615     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
6616     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6617 
6618   MachineFunction &MF = DAG.getMachineFunction();
6619 
6620   switch (CallConv) {
6621   default:
6622     report_fatal_error("Unsupported calling convention");
6623   case CallingConv::C:
6624   case CallingConv::Fast:
6625     break;
6626   case CallingConv::GHC:
6627     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
6628         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
6629       report_fatal_error(
6630         "GHC calling convention requires the F and D instruction set extensions");
6631   }
6632 
6633   const Function &Func = MF.getFunction();
6634   if (Func.hasFnAttribute("interrupt")) {
6635     if (!Func.arg_empty())
6636       report_fatal_error(
6637         "Functions with the interrupt attribute cannot have arguments!");
6638 
6639     StringRef Kind =
6640       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
6641 
6642     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
6643       report_fatal_error(
6644         "Function interrupt attribute argument not supported!");
6645   }
6646 
6647   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6648   MVT XLenVT = Subtarget.getXLenVT();
6649   unsigned XLenInBytes = Subtarget.getXLen() / 8;
6650   // Used with vargs to acumulate store chains.
6651   std::vector<SDValue> OutChains;
6652 
6653   // Assign locations to all of the incoming arguments.
6654   SmallVector<CCValAssign, 16> ArgLocs;
6655   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
6656 
6657   if (CallConv == CallingConv::Fast)
6658     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC);
6659   else if (CallConv == CallingConv::GHC)
6660     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
6661   else
6662     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
6663 
6664   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
6665     CCValAssign &VA = ArgLocs[i];
6666     SDValue ArgValue;
6667     // Passing f64 on RV32D with a soft float ABI must be handled as a special
6668     // case.
6669     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
6670       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
6671     else if (VA.isRegLoc())
6672       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
6673     else
6674       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
6675 
6676     if (VA.getLocInfo() == CCValAssign::Indirect) {
6677       // If the original argument was split and passed by reference (e.g. i128
6678       // on RV32), we need to load all parts of it here (using the same
6679       // address). Vectors may be partly split to registers and partly to the
6680       // stack, in which case the base address is partly offset and subsequent
6681       // stores are relative to that.
6682       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
6683                                    MachinePointerInfo()));
6684       unsigned ArgIndex = Ins[i].OrigArgIndex;
6685       unsigned ArgPartOffset = Ins[i].PartOffset;
6686       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
6687       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
6688         CCValAssign &PartVA = ArgLocs[i + 1];
6689         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
6690         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
6691                                       DAG.getIntPtrConstant(PartOffset, DL));
6692         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
6693                                      MachinePointerInfo()));
6694         ++i;
6695       }
6696       continue;
6697     }
6698     InVals.push_back(ArgValue);
6699   }
6700 
6701   if (IsVarArg) {
6702     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
6703     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
6704     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
6705     MachineFrameInfo &MFI = MF.getFrameInfo();
6706     MachineRegisterInfo &RegInfo = MF.getRegInfo();
6707     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
6708 
6709     // Offset of the first variable argument from stack pointer, and size of
6710     // the vararg save area. For now, the varargs save area is either zero or
6711     // large enough to hold a0-a7.
6712     int VaArgOffset, VarArgsSaveSize;
6713 
6714     // If all registers are allocated, then all varargs must be passed on the
6715     // stack and we don't need to save any argregs.
6716     if (ArgRegs.size() == Idx) {
6717       VaArgOffset = CCInfo.getNextStackOffset();
6718       VarArgsSaveSize = 0;
6719     } else {
6720       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
6721       VaArgOffset = -VarArgsSaveSize;
6722     }
6723 
6724     // Record the frame index of the first variable argument
6725     // which is a value necessary to VASTART.
6726     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
6727     RVFI->setVarArgsFrameIndex(FI);
6728 
6729     // If saving an odd number of registers then create an extra stack slot to
6730     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
6731     // offsets to even-numbered registered remain 2*XLEN-aligned.
6732     if (Idx % 2) {
6733       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
6734       VarArgsSaveSize += XLenInBytes;
6735     }
6736 
6737     // Copy the integer registers that may have been used for passing varargs
6738     // to the vararg save area.
6739     for (unsigned I = Idx; I < ArgRegs.size();
6740          ++I, VaArgOffset += XLenInBytes) {
6741       const Register Reg = RegInfo.createVirtualRegister(RC);
6742       RegInfo.addLiveIn(ArgRegs[I], Reg);
6743       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
6744       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
6745       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
6746       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
6747                                    MachinePointerInfo::getFixedStack(MF, FI));
6748       cast<StoreSDNode>(Store.getNode())
6749           ->getMemOperand()
6750           ->setValue((Value *)nullptr);
6751       OutChains.push_back(Store);
6752     }
6753     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
6754   }
6755 
6756   // All stores are grouped in one node to allow the matching between
6757   // the size of Ins and InVals. This only happens for vararg functions.
6758   if (!OutChains.empty()) {
6759     OutChains.push_back(Chain);
6760     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
6761   }
6762 
6763   return Chain;
6764 }
6765 
6766 /// isEligibleForTailCallOptimization - Check whether the call is eligible
6767 /// for tail call optimization.
6768 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
6769 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
6770     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
6771     const SmallVector<CCValAssign, 16> &ArgLocs) const {
6772 
6773   auto &Callee = CLI.Callee;
6774   auto CalleeCC = CLI.CallConv;
6775   auto &Outs = CLI.Outs;
6776   auto &Caller = MF.getFunction();
6777   auto CallerCC = Caller.getCallingConv();
6778 
6779   // Exception-handling functions need a special set of instructions to
6780   // indicate a return to the hardware. Tail-calling another function would
6781   // probably break this.
6782   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
6783   // should be expanded as new function attributes are introduced.
6784   if (Caller.hasFnAttribute("interrupt"))
6785     return false;
6786 
6787   // Do not tail call opt if the stack is used to pass parameters.
6788   if (CCInfo.getNextStackOffset() != 0)
6789     return false;
6790 
6791   // Do not tail call opt if any parameters need to be passed indirectly.
6792   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
6793   // passed indirectly. So the address of the value will be passed in a
6794   // register, or if not available, then the address is put on the stack. In
6795   // order to pass indirectly, space on the stack often needs to be allocated
6796   // in order to store the value. In this case the CCInfo.getNextStackOffset()
6797   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
6798   // are passed CCValAssign::Indirect.
6799   for (auto &VA : ArgLocs)
6800     if (VA.getLocInfo() == CCValAssign::Indirect)
6801       return false;
6802 
6803   // Do not tail call opt if either caller or callee uses struct return
6804   // semantics.
6805   auto IsCallerStructRet = Caller.hasStructRetAttr();
6806   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
6807   if (IsCallerStructRet || IsCalleeStructRet)
6808     return false;
6809 
6810   // Externally-defined functions with weak linkage should not be
6811   // tail-called. The behaviour of branch instructions in this situation (as
6812   // used for tail calls) is implementation-defined, so we cannot rely on the
6813   // linker replacing the tail call with a return.
6814   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
6815     const GlobalValue *GV = G->getGlobal();
6816     if (GV->hasExternalWeakLinkage())
6817       return false;
6818   }
6819 
6820   // The callee has to preserve all registers the caller needs to preserve.
6821   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
6822   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
6823   if (CalleeCC != CallerCC) {
6824     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
6825     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
6826       return false;
6827   }
6828 
6829   // Byval parameters hand the function a pointer directly into the stack area
6830   // we want to reuse during a tail call. Working around this *is* possible
6831   // but less efficient and uglier in LowerCall.
6832   for (auto &Arg : Outs)
6833     if (Arg.Flags.isByVal())
6834       return false;
6835 
6836   return true;
6837 }
6838 
6839 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
6840 // and output parameter nodes.
6841 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
6842                                        SmallVectorImpl<SDValue> &InVals) const {
6843   SelectionDAG &DAG = CLI.DAG;
6844   SDLoc &DL = CLI.DL;
6845   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
6846   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
6847   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
6848   SDValue Chain = CLI.Chain;
6849   SDValue Callee = CLI.Callee;
6850   bool &IsTailCall = CLI.IsTailCall;
6851   CallingConv::ID CallConv = CLI.CallConv;
6852   bool IsVarArg = CLI.IsVarArg;
6853   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6854   MVT XLenVT = Subtarget.getXLenVT();
6855 
6856   MachineFunction &MF = DAG.getMachineFunction();
6857 
6858   // Analyze the operands of the call, assigning locations to each operand.
6859   SmallVector<CCValAssign, 16> ArgLocs;
6860   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
6861 
6862   if (CallConv == CallingConv::Fast)
6863     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC);
6864   else if (CallConv == CallingConv::GHC)
6865     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
6866   else
6867     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
6868 
6869   // Check if it's really possible to do a tail call.
6870   if (IsTailCall)
6871     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
6872 
6873   if (IsTailCall)
6874     ++NumTailCalls;
6875   else if (CLI.CB && CLI.CB->isMustTailCall())
6876     report_fatal_error("failed to perform tail call elimination on a call "
6877                        "site marked musttail");
6878 
6879   // Get a count of how many bytes are to be pushed on the stack.
6880   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
6881 
6882   // Create local copies for byval args
6883   SmallVector<SDValue, 8> ByValArgs;
6884   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
6885     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6886     if (!Flags.isByVal())
6887       continue;
6888 
6889     SDValue Arg = OutVals[i];
6890     unsigned Size = Flags.getByValSize();
6891     Align Alignment = Flags.getNonZeroByValAlign();
6892 
6893     int FI =
6894         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
6895     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
6896     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
6897 
6898     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
6899                           /*IsVolatile=*/false,
6900                           /*AlwaysInline=*/false, IsTailCall,
6901                           MachinePointerInfo(), MachinePointerInfo());
6902     ByValArgs.push_back(FIPtr);
6903   }
6904 
6905   if (!IsTailCall)
6906     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
6907 
6908   // Copy argument values to their designated locations.
6909   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
6910   SmallVector<SDValue, 8> MemOpChains;
6911   SDValue StackPtr;
6912   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
6913     CCValAssign &VA = ArgLocs[i];
6914     SDValue ArgValue = OutVals[i];
6915     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6916 
6917     // Handle passing f64 on RV32D with a soft float ABI as a special case.
6918     bool IsF64OnRV32DSoftABI =
6919         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
6920     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
6921       SDValue SplitF64 = DAG.getNode(
6922           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
6923       SDValue Lo = SplitF64.getValue(0);
6924       SDValue Hi = SplitF64.getValue(1);
6925 
6926       Register RegLo = VA.getLocReg();
6927       RegsToPass.push_back(std::make_pair(RegLo, Lo));
6928 
6929       if (RegLo == RISCV::X17) {
6930         // Second half of f64 is passed on the stack.
6931         // Work out the address of the stack slot.
6932         if (!StackPtr.getNode())
6933           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
6934         // Emit the store.
6935         MemOpChains.push_back(
6936             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
6937       } else {
6938         // Second half of f64 is passed in another GPR.
6939         assert(RegLo < RISCV::X31 && "Invalid register pair");
6940         Register RegHigh = RegLo + 1;
6941         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
6942       }
6943       continue;
6944     }
6945 
6946     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
6947     // as any other MemLoc.
6948 
6949     // Promote the value if needed.
6950     // For now, only handle fully promoted and indirect arguments.
6951     if (VA.getLocInfo() == CCValAssign::Indirect) {
6952       // Store the argument in a stack slot and pass its address.
6953       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
6954       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
6955       MemOpChains.push_back(
6956           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
6957                        MachinePointerInfo::getFixedStack(MF, FI)));
6958       // If the original argument was split (e.g. i128), we need
6959       // to store the required parts of it here (and pass just one address).
6960       // Vectors may be partly split to registers and partly to the stack, in
6961       // which case the base address is partly offset and subsequent stores are
6962       // relative to that.
6963       unsigned ArgIndex = Outs[i].OrigArgIndex;
6964       unsigned ArgPartOffset = Outs[i].PartOffset;
6965       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
6966       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
6967         SDValue PartValue = OutVals[i + 1];
6968         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
6969         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
6970                                       DAG.getIntPtrConstant(PartOffset, DL));
6971         MemOpChains.push_back(
6972             DAG.getStore(Chain, DL, PartValue, Address,
6973                          MachinePointerInfo::getFixedStack(MF, FI)));
6974         ++i;
6975       }
6976       ArgValue = SpillSlot;
6977     } else {
6978       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
6979     }
6980 
6981     // Use local copy if it is a byval arg.
6982     if (Flags.isByVal())
6983       ArgValue = ByValArgs[j++];
6984 
6985     if (VA.isRegLoc()) {
6986       // Queue up the argument copies and emit them at the end.
6987       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
6988     } else {
6989       assert(VA.isMemLoc() && "Argument not register or memory");
6990       assert(!IsTailCall && "Tail call not allowed if stack is used "
6991                             "for passing parameters");
6992 
6993       // Work out the address of the stack slot.
6994       if (!StackPtr.getNode())
6995         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
6996       SDValue Address =
6997           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
6998                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
6999 
7000       // Emit the store.
7001       MemOpChains.push_back(
7002           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
7003     }
7004   }
7005 
7006   // Join the stores, which are independent of one another.
7007   if (!MemOpChains.empty())
7008     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
7009 
7010   SDValue Glue;
7011 
7012   // Build a sequence of copy-to-reg nodes, chained and glued together.
7013   for (auto &Reg : RegsToPass) {
7014     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
7015     Glue = Chain.getValue(1);
7016   }
7017 
7018   // Validate that none of the argument registers have been marked as
7019   // reserved, if so report an error. Do the same for the return address if this
7020   // is not a tailcall.
7021   validateCCReservedRegs(RegsToPass, MF);
7022   if (!IsTailCall &&
7023       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
7024     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
7025         MF.getFunction(),
7026         "Return address register required, but has been reserved."});
7027 
7028   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
7029   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
7030   // split it and then direct call can be matched by PseudoCALL.
7031   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
7032     const GlobalValue *GV = S->getGlobal();
7033 
7034     unsigned OpFlags = RISCVII::MO_CALL;
7035     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
7036       OpFlags = RISCVII::MO_PLT;
7037 
7038     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
7039   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
7040     unsigned OpFlags = RISCVII::MO_CALL;
7041 
7042     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
7043                                                  nullptr))
7044       OpFlags = RISCVII::MO_PLT;
7045 
7046     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
7047   }
7048 
7049   // The first call operand is the chain and the second is the target address.
7050   SmallVector<SDValue, 8> Ops;
7051   Ops.push_back(Chain);
7052   Ops.push_back(Callee);
7053 
7054   // Add argument registers to the end of the list so that they are
7055   // known live into the call.
7056   for (auto &Reg : RegsToPass)
7057     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
7058 
7059   if (!IsTailCall) {
7060     // Add a register mask operand representing the call-preserved registers.
7061     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
7062     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
7063     assert(Mask && "Missing call preserved mask for calling convention");
7064     Ops.push_back(DAG.getRegisterMask(Mask));
7065   }
7066 
7067   // Glue the call to the argument copies, if any.
7068   if (Glue.getNode())
7069     Ops.push_back(Glue);
7070 
7071   // Emit the call.
7072   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7073 
7074   if (IsTailCall) {
7075     MF.getFrameInfo().setHasTailCall();
7076     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
7077   }
7078 
7079   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
7080   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
7081   Glue = Chain.getValue(1);
7082 
7083   // Mark the end of the call, which is glued to the call itself.
7084   Chain = DAG.getCALLSEQ_END(Chain,
7085                              DAG.getConstant(NumBytes, DL, PtrVT, true),
7086                              DAG.getConstant(0, DL, PtrVT, true),
7087                              Glue, DL);
7088   Glue = Chain.getValue(1);
7089 
7090   // Assign locations to each value returned by this call.
7091   SmallVector<CCValAssign, 16> RVLocs;
7092   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
7093   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
7094 
7095   // Copy all of the result registers out of their specified physreg.
7096   for (auto &VA : RVLocs) {
7097     // Copy the value out
7098     SDValue RetValue =
7099         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
7100     // Glue the RetValue to the end of the call sequence
7101     Chain = RetValue.getValue(1);
7102     Glue = RetValue.getValue(2);
7103 
7104     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
7105       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
7106       SDValue RetValue2 =
7107           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
7108       Chain = RetValue2.getValue(1);
7109       Glue = RetValue2.getValue(2);
7110       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
7111                              RetValue2);
7112     }
7113 
7114     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
7115 
7116     InVals.push_back(RetValue);
7117   }
7118 
7119   return Chain;
7120 }
7121 
7122 bool RISCVTargetLowering::CanLowerReturn(
7123     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
7124     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
7125   SmallVector<CCValAssign, 16> RVLocs;
7126   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
7127 
7128   Optional<unsigned> FirstMaskArgument;
7129   if (Subtarget.hasStdExtV())
7130     FirstMaskArgument = preAssignMask(Outs);
7131 
7132   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
7133     MVT VT = Outs[i].VT;
7134     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
7135     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7136     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
7137                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
7138                  *this, FirstMaskArgument))
7139       return false;
7140   }
7141   return true;
7142 }
7143 
7144 SDValue
7145 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7146                                  bool IsVarArg,
7147                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
7148                                  const SmallVectorImpl<SDValue> &OutVals,
7149                                  const SDLoc &DL, SelectionDAG &DAG) const {
7150   const MachineFunction &MF = DAG.getMachineFunction();
7151   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
7152 
7153   // Stores the assignment of the return value to a location.
7154   SmallVector<CCValAssign, 16> RVLocs;
7155 
7156   // Info about the registers and stack slot.
7157   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
7158                  *DAG.getContext());
7159 
7160   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
7161                     nullptr);
7162 
7163   if (CallConv == CallingConv::GHC && !RVLocs.empty())
7164     report_fatal_error("GHC functions return void only");
7165 
7166   SDValue Glue;
7167   SmallVector<SDValue, 4> RetOps(1, Chain);
7168 
7169   // Copy the result values into the output registers.
7170   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
7171     SDValue Val = OutVals[i];
7172     CCValAssign &VA = RVLocs[i];
7173     assert(VA.isRegLoc() && "Can only return in registers!");
7174 
7175     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
7176       // Handle returning f64 on RV32D with a soft float ABI.
7177       assert(VA.isRegLoc() && "Expected return via registers");
7178       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
7179                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
7180       SDValue Lo = SplitF64.getValue(0);
7181       SDValue Hi = SplitF64.getValue(1);
7182       Register RegLo = VA.getLocReg();
7183       assert(RegLo < RISCV::X31 && "Invalid register pair");
7184       Register RegHi = RegLo + 1;
7185 
7186       if (STI.isRegisterReservedByUser(RegLo) ||
7187           STI.isRegisterReservedByUser(RegHi))
7188         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
7189             MF.getFunction(),
7190             "Return value register required, but has been reserved."});
7191 
7192       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
7193       Glue = Chain.getValue(1);
7194       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
7195       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
7196       Glue = Chain.getValue(1);
7197       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
7198     } else {
7199       // Handle a 'normal' return.
7200       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
7201       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
7202 
7203       if (STI.isRegisterReservedByUser(VA.getLocReg()))
7204         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
7205             MF.getFunction(),
7206             "Return value register required, but has been reserved."});
7207 
7208       // Guarantee that all emitted copies are stuck together.
7209       Glue = Chain.getValue(1);
7210       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7211     }
7212   }
7213 
7214   RetOps[0] = Chain; // Update chain.
7215 
7216   // Add the glue node if we have it.
7217   if (Glue.getNode()) {
7218     RetOps.push_back(Glue);
7219   }
7220 
7221   // Interrupt service routines use different return instructions.
7222   const Function &Func = DAG.getMachineFunction().getFunction();
7223   if (Func.hasFnAttribute("interrupt")) {
7224     if (!Func.getReturnType()->isVoidTy())
7225       report_fatal_error(
7226           "Functions with the interrupt attribute must have void return type!");
7227 
7228     MachineFunction &MF = DAG.getMachineFunction();
7229     StringRef Kind =
7230       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
7231 
7232     unsigned RetOpc;
7233     if (Kind == "user")
7234       RetOpc = RISCVISD::URET_FLAG;
7235     else if (Kind == "supervisor")
7236       RetOpc = RISCVISD::SRET_FLAG;
7237     else
7238       RetOpc = RISCVISD::MRET_FLAG;
7239 
7240     return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
7241   }
7242 
7243   return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
7244 }
7245 
7246 void RISCVTargetLowering::validateCCReservedRegs(
7247     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
7248     MachineFunction &MF) const {
7249   const Function &F = MF.getFunction();
7250   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
7251 
7252   if (llvm::any_of(Regs, [&STI](auto Reg) {
7253         return STI.isRegisterReservedByUser(Reg.first);
7254       }))
7255     F.getContext().diagnose(DiagnosticInfoUnsupported{
7256         F, "Argument register required, but has been reserved."});
7257 }
7258 
7259 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
7260   return CI->isTailCall();
7261 }
7262 
7263 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
7264 #define NODE_NAME_CASE(NODE)                                                   \
7265   case RISCVISD::NODE:                                                         \
7266     return "RISCVISD::" #NODE;
7267   // clang-format off
7268   switch ((RISCVISD::NodeType)Opcode) {
7269   case RISCVISD::FIRST_NUMBER:
7270     break;
7271   NODE_NAME_CASE(RET_FLAG)
7272   NODE_NAME_CASE(URET_FLAG)
7273   NODE_NAME_CASE(SRET_FLAG)
7274   NODE_NAME_CASE(MRET_FLAG)
7275   NODE_NAME_CASE(CALL)
7276   NODE_NAME_CASE(SELECT_CC)
7277   NODE_NAME_CASE(BR_CC)
7278   NODE_NAME_CASE(BuildPairF64)
7279   NODE_NAME_CASE(SplitF64)
7280   NODE_NAME_CASE(TAIL)
7281   NODE_NAME_CASE(MULHSU)
7282   NODE_NAME_CASE(SLLW)
7283   NODE_NAME_CASE(SRAW)
7284   NODE_NAME_CASE(SRLW)
7285   NODE_NAME_CASE(DIVW)
7286   NODE_NAME_CASE(DIVUW)
7287   NODE_NAME_CASE(REMUW)
7288   NODE_NAME_CASE(ROLW)
7289   NODE_NAME_CASE(RORW)
7290   NODE_NAME_CASE(CLZW)
7291   NODE_NAME_CASE(CTZW)
7292   NODE_NAME_CASE(FSLW)
7293   NODE_NAME_CASE(FSRW)
7294   NODE_NAME_CASE(FSL)
7295   NODE_NAME_CASE(FSR)
7296   NODE_NAME_CASE(FMV_H_X)
7297   NODE_NAME_CASE(FMV_X_ANYEXTH)
7298   NODE_NAME_CASE(FMV_W_X_RV64)
7299   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
7300   NODE_NAME_CASE(READ_CYCLE_WIDE)
7301   NODE_NAME_CASE(GREV)
7302   NODE_NAME_CASE(GREVW)
7303   NODE_NAME_CASE(GORC)
7304   NODE_NAME_CASE(GORCW)
7305   NODE_NAME_CASE(SHFL)
7306   NODE_NAME_CASE(VMV_V_X_VL)
7307   NODE_NAME_CASE(VFMV_V_F_VL)
7308   NODE_NAME_CASE(VMV_X_S)
7309   NODE_NAME_CASE(VMV_S_X_VL)
7310   NODE_NAME_CASE(VFMV_S_F_VL)
7311   NODE_NAME_CASE(SPLAT_VECTOR_I64)
7312   NODE_NAME_CASE(READ_VLENB)
7313   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
7314   NODE_NAME_CASE(VLEFF)
7315   NODE_NAME_CASE(VLEFF_MASK)
7316   NODE_NAME_CASE(VSLIDEUP_VL)
7317   NODE_NAME_CASE(VSLIDE1UP_VL)
7318   NODE_NAME_CASE(VSLIDEDOWN_VL)
7319   NODE_NAME_CASE(VSLIDE1DOWN_VL)
7320   NODE_NAME_CASE(VID_VL)
7321   NODE_NAME_CASE(VFNCVT_ROD_VL)
7322   NODE_NAME_CASE(VECREDUCE_ADD_VL)
7323   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
7324   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
7325   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
7326   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
7327   NODE_NAME_CASE(VECREDUCE_AND_VL)
7328   NODE_NAME_CASE(VECREDUCE_OR_VL)
7329   NODE_NAME_CASE(VECREDUCE_XOR_VL)
7330   NODE_NAME_CASE(VECREDUCE_FADD_VL)
7331   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
7332   NODE_NAME_CASE(ADD_VL)
7333   NODE_NAME_CASE(AND_VL)
7334   NODE_NAME_CASE(MUL_VL)
7335   NODE_NAME_CASE(OR_VL)
7336   NODE_NAME_CASE(SDIV_VL)
7337   NODE_NAME_CASE(SHL_VL)
7338   NODE_NAME_CASE(SREM_VL)
7339   NODE_NAME_CASE(SRA_VL)
7340   NODE_NAME_CASE(SRL_VL)
7341   NODE_NAME_CASE(SUB_VL)
7342   NODE_NAME_CASE(UDIV_VL)
7343   NODE_NAME_CASE(UREM_VL)
7344   NODE_NAME_CASE(XOR_VL)
7345   NODE_NAME_CASE(FADD_VL)
7346   NODE_NAME_CASE(FSUB_VL)
7347   NODE_NAME_CASE(FMUL_VL)
7348   NODE_NAME_CASE(FDIV_VL)
7349   NODE_NAME_CASE(FNEG_VL)
7350   NODE_NAME_CASE(FABS_VL)
7351   NODE_NAME_CASE(FSQRT_VL)
7352   NODE_NAME_CASE(FMA_VL)
7353   NODE_NAME_CASE(FCOPYSIGN_VL)
7354   NODE_NAME_CASE(SMIN_VL)
7355   NODE_NAME_CASE(SMAX_VL)
7356   NODE_NAME_CASE(UMIN_VL)
7357   NODE_NAME_CASE(UMAX_VL)
7358   NODE_NAME_CASE(MULHS_VL)
7359   NODE_NAME_CASE(MULHU_VL)
7360   NODE_NAME_CASE(FP_TO_SINT_VL)
7361   NODE_NAME_CASE(FP_TO_UINT_VL)
7362   NODE_NAME_CASE(SINT_TO_FP_VL)
7363   NODE_NAME_CASE(UINT_TO_FP_VL)
7364   NODE_NAME_CASE(FP_EXTEND_VL)
7365   NODE_NAME_CASE(FP_ROUND_VL)
7366   NODE_NAME_CASE(SETCC_VL)
7367   NODE_NAME_CASE(VSELECT_VL)
7368   NODE_NAME_CASE(VMAND_VL)
7369   NODE_NAME_CASE(VMOR_VL)
7370   NODE_NAME_CASE(VMXOR_VL)
7371   NODE_NAME_CASE(VMCLR_VL)
7372   NODE_NAME_CASE(VMSET_VL)
7373   NODE_NAME_CASE(VRGATHER_VX_VL)
7374   NODE_NAME_CASE(VRGATHER_VV_VL)
7375   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
7376   NODE_NAME_CASE(VSEXT_VL)
7377   NODE_NAME_CASE(VZEXT_VL)
7378   NODE_NAME_CASE(VPOPC_VL)
7379   NODE_NAME_CASE(VLE_VL)
7380   NODE_NAME_CASE(VSE_VL)
7381   NODE_NAME_CASE(READ_CSR)
7382   NODE_NAME_CASE(WRITE_CSR)
7383   NODE_NAME_CASE(SWAP_CSR)
7384   }
7385   // clang-format on
7386   return nullptr;
7387 #undef NODE_NAME_CASE
7388 }
7389 
7390 /// getConstraintType - Given a constraint letter, return the type of
7391 /// constraint it is for this target.
7392 RISCVTargetLowering::ConstraintType
7393 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
7394   if (Constraint.size() == 1) {
7395     switch (Constraint[0]) {
7396     default:
7397       break;
7398     case 'f':
7399     case 'v':
7400       return C_RegisterClass;
7401     case 'I':
7402     case 'J':
7403     case 'K':
7404       return C_Immediate;
7405     case 'A':
7406       return C_Memory;
7407     }
7408   }
7409   return TargetLowering::getConstraintType(Constraint);
7410 }
7411 
7412 std::pair<unsigned, const TargetRegisterClass *>
7413 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
7414                                                   StringRef Constraint,
7415                                                   MVT VT) const {
7416   // First, see if this is a constraint that directly corresponds to a
7417   // RISCV register class.
7418   if (Constraint.size() == 1) {
7419     switch (Constraint[0]) {
7420     case 'r':
7421       return std::make_pair(0U, &RISCV::GPRRegClass);
7422     case 'f':
7423       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
7424         return std::make_pair(0U, &RISCV::FPR16RegClass);
7425       if (Subtarget.hasStdExtF() && VT == MVT::f32)
7426         return std::make_pair(0U, &RISCV::FPR32RegClass);
7427       if (Subtarget.hasStdExtD() && VT == MVT::f64)
7428         return std::make_pair(0U, &RISCV::FPR64RegClass);
7429       break;
7430     case 'v':
7431       for (const auto *RC :
7432            {&RISCV::VMRegClass, &RISCV::VRRegClass, &RISCV::VRM2RegClass,
7433             &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
7434         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
7435           return std::make_pair(0U, RC);
7436       }
7437       break;
7438     default:
7439       break;
7440     }
7441   }
7442 
7443   // Clang will correctly decode the usage of register name aliases into their
7444   // official names. However, other frontends like `rustc` do not. This allows
7445   // users of these frontends to use the ABI names for registers in LLVM-style
7446   // register constraints.
7447   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
7448                                .Case("{zero}", RISCV::X0)
7449                                .Case("{ra}", RISCV::X1)
7450                                .Case("{sp}", RISCV::X2)
7451                                .Case("{gp}", RISCV::X3)
7452                                .Case("{tp}", RISCV::X4)
7453                                .Case("{t0}", RISCV::X5)
7454                                .Case("{t1}", RISCV::X6)
7455                                .Case("{t2}", RISCV::X7)
7456                                .Cases("{s0}", "{fp}", RISCV::X8)
7457                                .Case("{s1}", RISCV::X9)
7458                                .Case("{a0}", RISCV::X10)
7459                                .Case("{a1}", RISCV::X11)
7460                                .Case("{a2}", RISCV::X12)
7461                                .Case("{a3}", RISCV::X13)
7462                                .Case("{a4}", RISCV::X14)
7463                                .Case("{a5}", RISCV::X15)
7464                                .Case("{a6}", RISCV::X16)
7465                                .Case("{a7}", RISCV::X17)
7466                                .Case("{s2}", RISCV::X18)
7467                                .Case("{s3}", RISCV::X19)
7468                                .Case("{s4}", RISCV::X20)
7469                                .Case("{s5}", RISCV::X21)
7470                                .Case("{s6}", RISCV::X22)
7471                                .Case("{s7}", RISCV::X23)
7472                                .Case("{s8}", RISCV::X24)
7473                                .Case("{s9}", RISCV::X25)
7474                                .Case("{s10}", RISCV::X26)
7475                                .Case("{s11}", RISCV::X27)
7476                                .Case("{t3}", RISCV::X28)
7477                                .Case("{t4}", RISCV::X29)
7478                                .Case("{t5}", RISCV::X30)
7479                                .Case("{t6}", RISCV::X31)
7480                                .Default(RISCV::NoRegister);
7481   if (XRegFromAlias != RISCV::NoRegister)
7482     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
7483 
7484   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
7485   // TableGen record rather than the AsmName to choose registers for InlineAsm
7486   // constraints, plus we want to match those names to the widest floating point
7487   // register type available, manually select floating point registers here.
7488   //
7489   // The second case is the ABI name of the register, so that frontends can also
7490   // use the ABI names in register constraint lists.
7491   if (Subtarget.hasStdExtF()) {
7492     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
7493                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
7494                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
7495                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
7496                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
7497                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
7498                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
7499                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
7500                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
7501                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
7502                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
7503                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
7504                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
7505                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
7506                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
7507                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
7508                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
7509                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
7510                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
7511                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
7512                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
7513                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
7514                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
7515                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
7516                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
7517                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
7518                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
7519                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
7520                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
7521                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
7522                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
7523                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
7524                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
7525                         .Default(RISCV::NoRegister);
7526     if (FReg != RISCV::NoRegister) {
7527       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
7528       if (Subtarget.hasStdExtD()) {
7529         unsigned RegNo = FReg - RISCV::F0_F;
7530         unsigned DReg = RISCV::F0_D + RegNo;
7531         return std::make_pair(DReg, &RISCV::FPR64RegClass);
7532       }
7533       return std::make_pair(FReg, &RISCV::FPR32RegClass);
7534     }
7535   }
7536 
7537   if (Subtarget.hasStdExtV()) {
7538     Register VReg = StringSwitch<Register>(Constraint.lower())
7539                         .Case("{v0}", RISCV::V0)
7540                         .Case("{v1}", RISCV::V1)
7541                         .Case("{v2}", RISCV::V2)
7542                         .Case("{v3}", RISCV::V3)
7543                         .Case("{v4}", RISCV::V4)
7544                         .Case("{v5}", RISCV::V5)
7545                         .Case("{v6}", RISCV::V6)
7546                         .Case("{v7}", RISCV::V7)
7547                         .Case("{v8}", RISCV::V8)
7548                         .Case("{v9}", RISCV::V9)
7549                         .Case("{v10}", RISCV::V10)
7550                         .Case("{v11}", RISCV::V11)
7551                         .Case("{v12}", RISCV::V12)
7552                         .Case("{v13}", RISCV::V13)
7553                         .Case("{v14}", RISCV::V14)
7554                         .Case("{v15}", RISCV::V15)
7555                         .Case("{v16}", RISCV::V16)
7556                         .Case("{v17}", RISCV::V17)
7557                         .Case("{v18}", RISCV::V18)
7558                         .Case("{v19}", RISCV::V19)
7559                         .Case("{v20}", RISCV::V20)
7560                         .Case("{v21}", RISCV::V21)
7561                         .Case("{v22}", RISCV::V22)
7562                         .Case("{v23}", RISCV::V23)
7563                         .Case("{v24}", RISCV::V24)
7564                         .Case("{v25}", RISCV::V25)
7565                         .Case("{v26}", RISCV::V26)
7566                         .Case("{v27}", RISCV::V27)
7567                         .Case("{v28}", RISCV::V28)
7568                         .Case("{v29}", RISCV::V29)
7569                         .Case("{v30}", RISCV::V30)
7570                         .Case("{v31}", RISCV::V31)
7571                         .Default(RISCV::NoRegister);
7572     if (VReg != RISCV::NoRegister) {
7573       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
7574         return std::make_pair(VReg, &RISCV::VMRegClass);
7575       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
7576         return std::make_pair(VReg, &RISCV::VRRegClass);
7577       for (const auto *RC :
7578            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
7579         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
7580           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
7581           return std::make_pair(VReg, RC);
7582         }
7583       }
7584     }
7585   }
7586 
7587   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7588 }
7589 
7590 unsigned
7591 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
7592   // Currently only support length 1 constraints.
7593   if (ConstraintCode.size() == 1) {
7594     switch (ConstraintCode[0]) {
7595     case 'A':
7596       return InlineAsm::Constraint_A;
7597     default:
7598       break;
7599     }
7600   }
7601 
7602   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
7603 }
7604 
7605 void RISCVTargetLowering::LowerAsmOperandForConstraint(
7606     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
7607     SelectionDAG &DAG) const {
7608   // Currently only support length 1 constraints.
7609   if (Constraint.length() == 1) {
7610     switch (Constraint[0]) {
7611     case 'I':
7612       // Validate & create a 12-bit signed immediate operand.
7613       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
7614         uint64_t CVal = C->getSExtValue();
7615         if (isInt<12>(CVal))
7616           Ops.push_back(
7617               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
7618       }
7619       return;
7620     case 'J':
7621       // Validate & create an integer zero operand.
7622       if (auto *C = dyn_cast<ConstantSDNode>(Op))
7623         if (C->getZExtValue() == 0)
7624           Ops.push_back(
7625               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
7626       return;
7627     case 'K':
7628       // Validate & create a 5-bit unsigned immediate operand.
7629       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
7630         uint64_t CVal = C->getZExtValue();
7631         if (isUInt<5>(CVal))
7632           Ops.push_back(
7633               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
7634       }
7635       return;
7636     default:
7637       break;
7638     }
7639   }
7640   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7641 }
7642 
7643 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7644                                                    Instruction *Inst,
7645                                                    AtomicOrdering Ord) const {
7646   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
7647     return Builder.CreateFence(Ord);
7648   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
7649     return Builder.CreateFence(AtomicOrdering::Release);
7650   return nullptr;
7651 }
7652 
7653 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7654                                                     Instruction *Inst,
7655                                                     AtomicOrdering Ord) const {
7656   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
7657     return Builder.CreateFence(AtomicOrdering::Acquire);
7658   return nullptr;
7659 }
7660 
7661 TargetLowering::AtomicExpansionKind
7662 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
7663   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
7664   // point operations can't be used in an lr/sc sequence without breaking the
7665   // forward-progress guarantee.
7666   if (AI->isFloatingPointOperation())
7667     return AtomicExpansionKind::CmpXChg;
7668 
7669   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
7670   if (Size == 8 || Size == 16)
7671     return AtomicExpansionKind::MaskedIntrinsic;
7672   return AtomicExpansionKind::None;
7673 }
7674 
7675 static Intrinsic::ID
7676 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
7677   if (XLen == 32) {
7678     switch (BinOp) {
7679     default:
7680       llvm_unreachable("Unexpected AtomicRMW BinOp");
7681     case AtomicRMWInst::Xchg:
7682       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
7683     case AtomicRMWInst::Add:
7684       return Intrinsic::riscv_masked_atomicrmw_add_i32;
7685     case AtomicRMWInst::Sub:
7686       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
7687     case AtomicRMWInst::Nand:
7688       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
7689     case AtomicRMWInst::Max:
7690       return Intrinsic::riscv_masked_atomicrmw_max_i32;
7691     case AtomicRMWInst::Min:
7692       return Intrinsic::riscv_masked_atomicrmw_min_i32;
7693     case AtomicRMWInst::UMax:
7694       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
7695     case AtomicRMWInst::UMin:
7696       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
7697     }
7698   }
7699 
7700   if (XLen == 64) {
7701     switch (BinOp) {
7702     default:
7703       llvm_unreachable("Unexpected AtomicRMW BinOp");
7704     case AtomicRMWInst::Xchg:
7705       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
7706     case AtomicRMWInst::Add:
7707       return Intrinsic::riscv_masked_atomicrmw_add_i64;
7708     case AtomicRMWInst::Sub:
7709       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
7710     case AtomicRMWInst::Nand:
7711       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
7712     case AtomicRMWInst::Max:
7713       return Intrinsic::riscv_masked_atomicrmw_max_i64;
7714     case AtomicRMWInst::Min:
7715       return Intrinsic::riscv_masked_atomicrmw_min_i64;
7716     case AtomicRMWInst::UMax:
7717       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
7718     case AtomicRMWInst::UMin:
7719       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
7720     }
7721   }
7722 
7723   llvm_unreachable("Unexpected XLen\n");
7724 }
7725 
7726 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
7727     IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
7728     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
7729   unsigned XLen = Subtarget.getXLen();
7730   Value *Ordering =
7731       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
7732   Type *Tys[] = {AlignedAddr->getType()};
7733   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
7734       AI->getModule(),
7735       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
7736 
7737   if (XLen == 64) {
7738     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
7739     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
7740     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
7741   }
7742 
7743   Value *Result;
7744 
7745   // Must pass the shift amount needed to sign extend the loaded value prior
7746   // to performing a signed comparison for min/max. ShiftAmt is the number of
7747   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
7748   // is the number of bits to left+right shift the value in order to
7749   // sign-extend.
7750   if (AI->getOperation() == AtomicRMWInst::Min ||
7751       AI->getOperation() == AtomicRMWInst::Max) {
7752     const DataLayout &DL = AI->getModule()->getDataLayout();
7753     unsigned ValWidth =
7754         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
7755     Value *SextShamt =
7756         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
7757     Result = Builder.CreateCall(LrwOpScwLoop,
7758                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
7759   } else {
7760     Result =
7761         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
7762   }
7763 
7764   if (XLen == 64)
7765     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
7766   return Result;
7767 }
7768 
7769 TargetLowering::AtomicExpansionKind
7770 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
7771     AtomicCmpXchgInst *CI) const {
7772   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
7773   if (Size == 8 || Size == 16)
7774     return AtomicExpansionKind::MaskedIntrinsic;
7775   return AtomicExpansionKind::None;
7776 }
7777 
7778 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
7779     IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
7780     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
7781   unsigned XLen = Subtarget.getXLen();
7782   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
7783   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
7784   if (XLen == 64) {
7785     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
7786     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
7787     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
7788     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
7789   }
7790   Type *Tys[] = {AlignedAddr->getType()};
7791   Function *MaskedCmpXchg =
7792       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
7793   Value *Result = Builder.CreateCall(
7794       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
7795   if (XLen == 64)
7796     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
7797   return Result;
7798 }
7799 
7800 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
7801   return false;
7802 }
7803 
7804 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
7805                                                      EVT VT) const {
7806   VT = VT.getScalarType();
7807 
7808   if (!VT.isSimple())
7809     return false;
7810 
7811   switch (VT.getSimpleVT().SimpleTy) {
7812   case MVT::f16:
7813     return Subtarget.hasStdExtZfh();
7814   case MVT::f32:
7815     return Subtarget.hasStdExtF();
7816   case MVT::f64:
7817     return Subtarget.hasStdExtD();
7818   default:
7819     break;
7820   }
7821 
7822   return false;
7823 }
7824 
7825 Register RISCVTargetLowering::getExceptionPointerRegister(
7826     const Constant *PersonalityFn) const {
7827   return RISCV::X10;
7828 }
7829 
7830 Register RISCVTargetLowering::getExceptionSelectorRegister(
7831     const Constant *PersonalityFn) const {
7832   return RISCV::X11;
7833 }
7834 
7835 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
7836   // Return false to suppress the unnecessary extensions if the LibCall
7837   // arguments or return value is f32 type for LP64 ABI.
7838   RISCVABI::ABI ABI = Subtarget.getTargetABI();
7839   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
7840     return false;
7841 
7842   return true;
7843 }
7844 
7845 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
7846   if (Subtarget.is64Bit() && Type == MVT::i32)
7847     return true;
7848 
7849   return IsSigned;
7850 }
7851 
7852 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
7853                                                  SDValue C) const {
7854   // Check integral scalar types.
7855   if (VT.isScalarInteger()) {
7856     // Omit the optimization if the sub target has the M extension and the data
7857     // size exceeds XLen.
7858     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
7859       return false;
7860     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
7861       // Break the MUL to a SLLI and an ADD/SUB.
7862       const APInt &Imm = ConstNode->getAPIntValue();
7863       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
7864           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
7865         return true;
7866       // Omit the following optimization if the sub target has the M extension
7867       // and the data size >= XLen.
7868       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
7869         return false;
7870       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
7871       // a pair of LUI/ADDI.
7872       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
7873         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
7874         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
7875             (1 - ImmS).isPowerOf2())
7876         return true;
7877       }
7878     }
7879   }
7880 
7881   return false;
7882 }
7883 
7884 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
7885   if (!Subtarget.useRVVForFixedLengthVectors())
7886     return false;
7887 
7888   if (!VT.isFixedLengthVector())
7889     return false;
7890 
7891   // Don't use RVV for vectors we cannot scalarize if required.
7892   switch (VT.getVectorElementType().SimpleTy) {
7893   // i1 is supported but has different rules.
7894   default:
7895     return false;
7896   case MVT::i1:
7897     // Masks can only use a single register.
7898     if (VT.getVectorNumElements() > Subtarget.getMinRVVVectorSizeInBits())
7899       return false;
7900     break;
7901   case MVT::i8:
7902   case MVT::i16:
7903   case MVT::i32:
7904   case MVT::i64:
7905     break;
7906   case MVT::f16:
7907     if (!Subtarget.hasStdExtZfh())
7908       return false;
7909     break;
7910   case MVT::f32:
7911     if (!Subtarget.hasStdExtF())
7912       return false;
7913     break;
7914   case MVT::f64:
7915     if (!Subtarget.hasStdExtD())
7916       return false;
7917     break;
7918   }
7919 
7920   unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT);
7921   // Don't use RVV for types that don't fit.
7922   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
7923     return false;
7924 
7925   // TODO: Perhaps an artificial restriction, but worth having whilst getting
7926   // the base fixed length RVV support in place.
7927   if (!VT.isPow2VectorType())
7928     return false;
7929 
7930   return true;
7931 }
7932 
7933 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
7934     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
7935     bool *Fast) const {
7936   if (!VT.isScalableVector())
7937     return false;
7938 
7939   EVT ElemVT = VT.getVectorElementType();
7940   if (Alignment >= ElemVT.getStoreSize()) {
7941     if (Fast)
7942       *Fast = true;
7943     return true;
7944   }
7945 
7946   return false;
7947 }
7948 
7949 bool RISCVTargetLowering::splitValueIntoRegisterParts(
7950     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
7951     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
7952   bool IsABIRegCopy = CC.hasValue();
7953   EVT ValueVT = Val.getValueType();
7954   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
7955     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
7956     // and cast to f32.
7957     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
7958     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
7959     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
7960                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
7961     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
7962     Parts[0] = Val;
7963     return true;
7964   }
7965 
7966   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
7967     LLVMContext &Context = *DAG.getContext();
7968     EVT ValueEltVT = ValueVT.getVectorElementType();
7969     EVT PartEltVT = PartVT.getVectorElementType();
7970     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
7971     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
7972     if (PartVTBitSize % ValueVTBitSize == 0) {
7973       // If the element types are different, bitcast to the same element type of
7974       // PartVT first.
7975       if (ValueEltVT != PartEltVT) {
7976         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
7977         assert(Count != 0 && "The number of element should not be zero.");
7978         EVT SameEltTypeVT =
7979             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
7980         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
7981       }
7982       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
7983                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
7984       Parts[0] = Val;
7985       return true;
7986     }
7987   }
7988   return false;
7989 }
7990 
7991 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
7992     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
7993     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
7994   bool IsABIRegCopy = CC.hasValue();
7995   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
7996     SDValue Val = Parts[0];
7997 
7998     // Cast the f32 to i32, truncate to i16, and cast back to f16.
7999     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
8000     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
8001     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
8002     return Val;
8003   }
8004 
8005   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
8006     LLVMContext &Context = *DAG.getContext();
8007     SDValue Val = Parts[0];
8008     EVT ValueEltVT = ValueVT.getVectorElementType();
8009     EVT PartEltVT = PartVT.getVectorElementType();
8010     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
8011     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
8012     if (PartVTBitSize % ValueVTBitSize == 0) {
8013       EVT SameEltTypeVT = ValueVT;
8014       // If the element types are different, convert it to the same element type
8015       // of PartVT.
8016       if (ValueEltVT != PartEltVT) {
8017         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
8018         assert(Count != 0 && "The number of element should not be zero.");
8019         SameEltTypeVT =
8020             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
8021       }
8022       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
8023                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
8024       if (ValueEltVT != PartEltVT)
8025         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
8026       return Val;
8027     }
8028   }
8029   return SDValue();
8030 }
8031 
8032 #define GET_REGISTER_MATCHER
8033 #include "RISCVGenAsmMatcher.inc"
8034 
8035 Register
8036 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
8037                                        const MachineFunction &MF) const {
8038   Register Reg = MatchRegisterAltName(RegName);
8039   if (Reg == RISCV::NoRegister)
8040     Reg = MatchRegisterName(RegName);
8041   if (Reg == RISCV::NoRegister)
8042     report_fatal_error(
8043         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
8044   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
8045   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
8046     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
8047                              StringRef(RegName) + "\"."));
8048   return Reg;
8049 }
8050 
8051 namespace llvm {
8052 namespace RISCVVIntrinsicsTable {
8053 
8054 #define GET_RISCVVIntrinsicsTable_IMPL
8055 #include "RISCVGenSearchableTables.inc"
8056 
8057 } // namespace RISCVVIntrinsicsTable
8058 
8059 } // namespace llvm
8060