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