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