LLVM 24.0.0git
RISCVISelLowering.cpp
Go to the documentation of this file.
1//===-- RISCVISelLowering.cpp - RISC-V 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 RISC-V uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RISCVISelLowering.h"
16#include "RISCV.h"
19#include "RISCVRegisterInfo.h"
21#include "RISCVSubtarget.h"
22#include "RISCVVectorUtils.h"
23#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/Statistic.h"
41#include "llvm/IR/IRBuilder.h"
44#include "llvm/IR/IntrinsicsRISCV.h"
51#include <optional>
52
53using namespace llvm;
54
55#define DEBUG_TYPE "riscv-lower"
56
57STATISTIC(NumTailCalls, "Number of tail calls");
58
59// TODO: Support more ops
66
68 const RISCVSubtarget &STI)
69 : TargetLowering(TM, STI), Subtarget(STI) {
70
71 RISCVABI::ABI ABI = Subtarget.getTargetABI();
72 // Note: Hard-float ABIs that don't match the F/D extensions are already
73 // rejected/ by RISCVABI::computeTargetABI() during subtarget construction.
74 assert(ABI != RISCVABI::ABI::Unknown && "Improperly initialised target ABI");
75
76 if (RISCVABI::isPurecap(ABI))
77 reportFatalUsageError("Don't know how to lower this ABI");
78
79 MVT XLenVT = Subtarget.getXLenVT();
80
81 // Set up the register classes.
82 addRegisterClass(XLenVT, &RISCV::GPRRegClass);
83
84 if (Subtarget.hasStdExtZfhmin())
85 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
86 if (Subtarget.hasStdExtZfbfmin() || Subtarget.hasVendorXAndesBFHCvt())
87 addRegisterClass(MVT::bf16, &RISCV::FPR16RegClass);
88 if (Subtarget.hasStdExtF())
89 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
90 if (Subtarget.hasStdExtD())
91 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
92 if (Subtarget.hasStdExtZhinxmin())
93 addRegisterClass(MVT::f16, &RISCV::GPRF16RegClass);
94 if (Subtarget.hasStdExtZfinx())
95 addRegisterClass(MVT::f32, &RISCV::GPRF32RegClass);
96 if (Subtarget.hasStdExtZdinx()) {
97 if (Subtarget.is64Bit())
98 addRegisterClass(MVT::f64, &RISCV::GPRRegClass);
99 else
100 addRegisterClass(MVT::f64, &RISCV::GPRPairRegClass);
101 }
102
103 static const MVT::SimpleValueType BoolVecVTs[] = {
104 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1,
105 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
106 static const MVT::SimpleValueType IntVecVTs[] = {
107 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8,
108 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16,
109 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
110 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
111 MVT::nxv4i64, MVT::nxv8i64};
112 static const MVT::SimpleValueType F16VecVTs[] = {
113 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16,
114 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
115 static const MVT::SimpleValueType BF16VecVTs[] = {
116 MVT::nxv1bf16, MVT::nxv2bf16, MVT::nxv4bf16,
117 MVT::nxv8bf16, MVT::nxv16bf16, MVT::nxv32bf16};
118 static const MVT::SimpleValueType F32VecVTs[] = {
119 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
120 static const MVT::SimpleValueType F64VecVTs[] = {
121 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
122 static const MVT::SimpleValueType VecTupleVTs[] = {
123 MVT::riscv_nxv1i8x2, MVT::riscv_nxv1i8x3, MVT::riscv_nxv1i8x4,
124 MVT::riscv_nxv1i8x5, MVT::riscv_nxv1i8x6, MVT::riscv_nxv1i8x7,
125 MVT::riscv_nxv1i8x8, MVT::riscv_nxv2i8x2, MVT::riscv_nxv2i8x3,
126 MVT::riscv_nxv2i8x4, MVT::riscv_nxv2i8x5, MVT::riscv_nxv2i8x6,
127 MVT::riscv_nxv2i8x7, MVT::riscv_nxv2i8x8, MVT::riscv_nxv4i8x2,
128 MVT::riscv_nxv4i8x3, MVT::riscv_nxv4i8x4, MVT::riscv_nxv4i8x5,
129 MVT::riscv_nxv4i8x6, MVT::riscv_nxv4i8x7, MVT::riscv_nxv4i8x8,
130 MVT::riscv_nxv8i8x2, MVT::riscv_nxv8i8x3, MVT::riscv_nxv8i8x4,
131 MVT::riscv_nxv8i8x5, MVT::riscv_nxv8i8x6, MVT::riscv_nxv8i8x7,
132 MVT::riscv_nxv8i8x8, MVT::riscv_nxv16i8x2, MVT::riscv_nxv16i8x3,
133 MVT::riscv_nxv16i8x4, MVT::riscv_nxv32i8x2};
134
135 if (Subtarget.hasVInstructions()) {
136 auto addRegClassForRVV = [this](MVT VT) {
137 // Disable the smallest fractional LMUL types if ELEN is less than
138 // RVVBitsPerBlock.
139 unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELen();
140 if (VT.getVectorMinNumElements() < MinElts)
141 return;
142
143 unsigned Size = VT.getSizeInBits().getKnownMinValue();
144 const TargetRegisterClass *RC;
146 RC = &RISCV::VRRegClass;
147 else if (Size == 2 * RISCV::RVVBitsPerBlock)
148 RC = &RISCV::VRM2RegClass;
149 else if (Size == 4 * RISCV::RVVBitsPerBlock)
150 RC = &RISCV::VRM4RegClass;
151 else if (Size == 8 * RISCV::RVVBitsPerBlock)
152 RC = &RISCV::VRM8RegClass;
153 else
154 llvm_unreachable("Unexpected size");
155
156 addRegisterClass(VT, RC);
157 };
158
159 for (MVT VT : BoolVecVTs)
160 addRegClassForRVV(VT);
161 for (MVT VT : IntVecVTs) {
162 if (VT.getVectorElementType() == MVT::i64 &&
163 !Subtarget.hasVInstructionsI64())
164 continue;
165 addRegClassForRVV(VT);
166 }
167
168 if (Subtarget.hasVInstructionsF16Minimal() ||
169 Subtarget.hasVendorXAndesVPackFPH())
170 for (MVT VT : F16VecVTs)
171 addRegClassForRVV(VT);
172
173 if (Subtarget.hasVInstructionsBF16Minimal() ||
174 Subtarget.hasVendorXAndesVBFHCvt())
175 for (MVT VT : BF16VecVTs)
176 addRegClassForRVV(VT);
177
178 if (Subtarget.hasVInstructionsF32())
179 for (MVT VT : F32VecVTs)
180 addRegClassForRVV(VT);
181
182 if (Subtarget.hasVInstructionsF64())
183 for (MVT VT : F64VecVTs)
184 addRegClassForRVV(VT);
185
186 if (Subtarget.useRVVForFixedLengthVectors()) {
187 auto addRegClassForFixedVectors = [this](MVT VT) {
189 unsigned RCID = getRegClassIDForVecVT(ContainerVT);
190 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
191 addRegisterClass(VT, TRI.getRegClass(RCID));
192 };
194 if (useRVVForFixedLengthVectorVT(VT))
195 addRegClassForFixedVectors(VT);
196
198 if (useRVVForFixedLengthVectorVT(VT))
199 addRegClassForFixedVectors(VT);
200 }
201
202 addRegisterClass(MVT::riscv_nxv1i8x2, &RISCV::VRN2M1RegClass);
203 addRegisterClass(MVT::riscv_nxv1i8x3, &RISCV::VRN3M1RegClass);
204 addRegisterClass(MVT::riscv_nxv1i8x4, &RISCV::VRN4M1RegClass);
205 addRegisterClass(MVT::riscv_nxv1i8x5, &RISCV::VRN5M1RegClass);
206 addRegisterClass(MVT::riscv_nxv1i8x6, &RISCV::VRN6M1RegClass);
207 addRegisterClass(MVT::riscv_nxv1i8x7, &RISCV::VRN7M1RegClass);
208 addRegisterClass(MVT::riscv_nxv1i8x8, &RISCV::VRN8M1RegClass);
209 addRegisterClass(MVT::riscv_nxv2i8x2, &RISCV::VRN2M1RegClass);
210 addRegisterClass(MVT::riscv_nxv2i8x3, &RISCV::VRN3M1RegClass);
211 addRegisterClass(MVT::riscv_nxv2i8x4, &RISCV::VRN4M1RegClass);
212 addRegisterClass(MVT::riscv_nxv2i8x5, &RISCV::VRN5M1RegClass);
213 addRegisterClass(MVT::riscv_nxv2i8x6, &RISCV::VRN6M1RegClass);
214 addRegisterClass(MVT::riscv_nxv2i8x7, &RISCV::VRN7M1RegClass);
215 addRegisterClass(MVT::riscv_nxv2i8x8, &RISCV::VRN8M1RegClass);
216 addRegisterClass(MVT::riscv_nxv4i8x2, &RISCV::VRN2M1RegClass);
217 addRegisterClass(MVT::riscv_nxv4i8x3, &RISCV::VRN3M1RegClass);
218 addRegisterClass(MVT::riscv_nxv4i8x4, &RISCV::VRN4M1RegClass);
219 addRegisterClass(MVT::riscv_nxv4i8x5, &RISCV::VRN5M1RegClass);
220 addRegisterClass(MVT::riscv_nxv4i8x6, &RISCV::VRN6M1RegClass);
221 addRegisterClass(MVT::riscv_nxv4i8x7, &RISCV::VRN7M1RegClass);
222 addRegisterClass(MVT::riscv_nxv4i8x8, &RISCV::VRN8M1RegClass);
223 addRegisterClass(MVT::riscv_nxv8i8x2, &RISCV::VRN2M1RegClass);
224 addRegisterClass(MVT::riscv_nxv8i8x3, &RISCV::VRN3M1RegClass);
225 addRegisterClass(MVT::riscv_nxv8i8x4, &RISCV::VRN4M1RegClass);
226 addRegisterClass(MVT::riscv_nxv8i8x5, &RISCV::VRN5M1RegClass);
227 addRegisterClass(MVT::riscv_nxv8i8x6, &RISCV::VRN6M1RegClass);
228 addRegisterClass(MVT::riscv_nxv8i8x7, &RISCV::VRN7M1RegClass);
229 addRegisterClass(MVT::riscv_nxv8i8x8, &RISCV::VRN8M1RegClass);
230 addRegisterClass(MVT::riscv_nxv16i8x2, &RISCV::VRN2M2RegClass);
231 addRegisterClass(MVT::riscv_nxv16i8x3, &RISCV::VRN3M2RegClass);
232 addRegisterClass(MVT::riscv_nxv16i8x4, &RISCV::VRN4M2RegClass);
233 addRegisterClass(MVT::riscv_nxv32i8x2, &RISCV::VRN2M4RegClass);
234 }
235
236 // fixed vector is stored in GPRs for P extension packed operations
237 if (Subtarget.hasStdExtP()) {
238 if (Subtarget.is64Bit()) {
239 addRegisterClass(MVT::v2i32, &RISCV::GPRRegClass);
240 addRegisterClass(MVT::v4i16, &RISCV::GPRRegClass);
241 addRegisterClass(MVT::v8i8, &RISCV::GPRRegClass);
242 } else {
243 addRegisterClass(MVT::v2i16, &RISCV::GPRRegClass);
244 addRegisterClass(MVT::v4i8, &RISCV::GPRRegClass);
245
246 addRegisterClass(MVT::v2i32, &RISCV::GPRPairRegClass);
247 addRegisterClass(MVT::v4i16, &RISCV::GPRPairRegClass);
248 addRegisterClass(MVT::v8i8, &RISCV::GPRPairRegClass);
249 }
250 }
251
252 // Compute derived properties from the register classes.
254
256
258 MVT::i1, Promote);
259 // DAGCombiner can call isLoadExtLegal for types that aren't legal.
261 MVT::i1, Promote);
262
263 // TODO: add all necessary setOperationAction calls.
265
270
275 if (!(Subtarget.hasVendorXCValu() && !Subtarget.is64Bit())) {
278 }
279
281
284
285 if (!Subtarget.hasVendorXTHeadBb() && !Subtarget.hasVendorXqcibm() &&
286 !Subtarget.hasVendorXAndesPerf())
288
290
291 if (!Subtarget.hasStdExtZbb() && !Subtarget.hasVendorXTHeadBb() &&
292 !Subtarget.hasVendorXqcibm() && !Subtarget.hasVendorXAndesPerf() &&
293 !(Subtarget.hasVendorXCValu() && !Subtarget.is64Bit()))
294 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
295
296 if (Subtarget.hasStdExtZilsd() && !Subtarget.is64Bit()) {
299 }
300
301 if (Subtarget.is64Bit()) {
303
306 MVT::i32, Custom);
309 } else if (Subtarget.hasStdExtP()) {
310 // Custom legalize i64 ADD/SUB/SHL/SRL/SRA for RV32+P.
313 }
314 if (!Subtarget.hasStdExtZmmul()) {
316 } else if (Subtarget.is64Bit()) {
319 } else {
321 }
322
323 if (!Subtarget.hasStdExtM()) {
325 Expand);
326 } else if (Subtarget.is64Bit()) {
328 {MVT::i8, MVT::i16, MVT::i32}, Custom);
329 }
330
332
333 // On RV32, the P extension has a WMUL(U) instruction we can use for
334 // (S/U)MUL_LOHI.
335 // FIXME: Does P imply Zmmul?
336 if (!Subtarget.hasStdExtP() || !Subtarget.hasStdExtZmmul() ||
337 Subtarget.is64Bit())
339
341 Custom);
342
343 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) {
344 if (Subtarget.is64Bit())
346 } else if (Subtarget.hasVendorXTHeadBb()) {
347 if (Subtarget.is64Bit())
350 } else if (Subtarget.hasVendorXCVbitmanip() && !Subtarget.is64Bit()) {
352 } else {
354 }
355
356 if (Subtarget.hasStdExtP()) {
358 if (!Subtarget.is64Bit())
360 }
361
363 Subtarget.hasREV8Like() ? Legal : Expand);
364
365 if (Subtarget.hasREVLike()) {
367 } else {
368 // Zbkb can use rev8+brev8 to implement bitreverse.
370 Subtarget.hasStdExtZbkb() ? Custom : Expand);
371 if (Subtarget.hasStdExtZbkb())
373 }
374
375 if (Subtarget.hasStdExtZbb() ||
376 (Subtarget.hasVendorXCValu() && !Subtarget.is64Bit())) {
378 Legal);
379 }
380
381 if (Subtarget.hasCTZLike()) {
382 if (Subtarget.is64Bit())
384 } else {
386 }
387
388 if (!Subtarget.hasCPOPLike()) {
389 // TODO: These should be set to LibCall, but this currently breaks
390 // the Linux kernel build. See #101786. Lacks i128 tests, too.
391 if (Subtarget.is64Bit())
393 else
396 }
397
398 if (Subtarget.hasCLZLike()) {
399 // We need the custom lowering to make sure that the resulting sequence
400 // for the 32bit case is efficient on 64bit targets.
401 // Use default promotion for i32 without Zbb.
402 if (Subtarget.is64Bit() &&
403 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtP()))
405 } else {
406 if (Subtarget.hasVendorXCVbitmanip() && !Subtarget.is64Bit())
409 }
410
411 if (Subtarget.hasStdExtP()) {
413 if (Subtarget.is64Bit())
415 }
416
417 if (Subtarget.hasStdExtP() ||
418 (Subtarget.hasVendorXCValu() && !Subtarget.is64Bit())) {
420 if (Subtarget.is64Bit())
422 } else if (Subtarget.hasShortForwardBranchIALU()) {
423 // We can use PseudoCCSUB to implement ABS.
425 } else if (Subtarget.is64Bit()) {
427 }
428
429 if (!Subtarget.useMIPSCCMovInsn() && !Subtarget.hasVendorXTHeadCondMov())
431
432 if ((Subtarget.hasStdExtP() || Subtarget.hasVendorXqcia()) &&
433 !Subtarget.is64Bit()) {
435 MVT::i32, Legal);
436 } else if (Subtarget.hasStdExtP() && Subtarget.is64Bit()) {
438 MVT::i32, Custom);
439 } else if (!Subtarget.hasStdExtZbb() && Subtarget.is64Bit()) {
441 MVT::i32, Custom);
442 }
443
444 if ((Subtarget.hasStdExtP() || Subtarget.hasVendorXqcia()) &&
445 !Subtarget.is64Bit()) {
446 // FIXME: Support i32 on RV64+P by inserting into a v2i32 vector, doing
447 // pssha.w/psshl.w and extracting.
450 }
451
452 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit()) {
453 // FIXME: Support i32 on RV64+P by inserting into a v2i32 vector, doing
454 // paadd.w, paaddu.w and extracting.
457 MVT::i32, Legal);
458 }
459
460 if (Subtarget.hasStdExtZbkc()) {
462 if (Subtarget.hasStdExtZbc())
464 } else if (Subtarget.hasStdExtZvbc() && Subtarget.is64Bit()) {
465 // FIXME: Support i32 on RV32 by zexting from XLEN to i64 and extracting
466 // half of the result (low for CLMUL, high for CLMULH).
467 // TODO: Zvbc32e allows us to do a lot more here.
469 }
470
471 static const unsigned FPLegalNodeTypes[] = {
479
480 static const ISD::CondCode FPCCToExpand[] = {
484
485 static const unsigned FPOpToExpand[] = {ISD::FSIN, ISD::FCOS, ISD::FSINCOS,
486 ISD::FPOW};
487 static const unsigned FPOpToLibCall[] = {ISD::FREM};
488
489 static const unsigned FPRndMode[] = {
492
493 static const unsigned ZfhminZfbfminPromoteOps[] = {
504
505 if (Subtarget.hasStdExtP()) {
506 static const MVT P32VecVTs[] = {MVT::v2i16, MVT::v4i8};
507 static const MVT P64VecVTs[] = {MVT::v2i32, MVT::v4i16, MVT::v8i8};
508 ArrayRef<MVT> VTs;
509 if (Subtarget.is64Bit()) {
510 VTs = P64VecVTs;
511 // There's no instruction for vector shamt in P extension so we unroll to
512 // scalar instructions. Vector VTs that are 32-bit are widened to 64-bit
513 // vector, e.g. v2i16 -> v4i16, before getting unrolled, so we need custom
514 // widen for those operations that will be unrolled.
516 {MVT::v2i16, MVT::v4i8}, Custom);
517 setOperationAction(ISD::INTRINSIC_WO_CHAIN, {MVT::v2i16, MVT::v4i8},
518 Custom);
519 } else {
520 VTs = P32VecVTs;
521 }
522 // By default everything must be expanded.
523 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
525
526 for (MVT VT : VTs) {
528 setTruncStoreAction(VT, OtherVT, Expand);
530 OtherVT, Expand);
531 }
532 }
533
543 VTs, Legal);
547 for (MVT VT : VTs) {
548 if (VT != MVT::v2i32)
550 if (VT.getVectorElementType() != MVT::i8) {
553 }
554 }
562 Custom);
564 Legal);
570 Expand);
572
573 if (!Subtarget.is64Bit())
574 setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v4i8}, Custom);
575 else
576 setOperationAction(ISD::BUILD_VECTOR, {MVT::v4i16, MVT::v8i8}, Custom);
577
578 // P extension vector comparisons produce all 1s for true, all 0s for false
580
581 if (!Subtarget.is64Bit()) {
582 // By default everything must be expanded.
583 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
584 setOperationAction(Op, P64VecVTs, Expand);
585
586 for (MVT VT : P64VecVTs) {
588 setTruncStoreAction(VT, OtherVT, Expand);
590 OtherVT, Expand);
591 }
592 }
593
598 setOperationAction({ISD::AND, ISD::OR, ISD::XOR}, {MVT::v4i16, MVT::v8i8},
599 Custom);
602 Legal);
607 P64VecVTs, Legal);
609 P64VecVTs, Legal);
611 {MVT::v4i16, MVT::v8i8}, Legal);
613 setOperationAction(ISD::SSHLSAT, {MVT::v2i32, MVT::v4i16}, Custom);
614 setOperationAction(ISD::BSWAP, MVT::v4i16, Legal);
621 setOperationAction(ISD::BUILD_VECTOR, {MVT::v4i16, MVT::v8i8}, Custom);
623 P64VecVTs, Custom);
624 setOperationAction(ISD::CONCAT_VECTORS, {MVT::v4i16, MVT::v8i8}, Legal);
625 setOperationAction(ISD::EXTRACT_SUBVECTOR, {MVT::v2i16, MVT::v4i8},
626 Legal);
627 setOperationAction({ISD::SELECT, ISD::VSELECT}, {MVT::v4i16, MVT::v8i8},
628 Custom);
630 {MVT::v4i16, MVT::v8i8}, Custom);
635 {MVT::v4i16, MVT::v2i32}, Legal);
636 setOperationAction(ISD::TRUNCATE, {MVT::v4i8, MVT::v2i16}, Legal);
640 P64VecVTs, Expand);
642 // Operation legalization queries the action using the result type.
643 setOperationAction(ISD::INSERT_SUBVECTOR, {MVT::v4i16, MVT::v8i8},
644 Custom);
645 } else {
646 setOperationAction(ISD::MUL, MVT::v2i32, Legal);
647 setOperationAction(ISD::MUL, {MVT::v4i16, MVT::v8i8}, Custom);
648 setOperationAction({ISD::MULHS, ISD::MULHU}, {MVT::v2i32, MVT::v4i16},
649 Legal);
652 {MVT::v4i16, MVT::v2i32}, Legal);
653 setOperationAction(ISD::ANY_EXTEND_VECTOR_INREG, {MVT::v4i16, MVT::v2i32},
654 Custom);
655 setOperationAction(ISD::TRUNCATE, {MVT::v4i8, MVT::v2i16}, Custom);
656 }
657 // LegalizeVectorOps uses result VT, LegalizeDAG uses ExtVT.
660 {MVT::v2i8, MVT::v4i8, MVT::v2i16, MVT::v4i16, MVT::v2i32}, Legal);
661 }
662
663 if (Subtarget.hasStdExtZfbfmin()) {
670 setOperationAction(ZfhminZfbfminPromoteOps, MVT::bf16, Promote);
677 }
678
679 if (Subtarget.hasStdExtZfhminOrZhinxmin()) {
680 if (Subtarget.hasStdExtZfhmin())
682 if (Subtarget.hasStdExtZfhOrZhinx()) {
683 setOperationAction(FPLegalNodeTypes, MVT::f16, Legal);
684 setOperationAction(FPRndMode, MVT::f16,
685 Subtarget.hasStdExtZfa() ? Legal : Custom);
688 Subtarget.hasStdExtZfa() ? Legal : Custom);
689 if (Subtarget.hasStdExtZfa())
691 } else {
692 setOperationAction(ZfhminZfbfminPromoteOps, MVT::f16, Promote);
697 setOperationAction(Op, MVT::f16, Custom);
703 }
704
705 if (!Subtarget.hasStdExtD()) {
706 // FIXME: handle f16 fma when f64 is not legal. Using an f32 fma
707 // instruction runs into double rounding issues, so this is wrong.
708 // Normally we'd use an f64 fma, but without the D extension the f64 type
709 // is not legal. This should probably be a libcall.
710 AddPromotedToType(ISD::FMA, MVT::f16, MVT::f32);
711 AddPromotedToType(ISD::STRICT_FMA, MVT::f16, MVT::f32);
712 }
713
715
718 setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
722
724 ISD::FNEARBYINT, MVT::f16,
725 Subtarget.hasStdExtZfh() && Subtarget.hasStdExtZfa() ? Legal : Promote);
730 MVT::f16, Promote);
731
732 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
733 // complete support for all operations in LegalizeDAG.
738 MVT::f16, Promote);
739
740 // We need to custom promote this.
741 if (Subtarget.is64Bit())
743 }
744
745 if (Subtarget.hasStdExtFOrZfinx()) {
746 if (Subtarget.hasStdExtF())
748 setOperationAction(FPLegalNodeTypes, MVT::f32, Legal);
749 setOperationAction(FPRndMode, MVT::f32,
750 Subtarget.hasStdExtZfa() ? Legal : Custom);
751 setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
755 setOperationAction(FPOpToExpand, MVT::f32, Expand);
756 setOperationAction(FPOpToLibCall, MVT::f32, LibCall);
757 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
758 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
759 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::bf16, Expand);
760 setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
764 Subtarget.isSoftFPABI() ? LibCall : Custom);
769
770 if (Subtarget.hasStdExtZfa()) {
774 } else {
776 }
777 }
778
779 if (Subtarget.hasStdExtFOrZfinx() && Subtarget.is64Bit())
781
782 if (Subtarget.hasStdExtDOrZdinx()) {
783 if (Subtarget.hasStdExtD())
785 setOperationAction(FPLegalNodeTypes, MVT::f64, Legal);
786
787 if (!Subtarget.is64Bit())
789
790 if (Subtarget.hasStdExtZdinx() && !Subtarget.hasStdExtZilsd() &&
791 !Subtarget.is64Bit()) {
794 }
795
796 if (Subtarget.hasStdExtZfa()) {
798 setOperationAction(FPRndMode, MVT::f64, Legal);
801 } else {
802 if (Subtarget.is64Bit())
803 setOperationAction(FPRndMode, MVT::f64, Custom);
804
806 }
807
810 setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
814 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
815 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
816 setOperationAction(FPOpToExpand, MVT::f64, Expand);
817 setOperationAction(FPOpToLibCall, MVT::f64, LibCall);
818 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
819 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
820 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::bf16, Expand);
821 setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
825 Subtarget.isSoftFPABI() ? LibCall : Custom);
830 }
831
832 if (Subtarget.is64Bit()) {
835 MVT::i32, Custom);
837 } else if (Subtarget.hasStdExtZfhminOrZhinxmin()) {
838 // i64 is not a legal type on RV32, so these are custom expanded in
839 // ReplaceNodeResults: f16 sources are converted to i32 and extended, other
840 // FP sources fall back to the default libcall expansion.
843 MVT::i64, Custom);
844 }
845
846 if (Subtarget.hasStdExtFOrZfinx()) {
848 Custom);
849
850 // f16/bf16 require custom handling.
852 Custom);
854 Custom);
855
864 }
865
868 XLenVT, Custom);
869
871
872 if (Subtarget.is64Bit())
874
875 // TODO: On M-mode only targets, the cycle[h]/time[h] CSR may not be present.
876 // Unfortunately this can't be determined just from the ISA naming string.
878 Subtarget.is64Bit() ? Legal : Custom);
880 Subtarget.is64Bit() ? Legal : Custom);
881
882 if (Subtarget.is64Bit()) {
885 }
886
889 if (Subtarget.is64Bit())
891
892 if (Subtarget.hasVendorXMIPSCBOP())
894 else
896
897 if (Subtarget.hasStdExtZalrsc()) {
898 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
899 if (Subtarget.hasStdExtZabha() && Subtarget.hasStdExtZacas())
901 else
903 } else if (Subtarget.hasForcedAtomics()) {
904 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
905 } else {
907 }
908
910
912
913 if (getTargetMachine().getTargetTriple().isOSLinux()) {
914 // Custom lowering of llvm.clear_cache.
916 }
917
918 if (Subtarget.hasVInstructions()) {
920
922
923 // RVV intrinsics may have illegal operands.
924 // We also need to custom legalize vmv.x.s.
927 {MVT::i8, MVT::i16}, Custom);
928 if (Subtarget.is64Bit())
930 MVT::i32, Custom);
931 else
933 MVT::i64, Custom);
934
936 MVT::Other, Custom);
937
938 static const unsigned IntegerVPOps[] = {
939 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM,
940 ISD::VP_UREM, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
941 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX,
942 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
943 ISD::VP_MERGE,
944 ISD::EXPERIMENTAL_VP_REVERSE, ISD::EXPERIMENTAL_VP_SPLICE,
945 ISD::VP_CTTZ_ELTS, ISD::VP_CTTZ_ELTS_ZERO_POISON};
946
947 static const unsigned FloatingPointVPOps[] = {
948 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
949 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,
950 ISD::VP_REDUCE_FMINIMUM, ISD::VP_REDUCE_FMAXIMUM};
951
952 static const unsigned IntegerVecReduceOps[] = {
956
957 static const unsigned FloatingPointVecReduceOps[] = {
960
961 static const unsigned FloatingPointLibCallOps[] = {
964
965 if (!Subtarget.is64Bit()) {
966 // We must custom-lower certain vXi64 operations on RV32 due to the vector
967 // element type being illegal.
969 MVT::i64, Custom);
970
971 setOperationAction(IntegerVecReduceOps, MVT::i64, Custom);
972
973 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
974 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
975 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
976 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
977 MVT::i64, Custom);
978 }
979
980 for (MVT VT : BoolVecVTs) {
981 if (!isTypeLegal(VT))
982 continue;
983
985
986 // Mask VTs are custom-expanded into a series of standard nodes
990 VT, Custom);
991
993 Custom);
994
997 Expand);
998 setOperationAction(ISD::VP_MERGE, VT, Custom);
999
1001 ISD::VP_CTTZ_ELTS, ISD::VP_CTTZ_ELTS_ZERO_POISON},
1002 VT, Custom);
1003
1006 Custom);
1007
1009 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
1010 Custom);
1011
1012 // RVV has native int->float & float->int conversions where the
1013 // element type sizes are within one power-of-two of each other. Any
1014 // wider distances between type sizes have to be lowered as sequences
1015 // which progressively narrow the gap in stages.
1020 VT, Custom);
1022 Custom);
1023
1024 // Expand all extending loads to types larger than this, and truncating
1025 // stores from types larger than this.
1027 setTruncStoreAction(VT, OtherVT, Expand);
1029 OtherVT, Expand);
1030 }
1031
1034 {2, 3, 4, 5, 6, 7, 8}, VT, Custom);
1035
1037
1038 setOperationAction(ISD::EXPERIMENTAL_VP_SPLICE, VT, Custom);
1039 setOperationAction(ISD::EXPERIMENTAL_VP_REVERSE, VT, Custom);
1040
1043 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount()));
1044
1046 }
1047
1048 for (MVT VT : IntVecVTs) {
1049 if (!isTypeLegal(VT))
1050 continue;
1051
1054
1055 // Vectors implement MULHS/MULHU.
1057
1058 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
1059 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
1061
1063 Legal);
1064
1065 if (Subtarget.hasStdExtZvabd()) {
1068 } else {
1070 }
1071
1072 // Custom-lower extensions and truncations from/to mask types.
1074 VT, Custom);
1075
1076 // RVV has native int->float & float->int conversions where the
1077 // element type sizes are within one power-of-two of each other. Any
1078 // wider distances between type sizes have to be lowered as sequences
1079 // which progressively narrow the gap in stages.
1084 VT, Custom);
1086 Custom);
1087 if (!Subtarget.avoidVXRM())
1090 Legal);
1093
1094 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
1095 // nodes which truncate by one power of two at a time.
1098 Custom);
1099
1100 // Custom-lower insert/extract operations to simplify patterns.
1102 Custom);
1103
1104 // Custom-lower reduction operations to set up the corresponding custom
1105 // nodes' operands.
1106 setOperationAction(IntegerVecReduceOps, VT, Custom);
1107
1108 setOperationAction(IntegerVPOps, VT, Custom);
1109
1111
1113 VT, Custom);
1114
1116 {ISD::VP_LOAD, ISD::VP_STORE, ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
1117 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER, ISD::VP_SCATTER},
1118 VT, Custom);
1119 setOperationAction(ISD::VP_LOAD_FF, VT, Custom);
1120
1123 VT, Custom);
1124
1127
1129
1131 setTruncStoreAction(VT, OtherVT, Expand);
1133 OtherVT, Expand);
1134 }
1135
1138 {2, 3, 4, 5, 6, 7, 8}, VT, Custom);
1139
1141 VT, Custom);
1142
1143 if (Subtarget.hasStdExtZvkb()) {
1145 } else {
1148 }
1149
1150 if (Subtarget.hasStdExtZvbb()) {
1152 } else {
1155
1156 // Lower CTLZ_ZERO_POISON and CTTZ_ZERO_POISON if element of VT in the
1157 // range of f32.
1158 EVT FloatVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1159 if (isTypeLegal(FloatVT)) {
1162 Custom);
1163 }
1164 }
1165
1166 if (VT.getVectorElementType() == MVT::i64) {
1167 if (Subtarget.hasStdExtZvbc())
1169 } else {
1170 if (Subtarget.hasStdExtZvbc32e()) {
1172 } else if (Subtarget.hasStdExtZvbc()) {
1173 // Promote to i64 if the lmul is small enough.
1174 // FIXME: Split if necessary to widen.
1175 // FIXME: Promote clmulh directly without legalizing to clmul first.
1176 MVT I64VecVT = MVT::getVectorVT(MVT::i64, VT.getVectorElementCount());
1177 if (isTypeLegal(I64VecVT))
1179 }
1180 }
1181
1185 VT, Legal);
1186 }
1187
1188 for (MVT VT : VecTupleVTs) {
1189 if (!isTypeLegal(VT))
1190 continue;
1191
1193 }
1194
1195 // Expand various CCs to best match the RVV ISA, which natively supports UNE
1196 // but no other unordered comparisons, and supports all ordered comparisons
1197 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
1198 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
1199 // and we pattern-match those back to the "original", swapping operands once
1200 // more. This way we catch both operations and both "vf" and "fv" forms with
1201 // fewer patterns.
1202 static const ISD::CondCode VFPCCToExpand[] = {
1206 };
1207
1208 // TODO: support more ops.
1209 static const unsigned ZvfhminZvfbfminPromoteOps[] = {
1214 ISD::FADD,
1215 ISD::FSUB,
1216 ISD::FMUL,
1217 ISD::FMA,
1218 ISD::FDIV,
1219 ISD::FSQRT,
1220 ISD::FCEIL,
1225 ISD::FRINT,
1228 ISD::SETCC,
1243
1244 // TODO: Make more of these ops legal.
1245 static const unsigned ZvfbfaPromoteOps[] = {ISD::FDIV,
1246 ISD::FSQRT,
1247 ISD::FCEIL,
1252 ISD::FRINT,
1261
1262 // TODO: support more vp ops.
1263 static const unsigned ZvfhminZvfbfminPromoteVPOps[] = {
1264 ISD::VP_REDUCE_FMIN,
1265 ISD::VP_REDUCE_FMAX,
1266 ISD::VP_REDUCE_FMINIMUM,
1267 ISD::VP_REDUCE_FMAXIMUM};
1268
1269 // Sets common operation actions on RVV floating-point vector types.
1270 const auto SetCommonVFPActions = [&](MVT VT) {
1272 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
1273 // sizes are within one power-of-two of each other. Therefore conversions
1274 // between vXf16 and vXf64 must be lowered as sequences which convert via
1275 // vXf32.
1279 // Custom-lower insert/extract operations to simplify patterns.
1281 Custom);
1282 // Expand various condition codes (explained above).
1283 setCondCodeAction(VFPCCToExpand, VT, Expand);
1284
1287 Legal);
1289
1293 VT, Custom);
1294
1295 setOperationAction(FloatingPointVecReduceOps, VT, Custom);
1296
1297 // Expand FP operations that need libcalls.
1298 setOperationAction(FloatingPointLibCallOps, VT, Expand);
1299
1301
1303
1305
1307 VT, Custom);
1308
1310 {ISD::VP_LOAD, ISD::VP_STORE, ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
1311 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER, ISD::VP_SCATTER},
1312 VT, Custom);
1313 setOperationAction(ISD::VP_LOAD_FF, VT, Custom);
1314
1317
1320 VT, Custom);
1321
1324 {2, 3, 4, 5, 6, 7, 8}, VT, Custom);
1325
1328 VT, Custom);
1329 setOperationAction(ISD::EXPERIMENTAL_VP_SPLICE, VT, Custom);
1330 setOperationAction(ISD::EXPERIMENTAL_VP_REVERSE, VT, Custom);
1331
1332 setOperationAction(FloatingPointVPOps, VT, Custom);
1333
1335 Custom);
1338 VT, Legal);
1343 VT, Custom);
1344
1346 };
1347
1348 // Sets common extload/truncstore actions on RVV floating-point vector
1349 // types.
1350 const auto SetCommonVFPExtLoadTruncStoreActions =
1351 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
1352 for (auto SmallVT : SmallerVTs) {
1353 setTruncStoreAction(VT, SmallVT, Expand);
1354 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
1355 }
1356 };
1357
1358 // Sets common actions for f16 and bf16 for when there's only
1359 // zvfhmin/zvfbfmin and we need to promote to f32 for most operations.
1360 const auto SetCommonPromoteToF32Actions = [&](MVT VT) {
1363 Custom);
1366 setOperationAction({ISD::VP_MERGE, ISD::SELECT}, VT,
1367 Custom);
1373 VT, Custom);
1376 {2, 3, 4, 5, 6, 7, 8}, VT, Custom);
1377 setOperationAction(ISD::EXPERIMENTAL_VP_SPLICE, VT, Custom);
1378 setOperationAction(ISD::EXPERIMENTAL_VP_REVERSE, VT, Custom);
1379 MVT EltVT = VT.getVectorElementType();
1380 if (isTypeLegal(EltVT))
1382 VT, Custom);
1383 else
1386 ISD::MGATHER, ISD::MSCATTER, ISD::VP_LOAD,
1387 ISD::VP_STORE, ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
1388 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER,
1389 ISD::VP_SCATTER},
1390 VT, Custom);
1391 setOperationAction(ISD::VP_LOAD_FF, VT, Custom);
1392
1396
1397 // Expand FP operations that need libcalls.
1398 setOperationAction(FloatingPointLibCallOps, VT, Expand);
1399
1401
1402 // Custom split nxv32[b]f16 since nxv32[b]f32 is not legal.
1403 if (getLMUL(VT) == RISCVVType::LMUL_8) {
1404 setOperationAction(ZvfhminZvfbfminPromoteOps, VT, Custom);
1405 setOperationAction(ZvfhminZvfbfminPromoteVPOps, VT, Custom);
1406 } else {
1407 MVT F32VecVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1408 setOperationPromotedToType(ZvfhminZvfbfminPromoteOps, VT, F32VecVT);
1409 setOperationPromotedToType(ZvfhminZvfbfminPromoteVPOps, VT, F32VecVT);
1410 }
1411 };
1412
1413 // Sets common actions for zvfbfa, some of instructions are supported
1414 // natively so that we don't need to promote them.
1415 const auto SetZvfbfaActions = [&](MVT VT) {
1418 Custom);
1421 setOperationAction({ISD::VP_MERGE, ISD::SELECT}, VT,
1422 Custom);
1429 VT, Custom);
1432 {2, 3, 4, 5, 6, 7, 8}, VT, Custom);
1435 Legal);
1438 setOperationAction(ISD::EXPERIMENTAL_VP_SPLICE, VT, Custom);
1439 setOperationAction(ISD::EXPERIMENTAL_VP_REVERSE, VT, Custom);
1440
1445 VT, Legal);
1446 setCondCodeAction(VFPCCToExpand, VT, Expand);
1447
1449 ISD::MGATHER, ISD::MSCATTER, ISD::VP_LOAD,
1450 ISD::VP_STORE, ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
1451 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER,
1452 ISD::VP_SCATTER},
1453 VT, Custom);
1454 setOperationAction(ISD::VP_LOAD_FF, VT, Custom);
1455
1456 // Expand FP operations that need libcalls.
1457 setOperationAction(FloatingPointLibCallOps, VT, Expand);
1458
1460
1461 // Custom split nxv32[b]f16 since nxv32[b]f32 is not legal.
1462 if (getLMUL(VT) == RISCVVType::LMUL_8) {
1463 setOperationAction(ZvfbfaPromoteOps, VT, Custom);
1464 setOperationAction(ZvfhminZvfbfminPromoteVPOps, VT, Custom);
1465 } else {
1466 MVT F32VecVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1467 setOperationPromotedToType(ZvfbfaPromoteOps, VT, F32VecVT);
1468 setOperationPromotedToType(ZvfhminZvfbfminPromoteVPOps, VT, F32VecVT);
1469 }
1470 };
1471
1472 if (Subtarget.hasVInstructionsF16()) {
1473 for (MVT VT : F16VecVTs) {
1474 if (!isTypeLegal(VT))
1475 continue;
1476 SetCommonVFPActions(VT);
1477 }
1478 } else if (Subtarget.hasVInstructionsF16Minimal()) {
1479 for (MVT VT : F16VecVTs) {
1480 if (!isTypeLegal(VT))
1481 continue;
1482 SetCommonPromoteToF32Actions(VT);
1483 }
1484 }
1485
1486 if (Subtarget.hasVInstructionsBF16()) {
1487 for (MVT VT : BF16VecVTs) {
1488 if (!isTypeLegal(VT))
1489 continue;
1490 SetZvfbfaActions(VT);
1491 }
1492 } else if (Subtarget.hasVInstructionsBF16Minimal()) {
1493 for (MVT VT : BF16VecVTs) {
1494 if (!isTypeLegal(VT))
1495 continue;
1496 SetCommonPromoteToF32Actions(VT);
1497 }
1498 }
1499
1500 if (Subtarget.hasStdExtZvfofp8min()) {
1501 for (MVT VT : BF16VecVTs) {
1502 if (!isTypeLegal(VT))
1503 continue;
1505 }
1506 }
1507
1508 if (Subtarget.hasVInstructionsF32()) {
1509 for (MVT VT : F32VecVTs) {
1510 if (!isTypeLegal(VT))
1511 continue;
1512 SetCommonVFPActions(VT);
1513 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
1514 SetCommonVFPExtLoadTruncStoreActions(VT, BF16VecVTs);
1515 }
1516 }
1517
1518 if (Subtarget.hasVInstructionsF64()) {
1519 for (MVT VT : F64VecVTs) {
1520 if (!isTypeLegal(VT))
1521 continue;
1522 SetCommonVFPActions(VT);
1523 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
1524 SetCommonVFPExtLoadTruncStoreActions(VT, BF16VecVTs);
1525 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
1526 }
1527 }
1528
1529 if (Subtarget.useRVVForFixedLengthVectors()) {
1531 if (!useRVVForFixedLengthVectorVT(VT))
1532 continue;
1533
1534 // By default everything must be expanded.
1535 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1538 setTruncStoreAction(VT, OtherVT, Expand);
1540 OtherVT, Expand);
1541 }
1542
1543 // Custom lower fixed vector undefs to scalable vector undefs to avoid
1544 // expansion to a build_vector of 0s.
1546
1547 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
1549 Custom);
1550
1553 Custom);
1554
1557 {2, 3, 4, 5, 6, 7, 8}, VT, Custom);
1558
1560 VT, Custom);
1561
1563
1565
1567
1569
1572 Custom);
1573
1575
1578 Custom);
1579
1581 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
1582 Custom);
1583
1585 {
1594 },
1595 VT, Custom);
1597 Custom);
1598
1600
1601 // Operations below are different for between masks and other vectors.
1602 if (VT.getVectorElementType() == MVT::i1) {
1604
1605 setOperationAction(ISD::VP_MERGE, VT, Custom);
1606
1607 setOperationAction(ISD::EXPERIMENTAL_VP_SPLICE, VT, Custom);
1608 setOperationAction(ISD::EXPERIMENTAL_VP_REVERSE, VT, Custom);
1609
1611 Custom);
1612
1614 continue;
1615 }
1616
1617 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
1618 // it before type legalization for i64 vectors on RV32. It will then be
1619 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
1620 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
1621 // improvements first.
1622 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
1625
1626 // Lower BUILD_VECTOR with i64 type to VID on RV32 if possible.
1628 }
1629
1632
1633 setOperationAction({ISD::VP_LOAD, ISD::VP_STORE,
1634 ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
1635 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER,
1636 ISD::VP_SCATTER},
1637 VT, Custom);
1638 setOperationAction(ISD::VP_LOAD_FF, VT, Custom);
1639
1643 VT, Custom);
1644
1647
1649
1650 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
1651 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
1653
1654 if (!Subtarget.avoidVXRM())
1657 VT, Custom);
1660 Custom);
1661
1663
1666
1667 // Custom-lower reduction operations to set up the corresponding custom
1668 // nodes' operands.
1672 VT, Custom);
1673
1674 setOperationAction(IntegerVPOps, VT, Custom);
1675
1676 if (Subtarget.hasStdExtZvkb())
1678
1679 if (Subtarget.hasStdExtZvbb()) {
1682 VT, Custom);
1683 } else {
1684 // Lower CTLZ_ZERO_POISON and CTTZ_ZERO_POISON if element of VT in the
1685 // range of f32.
1686 EVT FloatVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1687 if (isTypeLegal(FloatVT))
1690 Custom);
1691 }
1692
1693 if (VT.getVectorElementType() == MVT::i64) {
1694 if (Subtarget.hasStdExtZvbc())
1696 } else {
1697 if (Subtarget.hasStdExtZvbc32e()) {
1699 } else if (Subtarget.hasStdExtZvbc()) {
1700 // Promote to i64 as is done for scalable vectors.
1701 MVT I64VecVT =
1703 if (I64VecVT.isValid() && useRVVForFixedLengthVectorVT(I64VecVT))
1705 }
1706 }
1707
1711 VT, Custom);
1712 }
1713
1715 // There are no extending loads or truncating stores.
1716 for (MVT InnerVT : MVT::fp_fixedlen_vector_valuetypes()) {
1717 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1718 setTruncStoreAction(VT, InnerVT, Expand);
1719 }
1720
1721 if (!useRVVForFixedLengthVectorVT(VT))
1722 continue;
1723
1724 // By default everything must be expanded.
1725 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1727
1728 // Custom lower fixed vector undefs to scalable vector undefs to avoid
1729 // expansion to a build_vector of 0s.
1731
1736 VT, Custom);
1737 setOperationAction(ISD::EXPERIMENTAL_VP_SPLICE, VT, Custom);
1738 setOperationAction(ISD::EXPERIMENTAL_VP_REVERSE, VT, Custom);
1739
1742 {2, 3, 4, 5, 6, 7, 8}, VT, Custom);
1743
1746 VT, Custom);
1747 setOperationAction({ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER,
1748 ISD::VP_SCATTER, ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
1749 ISD::EXPERIMENTAL_VP_STRIDED_STORE},
1750 VT, Custom);
1751 setOperationAction(ISD::VP_LOAD_FF, VT, Custom);
1752
1755 Custom);
1756
1758
1759 if (VT.getVectorElementType() == MVT::f16 &&
1760 !Subtarget.hasVInstructionsF16()) {
1762 {ISD::VP_MERGE, ISD::VSELECT, ISD::SELECT}, VT,
1763 Custom);
1766 if (Subtarget.hasStdExtZfhmin()) {
1768 } else {
1769 // We need to custom legalize f16 build vectors if Zfhmin isn't
1770 // available.
1772 }
1776 MVT F32VecVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1777 // Don't promote f16 vector operations to f32 if f32 vector type is
1778 // not legal.
1779 // Custom lower maximum LMUL case to split to 2 half LMUL operations.
1780 // TODO: Support more operations.
1781 if (!isTypeLegal(F32VecVT)) {
1785 VT, Custom);
1787 continue;
1788 }
1789 setOperationPromotedToType(ZvfhminZvfbfminPromoteOps, VT, F32VecVT);
1790 setOperationPromotedToType(ZvfhminZvfbfminPromoteVPOps, VT, F32VecVT);
1791 continue;
1792 }
1793
1794 if (VT.getVectorElementType() == MVT::bf16) {
1797 if (Subtarget.hasStdExtZvfofp8min())
1799 if (Subtarget.hasStdExtZfbfmin()) {
1801 } else {
1802 // We need to custom legalize bf16 build vectors if Zfbfmin isn't
1803 // available.
1805 }
1806 if (Subtarget.hasVInstructionsBF16()) {
1808 setCondCodeAction(VFPCCToExpand, VT, Expand);
1809 }
1811 {ISD::VP_MERGE, ISD::VSELECT, ISD::SELECT}, VT,
1812 Custom);
1813 MVT F32VecVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1814 // Don't promote bf16 vector operations to f32 if f32 vector type is
1815 // not legal.
1816 // Custom lower maximum LMUL case to split to 2 half LMUL operations.
1817 // TODO: Support more operations.
1818 if (!isTypeLegal(F32VecVT)) {
1822 VT, Custom);
1824 continue;
1825 }
1826
1827 if (Subtarget.hasVInstructionsBF16())
1828 setOperationPromotedToType(ZvfbfaPromoteOps, VT, F32VecVT);
1829 else
1830 setOperationPromotedToType(ZvfhminZvfbfminPromoteOps, VT, F32VecVT);
1831 setOperationPromotedToType(ZvfhminZvfbfminPromoteVPOps, VT, F32VecVT);
1832 continue;
1833 }
1834
1836 Custom);
1837
1843 VT, Custom);
1844
1849 VT, Custom);
1850
1851 setCondCodeAction(VFPCCToExpand, VT, Expand);
1852
1855
1856 setOperationAction(FloatingPointVecReduceOps, VT, Custom);
1857
1858 setOperationAction(FloatingPointVPOps, VT, Custom);
1859
1866 VT, Custom);
1867 }
1868
1869 // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1870 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32}, Custom);
1871 if (Subtarget.is64Bit())
1873 if (Subtarget.hasStdExtZfhminOrZhinxmin())
1875 if (Subtarget.hasStdExtZfbfmin())
1877 if (Subtarget.hasStdExtFOrZfinx())
1879 if (Subtarget.hasStdExtDOrZdinx())
1881 }
1882 }
1883
1884 if (Subtarget.hasStdExtZaamo())
1886 {MVT::i8, MVT::i16, MVT::i32, XLenVT}, Expand);
1887
1888 if (Subtarget.hasForcedAtomics()) {
1889 // Force __sync libcalls to be emitted for atomic rmw/cas operations.
1895 {MVT::i8, MVT::i16, MVT::i32, XLenVT}, LibCall);
1896 }
1897
1898 if (Subtarget.hasVendorXTHeadMemIdx()) {
1899 for (unsigned im : {ISD::PRE_INC, ISD::POST_INC}) {
1900 setIndexedLoadAction(im, MVT::i8, Legal);
1901 setIndexedStoreAction(im, MVT::i8, Legal);
1902 setIndexedLoadAction(im, MVT::i16, Legal);
1903 setIndexedStoreAction(im, MVT::i16, Legal);
1904 setIndexedLoadAction(im, MVT::i32, Legal);
1905 setIndexedStoreAction(im, MVT::i32, Legal);
1906
1907 if (Subtarget.is64Bit()) {
1908 setIndexedLoadAction(im, MVT::i64, Legal);
1909 setIndexedStoreAction(im, MVT::i64, Legal);
1910 }
1911 }
1912 }
1913
1914 if (Subtarget.hasVendorXCVmem() && !Subtarget.is64Bit()) {
1918
1922 }
1923
1924 // zve32x is broken for partial_reduce_umla, but let's not make it worse.
1925 if (Subtarget.hasStdExtZvdot4a8i() && Subtarget.getELen() >= 64) {
1926 static const unsigned MLAOps[] = {ISD::PARTIAL_REDUCE_SMLA,
1929 setPartialReduceMLAAction(MLAOps, MVT::nxv1i32, MVT::nxv4i8, Custom);
1930 setPartialReduceMLAAction(MLAOps, MVT::nxv2i32, MVT::nxv8i8, Custom);
1931 setPartialReduceMLAAction(MLAOps, MVT::nxv4i32, MVT::nxv16i8, Custom);
1932 setPartialReduceMLAAction(MLAOps, MVT::nxv8i32, MVT::nxv32i8, Custom);
1933 setPartialReduceMLAAction(MLAOps, MVT::nxv16i32, MVT::nxv64i8, Custom);
1934
1935 // An i64 accumulator is handled by performing an i32 vdot4a* and widening
1936 // the result to i64 (see lowerPARTIAL_REDUCE_MLA).
1937 setPartialReduceMLAAction(MLAOps, MVT::nxv1i64, MVT::nxv8i8, Custom);
1938 setPartialReduceMLAAction(MLAOps, MVT::nxv2i64, MVT::nxv16i8, Custom);
1939 setPartialReduceMLAAction(MLAOps, MVT::nxv4i64, MVT::nxv32i8, Custom);
1940 setPartialReduceMLAAction(MLAOps, MVT::nxv8i64, MVT::nxv64i8, Custom);
1941
1942 if (Subtarget.useRVVForFixedLengthVectors()) {
1944 if ((VT.getVectorElementType() != MVT::i32 &&
1945 VT.getVectorElementType() != MVT::i64) ||
1946 !useRVVForFixedLengthVectorVT(VT))
1947 continue;
1948 ElementCount EC = VT.getVectorElementCount();
1949 unsigned Scale = VT.getVectorElementType() == MVT::i64 ? 8 : 4;
1950 MVT ArgVT = MVT::getVectorVT(MVT::i8, EC * Scale);
1951 setPartialReduceMLAAction(MLAOps, VT, ArgVT, Custom);
1952 }
1953 }
1954 }
1955
1956 // Customize load and store operation for bf16 if zfh isn't enabled.
1957 if (Subtarget.hasVendorXAndesBFHCvt() && !Subtarget.hasStdExtZfh()) {
1958 setOperationAction(ISD::LOAD, MVT::bf16, Custom);
1960 }
1961
1962 // Function alignments.
1963 const Align FunctionAlignment(Subtarget.hasStdExtZca() ? 2 : 4);
1964 setMinFunctionAlignment(FunctionAlignment);
1965 // Set preferred alignments.
1966 setPrefFunctionAlignment(Subtarget.getPrefFunctionAlignment());
1967 setPrefLoopAlignment(Subtarget.getPrefLoopAlignment());
1968
1972 ISD::SRA});
1974
1975 if (Subtarget.hasStdExtFOrZfinx())
1977
1978 // Allow scalar min/max to be combined with vector reductions.
1979 if (Subtarget.hasVInstructions())
1981 if (Subtarget.hasVInstructions() || Subtarget.hasStdExtP())
1983
1984 if ((Subtarget.hasStdExtZbs() && Subtarget.is64Bit()) ||
1985 Subtarget.hasVInstructions() || Subtarget.hasStdExtP())
1987
1988 if (Subtarget.hasStdExtZbkb())
1990
1991 if (Subtarget.hasStdExtZbc() && Subtarget.is64Bit())
1993
1994 if (Subtarget.hasStdExtFOrZfinx())
1997 if (Subtarget.hasVInstructions())
2002 ISD::MLOAD,
2003 ISD::VP_GATHER,
2004 ISD::VP_SCATTER,
2005 ISD::SRL,
2006 ISD::SHL,
2007 ISD::STORE,
2011 ISD::VP_STORE,
2012 ISD::EXPERIMENTAL_VP_REVERSE,
2013 ISD::SDIV,
2014 ISD::UDIV,
2015 ISD::SREM,
2016 ISD::UREM,
2018 ISD::ABS,
2020 ISD::CTPOP,
2022 ISD::FMA,
2026
2027 if (Subtarget.hasStdExtZvzip())
2029
2030 if (Subtarget.hasVendorXTHeadMemPair())
2032 if (Subtarget.useRVVForFixedLengthVectors() || Subtarget.hasStdExtP())
2034 if (Subtarget.hasStdExtP() && Subtarget.is64Bit())
2036
2037 setMaxDivRemBitWidthSupported(Subtarget.is64Bit() ? 128 : 64);
2038
2039 setMaxLargeFPConvertBitWidthSupported(Subtarget.is64Bit() ? 128 : 64);
2040
2041 setJumpIsExpensive(Subtarget.isJumpExpensive());
2042
2043 // Disable strict node mutation.
2044 IsStrictFPEnabled = true;
2045 EnableExtLdPromotion = true;
2046
2047 // Let the subtarget decide if a predictable select is more expensive than the
2048 // corresponding branch. This information is used in CGP/SelectOpt to decide
2049 // when to convert selects into branches.
2050 PredictableSelectIsExpensive = Subtarget.predictableSelectIsExpensive();
2051
2052 MaxStoresPerMemsetOptSize = Subtarget.getMaxStoresPerMemset(/*OptSize=*/true);
2053 MaxStoresPerMemset = Subtarget.getMaxStoresPerMemset(/*OptSize=*/false);
2054
2055 MaxGluedStoresPerMemcpy = Subtarget.getMaxGluedStoresPerMemcpy();
2056 MaxStoresPerMemcpyOptSize = Subtarget.getMaxStoresPerMemcpy(/*OptSize=*/true);
2057 MaxStoresPerMemcpy = Subtarget.getMaxStoresPerMemcpy(/*OptSize=*/false);
2058
2060 Subtarget.getMaxStoresPerMemmove(/*OptSize=*/true);
2061 MaxStoresPerMemmove = Subtarget.getMaxStoresPerMemmove(/*OptSize=*/false);
2062
2063 MaxLoadsPerMemcmpOptSize = Subtarget.getMaxLoadsPerMemcmp(/*OptSize=*/true);
2064 MaxLoadsPerMemcmp = Subtarget.getMaxLoadsPerMemcmp(/*OptSize=*/false);
2065}
2066
2069 if (Subtarget.is64Bit() && Subtarget.hasStdExtP())
2070 if (VT == MVT::v2i16 || VT == MVT::v4i8)
2071 return TypeWidenVector;
2072
2074}
2075
2077 LLVMContext &Context,
2078 EVT VT) const {
2079 if (!VT.isVector())
2080 return getPointerTy(DL);
2081 if (Subtarget.hasVInstructions() &&
2082 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
2083 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
2085}
2086
2089 const Value *LHS,
2090 const Value *RHS,
2091 const Function *F) const {
2092 if (F->hasOptSize())
2094
2095 // Merging conditions eliminates a branch, so the budget we are willing to
2096 // spend eagerly computing the RHS condition should scale with how expensive a
2097 // mispredicted branch is. A branch only costs the full penalty when actually
2098 // mispredicted, so scale it down by an assumed misprediction rate (~25%).
2099 const RISCVOptions &CLOpts = Subtarget.getCLOpts();
2100 int BaseCost = CLOpts.br_merging_base_cost.value_or(
2101 Subtarget.getMispredictionPenalty() / 4);
2102 return {BaseCost, CLOpts.br_merging_likely_bias,
2103 CLOpts.br_merging_unlikely_bias};
2104}
2105
2107 return Subtarget.getXLenVT();
2108}
2109
2110bool RISCVTargetLowering::isProfitableToFoldVScaleAdd(SDValue N) const {
2111 return N.hasOneUse();
2112}
2113
2114// Return false if we can lower get_vector_length to a vsetvli intrinsic.
2115bool RISCVTargetLowering::shouldExpandGetVectorLength(EVT TripCountVT,
2116 unsigned VF,
2117 bool IsScalable) const {
2118 if (!Subtarget.hasVInstructions())
2119 return true;
2120
2121 if (!IsScalable)
2122 return true;
2123
2124 if (TripCountVT != MVT::i32 && TripCountVT != Subtarget.getXLenVT())
2125 return true;
2126
2127 // Don't allow VF=1 if those types are't legal.
2128 if (VF < RISCV::RVVBitsPerBlock / Subtarget.getELen())
2129 return true;
2130
2131 // VLEN=32 support is incomplete.
2132 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock)
2133 return true;
2134
2135 // The maximum VF is for the smallest element width with LMUL=8.
2136 // VF must be a power of 2.
2137 unsigned MaxVF = RISCV::RVVBytesPerBlock * 8;
2138 return VF > MaxVF || !isPowerOf2_32(VF);
2139}
2140
2143 MachineFunction &MF, unsigned Intrinsic) const {
2144 IntrinsicInfo Info;
2145 auto &DL = I.getDataLayout();
2146
2147 auto SetRVVLoadStoreInfo = [&](unsigned PtrOp, bool IsStore,
2148 bool IsUnitStrided, bool UsePtrVal = false) {
2149 Info.opc = IsStore ? ISD::INTRINSIC_VOID : ISD::INTRINSIC_W_CHAIN;
2150 // We can't use ptrVal if the intrinsic can access memory before the
2151 // pointer. This means we can't use it for strided or indexed intrinsics.
2152 if (UsePtrVal)
2153 Info.ptrVal = I.getArgOperand(PtrOp);
2154 else
2155 Info.fallbackAddressSpace =
2156 I.getArgOperand(PtrOp)->getType()->getPointerAddressSpace();
2157 Type *MemTy;
2158 if (IsStore) {
2159 // Store value is the first operand.
2160 MemTy = I.getArgOperand(0)->getType();
2161 } else {
2162 // Use return type. If it's segment load, return type is a struct.
2163 MemTy = I.getType();
2164 if (MemTy->isStructTy())
2165 MemTy = MemTy->getStructElementType(0);
2166 }
2167 if (!IsUnitStrided)
2168 MemTy = MemTy->getScalarType();
2169
2170 Info.memVT = getValueType(DL, MemTy);
2171 if (MemTy->isTargetExtTy()) {
2172 // RISC-V vector tuple type's alignment type should be its element type.
2173 if (cast<TargetExtType>(MemTy)->getName() == "riscv.vector.tuple")
2174 MemTy = Type::getIntNTy(
2175 MemTy->getContext(),
2176 1 << cast<ConstantInt>(I.getArgOperand(I.arg_size() - 1))
2177 ->getZExtValue());
2178 Info.align = DL.getABITypeAlign(MemTy);
2179 } else {
2180 Info.align = Align(DL.getTypeStoreSize(MemTy->getScalarType()));
2181 }
2182 Info.size = MemoryLocation::UnknownSize;
2183 Info.flags |=
2185 Infos.push_back(Info);
2186 };
2187
2188 if (I.hasMetadata(LLVMContext::MD_nontemporal))
2190
2192 switch (Intrinsic) {
2193 default:
2194 return;
2195 case Intrinsic::riscv_masked_atomicrmw_xchg:
2196 case Intrinsic::riscv_masked_atomicrmw_add:
2197 case Intrinsic::riscv_masked_atomicrmw_sub:
2198 case Intrinsic::riscv_masked_atomicrmw_nand:
2199 case Intrinsic::riscv_masked_atomicrmw_max:
2200 case Intrinsic::riscv_masked_atomicrmw_min:
2201 case Intrinsic::riscv_masked_atomicrmw_umax:
2202 case Intrinsic::riscv_masked_atomicrmw_umin:
2203 case Intrinsic::riscv_masked_cmpxchg:
2204 // riscv_masked_{atomicrmw_*,cmpxchg} intrinsics represent an emulated
2205 // narrow atomic operation. These will be expanded to an LR/SC loop that
2206 // reads/writes to/from an aligned 4 byte location. And, or, shift, etc.
2207 // will be used to modify the appropriate part of the 4 byte data and
2208 // preserve the rest.
2209 Info.opc = ISD::INTRINSIC_W_CHAIN;
2210 Info.memVT = MVT::i32;
2211 Info.ptrVal = I.getArgOperand(0);
2212 Info.offset = 0;
2213 Info.align = Align(4);
2216 Infos.push_back(Info);
2217 return;
2218 case Intrinsic::riscv_seg2_load_mask:
2219 case Intrinsic::riscv_seg3_load_mask:
2220 case Intrinsic::riscv_seg4_load_mask:
2221 case Intrinsic::riscv_seg5_load_mask:
2222 case Intrinsic::riscv_seg6_load_mask:
2223 case Intrinsic::riscv_seg7_load_mask:
2224 case Intrinsic::riscv_seg8_load_mask:
2225 case Intrinsic::riscv_sseg2_load_mask:
2226 case Intrinsic::riscv_sseg3_load_mask:
2227 case Intrinsic::riscv_sseg4_load_mask:
2228 case Intrinsic::riscv_sseg5_load_mask:
2229 case Intrinsic::riscv_sseg6_load_mask:
2230 case Intrinsic::riscv_sseg7_load_mask:
2231 case Intrinsic::riscv_sseg8_load_mask:
2232 SetRVVLoadStoreInfo(/*PtrOp*/ 0, /*IsStore*/ false,
2233 /*IsUnitStrided*/ false, /*UsePtrVal*/ true);
2234 return;
2235 case Intrinsic::riscv_seg2_store_mask:
2236 case Intrinsic::riscv_seg3_store_mask:
2237 case Intrinsic::riscv_seg4_store_mask:
2238 case Intrinsic::riscv_seg5_store_mask:
2239 case Intrinsic::riscv_seg6_store_mask:
2240 case Intrinsic::riscv_seg7_store_mask:
2241 case Intrinsic::riscv_seg8_store_mask:
2242 // Operands are (vec, ..., vec, ptr, mask, vl)
2243 SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 3,
2244 /*IsStore*/ true,
2245 /*IsUnitStrided*/ false, /*UsePtrVal*/ true);
2246 return;
2247 case Intrinsic::riscv_sseg2_store_mask:
2248 case Intrinsic::riscv_sseg3_store_mask:
2249 case Intrinsic::riscv_sseg4_store_mask:
2250 case Intrinsic::riscv_sseg5_store_mask:
2251 case Intrinsic::riscv_sseg6_store_mask:
2252 case Intrinsic::riscv_sseg7_store_mask:
2253 case Intrinsic::riscv_sseg8_store_mask:
2254 // Operands are (vec, ..., vec, ptr, offset, mask, vl)
2255 SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 4,
2256 /*IsStore*/ true,
2257 /*IsUnitStrided*/ false, /*UsePtrVal*/ true);
2258 return;
2259 case Intrinsic::riscv_vlm:
2260 SetRVVLoadStoreInfo(/*PtrOp*/ 0,
2261 /*IsStore*/ false,
2262 /*IsUnitStrided*/ true,
2263 /*UsePtrVal*/ true);
2264 return;
2265 case Intrinsic::riscv_vle:
2266 case Intrinsic::riscv_vle_mask:
2267 case Intrinsic::riscv_vleff:
2268 case Intrinsic::riscv_vleff_mask:
2269 SetRVVLoadStoreInfo(/*PtrOp*/ 1,
2270 /*IsStore*/ false,
2271 /*IsUnitStrided*/ true,
2272 /*UsePtrVal*/ true);
2273 return;
2274 case Intrinsic::riscv_vsm:
2275 case Intrinsic::riscv_vse:
2276 case Intrinsic::riscv_vse_mask:
2277 SetRVVLoadStoreInfo(/*PtrOp*/ 1,
2278 /*IsStore*/ true,
2279 /*IsUnitStrided*/ true,
2280 /*UsePtrVal*/ true);
2281 return;
2282 case Intrinsic::riscv_vlse:
2283 case Intrinsic::riscv_vlse_mask:
2284 case Intrinsic::riscv_vloxei:
2285 case Intrinsic::riscv_vloxei_mask:
2286 case Intrinsic::riscv_vluxei:
2287 case Intrinsic::riscv_vluxei_mask:
2288 SetRVVLoadStoreInfo(/*PtrOp*/ 1,
2289 /*IsStore*/ false,
2290 /*IsUnitStrided*/ false);
2291 return;
2292 case Intrinsic::riscv_vsse:
2293 case Intrinsic::riscv_vsse_mask:
2294 case Intrinsic::riscv_vsoxei:
2295 case Intrinsic::riscv_vsoxei_mask:
2296 case Intrinsic::riscv_vsuxei:
2297 case Intrinsic::riscv_vsuxei_mask:
2298 SetRVVLoadStoreInfo(/*PtrOp*/ 1,
2299 /*IsStore*/ true,
2300 /*IsUnitStrided*/ false);
2301 return;
2302 case Intrinsic::riscv_vlseg2:
2303 case Intrinsic::riscv_vlseg3:
2304 case Intrinsic::riscv_vlseg4:
2305 case Intrinsic::riscv_vlseg5:
2306 case Intrinsic::riscv_vlseg6:
2307 case Intrinsic::riscv_vlseg7:
2308 case Intrinsic::riscv_vlseg8:
2309 case Intrinsic::riscv_vlseg2ff:
2310 case Intrinsic::riscv_vlseg3ff:
2311 case Intrinsic::riscv_vlseg4ff:
2312 case Intrinsic::riscv_vlseg5ff:
2313 case Intrinsic::riscv_vlseg6ff:
2314 case Intrinsic::riscv_vlseg7ff:
2315 case Intrinsic::riscv_vlseg8ff:
2316 SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 3,
2317 /*IsStore*/ false,
2318 /*IsUnitStrided*/ false, /*UsePtrVal*/ true);
2319 return;
2320 case Intrinsic::riscv_vlseg2_mask:
2321 case Intrinsic::riscv_vlseg3_mask:
2322 case Intrinsic::riscv_vlseg4_mask:
2323 case Intrinsic::riscv_vlseg5_mask:
2324 case Intrinsic::riscv_vlseg6_mask:
2325 case Intrinsic::riscv_vlseg7_mask:
2326 case Intrinsic::riscv_vlseg8_mask:
2327 case Intrinsic::riscv_vlseg2ff_mask:
2328 case Intrinsic::riscv_vlseg3ff_mask:
2329 case Intrinsic::riscv_vlseg4ff_mask:
2330 case Intrinsic::riscv_vlseg5ff_mask:
2331 case Intrinsic::riscv_vlseg6ff_mask:
2332 case Intrinsic::riscv_vlseg7ff_mask:
2333 case Intrinsic::riscv_vlseg8ff_mask:
2334 SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 5,
2335 /*IsStore*/ false,
2336 /*IsUnitStrided*/ false, /*UsePtrVal*/ true);
2337 return;
2338 case Intrinsic::riscv_vlsseg2:
2339 case Intrinsic::riscv_vlsseg3:
2340 case Intrinsic::riscv_vlsseg4:
2341 case Intrinsic::riscv_vlsseg5:
2342 case Intrinsic::riscv_vlsseg6:
2343 case Intrinsic::riscv_vlsseg7:
2344 case Intrinsic::riscv_vlsseg8:
2345 case Intrinsic::riscv_vloxseg2:
2346 case Intrinsic::riscv_vloxseg3:
2347 case Intrinsic::riscv_vloxseg4:
2348 case Intrinsic::riscv_vloxseg5:
2349 case Intrinsic::riscv_vloxseg6:
2350 case Intrinsic::riscv_vloxseg7:
2351 case Intrinsic::riscv_vloxseg8:
2352 case Intrinsic::riscv_vluxseg2:
2353 case Intrinsic::riscv_vluxseg3:
2354 case Intrinsic::riscv_vluxseg4:
2355 case Intrinsic::riscv_vluxseg5:
2356 case Intrinsic::riscv_vluxseg6:
2357 case Intrinsic::riscv_vluxseg7:
2358 case Intrinsic::riscv_vluxseg8:
2359 SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 4,
2360 /*IsStore*/ false,
2361 /*IsUnitStrided*/ false);
2362 return;
2363 case Intrinsic::riscv_vlsseg2_mask:
2364 case Intrinsic::riscv_vlsseg3_mask:
2365 case Intrinsic::riscv_vlsseg4_mask:
2366 case Intrinsic::riscv_vlsseg5_mask:
2367 case Intrinsic::riscv_vlsseg6_mask:
2368 case Intrinsic::riscv_vlsseg7_mask:
2369 case Intrinsic::riscv_vlsseg8_mask:
2370 case Intrinsic::riscv_vloxseg2_mask:
2371 case Intrinsic::riscv_vloxseg3_mask:
2372 case Intrinsic::riscv_vloxseg4_mask:
2373 case Intrinsic::riscv_vloxseg5_mask:
2374 case Intrinsic::riscv_vloxseg6_mask:
2375 case Intrinsic::riscv_vloxseg7_mask:
2376 case Intrinsic::riscv_vloxseg8_mask:
2377 case Intrinsic::riscv_vluxseg2_mask:
2378 case Intrinsic::riscv_vluxseg3_mask:
2379 case Intrinsic::riscv_vluxseg4_mask:
2380 case Intrinsic::riscv_vluxseg5_mask:
2381 case Intrinsic::riscv_vluxseg6_mask:
2382 case Intrinsic::riscv_vluxseg7_mask:
2383 case Intrinsic::riscv_vluxseg8_mask:
2384 SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 6,
2385 /*IsStore*/ false,
2386 /*IsUnitStrided*/ false);
2387 return;
2388 case Intrinsic::riscv_vsseg2:
2389 case Intrinsic::riscv_vsseg3:
2390 case Intrinsic::riscv_vsseg4:
2391 case Intrinsic::riscv_vsseg5:
2392 case Intrinsic::riscv_vsseg6:
2393 case Intrinsic::riscv_vsseg7:
2394 case Intrinsic::riscv_vsseg8:
2395 SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 3,
2396 /*IsStore*/ true,
2397 /*IsUnitStrided*/ false);
2398 return;
2399 case Intrinsic::riscv_vsseg2_mask:
2400 case Intrinsic::riscv_vsseg3_mask:
2401 case Intrinsic::riscv_vsseg4_mask:
2402 case Intrinsic::riscv_vsseg5_mask:
2403 case Intrinsic::riscv_vsseg6_mask:
2404 case Intrinsic::riscv_vsseg7_mask:
2405 case Intrinsic::riscv_vsseg8_mask:
2406 SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 4,
2407 /*IsStore*/ true,
2408 /*IsUnitStrided*/ false);
2409 return;
2410 case Intrinsic::riscv_vssseg2:
2411 case Intrinsic::riscv_vssseg3:
2412 case Intrinsic::riscv_vssseg4:
2413 case Intrinsic::riscv_vssseg5:
2414 case Intrinsic::riscv_vssseg6:
2415 case Intrinsic::riscv_vssseg7:
2416 case Intrinsic::riscv_vssseg8:
2417 case Intrinsic::riscv_vsoxseg2:
2418 case Intrinsic::riscv_vsoxseg3:
2419 case Intrinsic::riscv_vsoxseg4:
2420 case Intrinsic::riscv_vsoxseg5:
2421 case Intrinsic::riscv_vsoxseg6:
2422 case Intrinsic::riscv_vsoxseg7:
2423 case Intrinsic::riscv_vsoxseg8:
2424 case Intrinsic::riscv_vsuxseg2:
2425 case Intrinsic::riscv_vsuxseg3:
2426 case Intrinsic::riscv_vsuxseg4:
2427 case Intrinsic::riscv_vsuxseg5:
2428 case Intrinsic::riscv_vsuxseg6:
2429 case Intrinsic::riscv_vsuxseg7:
2430 case Intrinsic::riscv_vsuxseg8:
2431 SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 4,
2432 /*IsStore*/ true,
2433 /*IsUnitStrided*/ false);
2434 return;
2435 case Intrinsic::riscv_vssseg2_mask:
2436 case Intrinsic::riscv_vssseg3_mask:
2437 case Intrinsic::riscv_vssseg4_mask:
2438 case Intrinsic::riscv_vssseg5_mask:
2439 case Intrinsic::riscv_vssseg6_mask:
2440 case Intrinsic::riscv_vssseg7_mask:
2441 case Intrinsic::riscv_vssseg8_mask:
2442 case Intrinsic::riscv_vsoxseg2_mask:
2443 case Intrinsic::riscv_vsoxseg3_mask:
2444 case Intrinsic::riscv_vsoxseg4_mask:
2445 case Intrinsic::riscv_vsoxseg5_mask:
2446 case Intrinsic::riscv_vsoxseg6_mask:
2447 case Intrinsic::riscv_vsoxseg7_mask:
2448 case Intrinsic::riscv_vsoxseg8_mask:
2449 case Intrinsic::riscv_vsuxseg2_mask:
2450 case Intrinsic::riscv_vsuxseg3_mask:
2451 case Intrinsic::riscv_vsuxseg4_mask:
2452 case Intrinsic::riscv_vsuxseg5_mask:
2453 case Intrinsic::riscv_vsuxseg6_mask:
2454 case Intrinsic::riscv_vsuxseg7_mask:
2455 case Intrinsic::riscv_vsuxseg8_mask:
2456 SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 5,
2457 /*IsStore*/ true,
2458 /*IsUnitStrided*/ false);
2459 return;
2460 case Intrinsic::riscv_sf_vlte8:
2461 case Intrinsic::riscv_sf_vlte16:
2462 case Intrinsic::riscv_sf_vlte32:
2463 case Intrinsic::riscv_sf_vlte64:
2464 Info.opc = ISD::INTRINSIC_VOID;
2465 Info.ptrVal = I.getArgOperand(1);
2466 switch (Intrinsic) {
2467 case Intrinsic::riscv_sf_vlte8:
2468 Info.memVT = MVT::i8;
2469 Info.align = Align(1);
2470 break;
2471 case Intrinsic::riscv_sf_vlte16:
2472 Info.memVT = MVT::i16;
2473 Info.align = Align(2);
2474 break;
2475 case Intrinsic::riscv_sf_vlte32:
2476 Info.memVT = MVT::i32;
2477 Info.align = Align(4);
2478 break;
2479 case Intrinsic::riscv_sf_vlte64:
2480 Info.memVT = MVT::i64;
2481 Info.align = Align(8);
2482 break;
2483 }
2484 Info.size = MemoryLocation::UnknownSize;
2485 Info.flags |= MachineMemOperand::MOLoad;
2486 Infos.push_back(Info);
2487 return;
2488 case Intrinsic::riscv_sf_vste8:
2489 case Intrinsic::riscv_sf_vste16:
2490 case Intrinsic::riscv_sf_vste32:
2491 case Intrinsic::riscv_sf_vste64:
2492 Info.opc = ISD::INTRINSIC_VOID;
2493 Info.ptrVal = I.getArgOperand(1);
2494 switch (Intrinsic) {
2495 case Intrinsic::riscv_sf_vste8:
2496 Info.memVT = MVT::i8;
2497 Info.align = Align(1);
2498 break;
2499 case Intrinsic::riscv_sf_vste16:
2500 Info.memVT = MVT::i16;
2501 Info.align = Align(2);
2502 break;
2503 case Intrinsic::riscv_sf_vste32:
2504 Info.memVT = MVT::i32;
2505 Info.align = Align(4);
2506 break;
2507 case Intrinsic::riscv_sf_vste64:
2508 Info.memVT = MVT::i64;
2509 Info.align = Align(8);
2510 break;
2511 }
2512 Info.size = MemoryLocation::UnknownSize;
2513 Info.flags |= MachineMemOperand::MOStore;
2514 Infos.push_back(Info);
2515 return;
2516 }
2517}
2518
2520 const AddrMode &AM, Type *Ty,
2521 unsigned AS,
2522 Instruction *I) const {
2523 // No global is ever allowed as a base.
2524 if (AM.BaseGV)
2525 return false;
2526
2527 // None of our addressing modes allows a scalable offset
2528 if (AM.ScalableOffset)
2529 return false;
2530
2531 // RVV instructions only support register addressing.
2532 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
2533 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
2534
2535 // The Xqcilo extension provides load/store instructions with a 26-bit signed
2536 // offset.
2537 if (Subtarget.hasVendorXqcilo()) {
2538 if (!isInt<26>(AM.BaseOffs))
2539 return false;
2540 } else if (!isInt<12>(AM.BaseOffs)) {
2541 // Otherwise require a 12-bit signed offset.
2542 return false;
2543 }
2544
2545 switch (AM.Scale) {
2546 case 0: // "r+i" or just "i", depending on HasBaseReg.
2547 break;
2548 case 1:
2549 if (!AM.HasBaseReg) // allow "r+i".
2550 break;
2551 return false; // disallow "r+r" or "r+r+i".
2552 default:
2553 return false;
2554 }
2555
2556 return true;
2557}
2558
2560 return isInt<12>(Imm);
2561}
2562
2564 // The Xqcilia extension provides add-immediate instructions with a 26-bit
2565 // signed immediate.
2566 if (Subtarget.hasVendorXqcilia())
2567 return isInt<26>(Imm);
2568 return isInt<12>(Imm);
2569}
2570
2571// On RV32, 64-bit integers are split into their high and low parts and held
2572// in two different registers, so the trunc is free since the low register can
2573// just be used.
2574// FIXME: Should we consider i64->i32 free on RV64 to match the EVT version of
2575// isTruncateFree?
2577 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
2578 return false;
2579 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
2580 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
2581 return (SrcBits == 64 && DestBits == 32);
2582}
2583
2585 // We consider i64->i32 free on RV64 since we have good selection of W
2586 // instructions that make promoting operations back to i64 free in many cases.
2587 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
2588 !DstVT.isInteger())
2589 return false;
2590 unsigned SrcBits = SrcVT.getSizeInBits();
2591 unsigned DestBits = DstVT.getSizeInBits();
2592 return (SrcBits == 64 && DestBits == 32);
2593}
2594
2596 EVT SrcVT = Val.getValueType();
2597 // free truncate from vnsrl and vnsra
2598 if (Subtarget.hasVInstructions() &&
2599 (Val.getOpcode() == ISD::SRL || Val.getOpcode() == ISD::SRA) &&
2600 SrcVT.isVector() && VT2.isVector()) {
2601 unsigned SrcBits = SrcVT.getVectorElementType().getSizeInBits();
2602 unsigned DestBits = VT2.getVectorElementType().getSizeInBits();
2603 if (SrcBits == DestBits * 2) {
2604 return true;
2605 }
2606 }
2607 return TargetLowering::isTruncateFree(Val, VT2);
2608}
2609
2611 // Zexts are free if they can be combined with a load.
2612 // Don't advertise i32->i64 zextload as being free for RV64. It interacts
2613 // poorly with type legalization of compares preferring sext.
2614 if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
2615 EVT MemVT = LD->getMemoryVT();
2616 if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
2617 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
2618 LD->getExtensionType() == ISD::ZEXTLOAD))
2619 return true;
2620 }
2621
2622 return TargetLowering::isZExtFree(Val, VT2);
2623}
2624
2626 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
2627}
2628
2630 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
2631}
2632
2634 return Subtarget.hasCTZLike();
2635}
2636
2638 return Subtarget.hasCLZLike();
2639}
2640
2642 const Instruction &AndI) const {
2643 // We expect to be able to match a bit extraction instruction if the Zbs
2644 // extension is supported and the mask is a power of two. However, we
2645 // conservatively return false if the mask would fit in an ANDI instruction,
2646 // on the basis that it's possible the sinking+duplication of the AND in
2647 // CodeGenPrepare triggered by this hook wouldn't decrease the instruction
2648 // count and would increase code size (e.g. ANDI+BNEZ => BEXTI+BNEZ).
2649 if (!Subtarget.hasBEXTILike())
2650 return false;
2652 if (!Mask)
2653 return false;
2654 return !Mask->getValue().isSignedIntN(12) && Mask->getValue().isPowerOf2();
2655}
2656
2658 EVT VT = Y.getValueType();
2659
2660 if (VT.isVector())
2661 return false;
2662
2663 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) &&
2664 (!isa<ConstantSDNode>(Y) || cast<ConstantSDNode>(Y)->isOpaque());
2665}
2666
2668 EVT VT = Y.getValueType();
2669
2670 if (!VT.isVector())
2671 return hasAndNotCompare(Y);
2672
2673 // vmandn.mm
2674 if (VT.getVectorElementType() == MVT::i1)
2675 return Subtarget.hasVInstructions();
2676
2677 return Subtarget.hasStdExtZvkb();
2678}
2679
2681 // Zbs provides BEXT[_I], which can be used with SEQZ/SNEZ as a bit test.
2682 if (Subtarget.hasStdExtZbs())
2683 return X.getValueType().isScalarInteger();
2684 auto *C = dyn_cast<ConstantSDNode>(Y);
2685 // XTheadBs provides th.tst (similar to bexti), if Y is a constant
2686 if (Subtarget.hasVendorXTHeadBs())
2687 return C != nullptr;
2688 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
2689 return C && C->getAPIntValue().ule(10);
2690}
2691
2693 unsigned BinOpcode, EVT VT, unsigned SelectOpcode, SDValue X,
2694 SDValue Y) const {
2695 if (SelectOpcode != ISD::VSELECT)
2696 return false;
2697
2698 // Only enable for rvv.
2699 if (!VT.isVector() || !Subtarget.hasVInstructions())
2700 return false;
2701
2702 if (VT.isFixedLengthVector() && !isTypeLegal(VT))
2703 return false;
2704
2705 return true;
2706}
2707
2709 Type *Ty) const {
2710 assert(Ty->isIntegerTy());
2711
2712 unsigned BitSize = Ty->getIntegerBitWidth();
2713 if (BitSize > Subtarget.getXLen())
2714 return false;
2715
2716 // Fast path, assume 32-bit immediates are cheap.
2717 int64_t Val = Imm.getSExtValue();
2718 if (isInt<32>(Val))
2719 return true;
2720
2721 // A constant pool entry may be more aligned than the load we're trying to
2722 // replace. If we don't support unaligned scalar mem, prefer the constant
2723 // pool.
2724 // TODO: Can the caller pass down the alignment?
2725 if (!Subtarget.enableUnalignedScalarMem())
2726 return true;
2727
2728 // Prefer to keep the load if it would require many instructions.
2729 // This uses the same threshold we use for constant pools but doesn't
2730 // check useConstantPoolForLargeInts.
2731 // TODO: Should we keep the load only when we're definitely going to emit a
2732 // constant pool?
2733
2735 return Seq.size() <= Subtarget.getMaxBuildIntsCost();
2736}
2737
2741 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
2742 SelectionDAG &DAG) const {
2743 // One interesting pattern that we'd want to form is 'bit extract':
2744 // ((1 >> Y) & 1) ==/!= 0
2745 // But we also need to be careful not to try to reverse that fold.
2746
2747 // Is this '((1 >> Y) & 1)'?
2748 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
2749 return false; // Keep the 'bit extract' pattern.
2750
2751 // Will this be '((1 >> Y) & 1)' after the transform?
2752 if (NewShiftOpcode == ISD::SRL && CC->isOne())
2753 return true; // Do form the 'bit extract' pattern.
2754
2755 // If 'X' is a constant, and we transform, then we will immediately
2756 // try to undo the fold, thus causing endless combine loop.
2757 // So only do the transform if X is not a constant. This matches the default
2758 // implementation of this function.
2759 return !XC;
2760}
2761
2763 unsigned Opc = VecOp.getOpcode();
2764
2765 // Assume target opcodes can't be scalarized.
2766 // TODO - do we have any exceptions?
2767 if (Opc >= ISD::BUILTIN_OP_END || !isBinOp(Opc))
2768 return false;
2769
2770 // If the vector op is not supported, try to convert to scalar.
2771 EVT VecVT = VecOp.getValueType();
2773 return true;
2774
2775 // If the vector op is supported, but the scalar op is not, the transform may
2776 // not be worthwhile.
2777 // Permit a vector binary operation can be converted to scalar binary
2778 // operation which is custom lowered with illegal type.
2779 EVT ScalarVT = VecVT.getScalarType();
2780 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT) ||
2781 isOperationCustom(Opc, ScalarVT);
2782}
2783
2785 const GlobalAddressSDNode *GA) const {
2786 // In order to maximise the opportunity for common subexpression elimination,
2787 // keep a separate ADD node for the global address offset instead of folding
2788 // it in the global address node. Later peephole optimisations may choose to
2789 // fold it back in when profitable.
2790 return false;
2791}
2792
2793// Returns 0-31 if the fli instruction is available for the type and this is
2794// legal FP immediate for the type. Returns -1 otherwise.
2796 if (!Subtarget.hasStdExtZfa())
2797 return -1;
2798
2799 bool IsSupportedVT = false;
2800 if (VT == MVT::f16) {
2801 IsSupportedVT = Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZvfh();
2802 } else if (VT == MVT::f32) {
2803 IsSupportedVT = true;
2804 } else if (VT == MVT::f64) {
2805 assert(Subtarget.hasStdExtD() && "Expect D extension");
2806 IsSupportedVT = true;
2807 }
2808
2809 if (!IsSupportedVT)
2810 return -1;
2811
2813}
2814
2817 bool ForCodeSize) const {
2818 bool IsLegalVT = false;
2819 if (VT == MVT::f16)
2820 IsLegalVT = Subtarget.hasStdExtZfhminOrZhinxmin();
2821 else if (VT == MVT::f32)
2822 IsLegalVT = Subtarget.hasStdExtFOrZfinx();
2823 else if (VT == MVT::f64)
2824 IsLegalVT = Subtarget.hasStdExtDOrZdinx();
2825 else if (VT == MVT::bf16)
2826 IsLegalVT = Subtarget.hasStdExtZfbfmin();
2827
2828 if (!IsLegalVT)
2830
2831 if (getLegalZfaFPImm(Imm, VT) >= 0)
2832 return FPImmAction::Legal;
2833
2834 // Some constants can be produced by fli+fneg.
2835 if (Imm.isNegative() && getLegalZfaFPImm(-Imm, VT) >= 0)
2836 return FPImmAction::Legal;
2837
2838 // Cannot create a 64 bit floating-point immediate value for rv32.
2839 if (Subtarget.getXLen() < VT.getScalarSizeInBits()) {
2840 // td can handle +0.0 or -0.0 already.
2841 // -0.0 can be created by fmv + fneg.
2843 }
2844
2845 // Special case: fmv + fneg
2846 if (Imm.isNegZero())
2847 return FPImmAction::Legal;
2848
2849 // Building an integer and then converting requires a fmv at the end of
2850 // the integer sequence. The fmv is not required for Zfinx.
2851 const int FmvCost = Subtarget.hasStdExtZfinx() ? 0 : 1;
2852 const int Cost =
2853 FmvCost + RISCVMatInt::getIntMatCost(Imm.bitcastToAPInt(),
2854 Subtarget.getXLen(), Subtarget);
2855 return Cost <= Subtarget.getCLOpts().lower_fpimm_cost
2858}
2859
2860static bool hasFPType(const RISCVSubtarget &Subtarget, LLT Ty) {
2861 if (Ty.isBFloat16())
2862 return Subtarget.hasStdExtZfbfmin();
2863
2864 switch (Ty.getSizeInBits()) {
2865 case 16:
2866 return Subtarget.hasStdExtZfhmin();
2867 case 32:
2868 return Subtarget.hasStdExtF();
2869 case 64:
2870 return Subtarget.hasStdExtD();
2871 default:
2872 return false;
2873 }
2874}
2875
2878 bool ForCodeSize) const {
2879 return hasFPType(Subtarget, Ty) ? FPImmAction::ConstantPool
2881}
2882
2883// TODO: This is very conservative.
2886 unsigned Index) const {
2887 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() &&
2888 (ResVT == MVT::v4i8 || ResVT == MVT::v2i16)) {
2889 if ((Index % ResVT.getVectorNumElements()) == 0)
2892 }
2893
2894 if (!Subtarget.hasVInstructions())
2896
2899
2900 // Extracts from index 0 are just subreg extracts.
2901 if (Index == 0)
2903
2904 // Only support extracting a fixed from a fixed vector for now.
2905 if (ResVT.isScalableVector() || SrcVT.isScalableVector())
2907
2908 EVT EltVT = ResVT.getVectorElementType();
2909 assert(EltVT == SrcVT.getVectorElementType() && "Should hold for node");
2910
2911 // The smallest type we can slide is i8.
2912 if (EltVT == MVT::i1)
2914
2915 unsigned ResElts = ResVT.getVectorNumElements();
2916 unsigned SrcElts = SrcVT.getVectorNumElements();
2917
2918 unsigned MinVLen = Subtarget.getRealMinVLen();
2919 unsigned MinVLMAX = MinVLen / EltVT.getSizeInBits();
2920
2921 // If we're extracting only data from the first VLEN bits of the source
2922 // then we can always do this with an m1 vslidedown.vx. Restricting the
2923 // Index ensures we can use a vslidedown.vi.
2924 // TODO: We can generalize this when the exact VLEN is known.
2925 if (Index + ResElts <= MinVLMAX && Index < 31)
2927
2928 // Convervatively only handle extracting half of a vector.
2929 // TODO: We can do arbitrary slidedowns, but for now only support extracting
2930 // the upper half of a vector until we have more test coverage.
2931 // TODO: For sizes which aren't multiples of VLEN sizes, this may not be
2932 // a cheap extract. However, this case is important in practice for
2933 // shuffled extracts of longer vectors. How resolve?
2934 if ((ResElts * 2) == SrcElts && Index == ResElts)
2937}
2938
2941 EVT VT) const {
2942 // Use f32 to pass f16 if it is legal and Zfh/Zfhmin is not enabled.
2943 // We might still end up using a GPR but that will be decided based on ABI.
2944 if (VT == MVT::f16 && Subtarget.hasStdExtFOrZfinx() &&
2945 !Subtarget.hasStdExtZfhminOrZhinxmin())
2946 return MVT::f32;
2947
2949}
2950
2951unsigned
2953 std::optional<MVT> RegisterVT) const {
2954 // Pair inline assembly operand
2955 if (VT == (Subtarget.is64Bit() ? MVT::i128 : MVT::i64) && RegisterVT &&
2956 *RegisterVT == MVT::Untyped)
2957 return 1;
2958
2959 return TargetLowering::getNumRegisters(Context, VT, RegisterVT);
2960}
2961
2964 EVT VT) const {
2965 // Use f32 to pass f16 if it is legal and Zfh/Zfhmin is not enabled.
2966 // We might still end up using a GPR but that will be decided based on ABI.
2967 if (VT == MVT::f16 && Subtarget.hasStdExtFOrZfinx() &&
2968 !Subtarget.hasStdExtZfhminOrZhinxmin())
2969 return 1;
2970
2972}
2973
2974// Changes the condition code and swaps operands if necessary, so the SetCC
2975// operation matches one of the comparisons supported directly by branches
2976// in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
2977// with 1/-1.
2980 const RISCVSubtarget &Subtarget) {
2981 // If this is a single bit test that can't be handled by ANDI, shift the
2982 // bit to be tested to the MSB and perform a signed compare with 0.
2983 if (isIntEqualitySetCC(CC) && isNullConstant(RHS) &&
2984 LHS.getOpcode() == ISD::AND && LHS.hasOneUse() &&
2985 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2986 // XAndesPerf supports branch on test bit.
2987 !Subtarget.hasVendorXAndesPerf()) {
2988 uint64_t Mask = LHS.getConstantOperandVal(1);
2989 if ((isPowerOf2_64(Mask) || isMask_64(Mask)) && !isInt<12>(Mask)) {
2990 unsigned ShAmt = 0;
2991 if (isPowerOf2_64(Mask)) {
2993 ShAmt = LHS.getValueSizeInBits() - 1 - Log2_64(Mask);
2994 } else {
2995 ShAmt = LHS.getValueSizeInBits() - llvm::bit_width(Mask);
2996 }
2997
2998 LHS = LHS.getOperand(0);
2999 if (ShAmt != 0)
3000 LHS = DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS,
3001 DAG.getConstant(ShAmt, DL, LHS.getValueType()));
3002 return;
3003 }
3004 }
3005
3006 if (auto *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3007 int64_t C = RHSC->getSExtValue();
3008 switch (CC) {
3009 default: break;
3010 case ISD::SETGT:
3011 // Convert X > -1 to X >= 0.
3012 if (C == -1) {
3013 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3014 CC = ISD::SETGE;
3015 return;
3016 }
3017 if ((Subtarget.hasVendorXqcicm() || Subtarget.hasVendorXqcicli()) &&
3018 C != INT64_MAX && isInt<5>(C + 1)) {
3019 // We have a conditional move instruction for SETGE but not SETGT.
3020 // Convert X > C to X >= C + 1, if (C + 1) is a 5-bit signed immediate.
3021 RHS = DAG.getSignedConstant(C + 1, DL, RHS.getValueType());
3022 CC = ISD::SETGE;
3023 return;
3024 }
3025 if (Subtarget.hasVendorXqcibi() && C != INT64_MAX && isInt<16>(C + 1)) {
3026 // We have a branch immediate instruction for SETGE but not SETGT.
3027 // Convert X > C to X >= C + 1, if (C + 1) is a 16-bit signed immediate.
3028 RHS = DAG.getSignedConstant(C + 1, DL, RHS.getValueType());
3029 CC = ISD::SETGE;
3030 return;
3031 }
3032 break;
3033 case ISD::SETLT:
3034 // Convert X < 1 to 0 >= X.
3035 if (C == 1) {
3036 RHS = LHS;
3037 LHS = DAG.getConstant(0, DL, RHS.getValueType());
3038 CC = ISD::SETGE;
3039 return;
3040 }
3041 break;
3042 case ISD::SETUGT:
3043 if ((Subtarget.hasVendorXqcicm() || Subtarget.hasVendorXqcicli()) &&
3044 C != INT64_MAX && isUInt<5>(C + 1)) {
3045 // We have a conditional move instruction for SETUGE but not SETUGT.
3046 // Convert X > C to X >= C + 1, if (C + 1) is a 5-bit signed immediate.
3047 RHS = DAG.getConstant(C + 1, DL, RHS.getValueType());
3048 CC = ISD::SETUGE;
3049 return;
3050 }
3051 if (Subtarget.hasVendorXqcibi() && C != INT64_MAX && isUInt<16>(C + 1)) {
3052 // We have a branch immediate instruction for SETUGE but not SETUGT.
3053 // Convert X > C to X >= C + 1, if (C + 1) is a 16-bit unsigned
3054 // immediate.
3055 RHS = DAG.getConstant(C + 1, DL, RHS.getValueType());
3056 CC = ISD::SETUGE;
3057 return;
3058 }
3059 break;
3060 }
3061 }
3062
3063 switch (CC) {
3064 default:
3065 break;
3066 case ISD::SETGT:
3067 case ISD::SETLE:
3068 case ISD::SETUGT:
3069 case ISD::SETULE:
3071 std::swap(LHS, RHS);
3072 break;
3073 }
3074}
3075
3077 if (VT.isRISCVVectorTuple()) {
3078 if (VT.SimpleTy >= MVT::riscv_nxv1i8x2 &&
3079 VT.SimpleTy <= MVT::riscv_nxv1i8x8)
3080 return RISCVVType::LMUL_F8;
3081 if (VT.SimpleTy >= MVT::riscv_nxv2i8x2 &&
3082 VT.SimpleTy <= MVT::riscv_nxv2i8x8)
3083 return RISCVVType::LMUL_F4;
3084 if (VT.SimpleTy >= MVT::riscv_nxv4i8x2 &&
3085 VT.SimpleTy <= MVT::riscv_nxv4i8x8)
3086 return RISCVVType::LMUL_F2;
3087 if (VT.SimpleTy >= MVT::riscv_nxv8i8x2 &&
3088 VT.SimpleTy <= MVT::riscv_nxv8i8x8)
3089 return RISCVVType::LMUL_1;
3090 if (VT.SimpleTy >= MVT::riscv_nxv16i8x2 &&
3091 VT.SimpleTy <= MVT::riscv_nxv16i8x4)
3092 return RISCVVType::LMUL_2;
3093 if (VT.SimpleTy == MVT::riscv_nxv32i8x2)
3094 return RISCVVType::LMUL_4;
3095 llvm_unreachable("Invalid vector tuple type LMUL.");
3096 }
3097
3098 assert(VT.isScalableVector() && "Expecting a scalable vector type");
3099 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
3100 if (VT.getVectorElementType() == MVT::i1)
3101 KnownSize *= 8;
3102
3103 switch (KnownSize) {
3104 default:
3105 llvm_unreachable("Invalid LMUL.");
3106 case 8:
3107 return RISCVVType::LMUL_F8;
3108 case 16:
3109 return RISCVVType::LMUL_F4;
3110 case 32:
3111 return RISCVVType::LMUL_F2;
3112 case 64:
3113 return RISCVVType::LMUL_1;
3114 case 128:
3115 return RISCVVType::LMUL_2;
3116 case 256:
3117 return RISCVVType::LMUL_4;
3118 case 512:
3119 return RISCVVType::LMUL_8;
3120 }
3121}
3122
3124 switch (LMul) {
3125 default:
3126 llvm_unreachable("Invalid LMUL.");
3130 case RISCVVType::LMUL_1:
3131 return RISCV::VRRegClassID;
3132 case RISCVVType::LMUL_2:
3133 return RISCV::VRM2RegClassID;
3134 case RISCVVType::LMUL_4:
3135 return RISCV::VRM4RegClassID;
3136 case RISCVVType::LMUL_8:
3137 return RISCV::VRM8RegClassID;
3138 }
3139}
3140
3141unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
3142 RISCVVType::VLMUL LMUL = getLMUL(VT);
3143 if (LMUL == RISCVVType::LMUL_F8 || LMUL == RISCVVType::LMUL_F4 ||
3144 LMUL == RISCVVType::LMUL_F2 || LMUL == RISCVVType::LMUL_1) {
3145 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
3146 "Unexpected subreg numbering");
3147 return RISCV::sub_vrm1_0 + Index;
3148 }
3149 if (LMUL == RISCVVType::LMUL_2) {
3150 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
3151 "Unexpected subreg numbering");
3152 return RISCV::sub_vrm2_0 + Index;
3153 }
3154 if (LMUL == RISCVVType::LMUL_4) {
3155 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
3156 "Unexpected subreg numbering");
3157 return RISCV::sub_vrm4_0 + Index;
3158 }
3159 llvm_unreachable("Invalid vector type.");
3160}
3161
3163 if (VT.isRISCVVectorTuple()) {
3164 unsigned NF = VT.getRISCVVectorTupleNumFields();
3165 unsigned RegsPerField =
3166 std::max(1U, (unsigned)VT.getSizeInBits().getKnownMinValue() /
3167 (NF * RISCV::RVVBitsPerBlock));
3168 switch (RegsPerField) {
3169 case 1:
3170 if (NF == 2)
3171 return RISCV::VRN2M1RegClassID;
3172 if (NF == 3)
3173 return RISCV::VRN3M1RegClassID;
3174 if (NF == 4)
3175 return RISCV::VRN4M1RegClassID;
3176 if (NF == 5)
3177 return RISCV::VRN5M1RegClassID;
3178 if (NF == 6)
3179 return RISCV::VRN6M1RegClassID;
3180 if (NF == 7)
3181 return RISCV::VRN7M1RegClassID;
3182 if (NF == 8)
3183 return RISCV::VRN8M1RegClassID;
3184 break;
3185 case 2:
3186 if (NF == 2)
3187 return RISCV::VRN2M2RegClassID;
3188 if (NF == 3)
3189 return RISCV::VRN3M2RegClassID;
3190 if (NF == 4)
3191 return RISCV::VRN4M2RegClassID;
3192 break;
3193 case 4:
3194 assert(NF == 2);
3195 return RISCV::VRN2M4RegClassID;
3196 default:
3197 break;
3198 }
3199 llvm_unreachable("Invalid vector tuple type RegClass.");
3200 }
3201
3202 if (VT.getVectorElementType() == MVT::i1)
3203 return RISCV::VRRegClassID;
3204 return getRegClassIDForLMUL(getLMUL(VT));
3205}
3206
3207// Attempt to decompose a subvector insert/extract between VecVT and
3208// SubVecVT via subregister indices. Returns the subregister index that
3209// can perform the subvector insert/extract with the given element index, as
3210// well as the index corresponding to any leftover subvectors that must be
3211// further inserted/extracted within the register class for SubVecVT.
3212std::pair<unsigned, unsigned>
3214 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
3215 const RISCVRegisterInfo *TRI) {
3216 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
3217 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
3218 RISCV::VRM2RegClassID > RISCV::VRRegClassID),
3219 "Register classes not ordered");
3220 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
3221 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
3222
3223 // If VecVT is a vector tuple type, either it's the tuple type with same
3224 // RegClass with SubVecVT or SubVecVT is a actually a subvector of the VecVT.
3225 if (VecVT.isRISCVVectorTuple()) {
3226 if (VecRegClassID == SubRegClassID)
3227 return {RISCV::NoSubRegister, 0};
3228
3229 assert(SubVecVT.isScalableVector() &&
3230 "Only allow scalable vector subvector.");
3231 assert(getLMUL(VecVT) == getLMUL(SubVecVT) &&
3232 "Invalid vector tuple insert/extract for vector and subvector with "
3233 "different LMUL.");
3234 return {getSubregIndexByMVT(VecVT, InsertExtractIdx), 0};
3235 }
3236
3237 // Try to compose a subregister index that takes us from the incoming
3238 // LMUL>1 register class down to the outgoing one. At each step we half
3239 // the LMUL:
3240 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
3241 // Note that this is not guaranteed to find a subregister index, such as
3242 // when we are extracting from one VR type to another.
3243 unsigned SubRegIdx = RISCV::NoSubRegister;
3244 for (const unsigned RCID :
3245 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
3246 if (VecRegClassID > RCID && SubRegClassID <= RCID) {
3247 VecVT = VecVT.getHalfNumVectorElementsVT();
3248 bool IsHi =
3249 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
3250 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
3251 getSubregIndexByMVT(VecVT, IsHi));
3252 if (IsHi)
3253 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
3254 }
3255 return {SubRegIdx, InsertExtractIdx};
3256}
3257
3258// Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
3259// stores for those types.
3260bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
3261 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() &&
3262 (VT == MVT::i32 || VT == MVT::v2i16 || VT == MVT::v4i8))
3263 return false;
3264
3265 return !Subtarget.useRVVForFixedLengthVectors() ||
3266 VT.isFixedLengthVectorOf(MVT::i1);
3267}
3268
3270 if (!ScalarTy.isSimple())
3271 return false;
3272 switch (ScalarTy.getSimpleVT().SimpleTy) {
3273 case MVT::iPTR:
3274 return Subtarget.is64Bit() ? Subtarget.hasVInstructionsI64() : true;
3275 case MVT::i8:
3276 case MVT::i16:
3277 case MVT::i32:
3278 return Subtarget.hasVInstructions();
3279 case MVT::i64:
3280 return Subtarget.hasVInstructionsI64();
3281 case MVT::f16:
3282 return Subtarget.hasVInstructionsF16Minimal();
3283 case MVT::bf16:
3284 return Subtarget.hasVInstructionsBF16Minimal();
3285 case MVT::f32:
3286 return Subtarget.hasVInstructionsF32();
3287 case MVT::f64:
3288 return Subtarget.hasVInstructionsF64();
3289 default:
3290 return false;
3291 }
3292}
3293
3294
3296 return Subtarget.getCLOpts().lower_fp_repeated_divisors;
3297}
3298
3300 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3301 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3302 "Unexpected opcode");
3303 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
3304 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
3306 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
3307 if (!II)
3308 return SDValue();
3309 return Op.getOperand(II->VLOperand + 1 + HasChain);
3310}
3311
3313 const RISCVSubtarget &Subtarget) {
3314 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
3315 if (!Subtarget.useRVVForFixedLengthVectors())
3316 return false;
3317
3318 // We only support a set of vector types with a consistent maximum fixed size
3319 // across all supported vector element types to avoid legalization issues.
3320 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
3321 // fixed-length vector type we support is 1024 bytes.
3322 if (VT.getVectorNumElements() > 1024 || VT.getFixedSizeInBits() > 1024 * 8)
3323 return false;
3324
3325 unsigned MinVLen = Subtarget.getRealMinVLen();
3326
3327 MVT EltVT = VT.getVectorElementType();
3328
3329 // Don't use RVV for vectors we cannot scalarize if required.
3330 switch (EltVT.SimpleTy) {
3331 // i1 is supported but has different rules.
3332 default:
3333 return false;
3334 case MVT::i1:
3335 // Masks can only use a single register.
3336 if (VT.getVectorNumElements() > MinVLen)
3337 return false;
3338 MinVLen /= 8;
3339 break;
3340 case MVT::i8:
3341 case MVT::i16:
3342 case MVT::i32:
3343 break;
3344 case MVT::i64:
3345 if (!Subtarget.hasVInstructionsI64())
3346 return false;
3347 break;
3348 case MVT::f16:
3349 if (!Subtarget.hasVInstructionsF16Minimal())
3350 return false;
3351 break;
3352 case MVT::bf16:
3353 if (!Subtarget.hasVInstructionsBF16Minimal())
3354 return false;
3355 break;
3356 case MVT::f32:
3357 if (!Subtarget.hasVInstructionsF32())
3358 return false;
3359 break;
3360 case MVT::f64:
3361 if (!Subtarget.hasVInstructionsF64())
3362 return false;
3363 break;
3364 }
3365
3366 // Reject elements larger than ELEN.
3367 if (EltVT.getSizeInBits() > Subtarget.getELen())
3368 return false;
3369
3370 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
3371 // Don't use RVV for types that don't fit.
3372 if (LMul > 8)
3373 return false;
3374
3375 // TODO: Perhaps an artificial restriction, but worth having whilst getting
3376 // the base fixed length RVV support in place.
3377 if (!VT.isPow2VectorType())
3378 return false;
3379
3380 return true;
3381}
3382
3383bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
3384 return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
3385}
3386
3387// Return the largest legal scalable vector type that matches VT's element type.
3389 const RISCVSubtarget &Subtarget) {
3390 // This may be called before legal types are setup.
3391 assert(((VT.isFixedLengthVector() &&
3392 Subtarget.getTargetLowering()->isTypeLegal(VT)) ||
3394 "Expected legal fixed length vector!");
3395
3396 unsigned MinVLen = Subtarget.getRealMinVLen();
3397 unsigned MaxELen = Subtarget.getELen();
3398
3399 MVT EltVT = VT.getVectorElementType();
3400 switch (EltVT.SimpleTy) {
3401 default:
3402 llvm_unreachable("unexpected element type for RVV container");
3403 case MVT::i1:
3404 case MVT::i8:
3405 case MVT::i16:
3406 case MVT::i32:
3407 case MVT::i64:
3408 case MVT::bf16:
3409 case MVT::f16:
3410 case MVT::f32:
3411 case MVT::f64: {
3412 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
3413 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
3414 // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
3415 unsigned NumElts =
3417 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
3418 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
3419 return MVT::getScalableVectorVT(EltVT, NumElts);
3420 }
3421 }
3422}
3423
3425 return ::getContainerForFixedLengthVector(VT, getSubtarget());
3426}
3427
3428// Grow V to consume an entire RVV register.
3430 const RISCVSubtarget &Subtarget) {
3431 assert(VT.isScalableVector() &&
3432 "Expected to convert into a scalable vector!");
3433 assert(V.getValueType().isFixedLengthVector() &&
3434 "Expected a fixed length vector operand!");
3435 SDLoc DL(V);
3436 return DAG.getInsertSubvector(DL, DAG.getUNDEF(VT), V, 0);
3437}
3438
3439// Shrink V so it's just big enough to maintain a VT's worth of data.
3441 const RISCVSubtarget &Subtarget) {
3443 "Expected to convert into a fixed length vector!");
3444 assert(V.getValueType().isScalableVector() &&
3445 "Expected a scalable vector operand!");
3446 SDLoc DL(V);
3447 return DAG.getExtractSubvector(DL, VT, V, 0);
3448}
3449
3450/// Return the type of the mask type suitable for masking the provided
3451/// vector type. This is simply an i1 element type vector of the same
3452/// (possibly scalable) length.
3453static MVT getMaskTypeFor(MVT VecVT) {
3454 assert(VecVT.isVector());
3456 return MVT::getVectorVT(MVT::i1, EC);
3457}
3458
3459/// Creates an all ones mask suitable for masking a vector of type VecTy with
3460/// vector length VL. .
3461static SDValue getAllOnesMask(MVT VecVT, SDValue VL, const SDLoc &DL,
3462 SelectionDAG &DAG) {
3463 MVT MaskVT = getMaskTypeFor(VecVT);
3464 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3465}
3466
3467static std::pair<SDValue, SDValue>
3469 const RISCVSubtarget &Subtarget) {
3470 assert(VecVT.isScalableVector() && "Expecting a scalable vector");
3471 SDValue VL = DAG.getRegister(RISCV::X0, Subtarget.getXLenVT());
3472 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
3473 return {Mask, VL};
3474}
3475
3476static std::pair<SDValue, SDValue>
3478 SelectionDAG &DAG, const RISCVSubtarget &Subtarget) {
3479 assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
3480 SDValue VL = DAG.getConstant(NumElts, DL, Subtarget.getXLenVT());
3481 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
3482 return {Mask, VL};
3483}
3484
3485// Gets the two common "VL" operands: an all-ones mask and the vector length.
3486// VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
3487// the vector type that the fixed-length vector is contained in. Otherwise if
3488// VecVT is scalable, then ContainerVT should be the same as VecVT.
3489static std::pair<SDValue, SDValue>
3491 const RISCVSubtarget &Subtarget) {
3492 if (VecVT.isFixedLengthVector())
3493 return getDefaultVLOps(VecVT.getVectorNumElements(), ContainerVT, DL, DAG,
3494 Subtarget);
3495 assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
3497}
3498
3500 SelectionDAG &DAG) const {
3501 assert(VecVT.isScalableVector() && "Expected scalable vector");
3502 return DAG.getElementCount(DL, Subtarget.getXLenVT(),
3503 VecVT.getVectorElementCount());
3504}
3505
3506std::pair<unsigned, unsigned>
3508 const RISCVSubtarget &Subtarget) {
3509 assert(VecVT.isScalableVector() && "Expected scalable vector");
3510
3511 unsigned EltSize = VecVT.getScalarSizeInBits();
3512 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
3513
3514 unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
3515 unsigned MaxVLMAX =
3516 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
3517
3518 unsigned VectorBitsMin = Subtarget.getRealMinVLen();
3519 unsigned MinVLMAX =
3520 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
3521
3522 return std::make_pair(MinVLMAX, MaxVLMAX);
3523}
3524
3525// The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
3526// of either is (currently) supported. This can get us into an infinite loop
3527// where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
3528// as a ..., etc.
3529// Until either (or both) of these can reliably lower any node, reporting that
3530// we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
3531// the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
3532// which is not desirable.
3534 EVT VT, unsigned DefinedValues) const {
3535 return false;
3536}
3537
3539 // TODO: Here assume reciprocal throughput is 1 for LMUL_1, it is
3540 // implementation-defined.
3541 if (!VT.isVector())
3543 unsigned DLenFactor = Subtarget.getDLenFactor();
3544 unsigned Cost;
3545 if (VT.isScalableVector()) {
3546 unsigned LMul;
3547 bool Fractional;
3548 std::tie(LMul, Fractional) =
3550 if (Fractional)
3551 Cost = LMul <= DLenFactor ? (DLenFactor / LMul) : 1;
3552 else
3553 Cost = (LMul * DLenFactor);
3554 } else {
3555 Cost = divideCeil(VT.getSizeInBits(), Subtarget.getRealMinVLen() / DLenFactor);
3556 }
3557 return Cost;
3558}
3559
3560
3561/// Return the cost of a vrgather.vv instruction for the type VT. vrgather.vv
3562/// may be quadratic in the number of vreg implied by LMUL, and is assumed to
3563/// be by default. VRGatherCostModel reflects available options. Note that
3564/// operand (index and possibly mask) are handled separately.
3566 auto LMULCost = getLMULCost(VT);
3567 bool Log2CostModel =
3568 Subtarget.getVRGatherCostModel() == llvm::RISCVSubtarget::NLog2N;
3569 if (Log2CostModel && LMULCost.isValid()) {
3570 unsigned Log = Log2_64(LMULCost.getValue());
3571 if (Log > 0)
3572 return LMULCost * Log;
3573 }
3574 return LMULCost * LMULCost;
3575}
3576
3577/// Return the cost of a vrgather.vi (or vx) instruction for the type VT.
3578/// vrgather.vi/vx may be linear in the number of vregs implied by LMUL,
3579/// or may track the vrgather.vv cost. It is implementation-dependent.
3583
3584/// Return the cost of a vslidedown.vx or vslideup.vx instruction
3585/// for the type VT. (This does not cover the vslide1up or vslide1down
3586/// variants.) Slides may be linear in the number of vregs implied by LMUL,
3587/// or may track the vrgather.vv cost. It is implementation-dependent.
3589 // Slides aren't as pipelined as arithmetic ops and don't have the same
3590 // throughput on most hardware.
3591 return getLMULCost(VT) * 2;
3592}
3593
3594/// Return the cost of a vslidedown.vi or vslideup.vi instruction
3595/// for the type VT. (This does not cover the vslide1up or vslide1down
3596/// variants.) Slides may be linear in the number of vregs implied by LMUL,
3597/// or may track the vrgather.vv cost. It is implementation-dependent.
3599 // Slides aren't as pipelined as arithmetic ops and don't have the same
3600 // throughput on most hardware.
3601 return getLMULCost(VT) * 2;
3602}
3603
3605 const RISCVSubtarget &Subtarget) {
3606 // f16 conversions are promoted to f32 when Zfh/Zhinx are not supported.
3607 // bf16 conversions are always promoted to f32.
3608 if ((Op.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfhOrZhinx()) ||
3609 Op.getValueType() == MVT::bf16) {
3610 bool IsStrict = Op->isStrictFPOpcode();
3611
3612 SDLoc DL(Op);
3613 if (IsStrict) {
3614 SDValue Val = DAG.getNode(Op.getOpcode(), DL, {MVT::f32, MVT::Other},
3615 {Op.getOperand(0), Op.getOperand(1)});
3616 return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
3617 {Op.getValueType(), MVT::Other},
3618 {Val.getValue(1), Val.getValue(0),
3619 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true)});
3620 }
3621 return DAG.getNode(
3622 ISD::FP_ROUND, DL, Op.getValueType(),
3623 DAG.getNode(Op.getOpcode(), DL, MVT::f32, Op.getOperand(0)),
3624 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
3625 }
3626
3627 // Other operations are legal.
3628 return Op;
3629}
3630
3632 const RISCVSubtarget &Subtarget) {
3633 // RISC-V FP-to-int conversions saturate to the destination register size, but
3634 // don't produce 0 for nan. We can use a conversion instruction and fix the
3635 // nan case with a compare and a select.
3636 SDValue Src = Op.getOperand(0);
3637
3638 MVT DstVT = Op.getSimpleValueType();
3639 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3640
3641 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
3642
3643 if (!DstVT.isVector()) {
3644 // For bf16 or for f16 in absence of Zfh, promote to f32, then saturate
3645 // the result.
3646 if ((Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfhOrZhinx()) ||
3647 Src.getValueType() == MVT::bf16) {
3648 Src = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), MVT::f32, Src);
3649 }
3650
3651 unsigned Opc;
3652 if (SatVT == DstVT)
3653 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
3654 else if (DstVT == MVT::i64 && SatVT == MVT::i32)
3655 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
3656 else
3657 return SDValue();
3658 // FIXME: Support other SatVTs by clamping before or after the conversion.
3659
3660 SDLoc DL(Op);
3661 SDValue FpToInt = DAG.getNode(
3662 Opc, DL, DstVT, Src,
3664
3665 if (Opc == RISCVISD::FCVT_WU_RV64)
3666 FpToInt = DAG.getZeroExtendInReg(FpToInt, DL, MVT::i32);
3667
3668 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
3669 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt,
3671 }
3672
3673 // Vectors.
3674
3675 MVT DstEltVT = DstVT.getVectorElementType();
3676 MVT SrcVT = Src.getSimpleValueType();
3677 MVT SrcEltVT = SrcVT.getVectorElementType();
3678 unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3679 unsigned DstEltSize = DstEltVT.getSizeInBits();
3680
3681 // Only handle saturating to the destination type.
3682 if (SatVT != DstEltVT)
3683 return SDValue();
3684
3685 MVT DstContainerVT = DstVT;
3686 MVT SrcContainerVT = SrcVT;
3687 if (DstVT.isFixedLengthVector()) {
3688 DstContainerVT = getContainerForFixedLengthVector(DstVT, Subtarget);
3689 SrcContainerVT = getContainerForFixedLengthVector(SrcVT, Subtarget);
3690 assert(DstContainerVT.getVectorElementCount() ==
3691 SrcContainerVT.getVectorElementCount() &&
3692 "Expected same element count");
3693 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3694 }
3695
3696 SDLoc DL(Op);
3697
3698 auto [Mask, VL] = getDefaultVLOps(DstVT, DstContainerVT, DL, DAG, Subtarget);
3699
3700 SDValue IsNan = DAG.getNode(RISCVISD::SETCC_VL, DL, Mask.getValueType(),
3701 {Src, Src, DAG.getCondCode(ISD::SETNE),
3702 DAG.getUNDEF(Mask.getValueType()), Mask, VL});
3703
3704 // Need to widen by more than 1 step, promote the FP type, then do a widening
3705 // convert.
3706 if (DstEltSize > (2 * SrcEltSize)) {
3707 assert(SrcContainerVT.getVectorElementType() == MVT::f16 && "Unexpected VT!");
3708 MVT InterVT = SrcContainerVT.changeVectorElementType(MVT::f32);
3709 Src = DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterVT, Src, Mask, VL);
3710 }
3711
3712 MVT CvtContainerVT = DstContainerVT;
3713 MVT CvtEltVT = DstEltVT;
3714 if (SrcEltSize > (2 * DstEltSize)) {
3715 CvtEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3716 CvtContainerVT = CvtContainerVT.changeVectorElementType(CvtEltVT);
3717 }
3718
3719 unsigned RVVOpc =
3720 IsSigned ? RISCVISD::VFCVT_RTZ_X_F_VL : RISCVISD::VFCVT_RTZ_XU_F_VL;
3721 SDValue Res = DAG.getNode(RVVOpc, DL, CvtContainerVT, Src, Mask, VL);
3722
3723 while (CvtContainerVT != DstContainerVT) {
3724 CvtEltVT = MVT::getIntegerVT(CvtEltVT.getSizeInBits() / 2);
3725 CvtContainerVT = CvtContainerVT.changeVectorElementType(CvtEltVT);
3726 // Rounding mode here is arbitrary since we aren't shifting out any bits.
3727 unsigned ClipOpc = IsSigned ? RISCVISD::TRUNCATE_VECTOR_VL_SSAT
3728 : RISCVISD::TRUNCATE_VECTOR_VL_USAT;
3729 Res = DAG.getNode(ClipOpc, DL, CvtContainerVT, Res, Mask, VL);
3730 }
3731
3732 SDValue SplatZero = DAG.getNode(
3733 RISCVISD::VMV_V_X_VL, DL, DstContainerVT, DAG.getUNDEF(DstContainerVT),
3734 DAG.getConstant(0, DL, Subtarget.getXLenVT()), VL);
3735 Res = DAG.getNode(RISCVISD::VMERGE_VL, DL, DstContainerVT, IsNan, SplatZero,
3736 Res, DAG.getUNDEF(DstContainerVT), VL);
3737
3738 if (DstVT.isFixedLengthVector())
3739 Res = convertFromScalableVector(DstVT, Res, DAG, Subtarget);
3740
3741 return Res;
3742}
3743
3745 const RISCVSubtarget &Subtarget) {
3746 bool IsStrict = Op->isStrictFPOpcode();
3747 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3748
3749 // f16 conversions are promoted to f32 when Zfh/Zhinx is not enabled.
3750 // bf16 conversions are always promoted to f32.
3751 if ((SrcVal.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfhOrZhinx()) ||
3752 SrcVal.getValueType() == MVT::bf16) {
3753 SDLoc DL(Op);
3754 if (IsStrict) {
3755 SDValue Ext =
3756 DAG.getNode(ISD::STRICT_FP_EXTEND, DL, {MVT::f32, MVT::Other},
3757 {Op.getOperand(0), SrcVal});
3758 return DAG.getNode(Op.getOpcode(), DL, {Op.getValueType(), MVT::Other},
3759 {Ext.getValue(1), Ext.getValue(0)});
3760 }
3761 return DAG.getNode(Op.getOpcode(), DL, Op.getValueType(),
3762 DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, SrcVal));
3763 }
3764
3765 // Other operations are legal.
3766 return Op;
3767}
3768
3770 switch (Opc) {
3771 case ISD::FROUNDEVEN:
3773 return RISCVFPRndMode::RNE;
3774 case ISD::FTRUNC:
3775 case ISD::STRICT_FTRUNC:
3776 return RISCVFPRndMode::RTZ;
3777 case ISD::FFLOOR:
3778 case ISD::STRICT_FFLOOR:
3779 return RISCVFPRndMode::RDN;
3780 case ISD::FCEIL:
3781 case ISD::STRICT_FCEIL:
3782 return RISCVFPRndMode::RUP;
3783 case ISD::FROUND:
3784 case ISD::LROUND:
3785 case ISD::LLROUND:
3786 case ISD::STRICT_FROUND:
3787 case ISD::STRICT_LROUND:
3789 return RISCVFPRndMode::RMM;
3790 case ISD::FRINT:
3791 case ISD::LRINT:
3792 case ISD::LLRINT:
3793 case ISD::STRICT_FRINT:
3794 case ISD::STRICT_LRINT:
3795 case ISD::STRICT_LLRINT:
3796 return RISCVFPRndMode::DYN;
3797 }
3798
3800}
3801
3802// Expand vector FTRUNC, FCEIL, FFLOOR and FROUND by converting to
3803// the integer domain and back. Taking care to avoid converting values that are
3804// nan or already correct.
3805static SDValue
3807 const RISCVSubtarget &Subtarget) {
3808 MVT VT = Op.getSimpleValueType();
3809 assert(VT.isVector() && "Unexpected type");
3810
3811 SDLoc DL(Op);
3812
3813 SDValue Src = Op.getOperand(0);
3814
3815 // Freeze the source since we are increasing the number of uses.
3816 Src = DAG.getFreeze(Src);
3817
3818 MVT ContainerVT = VT;
3819 if (VT.isFixedLengthVector()) {
3822 }
3823
3824 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3825
3826 // We do the conversion on the absolute value and fix the sign at the end.
3827 SDValue Abs = DAG.getNode(RISCVISD::FABS_VL, DL, ContainerVT, Src, Mask, VL);
3828
3829 // Determine the largest integer that can be represented exactly. This and
3830 // values larger than it don't have any fractional bits so don't need to
3831 // be converted.
3832 const fltSemantics &FltSem = ContainerVT.getFltSemantics();
3833 unsigned Precision = APFloat::semanticsPrecision(FltSem);
3834 APFloat MaxVal = APFloat(FltSem);
3835 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
3836 /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
3837 SDValue MaxValNode =
3838 DAG.getConstantFP(MaxVal, DL, ContainerVT.getVectorElementType());
3839 SDValue MaxValSplat = DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, ContainerVT,
3840 DAG.getUNDEF(ContainerVT), MaxValNode, VL);
3841
3842 // If abs(Src) was larger than MaxVal or nan, keep it.
3843 MVT SetccVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3844 Mask =
3845 DAG.getNode(RISCVISD::SETCC_VL, DL, SetccVT,
3846 {Abs, MaxValSplat, DAG.getCondCode(ISD::SETOLT),
3847 Mask, Mask, VL});
3848
3849 // Truncate to integer and convert back to FP.
3850 MVT IntVT = ContainerVT.changeVectorElementTypeToInteger();
3851 MVT XLenVT = Subtarget.getXLenVT();
3852 SDValue Truncated;
3853
3854 switch (Op.getOpcode()) {
3855 default:
3856 llvm_unreachable("Unexpected opcode");
3857 case ISD::FRINT:
3858 case ISD::FCEIL:
3859 case ISD::FFLOOR:
3860 case ISD::FROUND:
3861 case ISD::FROUNDEVEN: {
3864 Truncated = DAG.getNode(RISCVISD::VFCVT_RM_X_F_VL, DL, IntVT, Src, Mask,
3865 DAG.getTargetConstant(FRM, DL, XLenVT), VL);
3866 break;
3867 }
3868 case ISD::FTRUNC:
3869 Truncated = DAG.getNode(RISCVISD::VFCVT_RTZ_X_F_VL, DL, IntVT, Src,
3870 Mask, VL);
3871 break;
3872 case ISD::FNEARBYINT:
3873 Truncated = DAG.getNode(RISCVISD::VFROUND_NOEXCEPT_VL, DL, ContainerVT, Src,
3874 Mask, VL);
3875 break;
3876 }
3877
3878 // VFROUND_NOEXCEPT_VL includes SINT_TO_FP_VL.
3879 if (Truncated.getOpcode() != RISCVISD::VFROUND_NOEXCEPT_VL)
3880 Truncated = DAG.getNode(RISCVISD::SINT_TO_FP_VL, DL, ContainerVT, Truncated,
3881 Mask, VL);
3882
3883 // Restore the original sign so that -0.0 is preserved.
3884 Truncated = DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Truncated,
3885 Src, Src, Mask, VL);
3886
3887 if (!VT.isFixedLengthVector())
3888 return Truncated;
3889
3890 return convertFromScalableVector(VT, Truncated, DAG, Subtarget);
3891}
3892
3893// Expand vector STRICT_FTRUNC, STRICT_FCEIL, STRICT_FFLOOR, STRICT_FROUND
3894// STRICT_FROUNDEVEN and STRICT_FNEARBYINT by converting sNan of the source to
3895// qNan and converting the new source to integer and back to FP.
3896static SDValue
3898 const RISCVSubtarget &Subtarget) {
3899 SDLoc DL(Op);
3900 MVT VT = Op.getSimpleValueType();
3901 SDValue Chain = Op.getOperand(0);
3902 SDValue Src = Op.getOperand(1);
3903
3904 MVT ContainerVT = VT;
3905 if (VT.isFixedLengthVector()) {
3908 }
3909
3910 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3911
3912 // Freeze the source since we are increasing the number of uses.
3913 Src = DAG.getFreeze(Src);
3914
3915 // Convert sNan to qNan by executing x + x for all unordered element x in Src.
3916 MVT MaskVT = Mask.getSimpleValueType();
3917 SDValue Unorder = DAG.getNode(RISCVISD::STRICT_FSETCC_VL, DL,
3918 DAG.getVTList(MaskVT, MVT::Other),
3919 {Chain, Src, Src, DAG.getCondCode(ISD::SETUNE),
3920 DAG.getUNDEF(MaskVT), Mask, VL});
3921 Chain = Unorder.getValue(1);
3922 Src = DAG.getNode(RISCVISD::STRICT_FADD_VL, DL,
3923 DAG.getVTList(ContainerVT, MVT::Other),
3924 {Chain, Src, Src, Src, Unorder, VL});
3925 Chain = Src.getValue(1);
3926
3927 // We do the conversion on the absolute value and fix the sign at the end.
3928 SDValue Abs = DAG.getNode(RISCVISD::FABS_VL, DL, ContainerVT, Src, Mask, VL);
3929
3930 // Determine the largest integer that can be represented exactly. This and
3931 // values larger than it don't have any fractional bits so don't need to
3932 // be converted.
3933 const fltSemantics &FltSem = ContainerVT.getFltSemantics();
3934 unsigned Precision = APFloat::semanticsPrecision(FltSem);
3935 APFloat MaxVal = APFloat(FltSem);
3936 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
3937 /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
3938 SDValue MaxValNode =
3939 DAG.getConstantFP(MaxVal, DL, ContainerVT.getVectorElementType());
3940 SDValue MaxValSplat = DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, ContainerVT,
3941 DAG.getUNDEF(ContainerVT), MaxValNode, VL);
3942
3943 // If abs(Src) was larger than MaxVal or nan, keep it.
3944 Mask = DAG.getNode(
3945 RISCVISD::SETCC_VL, DL, MaskVT,
3946 {Abs, MaxValSplat, DAG.getCondCode(ISD::SETOLT), Mask, Mask, VL});
3947
3948 // Truncate to integer and convert back to FP.
3949 MVT IntVT = ContainerVT.changeVectorElementTypeToInteger();
3950 MVT XLenVT = Subtarget.getXLenVT();
3951 SDValue Truncated;
3952
3953 switch (Op.getOpcode()) {
3954 default:
3955 llvm_unreachable("Unexpected opcode");
3956 case ISD::STRICT_FCEIL:
3957 case ISD::STRICT_FFLOOR:
3958 case ISD::STRICT_FROUND:
3962 Truncated = DAG.getNode(
3963 RISCVISD::STRICT_VFCVT_RM_X_F_VL, DL, DAG.getVTList(IntVT, MVT::Other),
3964 {Chain, Src, Mask, DAG.getTargetConstant(FRM, DL, XLenVT), VL});
3965 break;
3966 }
3967 case ISD::STRICT_FTRUNC:
3968 Truncated =
3969 DAG.getNode(RISCVISD::STRICT_VFCVT_RTZ_X_F_VL, DL,
3970 DAG.getVTList(IntVT, MVT::Other), Chain, Src, Mask, VL);
3971 break;
3973 Truncated = DAG.getNode(RISCVISD::STRICT_VFROUND_NOEXCEPT_VL, DL,
3974 DAG.getVTList(ContainerVT, MVT::Other), Chain, Src,
3975 Mask, VL);
3976 break;
3977 }
3978 Chain = Truncated.getValue(1);
3979
3980 // VFROUND_NOEXCEPT_VL includes SINT_TO_FP_VL.
3981 if (Op.getOpcode() != ISD::STRICT_FNEARBYINT) {
3982 Truncated = DAG.getNode(RISCVISD::STRICT_SINT_TO_FP_VL, DL,
3983 DAG.getVTList(ContainerVT, MVT::Other), Chain,
3984 Truncated, Mask, VL);
3985 Chain = Truncated.getValue(1);
3986 }
3987
3988 // Restore the original sign so that -0.0 is preserved.
3989 Truncated = DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Truncated,
3990 Src, Src, Mask, VL);
3991
3992 if (VT.isFixedLengthVector())
3993 Truncated = convertFromScalableVector(VT, Truncated, DAG, Subtarget);
3994 return DAG.getMergeValues({Truncated, Chain}, DL);
3995}
3996
3997static SDValue
3999 const RISCVSubtarget &Subtarget) {
4000 MVT VT = Op.getSimpleValueType();
4001 if (VT.isVector())
4003
4004 if (DAG.shouldOptForSize())
4005 return SDValue();
4006
4007 SDLoc DL(Op);
4008 SDValue Src = Op.getOperand(0);
4009
4010 // Create an integer the size of the mantissa with the MSB set. This and all
4011 // values larger than it don't have any fractional bits so don't need to be
4012 // converted.
4013 const fltSemantics &FltSem = VT.getFltSemantics();
4014 unsigned Precision = APFloat::semanticsPrecision(FltSem);
4015 APFloat MaxVal = APFloat(FltSem);
4016 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
4017 /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
4018 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
4019
4021 return DAG.getNode(RISCVISD::FROUND, DL, VT, Src, MaxValNode,
4022 DAG.getTargetConstant(FRM, DL, Subtarget.getXLenVT()));
4023}
4024
4025// Expand vector [L]LRINT and [L]LROUND by converting to the integer domain.
4027 const RISCVSubtarget &Subtarget) {
4028 SDLoc DL(Op);
4029 MVT DstVT = Op.getSimpleValueType();
4030 SDValue Src = Op.getOperand(0);
4031 MVT SrcVT = Src.getSimpleValueType();
4032 assert(SrcVT.isVector() && DstVT.isVector() &&
4033 !(SrcVT.isFixedLengthVector() ^ DstVT.isFixedLengthVector()) &&
4034 "Unexpected type");
4035
4036 MVT DstContainerVT = DstVT;
4037 MVT SrcContainerVT = SrcVT;
4038
4039 if (DstVT.isFixedLengthVector()) {
4040 DstContainerVT = getContainerForFixedLengthVector(DstVT, Subtarget);
4041 SrcContainerVT = getContainerForFixedLengthVector(SrcVT, Subtarget);
4042 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4043 }
4044
4045 auto [Mask, VL] = getDefaultVLOps(SrcVT, SrcContainerVT, DL, DAG, Subtarget);
4046
4047 // [b]f16 -> f32
4048 MVT SrcElemType = SrcVT.getVectorElementType();
4049 if (SrcElemType == MVT::f16 || SrcElemType == MVT::bf16) {
4050 MVT F32VT = SrcContainerVT.changeVectorElementType(MVT::f32);
4051 Src = DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, F32VT, Src, Mask, VL);
4052 }
4053
4054 SDValue Res =
4055 DAG.getNode(RISCVISD::VFCVT_RM_X_F_VL, DL, DstContainerVT, Src, Mask,
4056 DAG.getTargetConstant(matchRoundingOp(Op.getOpcode()), DL,
4057 Subtarget.getXLenVT()),
4058 VL);
4059
4060 if (!DstVT.isFixedLengthVector())
4061 return Res;
4062
4063 return convertFromScalableVector(DstVT, Res, DAG, Subtarget);
4064}
4065
4066static SDValue
4068 const SDLoc &DL, EVT VT, SDValue Passthru, SDValue Op,
4069 SDValue Offset, SDValue Mask, SDValue VL,
4071 if (Passthru.isUndef())
4073 SDValue PolicyOp = DAG.getTargetConstant(Policy, DL, Subtarget.getXLenVT());
4074 SDValue Ops[] = {Passthru, Op, Offset, Mask, VL, PolicyOp};
4075 return DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VT, Ops);
4076}
4077
4078static SDValue
4080 EVT VT, SDValue Passthru, SDValue Op, SDValue Offset, SDValue Mask,
4081 SDValue VL,
4083 if (Passthru.isUndef())
4085 SDValue PolicyOp = DAG.getTargetConstant(Policy, DL, Subtarget.getXLenVT());
4086 SDValue Ops[] = {Passthru, Op, Offset, Mask, VL, PolicyOp};
4087 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VT, Ops);
4088}
4089
4093 int64_t Addend;
4094};
4095
4096static std::optional<APInt> getExactInteger(const APFloat &APF,
4098 // We will use a SINT_TO_FP to materialize this constant so we should use a
4099 // signed APSInt here.
4100 APSInt ValInt(BitWidth, /*IsUnsigned*/ false);
4101 // We use an arbitrary rounding mode here. If a floating-point is an exact
4102 // integer (e.g., 1.0), the rounding mode does not affect the output value. If
4103 // the rounding mode changes the output value, then it is not an exact
4104 // integer.
4106 bool IsExact;
4107 // If it is out of signed integer range, it will return an invalid operation.
4108 // If it is not an exact integer, IsExact is false.
4109 if ((APF.convertToInteger(ValInt, ArbitraryRM, &IsExact) ==
4111 !IsExact)
4112 return std::nullopt;
4113 return ValInt.extractBits(BitWidth, 0);
4114}
4115
4116// Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
4117// to the (non-zero) step S and start value X. This can be then lowered as the
4118// RVV sequence (VID * S) + X, for example.
4119// The step S is represented as an integer numerator divided by a positive
4120// denominator. Note that the implementation currently only identifies
4121// sequences in which either the numerator is +/- 1 or the denominator is 1. It
4122// cannot detect 2/3, for example.
4123// Note that this method will also match potentially unappealing index
4124// sequences, like <i32 0, i32 50939494>, however it is left to the caller to
4125// determine whether this is worth generating code for.
4126//
4127// EltSizeInBits is the size of the type that the sequence will be calculated
4128// in, i.e. SEW for build_vectors or XLEN for address calculations.
4129static std::optional<VIDSequence> isSimpleVIDSequence(SDValue Op,
4130 unsigned EltSizeInBits) {
4131 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
4133 return std::nullopt;
4134 bool IsInteger = Op.getValueType().isInteger();
4135
4136 std::optional<unsigned> SeqStepDenom;
4137 std::optional<APInt> SeqStepNum;
4138 std::optional<APInt> SeqAddend;
4139 std::optional<std::pair<APInt, unsigned>> PrevElt;
4140 assert(EltSizeInBits >= Op.getValueType().getScalarSizeInBits());
4141
4142 // First extract the ops into a list of constant integer values. This may not
4143 // be possible for floats if they're not all representable as integers.
4144 SmallVector<std::optional<APInt>> Elts(Op.getNumOperands());
4145 const unsigned OpSize = Op.getScalarValueSizeInBits();
4146 for (auto [Idx, Elt] : enumerate(Op->op_values())) {
4147 if (Elt.isUndef()) {
4148 Elts[Idx] = std::nullopt;
4149 continue;
4150 }
4151 if (IsInteger) {
4152 Elts[Idx] = Elt->getAsAPIntVal().trunc(OpSize).zext(EltSizeInBits);
4153 } else {
4154 auto ExactInteger =
4155 getExactInteger(cast<ConstantFPSDNode>(Elt)->getValueAPF(), OpSize);
4156 if (!ExactInteger)
4157 return std::nullopt;
4158 Elts[Idx] = *ExactInteger;
4159 }
4160 }
4161
4162 for (auto [Idx, Elt] : enumerate(Elts)) {
4163 // Assume undef elements match the sequence; we just have to be careful
4164 // when interpolating across them.
4165 if (!Elt)
4166 continue;
4167
4168 if (PrevElt) {
4169 // Calculate the step since the last non-undef element, and ensure
4170 // it's consistent across the entire sequence.
4171 unsigned IdxDiff = Idx - PrevElt->second;
4172 APInt ValDiff = *Elt - PrevElt->first;
4173
4174 // A zero-value value difference means that we're somewhere in the middle
4175 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
4176 // step change before evaluating the sequence.
4177 if (ValDiff == 0)
4178 continue;
4179
4180 int64_t Remainder = ValDiff.srem(IdxDiff);
4181 // Normalize the step if it's greater than 1.
4182 if (Remainder != ValDiff.getSExtValue()) {
4183 // The difference must cleanly divide the element span.
4184 if (Remainder != 0)
4185 return std::nullopt;
4186 ValDiff = ValDiff.sdiv(IdxDiff);
4187 IdxDiff = 1;
4188 }
4189
4190 if (!SeqStepNum)
4191 SeqStepNum = ValDiff;
4192 else if (ValDiff != SeqStepNum)
4193 return std::nullopt;
4194
4195 if (!SeqStepDenom)
4196 SeqStepDenom = IdxDiff;
4197 else if (IdxDiff != *SeqStepDenom)
4198 return std::nullopt;
4199 }
4200
4201 // Record this non-undef element for later.
4202 if (!PrevElt || PrevElt->first != *Elt)
4203 PrevElt = std::make_pair(*Elt, Idx);
4204 }
4205
4206 // We need to have logged a step for this to count as a legal index sequence.
4207 if (!SeqStepNum || !SeqStepDenom)
4208 return std::nullopt;
4209
4210 // Loop back through the sequence and validate elements we might have skipped
4211 // while waiting for a valid step. While doing this, log any sequence addend.
4212 for (auto [Idx, Elt] : enumerate(Elts)) {
4213 if (!Elt)
4214 continue;
4215 APInt ExpectedVal =
4216 (APInt(EltSizeInBits, Idx, /*isSigned=*/false, /*implicitTrunc=*/true) *
4217 *SeqStepNum)
4218 .sdiv(*SeqStepDenom);
4219
4220 APInt Addend = *Elt - ExpectedVal;
4221 if (!SeqAddend)
4222 SeqAddend = Addend;
4223 else if (Addend != SeqAddend)
4224 return std::nullopt;
4225 }
4226
4227 assert(SeqAddend && "Must have an addend if we have a step");
4228
4229 return VIDSequence{SeqStepNum->getSExtValue(), *SeqStepDenom,
4230 SeqAddend->getSExtValue()};
4231}
4232
4233// Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
4234// and lower it as a VRGATHER_VX_VL from the source vector.
4235static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
4236 SelectionDAG &DAG,
4237 const RISCVSubtarget &Subtarget) {
4238 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
4239 return SDValue();
4240 SDValue Src = SplatVal.getOperand(0);
4241 // Don't perform this optimization for i1 vectors, or if the element types are
4242 // different
4243 // FIXME: Support i1 vectors, maybe by promoting to i8?
4244 MVT EltTy = VT.getVectorElementType();
4245 if (EltTy == MVT::i1 ||
4246 !DAG.getTargetLoweringInfo().isTypeLegal(Src.getValueType()))
4247 return SDValue();
4248 MVT SrcVT = Src.getSimpleValueType();
4249 if (EltTy != SrcVT.getVectorElementType())
4250 return SDValue();
4251 SDValue Idx = SplatVal.getOperand(1);
4252 // The index must be a legal type.
4253 if (Idx.getValueType() != Subtarget.getXLenVT())
4254 return SDValue();
4255
4256 // Check that we know Idx lies within VT
4257 if (!TypeSize::isKnownLE(SrcVT.getSizeInBits(), VT.getSizeInBits())) {
4258 auto *CIdx = dyn_cast<ConstantSDNode>(Idx);
4259 if (!CIdx || CIdx->getZExtValue() >= VT.getVectorMinNumElements())
4260 return SDValue();
4261 }
4262
4263 // Convert fixed length vectors to scalable
4264 MVT ContainerVT = VT;
4265 if (VT.isFixedLengthVector())
4267
4268 MVT SrcContainerVT = SrcVT;
4269 if (SrcVT.isFixedLengthVector()) {
4270 SrcContainerVT = getContainerForFixedLengthVector(SrcVT, Subtarget);
4271 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4272 }
4273
4274 // Put Vec in a VT sized vector
4275 if (SrcContainerVT.getVectorMinNumElements() <
4276 ContainerVT.getVectorMinNumElements())
4277 Src = DAG.getInsertSubvector(DL, DAG.getUNDEF(ContainerVT), Src, 0);
4278 else
4279 Src = DAG.getExtractSubvector(DL, ContainerVT, Src, 0);
4280
4281 // We checked that Idx fits inside VT earlier
4282 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4283 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Src,
4284 Idx, DAG.getUNDEF(ContainerVT), Mask, VL);
4285 if (VT.isFixedLengthVector())
4286 Gather = convertFromScalableVector(VT, Gather, DAG, Subtarget);
4287 return Gather;
4288}
4289
4291 const RISCVSubtarget &Subtarget) {
4292 MVT VT = Op.getSimpleValueType();
4293 assert(VT.isFixedLengthVector() && "Unexpected vector!");
4294
4296
4297 SDLoc DL(Op);
4298 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4299
4300 if (auto SimpleVID = isSimpleVIDSequence(Op, Op.getScalarValueSizeInBits())) {
4301 int64_t StepNumerator = SimpleVID->StepNumerator;
4302 unsigned StepDenominator = SimpleVID->StepDenominator;
4303 int64_t Addend = SimpleVID->Addend;
4304
4305 assert(StepNumerator != 0 && "Invalid step");
4306 bool Negate = false;
4307 int64_t SplatStepVal = StepNumerator;
4308 unsigned StepOpcode = ISD::MUL;
4309 // Exclude INT64_MIN to avoid passing it to std::abs. We won't optimize it
4310 // anyway as the shift of 63 won't fit in uimm5.
4311 if (StepNumerator != 1 && StepNumerator != INT64_MIN &&
4312 isPowerOf2_64(std::abs(StepNumerator))) {
4313 Negate = StepNumerator < 0;
4314 StepOpcode = ISD::SHL;
4315 SplatStepVal = Log2_64(std::abs(StepNumerator));
4316 }
4317
4318 // Only emit VIDs with suitably-small steps. We use imm5 as a threshold
4319 // since it's the immediate value many RVV instructions accept. There is
4320 // no vmul.vi instruction so ensure multiply constant can fit in a
4321 // single addi instruction. For the addend, we allow up to 32 bits..
4322 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
4323 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
4324 isPowerOf2_32(StepDenominator) &&
4325 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<32>(Addend)) {
4326 MVT VIDVT =
4328 MVT VIDContainerVT = getContainerForFixedLengthVector(VIDVT, Subtarget);
4329 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VIDContainerVT, Mask, VL);
4330 // Convert right out of the scalable type so we can use standard ISD
4331 // nodes for the rest of the computation. If we used scalable types with
4332 // these, we'd lose the fixed-length vector info and generate worse
4333 // vsetvli code.
4334 VID = convertFromScalableVector(VIDVT, VID, DAG, Subtarget);
4335 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
4336 (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
4337 SDValue SplatStep = DAG.getSignedConstant(SplatStepVal, DL, VIDVT);
4338 VID = DAG.getNode(StepOpcode, DL, VIDVT, VID, SplatStep);
4339 }
4340 if (StepDenominator != 1) {
4341 SDValue SplatStep =
4342 DAG.getConstant(Log2_64(StepDenominator), DL, VIDVT);
4343 VID = DAG.getNode(ISD::SRL, DL, VIDVT, VID, SplatStep);
4344 }
4345 if (Addend != 0 || Negate) {
4346 SDValue SplatAddend = DAG.getSignedConstant(Addend, DL, VIDVT);
4347 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VIDVT, SplatAddend,
4348 VID);
4349 }
4350 if (VT.isFloatingPoint()) {
4351 // TODO: Use vfwcvt to reduce register pressure.
4352 VID = DAG.getNode(ISD::SINT_TO_FP, DL, VT, VID);
4353 }
4354 return VID;
4355 }
4356 }
4357
4358 return SDValue();
4359}
4360
4361/// Try and optimize BUILD_VECTORs with "dominant values" - these are values
4362/// which constitute a large proportion of the elements. In such cases we can
4363/// splat a vector with the dominant element and make up the shortfall with
4364/// INSERT_VECTOR_ELTs. Returns SDValue if not profitable.
4365/// Note that this includes vectors of 2 elements by association. The
4366/// upper-most element is the "dominant" one, allowing us to use a splat to
4367/// "insert" the upper element, and an insert of the lower element at position
4368/// 0, which improves codegen.
4370 const RISCVSubtarget &Subtarget) {
4371 MVT VT = Op.getSimpleValueType();
4372 assert(VT.isFixedLengthVector() && "Unexpected vector!");
4373
4375
4376 SDLoc DL(Op);
4377 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4378
4379 MVT XLenVT = Subtarget.getXLenVT();
4380 unsigned NumElts = Op.getNumOperands();
4381
4382 SDValue DominantValue;
4383 unsigned MostCommonCount = 0;
4384 DenseMap<SDValue, unsigned> ValueCounts;
4385 unsigned NumUndefElts =
4386 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
4387
4388 // Track the number of scalar loads we know we'd be inserting, estimated as
4389 // any non-zero floating-point constant. Other kinds of element are either
4390 // already in registers or are materialized on demand. The threshold at which
4391 // a vector load is more desirable than several scalar materializion and
4392 // vector-insertion instructions is not known.
4393 unsigned NumScalarLoads = 0;
4394
4395 for (SDValue V : Op->op_values()) {
4396 if (V.isUndef())
4397 continue;
4398
4399 unsigned &Count = ValueCounts[V];
4400 if (0 == Count)
4401 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
4402 NumScalarLoads += !CFP->isPosZero();
4403
4404 // Is this value dominant? In case of a tie, prefer the highest element as
4405 // it's cheaper to insert near the beginning of a vector than it is at the
4406 // end.
4407 if (++Count >= MostCommonCount) {
4408 DominantValue = V;
4409 MostCommonCount = Count;
4410 }
4411 }
4412
4413 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
4414 unsigned NumDefElts = NumElts - NumUndefElts;
4415 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
4416
4417 // Don't perform this optimization when optimizing for size, since
4418 // materializing elements and inserting them tends to cause code bloat.
4419 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
4420 (NumElts != 2 || ISD::isBuildVectorOfConstantSDNodes(Op)) &&
4421 ((MostCommonCount > DominantValueCountThreshold) ||
4422 (ValueCounts.size() <= Log2_32(NumDefElts)))) {
4423 // Start by splatting the most common element.
4424 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
4425
4426 DenseSet<SDValue> Processed{DominantValue};
4427
4428 // We can handle an insert into the last element (of a splat) via
4429 // v(f)slide1down. This is slightly better than the vslideup insert
4430 // lowering as it avoids the need for a vector group temporary. It
4431 // is also better than using vmerge.vx as it avoids the need to
4432 // materialize the mask in a vector register.
4433 if (SDValue LastOp = Op->getOperand(Op->getNumOperands() - 1);
4434 !LastOp.isUndef() && ValueCounts[LastOp] == 1 &&
4435 LastOp != DominantValue) {
4437 auto OpCode =
4438 VT.isFloatingPoint() ? RISCVISD::VFSLIDE1DOWN_VL : RISCVISD::VSLIDE1DOWN_VL;
4439 if (!VT.isFloatingPoint())
4440 LastOp = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, LastOp);
4441 Vec = DAG.getNode(OpCode, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Vec,
4442 LastOp, Mask, VL);
4443 Vec = convertFromScalableVector(VT, Vec, DAG, Subtarget);
4444 Processed.insert(LastOp);
4445 }
4446
4447 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
4448 for (const auto &OpIdx : enumerate(Op->ops())) {
4449 const SDValue &V = OpIdx.value();
4450 if (V.isUndef() || !Processed.insert(V).second)
4451 continue;
4452 if (ValueCounts[V] == 1) {
4453 Vec = DAG.getInsertVectorElt(DL, Vec, V, OpIdx.index());
4454 } else {
4455 // Blend in all instances of this value using a VSELECT, using a
4456 // mask where each bit signals whether that element is the one
4457 // we're after.
4459 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
4460 return DAG.getConstant(V == V1, DL, XLenVT);
4461 });
4462 Vec = DAG.getNode(ISD::VSELECT, DL, VT,
4463 DAG.getBuildVector(SelMaskTy, DL, Ops),
4464 DAG.getSplatBuildVector(VT, DL, V), Vec);
4465 }
4466 }
4467
4468 return Vec;
4469 }
4470
4471 return SDValue();
4472}
4473
4475 const RISCVSubtarget &Subtarget) {
4476 MVT VT = Op.getSimpleValueType();
4477 assert(VT.isFixedLengthVector() && "Unexpected vector!");
4478
4480
4481 SDLoc DL(Op);
4482 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4483
4484 MVT XLenVT = Subtarget.getXLenVT();
4485 unsigned NumElts = Op.getNumOperands();
4486
4487 if (VT.getVectorElementType() == MVT::i1) {
4489 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
4490 return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
4491 }
4492
4494 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4495 return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
4496 }
4497
4498 // Lower constant mask BUILD_VECTORs via an integer vector type, in
4499 // scalar integer chunks whose bit-width depends on the number of mask
4500 // bits and XLEN.
4501 // First, determine the most appropriate scalar integer type to use. This
4502 // is at most XLenVT, but may be shrunk to a smaller vector element type
4503 // according to the size of the final vector - use i8 chunks rather than
4504 // XLenVT if we're producing a v8i1. This results in more consistent
4505 // codegen across RV32 and RV64.
4506 unsigned NumViaIntegerBits = std::clamp(NumElts, 8u, Subtarget.getXLen());
4507 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELen());
4508 // If we have to use more than one INSERT_VECTOR_ELT then this
4509 // optimization is likely to increase code size; avoid performing it in
4510 // such a case. We can use a load from a constant pool in this case.
4511 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
4512 return SDValue();
4513 // Now we can create our integer vector type. Note that it may be larger
4514 // than the resulting mask type: v4i1 would use v1i8 as its integer type.
4515 unsigned IntegerViaVecElts = divideCeil(NumElts, NumViaIntegerBits);
4516 MVT IntegerViaVecVT =
4517 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
4518 IntegerViaVecElts);
4519
4520 uint64_t Bits = 0;
4521 unsigned BitPos = 0, IntegerEltIdx = 0;
4522 SmallVector<SDValue, 8> Elts(IntegerViaVecElts);
4523
4524 for (unsigned I = 0; I < NumElts;) {
4525 SDValue V = Op.getOperand(I);
4526 bool BitValue = !V.isUndef() && V->getAsZExtVal();
4527 Bits |= ((uint64_t)BitValue << BitPos);
4528 ++BitPos;
4529 ++I;
4530
4531 // Once we accumulate enough bits to fill our scalar type or process the
4532 // last element, insert into our vector and clear our accumulated data.
4533 if (I % NumViaIntegerBits == 0 || I == NumElts) {
4534 if (NumViaIntegerBits <= 32)
4535 Bits = SignExtend64<32>(Bits);
4536 SDValue Elt = DAG.getSignedConstant(Bits, DL, XLenVT);
4537 Elts[IntegerEltIdx] = Elt;
4538 Bits = 0;
4539 BitPos = 0;
4540 IntegerEltIdx++;
4541 }
4542 }
4543
4544 SDValue Vec = DAG.getBuildVector(IntegerViaVecVT, DL, Elts);
4545
4546 if (NumElts < NumViaIntegerBits) {
4547 // If we're producing a smaller vector than our minimum legal integer
4548 // type, bitcast to the equivalent (known-legal) mask type, and extract
4549 // our final mask.
4550 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
4551 Vec = DAG.getBitcast(MVT::v8i1, Vec);
4552 Vec = DAG.getExtractSubvector(DL, VT, Vec, 0);
4553 } else {
4554 // Else we must have produced an integer type with the same size as the
4555 // mask type; bitcast for the final result.
4556 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
4557 Vec = DAG.getBitcast(VT, Vec);
4558 }
4559
4560 return Vec;
4561 }
4562
4564 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
4565 : RISCVISD::VMV_V_X_VL;
4566 if (!VT.isFloatingPoint())
4567 Splat = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Splat);
4568 Splat =
4570 return convertFromScalableVector(VT, Splat, DAG, Subtarget);
4571 }
4572
4573 // Try and match index sequences, which we can lower to the vid instruction
4574 // with optional modifications. An all-undef vector is matched by
4575 // getSplatValue, above.
4576 if (SDValue Res = lowerBuildVectorViaVID(Op, DAG, Subtarget))
4577 return Res;
4578
4579 // For very small build_vectors, use a single scalar insert of a constant.
4580 // TODO: Base this on constant rematerialization cost, not size.
4581 const unsigned EltBitSize = VT.getScalarSizeInBits();
4583 MVT ViaIntVT = MVT::getIntegerVT(VT.getSizeInBits());
4584 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32) &&
4585 "Unexpected sequence type");
4586 // If we can use the original VL with the modified element type, this
4587 // means we only have a VTYPE toggle, not a VL toggle. TODO: Should this
4588 // be moved into InsertVSETVLI?
4589 unsigned ViaVecLen =
4590 (Subtarget.getRealMinVLen() >= VT.getSizeInBits() * NumElts) ? NumElts : 1;
4591 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, ViaVecLen);
4592
4593 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
4594 uint64_t SplatValue = 0;
4595 // Construct the amalgamated value at this larger vector type.
4596 for (const auto &OpIdx : enumerate(Op->op_values())) {
4597 const auto &SeqV = OpIdx.value();
4598 if (!SeqV.isUndef())
4599 SplatValue |=
4600 ((SeqV->getAsZExtVal() & EltMask) << (OpIdx.index() * EltBitSize));
4601 }
4602
4603 // On RV64, sign-extend from 32 to 64 bits where possible in order to
4604 // achieve better constant materializion.
4605 // On RV32, we need to sign-extend to use getSignedConstant.
4606 if (ViaIntVT == MVT::i32)
4607 SplatValue = SignExtend64<32>(SplatValue);
4608
4609 SDValue Vec = DAG.getInsertVectorElt(
4610 DL, DAG.getUNDEF(ViaVecVT),
4611 DAG.getSignedConstant(SplatValue, DL, XLenVT), 0);
4612 if (ViaVecLen != 1)
4613 Vec = DAG.getExtractSubvector(DL, MVT::getVectorVT(ViaIntVT, 1), Vec, 0);
4614 return DAG.getBitcast(VT, Vec);
4615 }
4616
4617 // Attempt to detect "hidden" splats, which only reveal themselves as splats
4618 // when re-interpreted as a vector with a larger element type. For example,
4619 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
4620 // could be instead splat as
4621 // v2i32 = build_vector i32 0x00010000, i32 0x00010000
4622 // TODO: This optimization could also work on non-constant splats, but it
4623 // would require bit-manipulation instructions to construct the splat value.
4624 SmallVector<SDValue> Sequence;
4625 const auto *BV = cast<BuildVectorSDNode>(Op);
4626 if (VT.isInteger() && EltBitSize < Subtarget.getELen() &&
4628 BV->getRepeatedSequence(Sequence) &&
4629 (Sequence.size() * EltBitSize) <= Subtarget.getELen()) {
4630 unsigned SeqLen = Sequence.size();
4631 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
4632 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
4633 ViaIntVT == MVT::i64) &&
4634 "Unexpected sequence type");
4635
4636 // If we can use the original VL with the modified element type, this
4637 // means we only have a VTYPE toggle, not a VL toggle. TODO: Should this
4638 // be moved into InsertVSETVLI?
4639 const unsigned RequiredVL = NumElts / SeqLen;
4640 const unsigned ViaVecLen =
4641 (Subtarget.getRealMinVLen() >= ViaIntVT.getSizeInBits() * NumElts) ?
4642 NumElts : RequiredVL;
4643 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, ViaVecLen);
4644
4645 unsigned EltIdx = 0;
4646 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
4647 uint64_t SplatValue = 0;
4648 // Construct the amalgamated value which can be splatted as this larger
4649 // vector type.
4650 for (const auto &SeqV : Sequence) {
4651 if (!SeqV.isUndef())
4652 SplatValue |=
4653 ((SeqV->getAsZExtVal() & EltMask) << (EltIdx * EltBitSize));
4654 EltIdx++;
4655 }
4656
4657 // On RV64, sign-extend from 32 to 64 bits where possible in order to
4658 // achieve better constant materializion.
4659 // On RV32, we need to sign-extend to use getSignedConstant.
4660 if (ViaIntVT == MVT::i32)
4661 SplatValue = SignExtend64<32>(SplatValue);
4662
4663 // Since we can't introduce illegal i64 types at this stage, we can only
4664 // perform an i64 splat on RV32 if it is its own sign-extended value. That
4665 // way we can use RVV instructions to splat.
4666 assert((ViaIntVT.bitsLE(XLenVT) ||
4667 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
4668 "Unexpected bitcast sequence");
4669 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
4670 SDValue ViaVL =
4671 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
4672 MVT ViaContainerVT =
4674 SDValue Splat =
4675 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
4676 DAG.getUNDEF(ViaContainerVT),
4677 DAG.getSignedConstant(SplatValue, DL, XLenVT), ViaVL);
4679 if (ViaVecLen != RequiredVL)
4681 DL, MVT::getVectorVT(ViaIntVT, RequiredVL), Splat, 0);
4682 return DAG.getBitcast(VT, Splat);
4683 }
4684 }
4685
4686 // If the number of signbits allows, see if we can lower as a <N x i8>.
4687 // Our main goal here is to reduce LMUL (and thus work) required to
4688 // build the constant, but we will also narrow if the resulting
4689 // narrow vector is known to materialize cheaply.
4690 // TODO: We really should be costing the smaller vector. There are
4691 // profitable cases this misses.
4692 if (EltBitSize > 8 && VT.isInteger() &&
4693 (NumElts <= 4 || VT.getSizeInBits() > Subtarget.getRealMinVLen()) &&
4694 DAG.ComputeMaxSignificantBits(Op) <= 8) {
4695 SDValue Source = DAG.getBuildVector(VT.changeVectorElementType(MVT::i8),
4696 DL, Op->ops());
4697 Source = convertToScalableVector(ContainerVT.changeVectorElementType(MVT::i8),
4698 Source, DAG, Subtarget);
4699 SDValue Res = DAG.getNode(RISCVISD::VSEXT_VL, DL, ContainerVT, Source, Mask, VL);
4700 return convertFromScalableVector(VT, Res, DAG, Subtarget);
4701 }
4702
4704 return Res;
4705
4706 // For constant vectors, use generic constant pool lowering. Otherwise,
4707 // we'd have to materialize constants in GPRs just to move them into the
4708 // vector.
4709 return SDValue();
4710}
4711
4712static unsigned getPACKOpcode(unsigned DestBW,
4713 const RISCVSubtarget &Subtarget) {
4714 switch (DestBW) {
4715 default:
4716 llvm_unreachable("Unsupported pack size");
4717 case 16:
4718 return RISCV::PACKH;
4719 case 32:
4720 return Subtarget.is64Bit() ? RISCV::PACKW : RISCV::PACK;
4721 case 64:
4722 assert(Subtarget.is64Bit());
4723 return RISCV::PACK;
4724 }
4725}
4726
4727/// Double the element size of the build vector to reduce the number
4728/// of vslide1down in the build vector chain. In the worst case, this
4729/// trades three scalar operations for 1 vector operation. Scalar
4730/// operations are generally lower latency, and for out-of-order cores
4731/// we also benefit from additional parallelism.
4733 const RISCVSubtarget &Subtarget) {
4734 SDLoc DL(Op);
4735 MVT VT = Op.getSimpleValueType();
4736 assert(VT.isFixedLengthVector() && "Unexpected vector!");
4737 MVT ElemVT = VT.getVectorElementType();
4738 if (!ElemVT.isInteger())
4739 return SDValue();
4740
4741 // TODO: Relax these architectural restrictions, possibly with costing
4742 // of the actual instructions required.
4743 if (!Subtarget.hasStdExtZbb() || !Subtarget.hasStdExtZba())
4744 return SDValue();
4745
4746 unsigned NumElts = VT.getVectorNumElements();
4747 unsigned ElemSizeInBits = ElemVT.getSizeInBits();
4748 if (ElemSizeInBits >= std::min(Subtarget.getELen(), Subtarget.getXLen()) ||
4749 NumElts % 2 != 0)
4750 return SDValue();
4751
4752 // Produce [B,A] packed into a type twice as wide. Note that all
4753 // scalars are XLenVT, possibly masked (see below).
4754 MVT XLenVT = Subtarget.getXLenVT();
4755 SDValue Mask = DAG.getConstant(
4756 APInt::getLowBitsSet(XLenVT.getSizeInBits(), ElemSizeInBits), DL, XLenVT);
4757 auto pack = [&](SDValue A, SDValue B) {
4758 // Bias the scheduling of the inserted operations to near the
4759 // definition of the element - this tends to reduce register
4760 // pressure overall.
4761 SDLoc ElemDL(B);
4762 if (Subtarget.hasStdExtZbkb())
4763 // Note that we're relying on the high bits of the result being
4764 // don't care. For PACKW, the result is *sign* extended.
4765 return SDValue(
4766 DAG.getMachineNode(getPACKOpcode(ElemSizeInBits * 2, Subtarget),
4767 ElemDL, XLenVT, A, B),
4768 0);
4769
4770 A = DAG.getNode(ISD::AND, SDLoc(A), XLenVT, A, Mask);
4771 B = DAG.getNode(ISD::AND, SDLoc(B), XLenVT, B, Mask);
4772 SDValue ShtAmt = DAG.getConstant(ElemSizeInBits, ElemDL, XLenVT);
4773 return DAG.getNode(ISD::OR, ElemDL, XLenVT, A,
4774 DAG.getNode(ISD::SHL, ElemDL, XLenVT, B, ShtAmt),
4776 };
4777
4778 SmallVector<SDValue> NewOperands;
4779 NewOperands.reserve(NumElts / 2);
4780 for (unsigned i = 0; i < VT.getVectorNumElements(); i += 2)
4781 NewOperands.push_back(pack(Op.getOperand(i), Op.getOperand(i + 1)));
4782 assert(NumElts == NewOperands.size() * 2);
4783 MVT WideVT = MVT::getIntegerVT(ElemSizeInBits * 2);
4784 MVT WideVecVT = MVT::getVectorVT(WideVT, NumElts / 2);
4785 return DAG.getNode(ISD::BITCAST, DL, VT,
4786 DAG.getBuildVector(WideVecVT, DL, NewOperands));
4787}
4788
4789// Pack the scalars in Ops into the low elements of the XLen-sized vector VT,
4790// skipping work for undef elements. Ops.size() must be a power of 2. Each level
4791// PPAIREs the halves of Ops so that the first half supplies the even elements
4792// and the second half the odd elements of the wider element type.
4794 SelectionDAG &DAG, const SDLoc &DL) {
4795 assert(isPowerOf2_32(Ops.size()) && "Expected a power of 2 element count");
4796 auto IsUndef = [](SDValue V) { return V.isUndef(); };
4797 if (all_of(Ops, IsUndef))
4798 return DAG.getUNDEF(VT);
4799 if (Ops.size() == 1)
4800 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Ops[0]);
4801
4802 size_t N = Ops.size() / 2;
4803 SDValue Lo = buildVectorWithPPAIREs(Ops.take_front(N), VT, DAG, DL);
4804 if (all_of(Ops.drop_front(N), IsUndef))
4805 return Lo;
4806 SDValue Hi = buildVectorWithPPAIREs(Ops.drop_front(N), VT, DAG, DL);
4807
4808 // PPAIRE elements are as wide as the N scalars each operand packs.
4809 unsigned PairEltBits = VT.getScalarSizeInBits() * N;
4810 MVT PairVT = MVT::getVectorVT(MVT::getIntegerVT(PairEltBits),
4811 VT.getSizeInBits() / PairEltBits);
4812 SDValue Pair =
4813 DAG.getNode(RISCVISD::PPAIRE, DL, PairVT, DAG.getBitcast(PairVT, Lo),
4814 DAG.getBitcast(PairVT, Hi));
4815 return DAG.getBitcast(VT, Pair);
4816}
4817
4819 const RISCVSubtarget &Subtarget) {
4820 MVT VT = Op.getSimpleValueType();
4821 assert(VT.isFixedLengthVector() && "Unexpected vector!");
4822
4823 MVT EltVT = VT.getVectorElementType();
4824 MVT XLenVT = Subtarget.getXLenVT();
4825
4826 SDLoc DL(Op);
4827
4828 if (Subtarget.hasStdExtP()) {
4829 // Splats are legal; don't build them with PPAIRE/PACK.
4831 return DAG.getSplatVector(VT, DL, Splat);
4832
4833 if (Subtarget.is64Bit() || VT == MVT::v2i16) {
4834 assert((!Subtarget.is64Bit() || (VT == MVT::v4i16 || VT == MVT::v8i8)) &&
4835 "Unexpected RV64 P BUILD_VECTOR type");
4836 SmallVector<SDValue, 8> Elts(Op->op_values());
4837 return buildVectorWithPPAIREs(Elts, VT, DAG, DL);
4838 }
4839
4840 if (VT == MVT::v4i8) {
4841 // <4 x i8> BUILD_VECTOR a, b, c, d -> PACK(PPACK.DH pair(a, c), pair(b,
4842 // d))
4843 // FIXME: This is not the best lowering if the use of PPACK.DH forces the
4844 // use of MVs to make GPR pairs.
4845 SDValue Undef = DAG.getUNDEF(Op->getOperand(0).getValueType());
4846 SDValue BV1 =
4847 DAG.getBuildVector(MVT::v8i8, DL,
4848 {Op->getOperand(0), Undef, Undef, Undef,
4849 Op->getOperand(2), Undef, Undef, Undef});
4850 SDValue BV2 =
4851 DAG.getBuildVector(MVT::v8i8, DL,
4852 {Op->getOperand(1), Undef, Undef, Undef,
4853 Op->getOperand(3), Undef, Undef, Undef});
4854 SDValue PPairE = DAG.getNode(RISCVISD::PPAIRE, DL, MVT::v8i8, BV1, BV2);
4855
4856 SDValue Lo = DAG.getExtractSubvector(DL, MVT::v4i8, PPairE, 0);
4857 SDValue Hi = DAG.getExtractSubvector(DL, MVT::v4i8, PPairE, 4);
4858
4859 return DAG.getBitcast(MVT::v4i8,
4860 DAG.getNode(RISCVISD::PPAIRE, DL, MVT::v2i16,
4861 DAG.getBitcast(MVT::v2i16, Lo),
4862 DAG.getBitcast(MVT::v2i16, Hi)));
4863 }
4864
4865 if (VT == MVT::v8i8 || VT == MVT::v4i16) {
4866 // Build each 32-bit half separately and concatenate them.
4867 unsigned HalfN = VT.getVectorNumElements() / 2;
4868 MVT HalfVT = MVT::getVectorVT(EltVT, HalfN);
4869 SmallVector<SDValue, 8> Elts(Op->op_values());
4870 return DAG.getNode(
4872 buildVectorWithPPAIREs(ArrayRef(Elts).take_front(HalfN), HalfVT, DAG,
4873 DL),
4874 buildVectorWithPPAIREs(ArrayRef(Elts).drop_front(HalfN), HalfVT, DAG,
4875 DL));
4876 }
4877
4878 llvm_unreachable("Unexpected RV32 P BUILD_VECTOR type");
4879 }
4880
4881 // Proper support for f16 requires Zvfh. bf16 always requires special
4882 // handling. We need to cast the scalar to integer and create an integer
4883 // build_vector.
4884 if ((EltVT == MVT::f16 && !Subtarget.hasVInstructionsF16()) ||
4885 (EltVT == MVT::bf16 && !Subtarget.hasVInstructionsBF16())) {
4886 MVT IVT = VT.changeVectorElementType(MVT::i16);
4887 SmallVector<SDValue, 16> NewOps(Op.getNumOperands());
4888 for (const auto &[I, U] : enumerate(Op->ops())) {
4889 SDValue Elem = U.get();
4890 if ((EltVT == MVT::bf16 && Subtarget.hasStdExtZfbfmin()) ||
4891 (EltVT == MVT::f16 && Subtarget.hasStdExtZfhmin())) {
4892 // Called by LegalizeDAG, we need to use XLenVT operations since we
4893 // can't create illegal types.
4894 if (auto *C = dyn_cast<ConstantFPSDNode>(Elem)) {
4895 // Manually constant fold so the integer build_vector can be lowered
4896 // better. Waiting for DAGCombine will be too late.
4897 APInt V =
4898 C->getValueAPF().bitcastToAPInt().sext(XLenVT.getSizeInBits());
4899 NewOps[I] = DAG.getConstant(V, DL, XLenVT);
4900 } else {
4901 NewOps[I] = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Elem);
4902 }
4903 } else {
4904 // Called by scalar type legalizer, we can use i16.
4905 NewOps[I] = DAG.getBitcast(MVT::i16, Op.getOperand(I));
4906 }
4907 }
4908 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, IVT, NewOps);
4909 return DAG.getBitcast(VT, Res);
4910 }
4911
4915
4917
4918 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4919
4920 if (VT.getVectorElementType() == MVT::i1) {
4921 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
4922 // vector type, we have a legal equivalently-sized i8 type, so we can use
4923 // that.
4924 MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
4925 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
4926
4927 SDValue WideVec;
4929 // For a splat, perform a scalar truncate before creating the wider
4930 // vector.
4931 Splat = DAG.getNode(ISD::AND, DL, Splat.getValueType(), Splat,
4932 DAG.getConstant(1, DL, Splat.getValueType()));
4933 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
4934 } else {
4935 SmallVector<SDValue, 8> Ops(Op->op_values());
4936 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
4937 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
4938 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
4939 }
4940
4941 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
4942 }
4943
4945 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
4946 return Gather;
4947
4948 if (!VT.isFloatingPoint())
4949 Splat = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Splat);
4950
4951 // Prefer vmv.s.x/vfmv.s.f if legal to reduce work and register
4952 // pressure at high LMUL.
4953 bool IsScalar = all_of(Op->ops().drop_front(),
4954 [](const SDUse &U) { return U.get().isUndef(); });
4955 unsigned Opc =
4956 VT.isFloatingPoint()
4957 ? (IsScalar ? RISCVISD::VFMV_S_F_VL : RISCVISD::VFMV_V_F_VL)
4958 : (IsScalar ? RISCVISD::VMV_S_X_VL : RISCVISD::VMV_V_X_VL);
4959 Splat =
4961 return convertFromScalableVector(VT, Splat, DAG, Subtarget);
4962 }
4963
4965 return Res;
4966
4967 // If we're compiling for an exact VLEN value, we can split our work per
4968 // register in the register group.
4969 if (const auto VLen = Subtarget.getRealVLen();
4970 VLen && VT.getSizeInBits().getKnownMinValue() > *VLen) {
4971 MVT ElemVT = VT.getVectorElementType();
4972 unsigned ElemsPerVReg = *VLen / ElemVT.getFixedSizeInBits();
4974 MVT OneRegVT = MVT::getVectorVT(ElemVT, ElemsPerVReg);
4976 assert(M1VT == RISCVTargetLowering::getM1VT(M1VT));
4977
4978 // The following semantically builds up a fixed length concat_vector
4979 // of the component build_vectors. We eagerly lower to scalable and
4980 // insert_subvector here to avoid DAG combining it back to a large
4981 // build_vector.
4982 SmallVector<SDValue> BuildVectorOps(Op->ops());
4983 unsigned NumOpElts = M1VT.getVectorMinNumElements();
4984 SDValue Vec = DAG.getUNDEF(ContainerVT);
4985 for (unsigned i = 0; i < VT.getVectorNumElements(); i += ElemsPerVReg) {
4986 auto OneVRegOfOps = ArrayRef(BuildVectorOps).slice(i, ElemsPerVReg);
4987 SDValue SubBV =
4988 DAG.getNode(ISD::BUILD_VECTOR, DL, OneRegVT, OneVRegOfOps);
4989 SubBV = convertToScalableVector(M1VT, SubBV, DAG, Subtarget);
4990 unsigned InsertIdx = (i / ElemsPerVReg) * NumOpElts;
4991 Vec = DAG.getInsertSubvector(DL, Vec, SubBV, InsertIdx);
4992 }
4993 return convertFromScalableVector(VT, Vec, DAG, Subtarget);
4994 }
4995
4996 // If we're about to resort to vslide1down (or stack usage), pack our
4997 // elements into the widest scalar type we can. This will force a VL/VTYPE
4998 // toggle, but reduces the critical path, the number of vslide1down ops
4999 // required, and possibly enables scalar folds of the values.
5001 return Res;
5002
5003 // For m1 vectors, if we have non-undef values in both halves of our vector,
5004 // split the vector into low and high halves, build them separately, then
5005 // use a vselect to combine them. For long vectors, this cuts the critical
5006 // path of the vslide1down sequence in half, and gives us an opportunity
5007 // to special case each half independently. Note that we don't change the
5008 // length of the sub-vectors here, so if both fallback to the generic
5009 // vslide1down path, we should be able to fold the vselect into the final
5010 // vslidedown (for the undef tail) for the first half w/ masking.
5011 unsigned NumElts = VT.getVectorNumElements();
5012 unsigned NumUndefElts =
5013 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
5014 unsigned NumDefElts = NumElts - NumUndefElts;
5015 if (NumDefElts >= 8 && NumDefElts > NumElts / 2 &&
5017 SmallVector<SDValue> SubVecAOps, SubVecBOps;
5018 SmallVector<SDValue> MaskVals;
5019 SDValue UndefElem = DAG.getUNDEF(Op->getOperand(0)->getValueType(0));
5020 SubVecAOps.reserve(NumElts);
5021 SubVecBOps.reserve(NumElts);
5022 for (const auto &[Idx, U] : enumerate(Op->ops())) {
5023 SDValue Elem = U.get();
5024 if (Idx < NumElts / 2) {
5025 SubVecAOps.push_back(Elem);
5026 SubVecBOps.push_back(UndefElem);
5027 } else {
5028 SubVecAOps.push_back(UndefElem);
5029 SubVecBOps.push_back(Elem);
5030 }
5031 bool SelectMaskVal = (Idx < NumElts / 2);
5032 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
5033 }
5034 assert(SubVecAOps.size() == NumElts && SubVecBOps.size() == NumElts &&
5035 MaskVals.size() == NumElts);
5036
5037 SDValue SubVecA = DAG.getBuildVector(VT, DL, SubVecAOps);
5038 SDValue SubVecB = DAG.getBuildVector(VT, DL, SubVecBOps);
5039 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
5040 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
5041 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, SubVecA, SubVecB);
5042 }
5043
5044 // Cap the cost at a value linear to the number of elements in the vector.
5045 // The default lowering is to use the stack. The vector store + scalar loads
5046 // is linear in VL. However, at high lmuls vslide1down and vslidedown end up
5047 // being (at least) linear in LMUL. As a result, using the vslidedown
5048 // lowering for every element ends up being VL*LMUL..
5049 // TODO: Should we be directly costing the stack alternative? Doing so might
5050 // give us a more accurate upper bound.
5051 InstructionCost LinearBudget = VT.getVectorNumElements() * 2;
5052
5053 // TODO: unify with TTI getSlideCost.
5054 InstructionCost PerSlideCost = 1;
5056 default: break;
5057 case RISCVVType::LMUL_2:
5058 PerSlideCost = 2;
5059 break;
5060 case RISCVVType::LMUL_4:
5061 PerSlideCost = 4;
5062 break;
5063 case RISCVVType::LMUL_8:
5064 PerSlideCost = 8;
5065 break;
5066 }
5067
5068 // TODO: Should we be using the build instseq then cost + evaluate scheme
5069 // we use for integer constants here?
5070 unsigned UndefCount = 0;
5071 for (const SDValue &V : Op->ops()) {
5072 if (V.isUndef()) {
5073 UndefCount++;
5074 continue;
5075 }
5076 if (UndefCount) {
5077 LinearBudget -= PerSlideCost;
5078 UndefCount = 0;
5079 }
5080 LinearBudget -= PerSlideCost;
5081 }
5082 if (UndefCount) {
5083 LinearBudget -= PerSlideCost;
5084 }
5085
5086 if (LinearBudget < 0)
5087 return SDValue();
5088
5089 assert((!VT.isFloatingPoint() ||
5090 VT.getVectorElementType().getSizeInBits() <= Subtarget.getFLen()) &&
5091 "Illegal type which will result in reserved encoding");
5092
5093 const unsigned Policy = RISCVVType::TAIL_AGNOSTIC | RISCVVType::MASK_AGNOSTIC;
5094
5095 // General case: splat the first operand and slide other operands down one
5096 // by one to form a vector. Alternatively, if every operand is an
5097 // extraction from element 0 of a vector, we use that vector from the last
5098 // extraction as the start value and slide up instead of slide down. Such that
5099 // (1) we can avoid the initial splat (2) we can turn those vslide1up into
5100 // vslideup of 1 later and eliminate the vector to scalar movement, which is
5101 // something we cannot do with vslide1down/vslidedown.
5102 // Of course, using vslide1up/vslideup might increase the register pressure,
5103 // and that's why we conservatively limit to cases where every operand is an
5104 // extraction from the first element.
5105 SmallVector<SDValue> Operands(Op->op_begin(), Op->op_end());
5106 SDValue EVec;
5107 bool SlideUp = false;
5108 auto getVSlide = [&](EVT ContainerVT, SDValue Passthru, SDValue Vec,
5109 SDValue Offset, SDValue Mask, SDValue VL) -> SDValue {
5110 if (SlideUp)
5111 return getVSlideup(DAG, Subtarget, DL, ContainerVT, Passthru, Vec, Offset,
5112 Mask, VL, Policy);
5113 return getVSlidedown(DAG, Subtarget, DL, ContainerVT, Passthru, Vec, Offset,
5114 Mask, VL, Policy);
5115 };
5116
5117 // The reason we don't use all_of here is because we're also capturing EVec
5118 // from the last non-undef operand. If the std::execution_policy of the
5119 // underlying std::all_of is anything but std::sequenced_policy we might
5120 // capture the wrong EVec.
5121 for (SDValue V : Operands) {
5122 using namespace SDPatternMatch;
5123 SlideUp = V.isUndef() || sd_match(V, m_ExtractElt(m_Value(EVec), m_Zero()));
5124 if (!SlideUp)
5125 break;
5126 }
5127
5128 // Do not slideup if the element type of EVec is different.
5129 if (SlideUp) {
5130 MVT EVecEltVT = EVec.getSimpleValueType().getVectorElementType();
5131 MVT ContainerEltVT = ContainerVT.getVectorElementType();
5132 if (EVecEltVT != ContainerEltVT)
5133 SlideUp = false;
5134 }
5135
5136 if (SlideUp) {
5137 MVT EVecContainerVT = EVec.getSimpleValueType();
5138 // Make sure the original vector has scalable vector type.
5139 if (EVecContainerVT.isFixedLengthVector()) {
5140 EVecContainerVT =
5142 EVec = convertToScalableVector(EVecContainerVT, EVec, DAG, Subtarget);
5143 }
5144
5145 // Adapt EVec's type into ContainerVT.
5146 if (EVecContainerVT.getVectorMinNumElements() <
5147 ContainerVT.getVectorMinNumElements())
5148 EVec = DAG.getInsertSubvector(DL, DAG.getUNDEF(ContainerVT), EVec, 0);
5149 else
5150 EVec = DAG.getExtractSubvector(DL, ContainerVT, EVec, 0);
5151
5152 // Reverse the elements as we're going to slide up from the last element.
5153 std::reverse(Operands.begin(), Operands.end());
5154 }
5155
5156 SDValue Vec;
5157 UndefCount = 0;
5158 for (SDValue V : Operands) {
5159 if (V.isUndef()) {
5160 UndefCount++;
5161 continue;
5162 }
5163
5164 // Start our sequence with either a TA splat or extract source in the
5165 // hopes that hardware is able to recognize there's no dependency on the
5166 // prior value of our temporary register.
5167 if (!Vec) {
5168 if (SlideUp) {
5169 Vec = EVec;
5170 } else {
5171 Vec = DAG.getSplatVector(VT, DL, V);
5173 }
5174
5175 UndefCount = 0;
5176 continue;
5177 }
5178
5179 if (UndefCount) {
5180 const SDValue Offset = DAG.getConstant(UndefCount, DL, Subtarget.getXLenVT());
5181 Vec = getVSlide(ContainerVT, DAG.getUNDEF(ContainerVT), Vec, Offset, Mask,
5182 VL);
5183 UndefCount = 0;
5184 }
5185
5186 unsigned Opcode;
5187 if (VT.isFloatingPoint())
5188 Opcode = SlideUp ? RISCVISD::VFSLIDE1UP_VL : RISCVISD::VFSLIDE1DOWN_VL;
5189 else
5190 Opcode = SlideUp ? RISCVISD::VSLIDE1UP_VL : RISCVISD::VSLIDE1DOWN_VL;
5191
5192 if (!VT.isFloatingPoint())
5193 V = DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), V);
5194 Vec = DAG.getNode(Opcode, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Vec,
5195 V, Mask, VL);
5196 }
5197 if (UndefCount) {
5198 const SDValue Offset = DAG.getConstant(UndefCount, DL, Subtarget.getXLenVT());
5199 Vec = getVSlide(ContainerVT, DAG.getUNDEF(ContainerVT), Vec, Offset, Mask,
5200 VL);
5201 }
5202 return convertFromScalableVector(VT, Vec, DAG, Subtarget);
5203}
5204
5205static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
5207 SelectionDAG &DAG) {
5208 if (!Passthru)
5209 Passthru = DAG.getUNDEF(VT);
5211 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
5212 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
5213 // If Hi constant is all the same sign bit as Lo, lower this as a custom
5214 // node in order to try and match RVV vector/scalar instructions.
5215 if ((LoC >> 31) == HiC)
5216 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
5217
5218 // Use vmv.v.x with EEW=32. Use either a vsetivli or vsetvli to change
5219 // VL. This can temporarily increase VL if VL less than VLMAX.
5220 if (LoC == HiC && Passthru.isUndef()) {
5221 SDValue NewVL;
5222 if (isa<ConstantSDNode>(VL) && isUInt<4>(VL->getAsZExtVal()))
5223 NewVL = DAG.getNode(ISD::ADD, DL, VL.getValueType(), VL, VL);
5224 else
5225 NewVL = DAG.getRegister(RISCV::X0, MVT::i32);
5226 MVT InterVT =
5227 MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
5228 auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT,
5229 DAG.getUNDEF(InterVT), Lo, NewVL);
5230 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
5231 }
5232 }
5233
5234 // With identical nonconstant halves and undefined passthru, use vmv.v.x
5235 // with EEW=32. Double small constant VLs; otherwise use VLMAX.
5236 if (!isa<ConstantSDNode>(Lo) && Lo == Hi && Passthru.isUndef()) {
5237 SDValue NewVL;
5238 if (isa<ConstantSDNode>(VL) && isUInt<4>(VL->getAsZExtVal()))
5239 NewVL = DAG.getNode(ISD::ADD, DL, VL.getValueType(), VL, VL);
5240 else
5241 NewVL = DAG.getRegister(RISCV::X0, MVT::i32);
5242
5243 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
5244 SDValue InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT,
5245 DAG.getUNDEF(InterVT), Lo, NewVL);
5246 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
5247 }
5248
5249 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
5250 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
5251 isa<ConstantSDNode>(Hi.getOperand(1)) &&
5252 Hi.getConstantOperandVal(1) == 31)
5253 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
5254
5255 // If the hi bits of the splat are undefined, then it's fine to just splat Lo
5256 // even if it might be sign extended.
5257 if (Hi.isUndef())
5258 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
5259
5260 // Fall back to a stack store and stride x0 vector load.
5261 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
5262 Hi, VL);
5263}
5264
5265// Called by type legalization to handle splat of i64 on RV32.
5266// FIXME: We can optimize this when the type has sign or zero bits in one
5267// of the halves.
5268static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
5270 SelectionDAG &DAG) {
5271 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
5272 SDValue Lo, Hi;
5273 std::tie(Lo, Hi) = DAG.SplitScalar(Scalar, DL, MVT::i32, MVT::i32);
5274 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
5275}
5276
5277// This function lowers a splat of a scalar operand Splat with the vector
5278// length VL. It ensures the final sequence is type legal, which is useful when
5279// lowering a splat after type legalization.
5281 MVT VT, const SDLoc &DL, SelectionDAG &DAG,
5282 const RISCVSubtarget &Subtarget) {
5283 bool HasPassthru = Passthru && !Passthru.isUndef();
5284 if (!HasPassthru && !Passthru)
5285 Passthru = DAG.getUNDEF(VT);
5286
5287 MVT EltVT = VT.getVectorElementType();
5288 MVT XLenVT = Subtarget.getXLenVT();
5289
5290 if (VT.isFloatingPoint()) {
5291 if ((EltVT == MVT::f16 && !Subtarget.hasVInstructionsF16()) ||
5292 (EltVT == MVT::bf16 && !Subtarget.hasVInstructionsBF16())) {
5293 if ((EltVT == MVT::bf16 && Subtarget.hasStdExtZfbfmin()) ||
5294 (EltVT == MVT::f16 && Subtarget.hasStdExtZfhmin()))
5295 Scalar = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Scalar);
5296 else
5297 Scalar = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Scalar);
5298 MVT IVT = VT.changeVectorElementType(MVT::i16);
5299 Passthru = DAG.getNode(ISD::BITCAST, DL, IVT, Passthru);
5300 SDValue Splat =
5301 lowerScalarSplat(Passthru, Scalar, VL, IVT, DL, DAG, Subtarget);
5302 return DAG.getNode(ISD::BITCAST, DL, VT, Splat);
5303 }
5304 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
5305 }
5306
5307 // Simplest case is that the operand needs to be promoted to XLenVT.
5308 if (Scalar.getValueType().bitsLE(XLenVT)) {
5309 // If the operand is a constant, sign extend to increase our chances
5310 // of being able to use a .vi instruction. ANY_EXTEND would become a
5311 // a zero extend and the simm5 check in isel would fail.
5312 // FIXME: Should we ignore the upper bits in isel instead?
5313 unsigned ExtOpc =
5315 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
5316 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
5317 }
5318
5319 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
5320 "Unexpected scalar for splat lowering!");
5321
5323 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
5324 DAG.getConstant(0, DL, XLenVT), VL);
5325
5326 // Otherwise use the more complicated splatting algorithm.
5327 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
5328}
5329
5330// This function lowers an insert of a scalar operand Scalar into lane
5331// 0 of the vector regardless of the value of VL. The contents of the
5332// remaining lanes of the result vector are unspecified. VL is assumed
5333// to be non-zero.
5335 const SDLoc &DL, SelectionDAG &DAG,
5336 const RISCVSubtarget &Subtarget) {
5337 assert(VT.isScalableVector() && "Expect VT is scalable vector type.");
5338
5339 const MVT XLenVT = Subtarget.getXLenVT();
5340 SDValue Passthru = DAG.getUNDEF(VT);
5341
5342 if (Scalar.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5343 isNullConstant(Scalar.getOperand(1))) {
5344 SDValue ExtractedVal = Scalar.getOperand(0);
5345 // The element types must be the same.
5346 if (ExtractedVal.getValueType().getVectorElementType() ==
5347 VT.getVectorElementType()) {
5348 MVT ExtractedVT = ExtractedVal.getSimpleValueType();
5349 MVT ExtractedContainerVT = ExtractedVT;
5350 if (ExtractedContainerVT.isFixedLengthVector()) {
5351 ExtractedContainerVT =
5352 getContainerForFixedLengthVector(ExtractedContainerVT, Subtarget);
5353 ExtractedVal = convertToScalableVector(ExtractedContainerVT,
5354 ExtractedVal, DAG, Subtarget);
5355 }
5356 if (ExtractedContainerVT.bitsLE(VT))
5357 return DAG.getInsertSubvector(DL, Passthru, ExtractedVal, 0);
5358 return DAG.getExtractSubvector(DL, VT, ExtractedVal, 0);
5359 }
5360 }
5361
5362 if (VT.isFloatingPoint())
5363 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
5364 VL);
5365
5366 // Avoid the tricky legalization cases by falling back to using the
5367 // splat code which already handles it gracefully.
5368 if (!Scalar.getValueType().bitsLE(XLenVT))
5369 return lowerScalarSplat(DAG.getUNDEF(VT), Scalar,
5370 DAG.getConstant(1, DL, XLenVT),
5371 VT, DL, DAG, Subtarget);
5372
5373 // If the operand is a constant, sign extend to increase our chances
5374 // of being able to use a .vi instruction. ANY_EXTEND would become a
5375 // a zero extend and the simm5 check in isel would fail.
5376 // FIXME: Should we ignore the upper bits in isel instead?
5377 unsigned ExtOpc =
5379 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
5380 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
5381 VL);
5382}
5383
5384/// If concat_vector(V1,V2) could be folded away to some existing
5385/// vector source, return it. Note that the source may be larger
5386/// than the requested concat_vector (i.e. a extract_subvector
5387/// might be required.)
5389 EVT VT = V1.getValueType();
5390 assert(VT == V2.getValueType() && "argument types must match");
5391 // Both input must be extracts.
5392 if (V1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
5394 return SDValue();
5395
5396 // Extracting from the same source.
5397 SDValue Src = V1.getOperand(0);
5398 if (Src != V2.getOperand(0) ||
5399 VT.isScalableVector() != Src.getValueType().isScalableVector())
5400 return SDValue();
5401
5402 // The extracts must extract the two halves of the source.
5403 if (V1.getConstantOperandVal(1) != 0 ||
5405 return SDValue();
5406
5407 return Src;
5408}
5409
5410// Can this shuffle be performed on exactly one (possibly larger) input?
5412
5413 if (V2.isUndef())
5414 return V1;
5415
5416 unsigned NumElts = VT.getVectorNumElements();
5417 // Src needs to have twice the number of elements.
5418 // TODO: Update shuffle lowering to add the extract subvector
5419 if (SDValue Src = foldConcatVector(V1, V2);
5420 Src && Src.getValueType().getVectorNumElements() == (NumElts * 2))
5421 return Src;
5422
5423 return SDValue();
5424}
5425
5427 assert(ContainerVT.isScalableVector() && "Expected scalable vector type");
5428 unsigned MinSize = ContainerVT.getSizeInBits().getKnownMinValue();
5429 assert(isPowerOf2_32(MinSize) && MinSize >= 8 && MinSize <= 512 &&
5430 "Unexpected LMUL");
5431 return MinSize / (RISCV::RVVBitsPerBlock / 8);
5432}
5433
5434static bool
5441
5442static bool
5444 MVT ContainerVT = VT;
5445 if (VT.isFixedLengthVector()) {
5446 // VT is the interleaved result type, but lowerZvzipVZIP maps each
5447 // half-sized input to a scalable container before doubling that container
5448 // for the result. Mirror that order here because the minimum scalable
5449 // container size means mapping VT directly is not necessarily equivalent.
5450 // For example, interleaving two <2 x i32> inputs at VLEN=128 requires an
5451 // m2 result container, while mapping the <4 x i32> result directly yields
5452 // m1.
5455 ContainerVT = ContainerVT.getDoubleNumVectorElementsVT();
5456 }
5457 unsigned EltBits = VT.getScalarSizeInBits();
5458 unsigned LMULOctuple = getLMULOctuple(ContainerVT);
5459 // Perform 2 * SEW <= LMUL * min(ELEN, VLEN) check.
5460 return EltBits * 16 <= LMULOctuple * std::min(Subtarget.getELen(),
5461 Subtarget.getRealMinVLen());
5462}
5463
5464/// Is this shuffle interleaving contiguous elements from one vector into the
5465/// even elements and contiguous elements from another vector into the odd
5466/// elements. \p EvenSrc will contain the element that should be in the first
5467/// even element. \p OddSrc will contain the element that should be in the first
5468/// odd element. These can be the first element in a source or the element half
5469/// way through the source.
5470static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, int &EvenSrc,
5471 int &OddSrc, const RISCVSubtarget &Subtarget) {
5472 // We need to be able to widen elements to the next larger integer type or
5473 // use the vzip instruction at e64.
5474 if (VT.getScalarSizeInBits() >= Subtarget.getELen()) {
5475 if (!Subtarget.hasStdExtZvzip())
5476 return false;
5478 return false;
5479 }
5480
5481 int Size = Mask.size();
5482 int NumElts = VT.getVectorNumElements();
5483 assert(Size == (int)NumElts && "Unexpected mask size");
5484
5485 SmallVector<unsigned, 2> StartIndexes;
5486 if (!ShuffleVectorInst::isInterleaveMask(Mask, 2, Size * 2, StartIndexes))
5487 return false;
5488
5489 EvenSrc = StartIndexes[0];
5490 OddSrc = StartIndexes[1];
5491
5492 // One source should be low half of first vector.
5493 if (EvenSrc != 0 && OddSrc != 0)
5494 return false;
5495
5496 // Subvectors will be subtracted from either at the start of the two input
5497 // vectors, or at the start and middle of the first vector if it's an unary
5498 // interleave.
5499 // In both cases, HalfNumElts will be extracted.
5500 // We need to ensure that the extract indices are 0 or HalfNumElts otherwise
5501 // we'll create an illegal extract_subvector.
5502 // FIXME: We could support other values using a slidedown first.
5503 int HalfNumElts = NumElts / 2;
5504 return ((EvenSrc % HalfNumElts) == 0) && ((OddSrc % HalfNumElts) == 0);
5505}
5506
5507/// Is this mask representing a masked combination of two slides?
5509 std::array<std::pair<int, int>, 2> &SrcInfo) {
5510 if (!llvm::isMaskedSlidePair(Mask, Mask.size(), SrcInfo))
5511 return false;
5512
5513 // Avoid matching vselect idioms
5514 if (SrcInfo[0].second == 0 && SrcInfo[1].second == 0)
5515 return false;
5516 // Prefer vslideup as the second instruction, and identity
5517 // only as the initial instruction.
5518 if ((SrcInfo[0].second > 0 && SrcInfo[1].second < 0) ||
5519 SrcInfo[1].second == 0)
5520 std::swap(SrcInfo[0], SrcInfo[1]);
5521 assert(SrcInfo[0].first != -1 && "Must find one slide");
5522 return true;
5523}
5524
5525// Exactly matches the semantics of a previously existing custom matcher
5526// to allow migration to new matcher without changing output.
5527static bool isElementRotate(const std::array<std::pair<int, int>, 2> &SrcInfo,
5528 unsigned NumElts) {
5529 if (SrcInfo[1].first == -1)
5530 return true;
5531 return SrcInfo[0].second < 0 && SrcInfo[1].second > 0 &&
5532 SrcInfo[1].second - SrcInfo[0].second == (int)NumElts;
5533}
5534
5535// Lower a deinterleave shuffle to SRL and TRUNC. Factor must be
5536// 2, 4, 8 and the integer type Factor-times larger than VT's
5537// element type must be a legal element type.
5538// [a, p, b, q, c, r, d, s] -> [a, b, c, d] (Factor=2, Index=0)
5539// -> [p, q, r, s] (Factor=2, Index=1)
5541 SDValue Src, unsigned Factor,
5542 unsigned Index, SelectionDAG &DAG) {
5543 unsigned EltBits = VT.getScalarSizeInBits();
5544 ElementCount SrcEC = Src.getValueType().getVectorElementCount();
5545 MVT WideSrcVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Factor),
5546 SrcEC.divideCoefficientBy(Factor));
5547 MVT ResVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits),
5548 SrcEC.divideCoefficientBy(Factor));
5549 Src = DAG.getBitcast(WideSrcVT, Src);
5550
5551 unsigned Shift = Index * EltBits;
5552 SDValue Res = DAG.getNode(ISD::SRL, DL, WideSrcVT, Src,
5553 DAG.getConstant(Shift, DL, WideSrcVT));
5554 Res = DAG.getNode(ISD::TRUNCATE, DL, ResVT, Res);
5556 Res = DAG.getBitcast(CastVT, Res);
5557 return DAG.getInsertSubvector(DL, DAG.getUNDEF(VT), Res, 0);
5558}
5559
5560/// Match a single source shuffle which is an identity except that some
5561/// particular element is repeated. This can be lowered as a masked
5562/// vrgather.vi/vx. Note that the two source form of this is handled
5563/// by the recursive splitting logic and doesn't need special handling.
5566 SelectionDAG &DAG) {
5567
5568 SDLoc DL(SVN);
5569 MVT VT = SVN->getSimpleValueType(0);
5570 SDValue V1 = SVN->getOperand(0);
5571 assert(SVN->getOperand(1).isUndef());
5572 ArrayRef<int> Mask = SVN->getMask();
5573 const unsigned NumElts = VT.getVectorNumElements();
5574 MVT XLenVT = Subtarget.getXLenVT();
5575
5576 std::optional<int> SplatIdx;
5577 for (auto [I, M] : enumerate(Mask)) {
5578 if (M == -1 || I == (unsigned)M)
5579 continue;
5580 if (SplatIdx && *SplatIdx != M)
5581 return SDValue();
5582 SplatIdx = M;
5583 }
5584
5585 if (!SplatIdx)
5586 return SDValue();
5587
5588 SmallVector<SDValue> MaskVals;
5589 for (int MaskIndex : Mask) {
5590 bool SelectMaskVal = MaskIndex == *SplatIdx;
5591 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
5592 }
5593 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
5594 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
5595 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
5596 SDValue Splat = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT),
5597 SmallVector<int>(NumElts, *SplatIdx));
5598 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, Splat, V1);
5599}
5600
5601// Lower the following shuffle to vslidedown.
5602// a)
5603// t49: v8i8 = extract_subvector t13, Constant:i64<0>
5604// t109: v8i8 = extract_subvector t13, Constant:i64<8>
5605// t108: v8i8 = vector_shuffle<1,2,3,4,5,6,7,8> t49, t106
5606// b)
5607// t69: v16i16 = extract_subvector t68, Constant:i64<0>
5608// t23: v8i16 = extract_subvector t69, Constant:i64<0>
5609// t29: v4i16 = extract_subvector t23, Constant:i64<4>
5610// t26: v8i16 = extract_subvector t69, Constant:i64<8>
5611// t30: v4i16 = extract_subvector t26, Constant:i64<0>
5612// t54: v4i16 = vector_shuffle<1,2,3,4> t29, t30
5614 SDValue V1, SDValue V2,
5615 ArrayRef<int> Mask,
5617 SelectionDAG &DAG) {
5618 auto findNonEXTRACT_SUBVECTORParent =
5619 [](SDValue Parent) -> std::pair<SDValue, uint64_t> {
5620 uint64_t Offset = 0;
5621 while (Parent.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5622 // EXTRACT_SUBVECTOR can be used to extract a fixed-width vector from
5623 // a scalable vector. But we don't want to match the case.
5624 Parent.getOperand(0).getSimpleValueType().isFixedLengthVector()) {
5625 Offset += Parent.getConstantOperandVal(1);
5626 Parent = Parent.getOperand(0);
5627 }
5628 return std::make_pair(Parent, Offset);
5629 };
5630
5631 auto [V1Src, V1IndexOffset] = findNonEXTRACT_SUBVECTORParent(V1);
5632 auto [V2Src, V2IndexOffset] = findNonEXTRACT_SUBVECTORParent(V2);
5633
5634 // Extracting from the same source.
5635 SDValue Src = V1Src;
5636 if (Src != V2Src)
5637 return SDValue();
5638
5639 // Rebuild mask because Src may be from multiple EXTRACT_SUBVECTORs.
5640 SmallVector<int, 16> NewMask(Mask);
5641 for (size_t i = 0; i != NewMask.size(); ++i) {
5642 if (NewMask[i] == -1)
5643 continue;
5644
5645 if (static_cast<size_t>(NewMask[i]) < NewMask.size()) {
5646 NewMask[i] = NewMask[i] + V1IndexOffset;
5647 } else {
5648 // Minus NewMask.size() is needed. Otherwise, the b case would be
5649 // <5,6,7,12> instead of <5,6,7,8>.
5650 NewMask[i] = NewMask[i] - NewMask.size() + V2IndexOffset;
5651 }
5652 }
5653
5654 // First index must be known and non-zero. It will be used as the slidedown
5655 // amount.
5656 if (NewMask[0] <= 0)
5657 return SDValue();
5658
5659 // NewMask is also continuous.
5660 for (unsigned i = 1; i != NewMask.size(); ++i)
5661 if (NewMask[i - 1] + 1 != NewMask[i])
5662 return SDValue();
5663
5664 MVT XLenVT = Subtarget.getXLenVT();
5665 MVT SrcVT = Src.getSimpleValueType();
5667 auto [TrueMask, VL] = getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
5668 SDValue Slidedown =
5671 DAG.getConstant(NewMask[0], DL, XLenVT), TrueMask, VL);
5672 return DAG.getExtractSubvector(
5673 DL, VT, convertFromScalableVector(SrcVT, Slidedown, DAG, Subtarget), 0);
5674}
5675
5676// Because vslideup leaves the destination elements at the start intact, we can
5677// use it to perform shuffles that insert subvectors:
5678//
5679// vector_shuffle v8:v8i8, v9:v8i8, <0, 1, 2, 3, 8, 9, 10, 11>
5680// ->
5681// vsetvli zero, 8, e8, mf2, ta, ma
5682// vslideup.vi v8, v9, 4
5683//
5684// vector_shuffle v8:v8i8, v9:v8i8 <0, 1, 8, 9, 10, 5, 6, 7>
5685// ->
5686// vsetvli zero, 5, e8, mf2, tu, ma
5687// vslideup.v1 v8, v9, 2
5689 SDValue V1, SDValue V2,
5690 ArrayRef<int> Mask,
5692 SelectionDAG &DAG) {
5693 unsigned NumElts = VT.getVectorNumElements();
5694 int NumSubElts, Index;
5695 if (!ShuffleVectorInst::isInsertSubvectorMask(Mask, NumElts, NumSubElts,
5696 Index))
5697 return SDValue();
5698
5699 bool OpsSwapped = Mask[Index] < (int)NumElts;
5700 SDValue InPlace = OpsSwapped ? V2 : V1;
5701 SDValue ToInsert = OpsSwapped ? V1 : V2;
5702
5703 MVT XLenVT = Subtarget.getXLenVT();
5705 auto TrueMask = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).first;
5706 // We slide up by the index that the subvector is being inserted at, and set
5707 // VL to the index + the number of elements being inserted.
5708 unsigned Policy =
5710 // If the we're adding a suffix to the in place vector, i.e. inserting right
5711 // up to the very end of it, then we don't actually care about the tail.
5712 if (NumSubElts + Index >= (int)NumElts)
5713 Policy |= RISCVVType::TAIL_AGNOSTIC;
5714
5715 InPlace = convertToScalableVector(ContainerVT, InPlace, DAG, Subtarget);
5716 ToInsert = convertToScalableVector(ContainerVT, ToInsert, DAG, Subtarget);
5717 SDValue VL = DAG.getConstant(NumSubElts + Index, DL, XLenVT);
5718
5719 SDValue Res;
5720 // If we're inserting into the lowest elements, use a tail undisturbed
5721 // vmv.v.v.
5722 if (Index == 0)
5723 Res = DAG.getNode(RISCVISD::VMV_V_V_VL, DL, ContainerVT, InPlace, ToInsert,
5724 VL);
5725 else
5726 Res = getVSlideup(DAG, Subtarget, DL, ContainerVT, InPlace, ToInsert,
5727 DAG.getConstant(Index, DL, XLenVT), TrueMask, VL, Policy);
5728 return convertFromScalableVector(VT, Res, DAG, Subtarget);
5729}
5730
5731// A shuffle of shuffles where the final data only is drawn from 2 input ops
5732// can be compressed into a single shuffle
5735 SelectionDAG &DAG) {
5736 SDValue V1 = SVN->getOperand(0);
5737 SDValue V2 = SVN->getOperand(1);
5738
5739 if (V1.getOpcode() != ISD::VECTOR_SHUFFLE ||
5741 return SDValue();
5742
5743 if (!V1.hasOneUse() || !V2.hasOneUse())
5744 return SDValue();
5745
5746 ArrayRef<int> Mask = SVN->getMask();
5747 ArrayRef<int> V1Mask = cast<ShuffleVectorSDNode>(V1.getNode())->getMask();
5748 ArrayRef<int> V2Mask = cast<ShuffleVectorSDNode>(V2.getNode())->getMask();
5749 unsigned NumElts = Mask.size();
5750 SmallVector<int> NewMask(NumElts, -1);
5751 for (unsigned Idx : seq<unsigned>(NumElts)) {
5752 int Lane = Mask[Idx];
5753 // Don't assign if poison
5754 if (Lane == -1)
5755 continue;
5756 int OrigLane;
5757 bool SecondOp = false;
5758 if ((unsigned)Lane < NumElts) {
5759 OrigLane = V1Mask[Lane];
5760 } else {
5761 OrigLane = V2Mask[Lane - NumElts];
5762 SecondOp = true;
5763 }
5764 if (OrigLane == -1)
5765 continue;
5766 // Don't handle if shuffling from a second operand
5767 if ((unsigned)OrigLane >= NumElts)
5768 return SDValue();
5769 if (SecondOp)
5770 OrigLane += NumElts;
5771 NewMask[Idx] = OrigLane;
5772 }
5773
5774 EVT VT = SVN->getValueType(0);
5775 SDLoc DL(SVN);
5776
5777 return DAG.getVectorShuffle(VT, DL, V1->getOperand(0), V2->getOperand(0),
5778 NewMask);
5779}
5780
5781/// Match v(f)slide1up/down idioms. These operations involve sliding
5782/// N-1 elements to make room for an inserted scalar at one end.
5784 SDValue V1, SDValue V2,
5785 ArrayRef<int> Mask,
5787 SelectionDAG &DAG) {
5788 bool OpsSwapped = false;
5789 if (!isa<BuildVectorSDNode>(V1)) {
5790 if (!isa<BuildVectorSDNode>(V2))
5791 return SDValue();
5792 std::swap(V1, V2);
5793 OpsSwapped = true;
5794 }
5795 SDValue Splat = cast<BuildVectorSDNode>(V1)->getSplatValue();
5796 if (!Splat)
5797 return SDValue();
5798
5799 // Return true if the mask could describe a slide of Mask.size() - 1
5800 // elements from concat_vector(V1, V2)[Base:] to [Offset:].
5801 auto isSlideMask = [](ArrayRef<int> Mask, unsigned Base, int Offset) {
5802 const unsigned S = (Offset > 0) ? 0 : -Offset;
5803 const unsigned E = Mask.size() - ((Offset > 0) ? Offset : 0);
5804 for (unsigned i = S; i != E; ++i)
5805 if (Mask[i] >= 0 && (unsigned)Mask[i] != Base + i + Offset)
5806 return false;
5807 return true;
5808 };
5809
5810 const unsigned NumElts = VT.getVectorNumElements();
5811 bool IsVSlidedown = isSlideMask(Mask, OpsSwapped ? 0 : NumElts, 1);
5812 if (!IsVSlidedown && !isSlideMask(Mask, OpsSwapped ? 0 : NumElts, -1))
5813 return SDValue();
5814
5815 const int InsertIdx = Mask[IsVSlidedown ? (NumElts - 1) : 0];
5816 // Inserted lane must come from splat, undef scalar is legal but not profitable.
5817 if (InsertIdx < 0 || InsertIdx / NumElts != (unsigned)OpsSwapped)
5818 return SDValue();
5819
5821 auto [TrueMask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5822
5823 // zvfhmin and zvfbfmin don't have vfslide1{down,up}.vf so use fmv.x.h +
5824 // vslide1{down,up}.vx instead.
5825 if ((VT.getVectorElementType() == MVT::bf16 &&
5826 !Subtarget.hasVInstructionsBF16()) ||
5827 (VT.getVectorElementType() == MVT::f16 &&
5828 !Subtarget.hasVInstructionsF16())) {
5829 MVT IntVT = ContainerVT.changeVectorElementTypeToInteger();
5830 Splat =
5831 DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, Subtarget.getXLenVT(), Splat);
5832 V2 = DAG.getBitcast(
5834 SDValue Vec = DAG.getNode(
5835 IsVSlidedown ? RISCVISD::VSLIDE1DOWN_VL : RISCVISD::VSLIDE1UP_VL, DL,
5836 IntVT, DAG.getUNDEF(IntVT), V2, Splat, TrueMask, VL);
5837 Vec = DAG.getBitcast(ContainerVT, Vec);
5838 return convertFromScalableVector(VT, Vec, DAG, Subtarget);
5839 }
5840
5841 auto OpCode = IsVSlidedown ?
5842 (VT.isFloatingPoint() ? RISCVISD::VFSLIDE1DOWN_VL : RISCVISD::VSLIDE1DOWN_VL) :
5843 (VT.isFloatingPoint() ? RISCVISD::VFSLIDE1UP_VL : RISCVISD::VSLIDE1UP_VL);
5844 if (!VT.isFloatingPoint())
5845 Splat = DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), Splat);
5846 auto Vec = DAG.getNode(OpCode, DL, ContainerVT,
5847 DAG.getUNDEF(ContainerVT),
5849 Splat, TrueMask, VL);
5850 return convertFromScalableVector(VT, Vec, DAG, Subtarget);
5851}
5852
5853/// Match a mask which "spreads" the leading elements of a vector evenly
5854/// across the result. Factor is the spread amount, and Index is the
5855/// offset applied. (on success, Index < Factor) This is the inverse
5856/// of a deinterleave with the same Factor and Index. This is analogous
5857/// to an interleave, except that all but one lane is undef.
5859 unsigned &Index) {
5860 SmallVector<bool> LaneIsUndef(Factor, true);
5861 for (unsigned i = 0; i < Mask.size(); i++)
5862 LaneIsUndef[i % Factor] &= (Mask[i] == -1);
5863
5864 bool Found = false;
5865 for (unsigned i = 0; i < Factor; i++) {
5866 if (LaneIsUndef[i])
5867 continue;
5868 if (Found)
5869 return false;
5870 Index = i;
5871 Found = true;
5872 }
5873 if (!Found)
5874 return false;
5875
5876 for (unsigned i = 0; i < Mask.size() / Factor; i++) {
5877 unsigned j = i * Factor + Index;
5878 if (Mask[j] != -1 && (unsigned)Mask[j] != i)
5879 return false;
5880 }
5881 return true;
5882}
5883
5884static SDValue lowerZvzipVPAIR(unsigned Opc, SDValue Op0, SDValue Op1,
5885 const SDLoc &DL, SelectionDAG &DAG,
5886 const RISCVSubtarget &Subtarget) {
5887 assert(RISCVISD::VPAIRE_VL == Opc || RISCVISD::VPAIRO_VL == Opc);
5889
5890 MVT VT = Op0.getSimpleValueType();
5892 Op0 = DAG.getBitcast(IntVT, Op0);
5893 Op1 = DAG.getBitcast(IntVT, Op1);
5894
5895 MVT ContainerVT = IntVT;
5896 if (VT.isFixedLengthVector()) {
5900 }
5901
5902 MVT InnerVT = ContainerVT;
5903 auto [Mask, VL] = getDefaultVLOps(IntVT, InnerVT, DL, DAG, Subtarget);
5904
5905 SDValue Passthru = DAG.getUNDEF(InnerVT);
5906 SDValue Res = DAG.getNode(Opc, DL, InnerVT, Op0, Op1, Passthru, Mask, VL);
5907 if (IntVT.isFixedLengthVector())
5908 Res = convertFromScalableVector(IntVT, Res, DAG, Subtarget);
5909 Res = DAG.getBitcast(VT, Res);
5910 return Res;
5911}
5912
5914 SelectionDAG &DAG,
5915 const RISCVSubtarget &Subtarget) {
5917 MVT VT = Op0.getSimpleValueType();
5919 Op0 = DAG.getBitcast(IntVT, Op0);
5920 Op1 = DAG.getBitcast(IntVT, Op1);
5921 MVT ContainerVT = IntVT;
5922 if (VT.isFixedLengthVector()) {
5926 }
5927 MVT ResVT = ContainerVT.getDoubleNumVectorElementsVT();
5928 MVT ResIntVT = IntVT.getDoubleNumVectorElementsVT();
5929 auto [Mask, VL] = getDefaultVLOps(ResIntVT, ResVT, DL, DAG, Subtarget);
5930 SDValue Passthru = DAG.getUNDEF(ResVT);
5931 SDValue Res =
5932 DAG.getNode(RISCVISD::VZIP_VL, DL, ResVT, Op0, Op1, Passthru, Mask, VL);
5933 if (IntVT.isFixedLengthVector())
5935 DAG, Subtarget);
5936 Res = DAG.getBitcast(VT.getDoubleNumVectorElementsVT(), Res);
5937 return Res;
5938}
5939
5940static SDValue lowerZvzipVUNZIP(unsigned Opc, SDValue Op, const SDLoc &DL,
5941 SelectionDAG &DAG,
5942 const RISCVSubtarget &Subtarget) {
5943 assert(Opc == RISCVISD::VUNZIPE_VL || Opc == RISCVISD::VUNZIPO_VL);
5944 MVT VT = Op.getSimpleValueType();
5946
5948 Op = DAG.getBitcast(IntVT, Op);
5949 MVT ContainerVT = IntVT;
5950 if (VT.isFixedLengthVector()) {
5952 // Ensure that halving the source container produces a legal result type.
5953 // In particular, E64 has no fractional LMUL types, and some Zve profiles
5954 // do not legalize the smallest fractional LMUL type.
5955 if (ContainerVT.getVectorMinNumElements() == 1 ||
5956 !Subtarget.getTargetLowering()->isTypeLegal(
5957 ContainerVT.getHalfNumVectorElementsVT()))
5958 ContainerVT = ContainerVT.getDoubleNumVectorElementsVT();
5960 }
5961
5962 MVT ResVT = ContainerVT.getHalfNumVectorElementsVT();
5963 MVT HalfVT = VT.getHalfNumVectorElementsVT();
5964 MVT HalfIntVT = IntVT.getHalfNumVectorElementsVT();
5965 auto [Mask, VL] = getDefaultVLOps(HalfIntVT, ResVT, DL, DAG, Subtarget);
5966 SDValue Passthru = DAG.getUNDEF(ResVT);
5967 SDValue Res = DAG.getNode(Opc, DL, ResVT, Op, Passthru, Mask, VL);
5968 if (HalfIntVT.isFixedLengthVector())
5969 Res = convertFromScalableVector(HalfIntVT, Res, DAG, Subtarget);
5970 Res = DAG.getBitcast(HalfVT, Res);
5971 return Res;
5972}
5973
5974// Given a vector a, b, c, d return a vector Factor times longer
5975// with Factor-1 undef's between elements. Ex:
5976// a, undef, b, undef, c, undef, d, undef (Factor=2, Index=0)
5977// undef, a, undef, b, undef, c, undef, d (Factor=2, Index=1)
5978static SDValue getWideningSpread(SDValue V, unsigned Factor, unsigned Index,
5979 const SDLoc &DL, SelectionDAG &DAG) {
5980
5981 MVT VT = V.getSimpleValueType();
5982 unsigned EltBits = VT.getScalarSizeInBits();
5984 V = DAG.getBitcast(VT.changeTypeToInteger(), V);
5985
5986 MVT WideVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Factor), EC);
5987
5988 SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, V);
5989 // TODO: On rv32, the constant becomes a splat_vector_parts which does not
5990 // allow the SHL to fold away if Index is 0.
5991 if (Index != 0)
5992 Result = DAG.getNode(ISD::SHL, DL, WideVT, Result,
5993 DAG.getConstant(EltBits * Index, DL, WideVT));
5994 // Make sure to use original element type
5995 MVT ResultVT = MVT::getVectorVT(VT.getVectorElementType(), EC * Factor);
5996 return DAG.getBitcast(ResultVT, Result);
5997}
5998
5999// Given two input vectors of <[vscale x ]n x ty>, use vwaddu.vv and vwmaccu.vx
6000// to create an interleaved vector of <[vscale x] n*2 x ty>.
6001// This requires that the size of ty is less than the subtarget's maximum ELEN.
6003 const SDLoc &DL, SelectionDAG &DAG,
6004 const RISCVSubtarget &Subtarget) {
6005
6006 // FIXME: Not only does this optimize the code, it fixes some correctness
6007 // issues because MIR does not have freeze.
6008 if (EvenV.isUndef())
6009 return getWideningSpread(OddV, 2, 1, DL, DAG);
6010 if (OddV.isUndef())
6011 return getWideningSpread(EvenV, 2, 0, DL, DAG);
6012
6013 MVT VecVT = EvenV.getSimpleValueType();
6014 MVT VecContainerVT = VecVT; // <vscale x n x ty>
6015 // Convert fixed vectors to scalable if needed
6016 if (VecContainerVT.isFixedLengthVector()) {
6017 VecContainerVT = getContainerForFixedLengthVector(VecVT, Subtarget);
6018 EvenV = convertToScalableVector(VecContainerVT, EvenV, DAG, Subtarget);
6019 OddV = convertToScalableVector(VecContainerVT, OddV, DAG, Subtarget);
6020 }
6021
6022 assert(VecVT.getScalarSizeInBits() < Subtarget.getELen());
6023
6024 // We're working with a vector of the same size as the resulting
6025 // interleaved vector, but with half the number of elements and
6026 // twice the SEW (Hence the restriction on not using the maximum
6027 // ELEN)
6028 MVT WideVT =
6030 VecVT.getVectorElementCount());
6031 MVT WideContainerVT = WideVT; // <vscale x n x ty*2>
6032 if (WideContainerVT.isFixedLengthVector())
6033 WideContainerVT = getContainerForFixedLengthVector(WideVT, Subtarget);
6034
6035 // Bitcast the input vectors to integers in case they are FP
6036 VecContainerVT = VecContainerVT.changeTypeToInteger();
6037 EvenV = DAG.getBitcast(VecContainerVT, EvenV);
6038 OddV = DAG.getBitcast(VecContainerVT, OddV);
6039
6040 auto [Mask, VL] = getDefaultVLOps(VecVT, VecContainerVT, DL, DAG, Subtarget);
6041 SDValue Passthru = DAG.getUNDEF(WideContainerVT);
6042
6043 SDValue Interleaved;
6044 if (Subtarget.hasStdExtZvbb()) {
6045 // Interleaved = (OddV << VecVT.getScalarSizeInBits()) + EvenV.
6046 SDValue OffsetVec =
6047 DAG.getConstant(VecVT.getScalarSizeInBits(), DL, VecContainerVT);
6048 Interleaved = DAG.getNode(RISCVISD::VWSLL_VL, DL, WideContainerVT, OddV,
6049 OffsetVec, Passthru, Mask, VL);
6050 Interleaved = DAG.getNode(RISCVISD::VWADDU_W_VL, DL, WideContainerVT,
6051 Interleaved, EvenV, Passthru, Mask, VL);
6052 } else {
6053 // FIXME: We should freeze the odd vector here. We already handled the case
6054 // of provably undef/poison above.
6055
6056 // Widen EvenV and OddV with 0s and add one copy of OddV to EvenV with
6057 // vwaddu.vv
6058 Interleaved = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideContainerVT, EvenV,
6059 OddV, Passthru, Mask, VL);
6060
6061 // Then get OddV * by 2^(VecVT.getScalarSizeInBits() - 1)
6062 SDValue AllOnesVec = DAG.getSplatVector(
6063 VecContainerVT, DL, DAG.getAllOnesConstant(DL, Subtarget.getXLenVT()));
6064 SDValue OddsMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideContainerVT,
6065 OddV, AllOnesVec, Passthru, Mask, VL);
6066
6067 // Add the two together so we get
6068 // (OddV * 0xff...ff) + (OddV + EvenV)
6069 // = (OddV * 0x100...00) + EvenV
6070 // = (OddV << VecVT.getScalarSizeInBits()) + EvenV
6071 // Note the ADD_VL and VLMULU_VL should get selected as vwmaccu.vx
6072 Interleaved = DAG.getNode(RISCVISD::ADD_VL, DL, WideContainerVT,
6073 Interleaved, OddsMul, Passthru, Mask, VL);
6074 }
6075
6076 // Bitcast from <vscale x n * ty*2> to <vscale x 2*n x ty>
6077 MVT ResultContainerVT = MVT::getVectorVT(
6078 VecVT.getVectorElementType(), // Make sure to use original type
6079 VecContainerVT.getVectorElementCount() * 2);
6080 Interleaved = DAG.getBitcast(ResultContainerVT, Interleaved);
6081
6082 // Convert back to a fixed vector if needed
6083 MVT ResultVT = MVT::getVectorVT(VecVT.getVectorElementType(),
6084 VecVT.getVectorElementCount() * 2);
6085 if (ResultVT.isFixedLengthVector())
6086 Interleaved =
6087 convertFromScalableVector(ResultVT, Interleaved, DAG, Subtarget);
6088
6089 return Interleaved;
6090}
6091
6092// If we have a vector of bits that we want to reverse, we can use a vbrev on a
6093// larger element type, e.g. v32i1 can be reversed with a v1i32 bitreverse.
6095 SelectionDAG &DAG,
6096 const RISCVSubtarget &Subtarget) {
6097 SDLoc DL(SVN);
6098 MVT VT = SVN->getSimpleValueType(0);
6099 SDValue V = SVN->getOperand(0);
6100 unsigned NumElts = VT.getVectorNumElements();
6101
6102 assert(VT.getVectorElementType() == MVT::i1);
6103
6105 SVN->getMask().size()) ||
6106 !SVN->getOperand(1).isUndef())
6107 return SDValue();
6108
6109 unsigned ViaEltSize = std::max((uint64_t)8, PowerOf2Ceil(NumElts));
6110 EVT ViaVT = EVT::getVectorVT(
6111 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), ViaEltSize), 1);
6112 EVT ViaBitVT =
6113 EVT::getVectorVT(*DAG.getContext(), MVT::i1, ViaVT.getScalarSizeInBits());
6114
6115 // If we don't have zvbb or the larger element type > ELEN, the operation will
6116 // be illegal.
6117 if (!Subtarget.getTargetLowering()->isOperationLegalOrCustom(ISD::BITREVERSE,
6118 ViaVT) ||
6119 !Subtarget.getTargetLowering()->isTypeLegal(ViaBitVT))
6120 return SDValue();
6121
6122 // If the bit vector doesn't fit exactly into the larger element type, we need
6123 // to insert it into the larger vector and then shift up the reversed bits
6124 // afterwards to get rid of the gap introduced.
6125 if (ViaEltSize > NumElts)
6126 V = DAG.getInsertSubvector(DL, DAG.getUNDEF(ViaBitVT), V, 0);
6127
6128 SDValue Res =
6129 DAG.getNode(ISD::BITREVERSE, DL, ViaVT, DAG.getBitcast(ViaVT, V));
6130
6131 // Shift up the reversed bits if the vector didn't exactly fit into the larger
6132 // element type.
6133 if (ViaEltSize > NumElts)
6134 Res = DAG.getNode(ISD::SRL, DL, ViaVT, Res,
6135 DAG.getConstant(ViaEltSize - NumElts, DL, ViaVT));
6136
6137 Res = DAG.getBitcast(ViaBitVT, Res);
6138
6139 if (ViaEltSize > NumElts)
6140 Res = DAG.getExtractSubvector(DL, VT, Res, 0);
6141 return Res;
6142}
6143
6146 MVT &RotateVT, unsigned &RotateAmt) {
6147 unsigned NumElts = VT.getVectorNumElements();
6148 unsigned EltSizeInBits = VT.getScalarSizeInBits();
6149 unsigned NumSubElts;
6150 if (!ShuffleVectorInst::isBitRotateMask(Mask, EltSizeInBits, 2,
6151 NumElts, NumSubElts, RotateAmt))
6152 return false;
6153 RotateVT = MVT::getVectorVT(MVT::getIntegerVT(EltSizeInBits * NumSubElts),
6154 NumElts / NumSubElts);
6155
6156 // We might have a RotateVT that isn't legal, e.g. v4i64 on zve32x.
6157 return Subtarget.getTargetLowering()->isTypeLegal(RotateVT);
6158}
6159
6160// Given a shuffle mask like <3, 0, 1, 2, 7, 4, 5, 6> for v8i8, we can
6161// reinterpret it as a v2i32 and rotate it right by 8 instead. We can lower this
6162// as a vror.vi if we have Zvkb, or otherwise as a vsll, vsrl and vor.
6164 SelectionDAG &DAG,
6165 const RISCVSubtarget &Subtarget) {
6166 SDLoc DL(SVN);
6167
6168 EVT VT = SVN->getValueType(0);
6169 unsigned RotateAmt;
6170 MVT RotateVT;
6171 if (!isLegalBitRotate(SVN->getMask(), VT, Subtarget, RotateVT, RotateAmt))
6172 return SDValue();
6173
6174 SDValue Op = DAG.getBitcast(RotateVT, SVN->getOperand(0));
6175
6176 SDValue Rotate;
6177 // A rotate of an i16 by 8 bits either direction is equivalent to a byteswap,
6178 // so canonicalize to vrev8.
6179 if (RotateVT.getScalarType() == MVT::i16 && RotateAmt == 8)
6180 Rotate = DAG.getNode(ISD::BSWAP, DL, RotateVT, Op);
6181 else
6182 Rotate = DAG.getNode(ISD::ROTL, DL, RotateVT, Op,
6183 DAG.getConstant(RotateAmt, DL, RotateVT));
6184
6185 return DAG.getBitcast(VT, Rotate);
6186}
6187
6188// If compiling with an exactly known VLEN, see if we can split a
6189// shuffle on m2 or larger into a small number of m1 sized shuffles
6190// which write each destination registers exactly once.
6192 SelectionDAG &DAG,
6193 const RISCVSubtarget &Subtarget) {
6194 SDLoc DL(SVN);
6195 MVT VT = SVN->getSimpleValueType(0);
6196 SDValue V1 = SVN->getOperand(0);
6197 SDValue V2 = SVN->getOperand(1);
6198 ArrayRef<int> Mask = SVN->getMask();
6199
6200 // If we don't know exact data layout, not much we can do. If this
6201 // is already m1 or smaller, no point in splitting further.
6202 const auto VLen = Subtarget.getRealVLen();
6203 if (!VLen || VT.getSizeInBits().getFixedValue() <= *VLen)
6204 return SDValue();
6205
6206 // Avoid picking up bitrotate patterns which we have a linear-in-lmul
6207 // expansion for.
6208 unsigned RotateAmt;
6209 MVT RotateVT;
6210 if (isLegalBitRotate(Mask, VT, Subtarget, RotateVT, RotateAmt))
6211 return SDValue();
6212
6213 MVT ElemVT = VT.getVectorElementType();
6214 unsigned ElemsPerVReg = *VLen / ElemVT.getFixedSizeInBits();
6215
6217 MVT OneRegVT = MVT::getVectorVT(ElemVT, ElemsPerVReg);
6219 assert(M1VT == RISCVTargetLowering::getM1VT(M1VT));
6220 unsigned NumOpElts = M1VT.getVectorMinNumElements();
6221 unsigned NumElts = ContainerVT.getVectorMinNumElements();
6222 unsigned NumOfSrcRegs = NumElts / NumOpElts;
6223 unsigned NumOfDestRegs = NumElts / NumOpElts;
6224 // The following semantically builds up a fixed length concat_vector
6225 // of the component shuffle_vectors. We eagerly lower to scalable here
6226 // to avoid DAG combining it back to a large shuffle_vector again.
6230 Operands;
6232 Mask, NumOfSrcRegs, NumOfDestRegs, NumOfDestRegs,
6233 [&]() { Operands.emplace_back(); },
6234 [&](ArrayRef<int> SrcSubMask, unsigned SrcVecIdx, unsigned DstVecIdx) {
6235 Operands.emplace_back().emplace_back(SrcVecIdx, UINT_MAX,
6236 SmallVector<int>(SrcSubMask));
6237 },
6238 [&](ArrayRef<int> SrcSubMask, unsigned Idx1, unsigned Idx2, bool NewReg) {
6239 if (NewReg)
6240 Operands.emplace_back();
6241 Operands.back().emplace_back(Idx1, Idx2, SmallVector<int>(SrcSubMask));
6242 });
6243 assert(Operands.size() == NumOfDestRegs && "Whole vector must be processed");
6244 // Note: check that we do not emit too many shuffles here to prevent code
6245 // size explosion.
6246 // TODO: investigate, if it can be improved by extra analysis of the masks to
6247 // check if the code is more profitable.
6248 unsigned NumShuffles = std::accumulate(
6249 Operands.begin(), Operands.end(), 0u,
6250 [&](unsigned N,
6251 ArrayRef<std::tuple<unsigned, unsigned, SmallVector<int>>> Data) {
6252 if (Data.empty())
6253 return N;
6254 N += Data.size();
6255 for (const auto &P : Data) {
6256 unsigned Idx2 = std::get<1>(P);
6257 ArrayRef<int> Mask = std::get<2>(P);
6258 if (Idx2 != UINT_MAX)
6259 ++N;
6260 else if (ShuffleVectorInst::isIdentityMask(Mask, Mask.size()))
6261 --N;
6262 }
6263 return N;
6264 });
6265 if ((NumOfDestRegs > 2 && NumShuffles > NumOfDestRegs) ||
6266 (NumOfDestRegs <= 2 && NumShuffles >= 4))
6267 return SDValue();
6268 auto ExtractValue = [&, &DAG = DAG](SDValue SrcVec, unsigned ExtractIdx) {
6269 SDValue SubVec = DAG.getExtractSubvector(DL, M1VT, SrcVec, ExtractIdx);
6270 SubVec = convertFromScalableVector(OneRegVT, SubVec, DAG, Subtarget);
6271 return SubVec;
6272 };
6273 auto PerformShuffle = [&, &DAG = DAG](SDValue SubVec1, SDValue SubVec2,
6275 SDValue SubVec = DAG.getVectorShuffle(OneRegVT, DL, SubVec1, SubVec2, Mask);
6276 return SubVec;
6277 };
6278 SDValue Vec = DAG.getUNDEF(ContainerVT);
6279 for (auto [I, Data] : enumerate(Operands)) {
6280 if (Data.empty())
6281 continue;
6283 for (unsigned I : seq<unsigned>(Data.size())) {
6284 const auto &[Idx1, Idx2, _] = Data[I];
6285 // If the shuffle contains permutation of odd number of elements,
6286 // Idx1 might be used already in the first iteration.
6287 //
6288 // Idx1 = shuffle Idx1, Idx2
6289 // Idx1 = shuffle Idx1, Idx3
6290 SDValue &V = Values.try_emplace(Idx1).first->getSecond();
6291 if (!V)
6292 V = ExtractValue(Idx1 >= NumOfSrcRegs ? V2 : V1,
6293 (Idx1 % NumOfSrcRegs) * NumOpElts);
6294 if (Idx2 != UINT_MAX) {
6295 SDValue &V = Values.try_emplace(Idx2).first->getSecond();
6296 if (!V)
6297 V = ExtractValue(Idx2 >= NumOfSrcRegs ? V2 : V1,
6298 (Idx2 % NumOfSrcRegs) * NumOpElts);
6299 }
6300 }
6301 SDValue V;
6302 for (const auto &[Idx1, Idx2, Mask] : Data) {
6303 SDValue V1 = Values.at(Idx1);
6304 SDValue V2 = Idx2 == UINT_MAX ? V1 : Values.at(Idx2);
6305 V = PerformShuffle(V1, V2, Mask);
6306 Values[Idx1] = V;
6307 }
6308
6309 unsigned InsertIdx = I * NumOpElts;
6310 V = convertToScalableVector(M1VT, V, DAG, Subtarget);
6311 Vec = DAG.getInsertSubvector(DL, Vec, V, InsertIdx);
6312 }
6313 return convertFromScalableVector(VT, Vec, DAG, Subtarget);
6314}
6315
6316// Matches a subset of compress masks with a contiguous prefix of output
6317// elements. This could be extended to allow gaps by deciding which
6318// source elements to spuriously demand.
6320 int Last = -1;
6321 bool SawUndef = false;
6322 for (const auto &[Idx, M] : enumerate(Mask)) {
6323 if (M == -1) {
6324 SawUndef = true;
6325 continue;
6326 }
6327 if (SawUndef)
6328 return false;
6329 if (Idx > (unsigned)M)
6330 return false;
6331 if (M <= Last)
6332 return false;
6333 Last = M;
6334 }
6335 return true;
6336}
6337
6338/// Given a shuffle where the indices are disjoint between the two sources,
6339/// e.g.:
6340///
6341/// t2:v4i8 = vector_shuffle t0:v4i8, t1:v4i8, <2, 7, 1, 4>
6342///
6343/// Merge the two sources into one and do a single source shuffle:
6344///
6345/// t2:v4i8 = vselect t1:v4i8, t0:v4i8, <0, 1, 0, 1>
6346/// t3:v4i8 = vector_shuffle t2:v4i8, undef, <2, 3, 1, 0>
6347///
6348/// A vselect will either be merged into a masked instruction or be lowered as a
6349/// vmerge.vvm, which is cheaper than a vrgather.vv.
6351 SelectionDAG &DAG,
6352 const RISCVSubtarget &Subtarget) {
6353 MVT VT = SVN->getSimpleValueType(0);
6354 MVT XLenVT = Subtarget.getXLenVT();
6355 SDLoc DL(SVN);
6356
6357 const ArrayRef<int> Mask = SVN->getMask();
6358
6359 // Work out which source each lane will come from.
6360 SmallVector<int, 16> Srcs(Mask.size(), -1);
6361
6362 for (int Idx : Mask) {
6363 if (Idx == -1)
6364 continue;
6365 unsigned SrcIdx = Idx % Mask.size();
6366 int Src = (uint32_t)Idx < Mask.size() ? 0 : 1;
6367 if (Srcs[SrcIdx] == -1)
6368 // Mark this source as using this lane.
6369 Srcs[SrcIdx] = Src;
6370 else if (Srcs[SrcIdx] != Src)
6371 // The other source is using this lane: not disjoint.
6372 return SDValue();
6373 }
6374
6375 SmallVector<SDValue> SelectMaskVals;
6376 for (int Lane : Srcs) {
6377 if (Lane == -1)
6378 SelectMaskVals.push_back(DAG.getUNDEF(XLenVT));
6379 else
6380 SelectMaskVals.push_back(DAG.getConstant(Lane ? 0 : 1, DL, XLenVT));
6381 }
6382 MVT MaskVT = VT.changeVectorElementType(MVT::i1);
6383 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, SelectMaskVals);
6384 SDValue Select = DAG.getNode(ISD::VSELECT, DL, VT, SelectMask,
6385 SVN->getOperand(0), SVN->getOperand(1));
6386
6387 // Move all indices relative to the first source.
6388 SmallVector<int> NewMask(Mask.size());
6389 for (unsigned I = 0; I < Mask.size(); I++) {
6390 if (Mask[I] == -1)
6391 NewMask[I] = -1;
6392 else
6393 NewMask[I] = Mask[I] % Mask.size();
6394 }
6395
6396 return DAG.getVectorShuffle(VT, DL, Select, DAG.getUNDEF(VT), NewMask);
6397}
6398
6399/// Is this mask local (i.e. elements only move within their local span), and
6400/// repeating (that is, the same rearrangement is being done within each span)?
6401static bool isLocalRepeatingShuffle(ArrayRef<int> Mask, int Span) {
6402 // Require a prefix from the original mask until the consumer code
6403 // is adjusted to rewrite the mask instead of just taking a prefix.
6404 for (auto [I, M] : enumerate(Mask)) {
6405 if (M == -1)
6406 continue;
6407 if ((M / Span) != (int)(I / Span))
6408 return false;
6409 int SpanIdx = I % Span;
6410 int Expected = M % Span;
6411 if (Mask[SpanIdx] != Expected)
6412 return false;
6413 }
6414 return true;
6415}
6416
6417/// Is this mask only using elements from the first span of the input?
6418static bool isLowSourceShuffle(ArrayRef<int> Mask, int Span) {
6419 return all_of(Mask, [&](const auto &Idx) { return Idx == -1 || Idx < Span; });
6420}
6421
6422/// Return true for a mask which performs an arbitrary shuffle within the first
6423/// span, and then repeats that same result across all remaining spans. Note
6424/// that this doesn't check if all the inputs come from a single span!
6425static bool isSpanSplatShuffle(ArrayRef<int> Mask, int Span) {
6426 // Require a prefix from the original mask until the consumer code
6427 // is adjusted to rewrite the mask instead of just taking a prefix.
6428 for (auto [I, M] : enumerate(Mask)) {
6429 if (M == -1)
6430 continue;
6431 int SpanIdx = I % Span;
6432 if (Mask[SpanIdx] != M)
6433 return false;
6434 }
6435 return true;
6436}
6437
6438/// Try to widen element type to get a new mask value for a better permutation
6439/// sequence. This doesn't try to inspect the widened mask for profitability;
6440/// we speculate the widened form is equal or better. This has the effect of
6441/// reducing mask constant sizes - allowing cheaper materialization sequences
6442/// - and index sequence sizes - reducing register pressure and materialization
6443/// cost, at the cost of (possibly) an extra VTYPE toggle.
6445 SDLoc DL(Op);
6446 MVT VT = Op.getSimpleValueType();
6447 MVT ScalarVT = VT.getVectorElementType();
6448 unsigned ElementSize = ScalarVT.getFixedSizeInBits();
6449 SDValue V0 = Op.getOperand(0);
6450 SDValue V1 = Op.getOperand(1);
6451 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6452
6453 // Avoid wasted work leading to isTypeLegal check failing below
6454 if (ElementSize > 32)
6455 return SDValue();
6456
6457 SmallVector<int, 8> NewMask;
6458 if (!widenShuffleMaskElts(Mask, NewMask))
6459 return SDValue();
6460
6461 MVT NewEltVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(ElementSize * 2)
6462 : MVT::getIntegerVT(ElementSize * 2);
6463 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
6464 if (!DAG.getTargetLoweringInfo().isTypeLegal(NewVT))
6465 return SDValue();
6466 V0 = DAG.getBitcast(NewVT, V0);
6467 V1 = DAG.getBitcast(NewVT, V1);
6468 return DAG.getBitcast(VT, DAG.getVectorShuffle(NewVT, DL, V0, V1, NewMask));
6469}
6470
6471// Match an interleave shuffle that forms a P-extension packed zip:
6472// <a0, b0, a1, b1, ...> -> zip*p/wzip*p
6473// <aN/2, bN/2, aN/2+1, bN/2+1, ...> -> zip*hp
6476 SelectionDAG &DAG) {
6477 SDValue V1 = SVN->getOperand(0);
6478 SDValue V2 = SVN->getOperand(1);
6479 SDLoc DL(SVN);
6480 MVT VT = SVN->getSimpleValueType(0);
6481 unsigned NumElts = VT.getVectorNumElements();
6482 ArrayRef<int> Mask = SVN->getMask();
6483
6484 if (VT != MVT::v8i8 && VT != MVT::v4i16)
6485 return SDValue();
6486
6487 SmallVector<unsigned, 2> StartIndexes;
6488 if (!V2.isUndef() &&
6489 ShuffleVectorInst::isInterleaveMask(Mask, 2, NumElts * 2, StartIndexes)) {
6490 unsigned EvenSrc = StartIndexes[0];
6491 unsigned OddSrc = StartIndexes[1];
6492 if (EvenSrc == 0 && OddSrc == NumElts) {
6493 if (Subtarget.is64Bit())
6494 return DAG.getNode(RISCVISD::PZIP, DL, VT, V1, V2);
6495 EVT HalfVT = VT.getHalfNumVectorElementsVT();
6496 V1 = DAG.getExtractSubvector(DL, HalfVT, V1, 0);
6497 V2 = DAG.getExtractSubvector(DL, HalfVT, V2, 0);
6498 return DAG.getNode(RISCVISD::PWZIP, DL, VT, V1, V2);
6499 }
6500 if (EvenSrc == NumElts && OddSrc == 0) {
6501 if (Subtarget.is64Bit())
6502 return DAG.getNode(RISCVISD::PZIP, DL, VT, V2, V1);
6503 EVT HalfVT = VT.getHalfNumVectorElementsVT();
6504 V1 = DAG.getExtractSubvector(DL, HalfVT, V1, 0);
6505 V2 = DAG.getExtractSubvector(DL, HalfVT, V2, 0);
6506 return DAG.getNode(RISCVISD::PWZIP, DL, VT, V2, V1);
6507 }
6508 if (Subtarget.is64Bit()) {
6509 unsigned HalfNumElts = NumElts / 2;
6510 if (EvenSrc == HalfNumElts && OddSrc == NumElts + HalfNumElts)
6511 return DAG.getNode(RISCVISD::PZIPH, DL, VT, V1, V2);
6512 if (EvenSrc == NumElts + HalfNumElts && OddSrc == HalfNumElts)
6513 return DAG.getNode(RISCVISD::PZIPH, DL, VT, V2, V1);
6514 }
6515 }
6516
6517 return SDValue();
6518}
6519
6520// Match a deinterleave shuffle that forms a P-extension packed unzip:
6521// <a0, a2, ..., b0, b2, ...> -> unzip*p
6522// <a1, a3, ..., b1, b3, ...> -> unzip*hp
6524 SelectionDAG &DAG, bool IsRV64) {
6525 MVT VT = SVN->getSimpleValueType(0);
6526 if (!IsRV64 || (VT != MVT::v8i8 && VT != MVT::v4i16))
6527 return SDValue();
6528
6529 SDValue V1 = SVN->getOperand(0);
6530 SDValue V2 = SVN->getOperand(1);
6531 SDLoc DL(SVN);
6532 ArrayRef<int> Mask = SVN->getMask();
6533
6534 unsigned Index = 0;
6536 return SDValue();
6537
6538 unsigned Opc = Index == 0 ? RISCVISD::PUNZIPE : RISCVISD::PUNZIPO;
6539 return DAG.getNode(Opc, DL, VT, V1, V2);
6540}
6541
6542// Match a slide by one element with a scalar inserted at either end:
6543// <b0, a0, ..., aN-2> -> slide1up
6544// <a1, ..., aN-1, b0> -> slide1down
6547 SelectionDAG &DAG) {
6548 MVT VT = SVN->getSimpleValueType(0);
6549 if (VT != MVT::v4i8 && VT != MVT::v8i8 && VT != MVT::v2i16 &&
6550 VT != MVT::v4i16 && VT != MVT::v2i32)
6551 return SDValue();
6552 if (!Subtarget.is64Bit() && VT == MVT::v2i32)
6553 return SDValue();
6554
6555 unsigned NumElts = VT.getVectorNumElements();
6556 ArrayRef<int> Mask = SVN->getMask();
6557 unsigned ActiveElts = NumElts;
6558 if (Subtarget.is64Bit() &&
6559 all_of(Mask.drop_front(NumElts / 2), [](int M) { return M < 0; }))
6560 ActiveElts /= 2;
6561
6562 ArrayRef<int> ActiveMask = Mask.take_front(ActiveElts);
6563 bool SlideUp = ActiveMask[0] == (int)NumElts &&
6564 all_of(enumerate(ActiveMask.drop_front()), [](const auto &M) {
6565 return M.value() == (int)M.index();
6566 });
6567 bool SlideDown = ActiveMask.back() == (int)NumElts &&
6568 all_of(enumerate(ActiveMask.drop_back()), [](const auto &M) {
6569 return M.value() == (int)M.index() + 1;
6570 });
6571 if (!SlideUp && !SlideDown)
6572 return SDValue();
6573
6574 SDValue V1 = SVN->getOperand(0);
6575 SDValue V2 = SVN->getOperand(1);
6576 SDLoc DL(SVN);
6577 unsigned EltBits = VT.getScalarSizeInBits();
6578 unsigned SlideBits = ActiveElts * EltBits;
6579 MVT XLenVT = Subtarget.getXLenVT();
6580 SDValue Scalar = DAG.getExtractVectorElt(DL, XLenVT, V2, 0);
6581
6582 // A two-element slide is exactly a packed pair operation.
6583 if (ActiveElts == 2) {
6584 SDValue ScalarVec = DAG.getBitcast(VT, Scalar);
6585 return DAG.getNode(SlideUp ? RISCVISD::PPAIRE : RISCVISD::PPAIROE, DL, VT,
6586 SlideUp ? ScalarVec : V1, SlideUp ? V1 : ScalarVec);
6587 }
6588
6589 // Lower a full-register slide to the funnel shift instruction that
6590 // implements it.
6591 if (SlideBits == Subtarget.getXLen()) {
6592 SDValue Bits = DAG.getBitcast(XLenVT, V1);
6593 SDValue Shamt = DAG.getConstant(EltBits, DL, XLenVT);
6594 if (SlideUp) {
6595 Scalar = DAG.getNode(ISD::SHL, DL, XLenVT, Scalar,
6596 DAG.getConstant(SlideBits - EltBits, DL, XLenVT));
6597 Bits = DAG.getNode(ISD::FSHL, DL, XLenVT, Bits, Scalar, Shamt);
6598 } else {
6599 Bits = DAG.getNode(ISD::FSHR, DL, XLenVT, Scalar, Bits, Shamt);
6600 }
6601 return DAG.getBitcast(VT, Bits);
6602 }
6603
6604 // A 32-bit packed slide on RV64 is carried in the low word of a GPR. Expand
6605 // it using XLEN operations or packed pair instructions.
6606 if (Subtarget.is64Bit()) {
6607 assert(SlideBits == 32 && "Unexpected RV64 packed slide width");
6608 SDValue Shamt = DAG.getConstant(EltBits, DL, MVT::i64);
6609 SDValue Bits = DAG.getBitcast(MVT::i64, V1);
6610 if (SlideUp) {
6611 Scalar = DAG.getNode(ISD::SHL, DL, MVT::i64, Scalar,
6612 DAG.getConstant(64 - EltBits, DL, MVT::i64));
6613 Bits = DAG.getNode(ISD::FSHL, DL, MVT::i64, Bits, Scalar, Shamt);
6614 } else {
6615 SDValue Pair = DAG.getNode(RISCVISD::PPAIRE, DL, MVT::v2i32,
6616 DAG.getBitcast(MVT::v2i32, V1),
6617 DAG.getBitcast(MVT::v2i32, Scalar));
6618 Bits = DAG.getNode(ISD::SRL, DL, MVT::i64, DAG.getBitcast(MVT::i64, Pair),
6619 Shamt);
6620 }
6621 return DAG.getBitcast(VT, Bits);
6622 }
6623
6624 // RV32 represents 64-bit packed values as two GPRs. Form each shifted half
6625 // directly so the slide uses two XLEN funnel shifts.
6626 assert(SlideBits == 64 && "Unexpected RV32 packed slide width");
6627 auto [LoVec, HiVec] = DAG.SplitVector(V1, DL);
6628 MVT HalfVT = LoVec.getSimpleValueType();
6629 SDValue Lo = DAG.getBitcast(MVT::i32, LoVec);
6630 SDValue Hi = DAG.getBitcast(MVT::i32, HiVec);
6631 SDValue Shamt = DAG.getConstant(EltBits, DL, MVT::i32);
6632 SDValue NewLo;
6633 SDValue NewHi;
6634 if (SlideUp) {
6635 SDValue Insert = DAG.getNode(ISD::SHL, DL, MVT::i32, Scalar,
6636 DAG.getConstant(32 - EltBits, DL, MVT::i32));
6637 NewLo = DAG.getNode(ISD::FSHL, DL, MVT::i32, Lo, Insert, Shamt);
6638 NewHi = DAG.getNode(ISD::FSHL, DL, MVT::i32, Hi, Lo, Shamt);
6639 } else {
6640 NewLo = DAG.getNode(ISD::FSHR, DL, MVT::i32, Hi, Lo, Shamt);
6641 NewHi = DAG.getNode(ISD::FSHR, DL, MVT::i32, Scalar, Hi, Shamt);
6642 }
6643 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, DAG.getBitcast(HalfVT, NewLo),
6644 DAG.getBitcast(HalfVT, NewHi));
6645}
6646
6647// Match the packed zero-extend shuffle mask <0, N, 2, N+2, ...>: even result
6648// lanes keep operand 0's even lanes and odd result lanes come from operand 1.
6649// The odd lanes may select any element of operand 1, which is looser than a
6650// strict pair-even mask; DAGCombiner::XformToShuffleWithZero forms exactly this
6651// from a packed zero-extend `and`, leaving each zeroed lane at its own
6652// position, and lowerVECTOR_SHUFFLEAsPPair then forms the PPAIRE. Undef lanes
6653// always match.
6655 unsigned NumElts = Mask.size();
6656 if (NumElts % 2 != 0)
6657 return false;
6658 for (unsigned I = 0; I != NumElts / 2; ++I)
6659 if ((Mask[2 * I] >= 0 && Mask[2 * I] != (int)(2 * I)) ||
6660 (Mask[2 * I + 1] >= 0 && Mask[2 * I + 1] < (int)NumElts))
6661 return false;
6662 return true;
6663}
6664
6665// Match a legalized deinterleave shuffle on two RV32 vector halves and lower
6666// it to an RV32 P narrowing shift on the concatenated source.
6667static SDValue
6670 SelectionDAG &DAG) {
6671 MVT VT = SVN->getSimpleValueType(0);
6672 if (VT != MVT::v4i8)
6673 return SDValue();
6674
6675 SDValue V1 = SVN->getOperand(0);
6676 SDValue V2 = SVN->getOperand(1);
6677 SDLoc DL(SVN);
6678 unsigned NumElts = VT.getVectorNumElements();
6679
6680 SDValue Src = foldConcatVector(V1, V2);
6681 if (!Src) {
6682 MVT SrcVT = VT == MVT::v4i8 ? MVT::v8i8 : MVT::v4i16;
6683 Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, V1, V2);
6684 }
6685
6686 // The source vector should be twice the size.
6687 if (Src.getValueType().getVectorNumElements() != 2 * NumElts)
6688 return SDValue();
6689
6690 unsigned Index = 0;
6692 return SDValue();
6693
6694 unsigned EltBits = VT.getVectorElementType().getSizeInBits();
6695 return DAG.getNode(RISCVISD::PNSRL, DL, VT, Src,
6696 DAG.getConstant(Index * EltBits, DL, MVT::i32));
6697}
6698
6699// Match a strided-interleave shuffle that forms a P-extension packed pair:
6700// <a0, b0, a2, b2, ...> -> ppaire.*
6701// <a0, b1, a2, b3, ...> -> ppaireo.*
6702// <a1, b0, a3, b2, ...> -> ppairoe.*
6703// <a1, b1, a3, b3, ...> -> ppairo.*
6705 SelectionDAG &DAG, bool IsRV64) {
6706 MVT VT = SVN->getSimpleValueType(0);
6707 if (VT != MVT::v4i8 && VT != MVT::v8i8 && VT != MVT::v2i16 &&
6708 VT != MVT::v4i16 && !(IsRV64 && VT == MVT::v2i32))
6709 return SDValue();
6710
6711 SDValue V1 = SVN->getOperand(0);
6712 SDValue V2 = SVN->getOperand(1);
6713 SDLoc DL(SVN);
6714 unsigned NumElts = VT.getVectorNumElements();
6715 ArrayRef<int> Mask = SVN->getMask();
6716
6717 // A splat operand's lanes are all equal, so a lane selecting from it matches
6718 // any of its positions. This covers the zero operand XformToShuffleWithZero
6719 // forms for a packed zero-extend, which keeps each zeroed lane at its own
6720 // position rather than the strided one.
6721 bool V1IsSplat = DAG.isSplatValue(V1);
6722 bool V2IsSplat = DAG.isSplatValue(V2);
6723
6724 // Walk the mask once, tracking the operand feeding the destination's even
6725 // lanes (index 0) and the operand feeding its odd lanes (index 1) — either
6726 // may turn out to be V1 or V2 — along with whether each pulls the even or
6727 // odd element out of its pair. All even (resp. odd) lanes must agree on
6728 // both the operand and the parity used; a splat operand's lanes are all
6729 // equal so it never constrains the parity.
6730 SDValue Src[2];
6731 std::optional<bool> Parity[2];
6732 for (unsigned I = 0; I != NumElts; ++I) {
6733 int M = Mask[I];
6734 if (M < 0)
6735 continue;
6736 unsigned Lane = I % 2;
6737 bool FromV1 = (unsigned)M < NumElts;
6738 SDValue Cand = FromV1 ? V1 : V2;
6739 unsigned Local = (unsigned)M % NumElts;
6740 if (!Src[Lane])
6741 Src[Lane] = Cand;
6742 else if (Src[Lane] != Cand)
6743 return SDValue();
6744
6745 // Splats don't constrain parity.
6746 if (FromV1 ? V1IsSplat : V2IsSplat)
6747 continue;
6748
6749 // The index must be from the even/odd element of its pair.
6750 if (Local / 2 != I / 2)
6751 return SDValue();
6752
6753 bool P = Local % 2;
6754 if (!Parity[Lane])
6755 Parity[Lane] = P;
6756 else if (*Parity[Lane] != P)
6757 return SDValue();
6758 }
6759
6760 // Make sure we have a source for both lanes.
6761 if (!Src[0] || !Src[1])
6762 return SDValue();
6763
6764 bool EvenIsOdd = Parity[0].value_or(false);
6765 bool OddIsOdd = Parity[1].value_or(false);
6766 unsigned Opc;
6767 if (!EvenIsOdd && !OddIsOdd)
6768 Opc = RISCVISD::PPAIRE;
6769 else if (EvenIsOdd && OddIsOdd)
6770 Opc = RISCVISD::PPAIRO;
6771 else if (!EvenIsOdd && OddIsOdd)
6772 Opc = RISCVISD::PPAIREO;
6773 else
6774 Opc = RISCVISD::PPAIROE;
6775
6776 return DAG.getNode(Opc, DL, VT, Src[0], Src[1]);
6777}
6778
6779SDValue RISCVTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
6780 SelectionDAG &DAG) const {
6781 SDValue V1 = Op.getOperand(0);
6782 SDValue V2 = Op.getOperand(1);
6783 SDLoc DL(Op);
6784 MVT XLenVT = Subtarget.getXLenVT();
6785 MVT VT = Op.getSimpleValueType();
6786 unsigned NumElts = VT.getVectorNumElements();
6787 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6788
6789 // Select RVP-specific packed shuffles before falling back to the generic
6790 // fixed/scalable-vector lowering below.
6791 if (Subtarget.hasStdExtP() && !Subtarget.hasVInstructions()) {
6792 ArrayRef<int> Mask = SVN->getMask();
6793
6794 // Select an element reverse shuffle to VECTOR_REVERSE. The tablegen
6795 // patterns select rev8/rev16/ppairoe.* from VECTOR_REVERSE.
6796 // Reverse of the low L lanes, higher lanes poison. L == NumElts is a plain
6797 // reverse; L == NumElts/2 is a widened RV64 v4i8/v2i16 reverse.
6798 auto IsLowReverse = [&](unsigned L) {
6799 return V2.isUndef() &&
6800 ShuffleVectorInst::isReverseMask(Mask.take_front(L), L) &&
6801 all_of(Mask.drop_front(L), [](int M) { return M < 0; });
6802 };
6803 if (IsLowReverse(NumElts))
6804 return DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V1);
6805 if (Subtarget.is64Bit() && VT == MVT::v4i16 && IsLowReverse(/*L=*/2))
6806 return DAG.getNode(RISCVISD::PPAIROE, DL, VT, V1, V1);
6807 // Widened: reversing sends the low-half lanes to the top half, so shift
6808 // them back down by half the register. Only the 64-bit packed types are
6809 // legal here, so the register is XLen (i64).
6810 if (Subtarget.is64Bit() && VT.getSizeInBits() == 64 &&
6811 IsLowReverse(NumElts / 2)) {
6812 SDValue Rev = DAG.getBitcast(
6813 MVT::i64, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V1));
6814 SDValue Srl =
6815 DAG.getNode(ISD::SRL, DL, MVT::i64, Rev,
6816 DAG.getConstant(VT.getSizeInBits() / 2, DL, MVT::i64));
6817 return DAG.getBitcast(VT, Srl);
6818 }
6819
6820 if (SDValue V = lowerVECTOR_SHUFFLEAsPSlide1(SVN, Subtarget, DAG))
6821 return V;
6822 if (SDValue V = lowerVECTOR_SHUFFLEAsPUnzip(SVN, DAG, Subtarget.is64Bit()))
6823 return V;
6824 if (SDValue V = lowerVECTOR_SHUFFLEAsPZip(SVN, Subtarget, DAG))
6825 return V;
6826 if (SDValue V =
6827 lowerVECTOR_SHUFFLEAsRV32PNarrowingShift(SVN, Subtarget, DAG))
6828 return V;
6829 if (SDValue V = lowerVECTOR_SHUFFLEAsPPair(SVN, DAG, Subtarget.is64Bit()))
6830 return V;
6831
6832 // As a last resort, widen the elements so the shuffle can be matched on a
6833 // wider type, e.g. v4i16 <0,1,6,7> -> v2i32 <0,3>.
6834 return tryWidenMaskForShuffle(Op, DAG);
6835 }
6836
6837 if (VT.getVectorElementType() == MVT::i1) {
6838 // Lower to a vror.vi of a larger element type if possible before we promote
6839 // i1s to i8s.
6840 if (SDValue V = lowerVECTOR_SHUFFLEAsRotate(SVN, DAG, Subtarget))
6841 return V;
6842 if (SDValue V = lowerBitreverseShuffle(SVN, DAG, Subtarget))
6843 return V;
6844
6845 // Promote i1 shuffle to i8 shuffle.
6846 MVT WidenVT = MVT::getVectorVT(MVT::i8, VT.getVectorElementCount());
6847 V1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, V1);
6848 V2 = V2.isUndef() ? DAG.getUNDEF(WidenVT)
6849 : DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, V2);
6850 SDValue Shuffled = DAG.getVectorShuffle(WidenVT, DL, V1, V2, SVN->getMask());
6851 return DAG.getSetCC(DL, VT, Shuffled, DAG.getConstant(0, DL, WidenVT),
6852 ISD::SETNE);
6853 }
6854
6856
6857 // Store the return value in a single variable instead of structured bindings
6858 // so that we can pass it to GetSlide below, which cannot capture structured
6859 // bindings until C++20.
6860 auto TrueMaskVL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6861 auto [TrueMask, VL] = TrueMaskVL;
6862
6863 if (SVN->isSplat()) {
6864 const int Lane = SVN->getSplatIndex();
6865 if (Lane >= 0) {
6866 MVT SVT = VT.getVectorElementType();
6867
6868 // Turn splatted vector load into a strided load with an X0 stride.
6869 SDValue V = V1;
6870 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
6871 // with undef.
6872 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
6873 int Offset = Lane;
6874 if (V.getOpcode() == ISD::CONCAT_VECTORS) {
6875 int OpElements =
6876 V.getOperand(0).getSimpleValueType().getVectorNumElements();
6877 V = V.getOperand(Offset / OpElements);
6878 Offset %= OpElements;
6879 }
6880
6881 // We need to ensure the load isn't atomic or volatile.
6882 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
6883 auto *Ld = cast<LoadSDNode>(V);
6884 Offset *= SVT.getStoreSize();
6885 SDValue NewAddr = DAG.getMemBasePlusOffset(
6886 Ld->getBasePtr(), TypeSize::getFixed(Offset), DL);
6887
6888 // If this is SEW=64 on RV32, use a strided load with a stride of x0.
6889 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
6890 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6891 SDValue IntID =
6892 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
6893 SDValue Ops[] = {Ld->getChain(),
6894 IntID,
6895 DAG.getUNDEF(ContainerVT),
6896 NewAddr,
6897 DAG.getRegister(RISCV::X0, XLenVT),
6898 VL};
6899 SDValue NewLoad = DAG.getMemIntrinsicNode(
6900 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
6902 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
6903 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
6904 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
6905 }
6906
6907 MVT SplatVT = ContainerVT;
6908
6909 // f16 with zvfhmin and bf16 need to use an integer scalar load.
6910 if (SVT == MVT::bf16 ||
6911 (SVT == MVT::f16 && !Subtarget.hasStdExtZfh())) {
6912 SVT = MVT::i16;
6913 SplatVT = ContainerVT.changeVectorElementType(SVT);
6914 }
6915
6916 // Otherwise use a scalar load and splat. This will give the best
6917 // opportunity to fold a splat into the operation. ISel can turn it into
6918 // the x0 strided load if we aren't able to fold away the select.
6919 if (SVT.isFloatingPoint())
6920 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
6921 Ld->getPointerInfo().getWithOffset(Offset),
6922 Ld->getBaseAlign(), Ld->getMemOperand()->getFlags());
6923 else
6924 V = DAG.getExtLoad(ISD::EXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
6925 Ld->getPointerInfo().getWithOffset(Offset), SVT,
6926 Ld->getBaseAlign(),
6927 Ld->getMemOperand()->getFlags());
6929
6930 unsigned Opc = SplatVT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
6931 : RISCVISD::VMV_V_X_VL;
6932 SDValue Splat =
6933 DAG.getNode(Opc, DL, SplatVT, DAG.getUNDEF(SplatVT), V, VL);
6935 return convertFromScalableVector(VT, Splat, DAG, Subtarget);
6936 }
6937
6938 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
6939 assert(Lane < (int)NumElts && "Unexpected lane!");
6940 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT,
6941 V1, DAG.getConstant(Lane, DL, XLenVT),
6942 DAG.getUNDEF(ContainerVT), TrueMask, VL);
6943 return convertFromScalableVector(VT, Gather, DAG, Subtarget);
6944 }
6945 }
6946
6947 // For exact VLEN m2 or greater, try to split to m1 operations if we
6948 // can split cleanly.
6949 if (SDValue V = lowerShuffleViaVRegSplitting(SVN, DAG, Subtarget))
6950 return V;
6951
6952 ArrayRef<int> Mask = SVN->getMask();
6953
6954 if (SDValue V =
6955 lowerVECTOR_SHUFFLEAsVSlide1(DL, VT, V1, V2, Mask, Subtarget, DAG))
6956 return V;
6957
6958 if (SDValue V =
6959 lowerVECTOR_SHUFFLEAsVSlidedown(DL, VT, V1, V2, Mask, Subtarget, DAG))
6960 return V;
6961
6962 // A bitrotate will be one instruction on Zvkb, so try to lower to it first if
6963 // available.
6964 if (Subtarget.hasStdExtZvkb())
6965 if (SDValue V = lowerVECTOR_SHUFFLEAsRotate(SVN, DAG, Subtarget))
6966 return V;
6967
6968 if (ShuffleVectorInst::isReverseMask(Mask, NumElts) && V2.isUndef() &&
6969 NumElts != 2)
6970 return DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V1);
6971
6972 // Try using vunzip{e,o} from Zvzip to lower deinterleave2.
6973 unsigned Index = 0;
6974 if (Subtarget.hasStdExtZvzip() &&
6976 1 < count_if(Mask, [](int Idx) { return Idx != -1; })) {
6977 bool UsesBothSources =
6978 1 < count_if(Mask,
6979 [&Mask](int Idx) { return Idx < (int)Mask.size(); }) &&
6980 1 < count_if(Mask,
6981 [&Mask](int Idx) { return Idx >= (int)Mask.size(); });
6982
6983 unsigned Opc = Index == 0 ? RISCVISD::VUNZIPE_VL : RISCVISD::VUNZIPO_VL;
6984 if (isLegalVTForZvzipDeinterleavedOperand(VT, Subtarget)) {
6985 MVT NewVT = VT.getDoubleNumVectorElementsVT();
6986 if (isTypeLegal(NewVT)) {
6987 SDValue Op;
6988 if (V2.isUndef()) {
6989 Op = DAG.getNode(ISD::CONCAT_VECTORS, DL, NewVT, V1, V2);
6990 } else if (auto VLEN = Subtarget.getRealVLen();
6991 VLEN && VT.getSizeInBits().getKnownMinValue() % *VLEN == 0) {
6992 Op = DAG.getNode(ISD::CONCAT_VECTORS, DL, NewVT, V1, V2);
6993 } else if (SDValue Src = foldConcatVector(V1, V2)) {
6994 Op = DAG.getExtractSubvector(DL, NewVT, Src, 0);
6995 }
6996 if (Op)
6997 return lowerZvzipVUNZIP(Opc, Op, DL, DAG, Subtarget);
6998 }
6999 }
7000
7001 MVT HalfVT = VT.getHalfNumVectorElementsVT();
7002 if (UsesBothSources &&
7003 isLegalVTForZvzipDeinterleavedOperand(HalfVT, Subtarget) &&
7004 V1.getSimpleValueType().getVectorMinNumElements() >= 2 &&
7006 SDValue Lo = lowerZvzipVUNZIP(Opc, V1, DL, DAG, Subtarget);
7007 SDValue Hi = lowerZvzipVUNZIP(Opc, V2, DL, DAG, Subtarget);
7008 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
7009 }
7010 }
7011
7012 // If this is a deinterleave(2,4,8) and we can widen the vector, then we can
7013 // use shift and truncate to perform the shuffle.
7014 // TODO: For Factor=6, we can perform the first step of the deinterleave via
7015 // shift-and-trunc reducing total cost for everything except an mf8 result.
7016 // TODO: For Factor=4,8, we can do the same when the ratio isn't high enough
7017 // to do the entire operation.
7018 if (VT.getScalarSizeInBits() < Subtarget.getELen()) {
7019 const unsigned MaxFactor = Subtarget.getELen() / VT.getScalarSizeInBits();
7020 assert(MaxFactor == 2 || MaxFactor == 4 || MaxFactor == 8);
7021 for (unsigned Factor = 2; Factor <= MaxFactor; Factor <<= 1) {
7022 unsigned Index = 0;
7023 if (ShuffleVectorInst::isDeInterleaveMaskOfFactor(Mask, Factor, Index) &&
7024 1 < count_if(Mask, [](int Idx) { return Idx != -1; })) {
7025 if (SDValue Src = getSingleShuffleSrc(VT, V1, V2))
7026 return getDeinterleaveShiftAndTrunc(DL, VT, Src, Factor, Index, DAG);
7027 if (1 < count_if(Mask,
7028 [&Mask](int Idx) { return Idx < (int)Mask.size(); }) &&
7029 1 < count_if(Mask, [&Mask](int Idx) {
7030 return Idx >= (int)Mask.size();
7031 })) {
7032 // Narrow each source and concatenate them.
7033 // FIXME: For small LMUL it is better to concatenate first.
7034 MVT EltVT = VT.getVectorElementType();
7035 auto EltCnt = VT.getVectorElementCount();
7036 MVT SubVT =
7037 MVT::getVectorVT(EltVT, EltCnt.divideCoefficientBy(Factor));
7038
7039 SDValue Lo =
7040 getDeinterleaveShiftAndTrunc(DL, SubVT, V1, Factor, Index, DAG);
7041 SDValue Hi =
7042 getDeinterleaveShiftAndTrunc(DL, SubVT, V2, Factor, Index, DAG);
7043
7044 SDValue Concat =
7047 if (Factor == 2)
7048 return Concat;
7049
7050 SDValue Vec = DAG.getUNDEF(VT);
7051 return DAG.getInsertSubvector(DL, Vec, Concat, 0);
7052 }
7053 }
7054 }
7055 }
7056
7057 if (SDValue V =
7058 lowerVECTOR_SHUFFLEAsVSlideup(DL, VT, V1, V2, Mask, Subtarget, DAG))
7059 return V;
7060
7061 // Detect an interleave shuffle and lower to
7062 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
7063 int EvenSrc, OddSrc;
7064 if (isInterleaveShuffle(Mask, VT, EvenSrc, OddSrc, Subtarget) &&
7065 !(NumElts == 2 &&
7067 // Extract the halves of the vectors.
7068 MVT HalfVT = VT.getHalfNumVectorElementsVT();
7069
7070 // Recognize if one half is actually undef; the matching above will
7071 // otherwise reuse the even stream for the undef one. This improves
7072 // spread(2) shuffles.
7073 bool LaneIsUndef[2] = { true, true};
7074 for (const auto &[Idx, M] : enumerate(Mask))
7075 LaneIsUndef[Idx % 2] &= (M == -1);
7076
7077 int Size = Mask.size();
7078 SDValue EvenV, OddV;
7079 if (LaneIsUndef[0]) {
7080 EvenV = DAG.getUNDEF(HalfVT);
7081 } else {
7082 assert(EvenSrc >= 0 && "Undef source?");
7083 EvenV = (EvenSrc / Size) == 0 ? V1 : V2;
7084 EvenV = DAG.getExtractSubvector(DL, HalfVT, EvenV, EvenSrc % Size);
7085 }
7086
7087 if (LaneIsUndef[1]) {
7088 OddV = DAG.getUNDEF(HalfVT);
7089 } else {
7090 assert(OddSrc >= 0 && "Undef source?");
7091 OddV = (OddSrc / Size) == 0 ? V1 : V2;
7092 OddV = DAG.getExtractSubvector(DL, HalfVT, OddV, OddSrc % Size);
7093 }
7094
7095 // Prefer vzip if available.
7096 // TODO: Extend to matching vzip if EvenSrc and OddSrc allow.
7097 if (Subtarget.hasStdExtZvzip() &&
7099 return lowerZvzipVZIP(EvenV, OddV, DL, DAG, Subtarget);
7100 return getWideningInterleave(EvenV, OddV, DL, DAG, Subtarget);
7101 }
7102
7103 // Recognize a pattern which can handled via a pair of vslideup/vslidedown
7104 // instructions (in any combination) with masking on the second instruction.
7105 // Also handles masked slides into an identity source, and single slides
7106 // without masking. Avoid matching bit rotates (which are not also element
7107 // rotates) as slide pairs. This is a performance heuristic, not a
7108 // functional check.
7109 std::array<std::pair<int, int>, 2> SrcInfo;
7110 unsigned RotateAmt;
7111 MVT RotateVT;
7112 if (::isMaskedSlidePair(Mask, SrcInfo) &&
7113 (isElementRotate(SrcInfo, NumElts) ||
7114 !isLegalBitRotate(Mask, VT, Subtarget, RotateVT, RotateAmt))) {
7115 SDValue Sources[2];
7116 auto GetSourceFor = [&](const std::pair<int, int> &Info) {
7117 int SrcIdx = Info.first;
7118 assert(SrcIdx == 0 || SrcIdx == 1);
7119 SDValue &Src = Sources[SrcIdx];
7120 if (!Src) {
7121 SDValue SrcV = SrcIdx == 0 ? V1 : V2;
7122 Src = convertToScalableVector(ContainerVT, SrcV, DAG, Subtarget);
7123 }
7124 return Src;
7125 };
7126 auto GetSlide = [&](const std::pair<int, int> &Src, SDValue Mask,
7127 SDValue Passthru) {
7128 auto [TrueMask, VL] = TrueMaskVL;
7129 SDValue SrcV = GetSourceFor(Src);
7130 int SlideAmt = Src.second;
7131 if (SlideAmt == 0) {
7132 // Should never be second operation
7133 assert(Mask == TrueMask);
7134 return SrcV;
7135 }
7136 if (SlideAmt < 0)
7137 return getVSlidedown(DAG, Subtarget, DL, ContainerVT, Passthru, SrcV,
7138 DAG.getConstant(-SlideAmt, DL, XLenVT), Mask, VL,
7140 return getVSlideup(DAG, Subtarget, DL, ContainerVT, Passthru, SrcV,
7141 DAG.getConstant(SlideAmt, DL, XLenVT), Mask, VL,
7143 };
7144
7145 if (SrcInfo[1].first == -1) {
7146 SDValue Res = DAG.getUNDEF(ContainerVT);
7147 Res = GetSlide(SrcInfo[0], TrueMask, Res);
7148 return convertFromScalableVector(VT, Res, DAG, Subtarget);
7149 }
7150
7151 if (Subtarget.hasStdExtZvzip()) {
7152 bool TryWiden = false;
7153 unsigned Factor;
7154 if (isPairEven(SrcInfo, Mask, Factor)) {
7155 if (Factor == 1) {
7156 SDValue Src1 = SrcInfo[0].first == 0 ? V1 : V2;
7157 SDValue Src2 = SrcInfo[1].first == 0 ? V1 : V2;
7158 return lowerZvzipVPAIR(RISCVISD::VPAIRE_VL, Src1, Src2, DL, DAG,
7159 Subtarget);
7160 }
7161 TryWiden = true;
7162 }
7163 if (isPairOdd(SrcInfo, Mask, Factor)) {
7164 if (Factor == 1) {
7165 SDValue Src1 = SrcInfo[1].first == 0 ? V1 : V2;
7166 SDValue Src2 = SrcInfo[0].first == 0 ? V1 : V2;
7167 return lowerZvzipVPAIR(RISCVISD::VPAIRO_VL, Src1, Src2, DL, DAG,
7168 Subtarget);
7169 }
7170 TryWiden = true;
7171 }
7172 // If we found a widening oppurtunity which would let us form a
7173 // pair-even or pair-odd, use the generic code to widen the shuffle
7174 // and recurse through this logic.
7175 if (TryWiden)
7176 if (SDValue V = tryWidenMaskForShuffle(Op, DAG))
7177 return V;
7178 }
7179
7180 // Build the mask. Note that vslideup unconditionally preserves elements
7181 // below the slide amount in the destination, and thus those elements are
7182 // undefined in the mask. If the mask ends up all true (or undef), it
7183 // will be folded away by general logic.
7184 SmallVector<SDValue> MaskVals;
7185 for (const auto &[Idx, M] : enumerate(Mask)) {
7186 if (M < 0 ||
7187 (SrcInfo[1].second > 0 && Idx < (unsigned)SrcInfo[1].second)) {
7188 MaskVals.push_back(DAG.getUNDEF(XLenVT));
7189 continue;
7190 }
7191 int Src = M >= (int)NumElts;
7192 int Diff = (int)Idx - (M % NumElts);
7193 bool C = Src == SrcInfo[1].first && Diff == SrcInfo[1].second;
7194 assert(C ^ (Src == SrcInfo[0].first && Diff == SrcInfo[0].second) &&
7195 "Must match exactly one of the two slides");
7196 MaskVals.push_back(DAG.getConstant(C, DL, XLenVT));
7197 }
7198 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
7199 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
7200 SDValue SelectMask = convertToScalableVector(
7202 DAG.getBuildVector(MaskVT, DL, MaskVals), DAG, Subtarget);
7203
7204 SDValue Res = DAG.getUNDEF(ContainerVT);
7205 Res = GetSlide(SrcInfo[0], TrueMask, Res);
7206 Res = GetSlide(SrcInfo[1], SelectMask, Res);
7207 return convertFromScalableVector(VT, Res, DAG, Subtarget);
7208 }
7209
7210 // Handle any remaining single source shuffles
7211 assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
7212 if (V2.isUndef()) {
7213 // We might be able to express the shuffle as a bitrotate. But even if we
7214 // don't have Zvkb and have to expand, the expanded sequence of approx. 2
7215 // shifts and a vor will have a higher throughput than a vrgather.
7216 if (SDValue V = lowerVECTOR_SHUFFLEAsRotate(SVN, DAG, Subtarget))
7217 return V;
7218
7219 if (SDValue V = lowerVECTOR_SHUFFLEAsVRGatherVX(SVN, Subtarget, DAG))
7220 return V;
7221
7222 // Match a spread(4,8) which can be done via extend and shift. Spread(2)
7223 // is fully covered in interleave(2) above, so it is ignored here.
7224 if (VT.getScalarSizeInBits() < Subtarget.getELen()) {
7225 unsigned MaxFactor = Subtarget.getELen() / VT.getScalarSizeInBits();
7226 assert(MaxFactor == 2 || MaxFactor == 4 || MaxFactor == 8);
7227 for (unsigned Factor = 4; Factor <= MaxFactor; Factor <<= 1) {
7228 unsigned Index;
7229 if (RISCVTargetLowering::isSpreadMask(Mask, Factor, Index)) {
7230 MVT NarrowVT =
7231 MVT::getVectorVT(VT.getVectorElementType(), NumElts / Factor);
7232 SDValue Src = DAG.getExtractSubvector(DL, NarrowVT, V1, 0);
7233 return getWideningSpread(Src, Factor, Index, DL, DAG);
7234 }
7235 }
7236 }
7237
7238 // If only a prefix of the source elements influence a prefix of the
7239 // destination elements, try to see if we can reduce the required LMUL
7240 unsigned MinVLen = Subtarget.getRealMinVLen();
7241 unsigned MinVLMAX = MinVLen / VT.getScalarSizeInBits();
7242 if (NumElts > MinVLMAX) {
7243 unsigned MaxIdx = 0;
7244 for (auto [I, M] : enumerate(Mask)) {
7245 if (M == -1)
7246 continue;
7247 MaxIdx = std::max({(unsigned)I, (unsigned)M, MaxIdx});
7248 }
7249 unsigned NewNumElts =
7250 std::max((uint64_t)MinVLMAX, PowerOf2Ceil(MaxIdx + 1));
7251 if (NewNumElts != NumElts) {
7252 MVT NewVT = MVT::getVectorVT(VT.getVectorElementType(), NewNumElts);
7253 V1 = DAG.getExtractSubvector(DL, NewVT, V1, 0);
7254 SDValue Res = DAG.getVectorShuffle(NewVT, DL, V1, DAG.getUNDEF(NewVT),
7255 Mask.take_front(NewNumElts));
7256 return DAG.getInsertSubvector(DL, DAG.getUNDEF(VT), Res, 0);
7257 }
7258 }
7259
7260 // Before hitting generic lowering fallbacks, try to widen the mask
7261 // to a wider SEW.
7262 if (SDValue V = tryWidenMaskForShuffle(Op, DAG))
7263 return V;
7264
7265 // Can we generate a vcompress instead of a vrgather? These scale better
7266 // at high LMUL, at the cost of not being able to fold a following select
7267 // into them. The mask constants are also smaller than the index vector
7268 // constants, and thus easier to materialize.
7269 if (isCompressMask(Mask)) {
7270 SmallVector<SDValue> MaskVals(NumElts,
7271 DAG.getConstant(false, DL, XLenVT));
7272 for (auto Idx : Mask) {
7273 if (Idx == -1)
7274 break;
7275 assert(Idx >= 0 && (unsigned)Idx < NumElts);
7276 MaskVals[Idx] = DAG.getConstant(true, DL, XLenVT);
7277 }
7278 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
7279 SDValue CompressMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
7280 return DAG.getNode(ISD::VECTOR_COMPRESS, DL, VT, V1, CompressMask,
7281 DAG.getUNDEF(VT));
7282 }
7283
7284 if (VT.getScalarSizeInBits() == 8 &&
7285 any_of(Mask, [&](const auto &Idx) { return Idx > 255; })) {
7286 // On such a vector we're unable to use i8 as the index type.
7287 // FIXME: We could promote the index to i16 and use vrgatherei16, but that
7288 // may involve vector splitting if we're already at LMUL=8, or our
7289 // user-supplied maximum fixed-length LMUL.
7290 return SDValue();
7291 }
7292
7293 // Base case for the two operand recursion below - handle the worst case
7294 // single source shuffle.
7295 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
7296 MVT IndexVT = VT.changeTypeToInteger();
7297 // Since we can't introduce illegal index types at this stage, use i16 and
7298 // vrgatherei16 if the corresponding index type for plain vrgather is greater
7299 // than XLenVT.
7300 if (IndexVT.getScalarType().bitsGT(XLenVT)) {
7301 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
7302 IndexVT = IndexVT.changeVectorElementType(MVT::i16);
7303 }
7304
7305 // If the mask allows, we can do all the index computation in 16 bits. This
7306 // requires less work and less register pressure at high LMUL, and creates
7307 // smaller constants which may be cheaper to materialize.
7308 if (IndexVT.getScalarType().bitsGT(MVT::i16) && isUInt<16>(NumElts - 1) &&
7309 (IndexVT.getSizeInBits() / Subtarget.getRealMinVLen()) > 1) {
7310 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
7311 IndexVT = IndexVT.changeVectorElementType(MVT::i16);
7312 }
7313
7314 MVT IndexContainerVT =
7316
7317 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
7318 SmallVector<SDValue> GatherIndicesLHS;
7319 for (int MaskIndex : Mask) {
7320 bool IsLHSIndex = MaskIndex < (int)NumElts && MaskIndex >= 0;
7321 GatherIndicesLHS.push_back(IsLHSIndex
7322 ? DAG.getConstant(MaskIndex, DL, XLenVT)
7323 : DAG.getUNDEF(XLenVT));
7324 }
7325 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
7326 LHSIndices =
7327 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
7328 // At m1 and less, there's no point trying any of the high LMUL splitting
7329 // techniques. TODO: Should we reconsider this for DLEN < VLEN?
7330 if (NumElts <= MinVLMAX) {
7331 SDValue Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
7332 DAG.getUNDEF(ContainerVT), TrueMask, VL);
7333 return convertFromScalableVector(VT, Gather, DAG, Subtarget);
7334 }
7335
7336 const MVT M1VT = RISCVTargetLowering::getM1VT(ContainerVT);
7337 EVT SubIndexVT = M1VT.changeVectorElementType(IndexVT.getScalarType());
7338 auto [InnerTrueMask, InnerVL] =
7339 getDefaultScalableVLOps(M1VT, DL, DAG, Subtarget);
7340 int N =
7342 assert(isPowerOf2_32(N) && N <= 8);
7343
7344 // If we have a locally repeating mask, then we can reuse the first
7345 // register in the index register group for all registers within the
7346 // source register group. TODO: This generalizes to m2, and m4.
7347 if (isLocalRepeatingShuffle(Mask, MinVLMAX)) {
7348 SDValue SubIndex = DAG.getExtractSubvector(DL, SubIndexVT, LHSIndices, 0);
7349 SDValue Gather = DAG.getUNDEF(ContainerVT);
7350 for (int i = 0; i < N; i++) {
7351 unsigned SubIdx = M1VT.getVectorMinNumElements() * i;
7352 SDValue SubV1 = DAG.getExtractSubvector(DL, M1VT, V1, SubIdx);
7353 SDValue SubVec =
7354 DAG.getNode(GatherVVOpc, DL, M1VT, SubV1, SubIndex,
7355 DAG.getUNDEF(M1VT), InnerTrueMask, InnerVL);
7356 Gather = DAG.getInsertSubvector(DL, Gather, SubVec, SubIdx);
7357 }
7358 return convertFromScalableVector(VT, Gather, DAG, Subtarget);
7359 }
7360
7361 // If we have a shuffle which only uses the first register in our source
7362 // register group, and repeats the same index across all spans, we can
7363 // use a single vrgather (and possibly some register moves).
7364 // TODO: This can be generalized for m2 or m4, or for any shuffle for
7365 // which we can do a linear number of shuffles to form an m1 which
7366 // contains all the output elements.
7367 if (isLowSourceShuffle(Mask, MinVLMAX) &&
7368 isSpanSplatShuffle(Mask, MinVLMAX)) {
7369 SDValue SubV1 = DAG.getExtractSubvector(DL, M1VT, V1, 0);
7370 SDValue SubIndex = DAG.getExtractSubvector(DL, SubIndexVT, LHSIndices, 0);
7371 SDValue SubVec = DAG.getNode(GatherVVOpc, DL, M1VT, SubV1, SubIndex,
7372 DAG.getUNDEF(M1VT), InnerTrueMask, InnerVL);
7373 SDValue Gather = DAG.getUNDEF(ContainerVT);
7374 for (int i = 0; i < N; i++)
7375 Gather = DAG.getInsertSubvector(DL, Gather, SubVec,
7376 M1VT.getVectorMinNumElements() * i);
7377 return convertFromScalableVector(VT, Gather, DAG, Subtarget);
7378 }
7379
7380 // If we have a shuffle which only uses the first register in our
7381 // source register group, we can do a linear number of m1 vrgathers
7382 // reusing the same source register (but with different indices)
7383 // TODO: This can be generalized for m2 or m4, or for any shuffle
7384 // for which we can do a vslidedown followed by this expansion.
7385 if (isLowSourceShuffle(Mask, MinVLMAX)) {
7386 SDValue SlideAmt =
7387 DAG.getElementCount(DL, XLenVT, M1VT.getVectorElementCount());
7388 SDValue SubV1 = DAG.getExtractSubvector(DL, M1VT, V1, 0);
7389 SDValue Gather = DAG.getUNDEF(ContainerVT);
7390 for (int i = 0; i < N; i++) {
7391 if (i != 0)
7392 LHSIndices = getVSlidedown(DAG, Subtarget, DL, IndexContainerVT,
7393 DAG.getUNDEF(IndexContainerVT), LHSIndices,
7394 SlideAmt, TrueMask, VL);
7395 SDValue SubIndex =
7396 DAG.getExtractSubvector(DL, SubIndexVT, LHSIndices, 0);
7397 SDValue SubVec =
7398 DAG.getNode(GatherVVOpc, DL, M1VT, SubV1, SubIndex,
7399 DAG.getUNDEF(M1VT), InnerTrueMask, InnerVL);
7400 Gather = DAG.getInsertSubvector(DL, Gather, SubVec,
7401 M1VT.getVectorMinNumElements() * i);
7402 }
7403 return convertFromScalableVector(VT, Gather, DAG, Subtarget);
7404 }
7405
7406 // Fallback to generic vrgather if we can't find anything better.
7407 // On many machines, this will be O(LMUL^2)
7408 SDValue Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
7409 DAG.getUNDEF(ContainerVT), TrueMask, VL);
7410 return convertFromScalableVector(VT, Gather, DAG, Subtarget);
7411 }
7412
7413 // As a backup, shuffles can be lowered via a vrgather instruction, possibly
7414 // merged with a second vrgather.
7415 SmallVector<int> ShuffleMaskLHS, ShuffleMaskRHS;
7416
7417 // Now construct the mask that will be used by the blended vrgather operation.
7418 // Construct the appropriate indices into each vector.
7419 for (int MaskIndex : Mask) {
7420 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
7421 ShuffleMaskLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
7422 ? MaskIndex : -1);
7423 ShuffleMaskRHS.push_back(IsLHSOrUndefIndex ? -1 : (MaskIndex - NumElts));
7424 }
7425
7426 // If the mask indices are disjoint between the two sources, we can lower it
7427 // as a vselect + a single source vrgather.vv. Don't do this if we think the
7428 // operands may end up being lowered to something cheaper than a vrgather.vv.
7429 if (!DAG.isSplatValue(V2) && !DAG.isSplatValue(V1) &&
7430 !ShuffleVectorSDNode::isSplatMask(ShuffleMaskLHS) &&
7431 !ShuffleVectorSDNode::isSplatMask(ShuffleMaskRHS) &&
7432 !ShuffleVectorInst::isIdentityMask(ShuffleMaskLHS, NumElts) &&
7433 !ShuffleVectorInst::isIdentityMask(ShuffleMaskRHS, NumElts))
7434 if (SDValue V = lowerDisjointIndicesShuffle(SVN, DAG, Subtarget))
7435 return V;
7436
7437 // Before hitting generic lowering fallbacks, try to widen the mask
7438 // to a wider SEW.
7439 if (SDValue V = tryWidenMaskForShuffle(Op, DAG))
7440 return V;
7441
7442 // Try to pick a profitable operand order.
7443 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
7444 SwapOps = SwapOps ^ ShuffleVectorInst::isIdentityMask(ShuffleMaskRHS, NumElts);
7445
7446 // Recursively invoke lowering for each operand if we had two
7447 // independent single source shuffles, and then combine the result via a
7448 // vselect. Note that the vselect will likely be folded back into the
7449 // second permute (vrgather, or other) by the post-isel combine.
7450 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), ShuffleMaskLHS);
7451 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), ShuffleMaskRHS);
7452
7453 SmallVector<SDValue> MaskVals;
7454 for (int MaskIndex : Mask) {
7455 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ !SwapOps;
7456 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
7457 }
7458
7459 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
7460 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
7461 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
7462
7463 if (SwapOps)
7464 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
7465 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V2, V1);
7466}
7467
7469 EVT VT) const {
7470 // Enable DAGCombiner::XformToShuffleWithZero to rewrite a packed zero-extend
7471 // `and` into shuffle(src, zero, ...), which lowerVECTOR_SHUFFLE turns into
7472 // RISCVISD::PPAIRE. Accept the packed byte/halfword views that lowering
7473 // handles; the 32-bit views are illegal on RV64 but reachable before type
7474 // legalization widens them to the legal 64-bit view.
7475 if (!Subtarget.hasStdExtP() || !VT.isSimple())
7476 return false;
7477 MVT SVT = VT.getSimpleVT();
7478 SmallVector<int> CommutedMask(M);
7480 return (SVT == MVT::v4i8 || SVT == MVT::v8i8 || SVT == MVT::v4i16) &&
7482}
7483
7485 // Only support legal VTs for other shuffles for now.
7486 if (!isTypeLegal(VT) || !Subtarget.hasVInstructions())
7487 return false;
7488
7489 // Support splats for any type. These should type legalize well.
7491 return true;
7492
7493 const unsigned NumElts = M.size();
7494 MVT SVT = VT.getSimpleVT();
7495
7496 // Not for i1 vectors.
7497 if (SVT.getScalarType() == MVT::i1)
7498 return false;
7499
7500 std::array<std::pair<int, int>, 2> SrcInfo;
7501 int Dummy1, Dummy2;
7502 return ShuffleVectorInst::isReverseMask(M, NumElts) ||
7503 (::isMaskedSlidePair(M, SrcInfo) &&
7504 isElementRotate(SrcInfo, NumElts)) ||
7505 isInterleaveShuffle(M, SVT, Dummy1, Dummy2, Subtarget);
7506}
7507
7508// Lower CTLZ_ZERO_POISON or CTTZ_ZERO_POISON by converting to FP and extracting
7509// the exponent.
7510SDValue
7511RISCVTargetLowering::lowerCTLZ_CTTZ_ZERO_POISON(SDValue Op,
7512 SelectionDAG &DAG) const {
7513 MVT VT = Op.getSimpleValueType();
7514 unsigned EltSize = VT.getScalarSizeInBits();
7515 SDValue Src = Op.getOperand(0);
7516 SDLoc DL(Op);
7517 MVT ContainerVT = VT;
7518
7519 // We choose FP type that can represent the value if possible. Otherwise, we
7520 // use rounding to zero conversion for correct exponent of the result.
7521 // TODO: Use f16 for i8 when possible?
7522 MVT FloatEltVT = (EltSize >= 32) ? MVT::f64 : MVT::f32;
7523 if (!isTypeLegal(MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount())))
7524 FloatEltVT = MVT::f32;
7525 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
7526
7527 // Legal types should have been checked in the RISCVTargetLowering
7528 // constructor.
7529 // TODO: Splitting may make sense in some cases.
7530 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
7531 "Expected legal float type!");
7532
7533 // For CTTZ_ZERO_POISON, we need to extract the lowest set bit using X & -X.
7534 // The trailing zero count is equal to log2 of this single bit value.
7535 if (Op.getOpcode() == ISD::CTTZ_ZERO_POISON) {
7536 SDValue Neg = DAG.getNegative(Src, DL, VT);
7537 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
7538 }
7539
7540 // We have a legal FP type, convert to it.
7541 SDValue FloatVal;
7542 if (FloatVT.bitsGT(VT)) {
7543 FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
7544 } else {
7545 // Use RTZ to avoid rounding influencing exponent of FloatVal.
7546 if (VT.isFixedLengthVector()) {
7548 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
7549 }
7550 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
7551 SDValue RTZRM =
7552 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT());
7553 MVT ContainerFloatVT =
7555 FloatVal = DAG.getNode(RISCVISD::VFCVT_RM_F_XU_VL, DL, ContainerFloatVT,
7556 Src, Mask, RTZRM, VL);
7557 if (VT.isFixedLengthVector())
7558 FloatVal = convertFromScalableVector(FloatVT, FloatVal, DAG, Subtarget);
7559 }
7560 // Bitcast to integer and shift the exponent to the LSB.
7561 EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
7562 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
7563 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
7564
7565 // Restore back to original type. Truncation after SRL is to generate vnsrl.
7566 SDValue Exp = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
7567 DAG.getConstant(ShiftAmt, DL, IntVT));
7568 if (IntVT.bitsLT(VT))
7569 Exp = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Exp);
7570 else if (IntVT.bitsGT(VT))
7571 Exp = DAG.getNode(ISD::TRUNCATE, DL, VT, Exp);
7572
7573 // The exponent contains log2 of the value in biased form.
7574 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
7575 // For trailing zeros, we just need to subtract the bias.
7576 if (Op.getOpcode() == ISD::CTTZ_ZERO_POISON)
7577 return DAG.getNode(ISD::SUB, DL, VT, Exp,
7578 DAG.getConstant(ExponentBias, DL, VT));
7579
7580 // For leading zeros, we need to remove the bias and convert from log2 to
7581 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
7582 unsigned Adjust = ExponentBias + (EltSize - 1);
7583 SDValue Res =
7584 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Exp);
7585
7586 // The above result with zero input equals to Adjust which is greater than
7587 // EltSize. Hence, we can do min(Res, EltSize) for CTLZ.
7588 if (Op.getOpcode() == ISD::CTLZ)
7589 Res = DAG.getNode(ISD::UMIN, DL, VT, Res, DAG.getConstant(EltSize, DL, VT));
7590
7591 return Res;
7592}
7593
7594SDValue RISCVTargetLowering::lowerVPCttzElements(SDValue Op,
7595 SelectionDAG &DAG) const {
7596 SDLoc DL(Op);
7597 MVT XLenVT = Subtarget.getXLenVT();
7598 SDValue Source = Op->getOperand(0);
7599 MVT SrcVT = Source.getSimpleValueType();
7600 SDValue Mask = Op->getOperand(1);
7601 SDValue EVL = Op->getOperand(2);
7602
7603 if (SrcVT.isFixedLengthVector()) {
7605 Source = convertToScalableVector(ContainerVT, Source, DAG, Subtarget);
7607 Subtarget);
7608 SrcVT = ContainerVT;
7609 }
7610
7611 // Convert to boolean vector.
7612 if (SrcVT.getScalarType() != MVT::i1) {
7613 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
7614 SrcVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorElementCount());
7615 Source = DAG.getNode(RISCVISD::SETCC_VL, DL, SrcVT,
7616 {Source, AllZero, DAG.getCondCode(ISD::SETNE),
7617 DAG.getUNDEF(SrcVT), Mask, EVL});
7618 }
7619
7620 SDValue Res = DAG.getNode(RISCVISD::VFIRST_VL, DL, XLenVT, Source, Mask, EVL);
7621 if (Op->getOpcode() == ISD::VP_CTTZ_ELTS_ZERO_POISON)
7622 // In this case, we can interpret poison as -1, so nothing to do further.
7623 return Res;
7624
7625 // Convert -1 to VL.
7626 SDValue SetCC =
7627 DAG.getSetCC(DL, XLenVT, Res, DAG.getConstant(0, DL, XLenVT), ISD::SETLT);
7628 Res = DAG.getSelect(DL, XLenVT, SetCC, EVL, Res);
7629 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Res);
7630}
7631
7632// While RVV has alignment restrictions, we should always be able to load as a
7633// legal equivalently-sized byte-typed vector instead. This method is
7634// responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
7635// the load is already correctly-aligned, it returns SDValue().
7636SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
7637 SelectionDAG &DAG) const {
7638 auto *Load = cast<LoadSDNode>(Op);
7639 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
7640
7642 Load->getMemoryVT(),
7643 *Load->getMemOperand()))
7644 return SDValue();
7645
7646 SDLoc DL(Op);
7647 MVT VT = Op.getSimpleValueType();
7648 unsigned EltSizeBits = VT.getScalarSizeInBits();
7649 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
7650 "Unexpected unaligned RVV load type");
7651 MVT NewVT =
7652 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
7653 assert(NewVT.isValid() &&
7654 "Expecting equally-sized RVV vector types to be legal");
7655 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
7656 Load->getPointerInfo(), Load->getBaseAlign(),
7657 Load->getMemOperand()->getFlags());
7658 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
7659}
7660
7661// While RVV has alignment restrictions, we should always be able to store as a
7662// legal equivalently-sized byte-typed vector instead. This method is
7663// responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
7664// returns SDValue() if the store is already correctly aligned.
7665SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
7666 SelectionDAG &DAG) const {
7667 auto *Store = cast<StoreSDNode>(Op);
7668 assert(Store && Store->getValue().getValueType().isVector() &&
7669 "Expected vector store");
7670
7672 Store->getMemoryVT(),
7673 *Store->getMemOperand()))
7674 return SDValue();
7675
7676 SDLoc DL(Op);
7677 SDValue StoredVal = Store->getValue();
7678 MVT VT = StoredVal.getSimpleValueType();
7679 unsigned EltSizeBits = VT.getScalarSizeInBits();
7680 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
7681 "Unexpected unaligned RVV store type");
7682 MVT NewVT =
7683 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
7684 assert(NewVT.isValid() &&
7685 "Expecting equally-sized RVV vector types to be legal");
7686 StoredVal = DAG.getBitcast(NewVT, StoredVal);
7687 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
7688 Store->getPointerInfo(), Store->getBaseAlign(),
7689 Store->getMemOperand()->getFlags());
7690}
7691
7692// While RVV has alignment restrictions, we should always be able to load as a
7693// legal equivalently-sized byte-typed vector instead. This method is
7694// responsible for re-expressing a ISD::VP_LOAD via a correctly-aligned type. If
7695// the load is already correctly-aligned, it returns SDValue().
7696SDValue RISCVTargetLowering::expandUnalignedVPLoad(SDValue Op,
7697 SelectionDAG &DAG) const {
7698 auto *Load = cast<VPLoadSDNode>(Op);
7699 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
7700
7702 Load->getMemoryVT(),
7703 *Load->getMemOperand()))
7704 return SDValue();
7705
7706 SDValue Mask = Load->getMask();
7707
7708 // FIXME: Handled masked loads somehow.
7710 return SDValue();
7711
7712 SDLoc DL(Op);
7713 MVT VT = Op.getSimpleValueType();
7714 unsigned EltSizeBits = VT.getScalarSizeInBits();
7715 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
7716 "Unexpected unaligned RVV load type");
7717 MVT NewVT =
7718 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
7719 assert(NewVT.isValid() &&
7720 "Expecting equally-sized RVV vector types to be legal");
7721
7722 SDValue VL = Load->getVectorLength();
7723 VL = DAG.getNode(ISD::MUL, DL, VL.getValueType(), VL,
7724 DAG.getConstant((EltSizeBits / 8), DL, VL.getValueType()));
7725
7726 MVT MaskVT = MVT::getVectorVT(MVT::i1, NewVT.getVectorElementCount());
7727 SDValue L = DAG.getLoadVP(NewVT, DL, Load->getChain(), Load->getBasePtr(),
7728 DAG.getAllOnesConstant(DL, MaskVT), VL,
7729 Load->getPointerInfo(), Load->getBaseAlign(),
7730 Load->getMemOperand()->getFlags(), AAMDNodes());
7731 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
7732}
7733
7734// While RVV has alignment restrictions, we should always be able to store as a
7735// legal equivalently-sized byte-typed vector instead. This method is
7736// responsible for re-expressing a ISD::VP STORE via a correctly-aligned type.
7737// It returns SDValue() if the store is already correctly aligned.
7738SDValue RISCVTargetLowering::expandUnalignedVPStore(SDValue Op,
7739 SelectionDAG &DAG) const {
7740 auto *Store = cast<VPStoreSDNode>(Op);
7741 assert(Store && Store->getValue().getValueType().isVector() &&
7742 "Expected vector store");
7743
7745 Store->getMemoryVT(),
7746 *Store->getMemOperand()))
7747 return SDValue();
7748
7749 SDValue Mask = Store->getMask();
7750
7751 // FIXME: Handled masked stores somehow.
7753 return SDValue();
7754
7755 SDLoc DL(Op);
7756 SDValue StoredVal = Store->getValue();
7757 MVT VT = StoredVal.getSimpleValueType();
7758 unsigned EltSizeBits = VT.getScalarSizeInBits();
7759 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
7760 "Unexpected unaligned RVV store type");
7761 MVT NewVT =
7762 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
7763 assert(NewVT.isValid() &&
7764 "Expecting equally-sized RVV vector types to be legal");
7765
7766 SDValue VL = Store->getVectorLength();
7767 VL = DAG.getNode(ISD::MUL, DL, VL.getValueType(), VL,
7768 DAG.getConstant((EltSizeBits / 8), DL, VL.getValueType()));
7769
7770 StoredVal = DAG.getBitcast(NewVT, StoredVal);
7771
7772 LocationSize Size = LocationSize::precise(NewVT.getStoreSize());
7774 MachineMemOperand *MMO = MF.getMachineMemOperand(
7775 Store->getPointerInfo(), Store->getMemOperand()->getFlags(), Size,
7776 Store->getBaseAlign());
7777
7778 MVT MaskVT = MVT::getVectorVT(MVT::i1, NewVT.getVectorElementCount());
7779 return DAG.getStoreVP(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
7780 DAG.getPOISON(Store->getBasePtr().getValueType()),
7781 DAG.getAllOnesConstant(DL, MaskVT), VL, NewVT, MMO,
7783}
7784
7786 const RISCVSubtarget &Subtarget) {
7787 assert(Op.getValueType() == MVT::i64 && "Unexpected VT");
7788
7789 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue();
7790
7791 // All simm32 constants should be handled by isel.
7792 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
7793 // this check redundant, but small immediates are common so this check
7794 // should have better compile time.
7795 if (isInt<32>(Imm))
7796 return Op;
7797
7798 // We only need to cost the immediate, if constant pool lowering is enabled.
7799 if (!Subtarget.useConstantPoolForLargeInts())
7800 return Op;
7801
7803 if (Seq.size() <= Subtarget.getMaxBuildIntsCost())
7804 return Op;
7805
7806 // Optimizations below are disabled for opt size. If we're optimizing for
7807 // size, use a constant pool.
7808 if (DAG.shouldOptForSize())
7809 return SDValue();
7810
7811 // Special case. See if we can build the constant as (ADD (SLLI X, C), X) do
7812 // that if it will avoid a constant pool.
7813 // It will require an extra temporary register though.
7814 // If we have Zba we can use (ADD_UW X, (SLLI X, 32)) to handle cases where
7815 // low and high 32 bits are the same and bit 31 and 63 are set.
7816 unsigned ShiftAmt, AddOpc;
7817 RISCVMatInt::InstSeq SeqLo =
7819 if (!SeqLo.empty() && (SeqLo.size() + 2) <= Subtarget.getMaxBuildIntsCost())
7820 return Op;
7821
7822 return SDValue();
7823}
7824
7825SDValue RISCVTargetLowering::lowerConstantFP(SDValue Op,
7826 SelectionDAG &DAG) const {
7827 MVT VT = Op.getSimpleValueType();
7828 const APFloat &Imm = cast<ConstantFPSDNode>(Op)->getValueAPF();
7829
7830 // Can this constant be selected by a Zfa FLI instruction?
7831 bool Negate = false;
7832 int Index = getLegalZfaFPImm(Imm, VT);
7833
7834 // If the constant is negative, try negating.
7835 if (Index < 0 && Imm.isNegative()) {
7836 Index = getLegalZfaFPImm(-Imm, VT);
7837 Negate = true;
7838 }
7839
7840 // If we couldn't find a FLI lowering, fall back to generic code.
7841 if (Index < 0)
7842 return SDValue();
7843
7844 // Emit an FLI+FNEG. We use a custom node to hide from constant folding.
7845 SDLoc DL(Op);
7846 SDValue Const =
7847 DAG.getNode(RISCVISD::FLI, DL, VT,
7848 DAG.getTargetConstant(Index, DL, Subtarget.getXLenVT()));
7849 if (!Negate)
7850 return Const;
7851
7852 return DAG.getNode(ISD::FNEG, DL, VT, Const);
7853}
7854
7856 SelectionDAG &DAG) {
7857
7858 unsigned IsData = Op.getConstantOperandVal(4);
7859
7860 // mips-p8700 we support data prefetch for now.
7861 if (Subtarget.hasVendorXMIPSCBOP() && !IsData)
7862 return Op.getOperand(0);
7863 return Op;
7864}
7865
7867 const RISCVSubtarget &Subtarget) {
7868 SDLoc dl(Op);
7869 AtomicOrdering FenceOrdering =
7870 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
7871 SyncScope::ID FenceSSID =
7872 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
7873
7874 if (Subtarget.hasStdExtZtso()) {
7875 // The only fence that needs an instruction is a sequentially-consistent
7876 // cross-thread fence.
7877 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
7878 FenceSSID == SyncScope::System)
7879 return Op;
7880
7881 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
7882 return DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
7883 }
7884
7885 // singlethread fences only synchronize with signal handlers on the same
7886 // thread and thus only need to preserve instruction order, not actually
7887 // enforce memory ordering.
7888 if (FenceSSID == SyncScope::SingleThread)
7889 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
7890 return DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
7891
7892 return Op;
7893}
7894
7895SDValue RISCVTargetLowering::LowerIS_FPCLASS(SDValue Op,
7896 SelectionDAG &DAG) const {
7897 SDLoc DL(Op);
7898 MVT VT = Op.getSimpleValueType();
7899 MVT XLenVT = Subtarget.getXLenVT();
7900 unsigned Check = Op.getConstantOperandVal(1);
7901 unsigned TDCMask = 0;
7902 if (Check & fcSNan)
7903 TDCMask |= RISCV::FPMASK_Signaling_NaN;
7904 if (Check & fcQNan)
7905 TDCMask |= RISCV::FPMASK_Quiet_NaN;
7906 if (Check & fcPosInf)
7908 if (Check & fcNegInf)
7910 if (Check & fcPosNormal)
7912 if (Check & fcNegNormal)
7914 if (Check & fcPosSubnormal)
7916 if (Check & fcNegSubnormal)
7918 if (Check & fcPosZero)
7919 TDCMask |= RISCV::FPMASK_Positive_Zero;
7920 if (Check & fcNegZero)
7921 TDCMask |= RISCV::FPMASK_Negative_Zero;
7922
7923 bool IsOneBitMask = isPowerOf2_32(TDCMask);
7924
7925 SDValue TDCMaskV = DAG.getConstant(TDCMask, DL, XLenVT);
7926
7927 if (VT.isVector()) {
7928 SDValue Op0 = Op.getOperand(0);
7929 MVT VT0 = Op.getOperand(0).getSimpleValueType();
7930
7931 if (VT.isScalableVector()) {
7932 MVT DstVT = VT0.changeVectorElementTypeToInteger();
7933 auto [Mask, VL] = getDefaultScalableVLOps(VT0, DL, DAG, Subtarget);
7934 SDValue FPCLASS = DAG.getNode(RISCVISD::FCLASS_VL, DL, DstVT, Op0, Mask,
7935 VL, Op->getFlags());
7936 if (IsOneBitMask)
7937 return DAG.getSetCC(DL, VT, FPCLASS,
7938 DAG.getConstant(TDCMask, DL, DstVT),
7940 SDValue AND = DAG.getNode(ISD::AND, DL, DstVT, FPCLASS,
7941 DAG.getConstant(TDCMask, DL, DstVT));
7942 return DAG.getSetCC(DL, VT, AND, DAG.getConstant(0, DL, DstVT),
7943 ISD::SETNE);
7944 }
7945
7946 MVT ContainerVT0 = getContainerForFixedLengthVector(VT0);
7948 MVT ContainerDstVT = ContainerVT0.changeVectorElementTypeToInteger();
7949 auto [Mask, VL] = getDefaultVLOps(VT0, ContainerVT0, DL, DAG, Subtarget);
7950 Op0 = convertToScalableVector(ContainerVT0, Op0, DAG, Subtarget);
7951
7952 SDValue FPCLASS = DAG.getNode(RISCVISD::FCLASS_VL, DL, ContainerDstVT, Op0,
7953 Mask, VL, Op->getFlags());
7954
7955 TDCMaskV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerDstVT,
7956 DAG.getUNDEF(ContainerDstVT), TDCMaskV, VL);
7957 if (IsOneBitMask) {
7958 SDValue VMSEQ =
7959 DAG.getNode(RISCVISD::SETCC_VL, DL, ContainerVT,
7960 {FPCLASS, TDCMaskV, DAG.getCondCode(ISD::SETEQ),
7961 DAG.getUNDEF(ContainerVT), Mask, VL});
7962 return convertFromScalableVector(VT, VMSEQ, DAG, Subtarget);
7963 }
7964 SDValue AND = DAG.getNode(RISCVISD::AND_VL, DL, ContainerDstVT, FPCLASS,
7965 TDCMaskV, DAG.getUNDEF(ContainerDstVT), Mask, VL);
7966
7967 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
7968 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerDstVT,
7969 DAG.getUNDEF(ContainerDstVT), SplatZero, VL);
7970
7971 SDValue VMSNE = DAG.getNode(RISCVISD::SETCC_VL, DL, ContainerVT,
7972 {AND, SplatZero, DAG.getCondCode(ISD::SETNE),
7973 DAG.getUNDEF(ContainerVT), Mask, VL});
7974 return convertFromScalableVector(VT, VMSNE, DAG, Subtarget);
7975 }
7976
7977 SDValue FCLASS = DAG.getNode(RISCVISD::FCLASS, DL, XLenVT, Op.getOperand(0));
7978 SDValue AND = DAG.getNode(ISD::AND, DL, XLenVT, FCLASS, TDCMaskV);
7979 SDValue Res = DAG.getSetCC(DL, XLenVT, AND, DAG.getConstant(0, DL, XLenVT),
7981 return DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
7982}
7983
7984// Lower fmaximum and fminimum. Unlike our fmax and fmin instructions, these
7985// operations propagate nans.
7987 const RISCVSubtarget &Subtarget) {
7988 SDLoc DL(Op);
7989 MVT VT = Op.getSimpleValueType();
7990
7991 SDValue X = Op.getOperand(0);
7992 SDValue Y = Op.getOperand(1);
7993
7994 if (!VT.isVector()) {
7995 MVT XLenVT = Subtarget.getXLenVT();
7996
7997 // If X is a nan, replace Y with X. If Y is a nan, replace X with Y. This
7998 // ensures that when one input is a nan, the other will also be a nan
7999 // allowing the nan to propagate. If both inputs are nan, this will swap the
8000 // inputs which is harmless.
8001
8002 SDValue NewY = Y;
8003 if (!Op->getFlags().hasNoNaNs() && !DAG.isKnownNeverNaN(X)) {
8004 SDValue XIsNonNan = DAG.getSetCC(DL, XLenVT, X, X, ISD::SETOEQ);
8005 NewY = DAG.getSelect(DL, VT, XIsNonNan, Y, X);
8006 }
8007
8008 SDValue NewX = X;
8009 if (!Op->getFlags().hasNoNaNs() && !DAG.isKnownNeverNaN(Y)) {
8010 SDValue YIsNonNan = DAG.getSetCC(DL, XLenVT, Y, Y, ISD::SETOEQ);
8011 NewX = DAG.getSelect(DL, VT, YIsNonNan, X, Y);
8012 }
8013
8014 unsigned Opc =
8015 Op.getOpcode() == ISD::FMAXIMUM ? RISCVISD::FMAX : RISCVISD::FMIN;
8016 return DAG.getNode(Opc, DL, VT, NewX, NewY);
8017 }
8018
8019 // Check no NaNs before converting to fixed vector scalable.
8020 bool XIsNeverNan = Op->getFlags().hasNoNaNs() || DAG.isKnownNeverNaN(X);
8021 bool YIsNeverNan = Op->getFlags().hasNoNaNs() || DAG.isKnownNeverNaN(Y);
8022
8023 MVT ContainerVT = VT;
8024 if (VT.isFixedLengthVector()) {
8028 }
8029
8030 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
8031
8032 SDValue NewY = Y;
8033 if (!XIsNeverNan) {
8034 SDValue XIsNonNan =
8035 DAG.getNode(RISCVISD::SETCC_VL, DL, Mask.getValueType(),
8036 {X, X, DAG.getCondCode(ISD::SETOEQ),
8037 DAG.getUNDEF(Mask.getValueType()), Mask, VL});
8038 NewY = DAG.getNode(RISCVISD::VMERGE_VL, DL, ContainerVT, XIsNonNan, Y, X,
8039 DAG.getUNDEF(ContainerVT), VL);
8040 }
8041
8042 SDValue NewX = X;
8043 if (!YIsNeverNan) {
8044 SDValue YIsNonNan =
8045 DAG.getNode(RISCVISD::SETCC_VL, DL, Mask.getValueType(),
8046 {Y, Y, DAG.getCondCode(ISD::SETOEQ),
8047 DAG.getUNDEF(Mask.getValueType()), Mask, VL});
8048 NewX = DAG.getNode(RISCVISD::VMERGE_VL, DL, ContainerVT, YIsNonNan, X, Y,
8049 DAG.getUNDEF(ContainerVT), VL);
8050 }
8051
8052 unsigned Opc =
8053 Op.getOpcode() == ISD::FMAXIMUM ? RISCVISD::VFMAX_VL : RISCVISD::VFMIN_VL;
8054 SDValue Res = DAG.getNode(Opc, DL, ContainerVT, NewX, NewY,
8055 DAG.getUNDEF(ContainerVT), Mask, VL);
8056 if (VT.isFixedLengthVector())
8057 Res = convertFromScalableVector(VT, Res, DAG, Subtarget);
8058 return Res;
8059}
8060
8062 const RISCVSubtarget &Subtarget) {
8063 bool IsFABS = Op.getOpcode() == ISD::FABS;
8064 assert((IsFABS || Op.getOpcode() == ISD::FNEG) &&
8065 "Wrong opcode for lowering FABS or FNEG.");
8066
8067 MVT XLenVT = Subtarget.getXLenVT();
8068 MVT VT = Op.getSimpleValueType();
8069 assert((VT == MVT::f16 || VT == MVT::bf16) && "Unexpected type");
8070
8071 SDLoc DL(Op);
8072 SDValue Fmv =
8073 DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op.getOperand(0));
8074
8075 APInt Mask = IsFABS ? APInt::getSignedMaxValue(16) : APInt::getSignMask(16);
8076 Mask = Mask.sext(Subtarget.getXLen());
8077
8078 unsigned LogicOpc = IsFABS ? ISD::AND : ISD::XOR;
8079 SDValue Logic =
8080 DAG.getNode(LogicOpc, DL, XLenVT, Fmv, DAG.getConstant(Mask, DL, XLenVT));
8081 return DAG.getNode(RISCVISD::FMV_H_X, DL, VT, Logic);
8082}
8083
8085 const RISCVSubtarget &Subtarget) {
8086 assert(Op.getOpcode() == ISD::FCOPYSIGN && "Unexpected opcode");
8087
8088 MVT XLenVT = Subtarget.getXLenVT();
8089 MVT VT = Op.getSimpleValueType();
8090 assert((VT == MVT::f16 || VT == MVT::bf16) && "Unexpected type");
8091
8092 SDValue Mag = Op.getOperand(0);
8093 SDValue Sign = Op.getOperand(1);
8094
8095 SDLoc DL(Op);
8096
8097 // Get sign bit into an integer value.
8098 unsigned SignSize = Sign.getValueSizeInBits();
8099 SDValue SignAsInt = [&]() {
8100 if (SignSize == Subtarget.getXLen())
8101 return DAG.getNode(ISD::BITCAST, DL, XLenVT, Sign);
8102 switch (SignSize) {
8103 case 16:
8104 return DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Sign);
8105 case 32:
8106 return DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, XLenVT, Sign);
8107 case 64: {
8108 assert(XLenVT == MVT::i32 && "Unexpected type");
8109 // Copy the upper word to integer.
8110 SignSize = 32;
8111 return DAG.getNode(RISCVISD::SplitF64, DL, {MVT::i32, MVT::i32}, Sign)
8112 .getValue(1);
8113 }
8114 default:
8115 llvm_unreachable("Unexpected sign size");
8116 }
8117 }();
8118
8119 // Get the signbit at the right position for MagAsInt.
8120 if (int ShiftAmount = (int)SignSize - (int)Mag.getValueSizeInBits())
8121 SignAsInt = DAG.getNode(ShiftAmount > 0 ? ISD::SRL : ISD::SHL, DL, XLenVT,
8122 SignAsInt,
8123 DAG.getConstant(std::abs(ShiftAmount), DL, XLenVT));
8124
8125 // Mask the sign bit and any bits above it. The extra bits will be dropped
8126 // when we convert back to FP.
8127 SDValue SignMask = DAG.getConstant(
8128 APInt::getSignMask(16).sext(Subtarget.getXLen()), DL, XLenVT);
8129 SDValue SignBit = DAG.getNode(ISD::AND, DL, XLenVT, SignAsInt, SignMask);
8130
8131 // Transform Mag value to integer, and clear the sign bit.
8132 SDValue MagAsInt = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Mag);
8133 SDValue ClearSignMask = DAG.getConstant(
8134 APInt::getSignedMaxValue(16).sext(Subtarget.getXLen()), DL, XLenVT);
8135 SDValue ClearedSign =
8136 DAG.getNode(ISD::AND, DL, XLenVT, MagAsInt, ClearSignMask);
8137
8138 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, XLenVT, ClearedSign, SignBit,
8140
8141 return DAG.getNode(RISCVISD::FMV_H_X, DL, VT, CopiedSign);
8142}
8143
8144/// Get a RISC-V target specified VL op for a given SDNode.
8145static unsigned getRISCVVLOp(SDValue Op) {
8146#define OP_CASE(NODE) \
8147 case ISD::NODE: \
8148 return RISCVISD::NODE##_VL;
8149#define VP_CASE(NODE) \
8150 case ISD::VP_##NODE: \
8151 return RISCVISD::NODE##_VL;
8152 // clang-format off
8153 switch (Op.getOpcode()) {
8154 default:
8155 llvm_unreachable("don't have RISC-V specified VL op for this SDNode");
8156 OP_CASE(ADD)
8157 OP_CASE(SUB)
8158 OP_CASE(MUL)
8159 OP_CASE(MULHS)
8160 OP_CASE(MULHU)
8161 OP_CASE(SDIV)
8162 OP_CASE(SREM)
8163 OP_CASE(UDIV)
8164 OP_CASE(UREM)
8165 OP_CASE(SHL)
8166 OP_CASE(SRA)
8167 OP_CASE(SRL)
8168 OP_CASE(ROTL)
8169 OP_CASE(ROTR)
8170 OP_CASE(BSWAP)
8171 OP_CASE(CTTZ)
8172 OP_CASE(CTLZ)
8173 OP_CASE(CTPOP)
8174 OP_CASE(BITREVERSE)
8175 OP_CASE(CLMUL)
8176 OP_CASE(CLMULH)
8177 OP_CASE(SADDSAT)
8178 OP_CASE(UADDSAT)
8179 OP_CASE(SSUBSAT)
8180 OP_CASE(USUBSAT)
8181 OP_CASE(AVGFLOORS)
8182 OP_CASE(AVGFLOORU)
8183 OP_CASE(AVGCEILS)
8184 OP_CASE(AVGCEILU)
8185 OP_CASE(FADD)
8186 OP_CASE(FSUB)
8187 OP_CASE(FMUL)
8188 OP_CASE(FDIV)
8189 OP_CASE(FNEG)
8190 OP_CASE(FABS)
8191 OP_CASE(FCOPYSIGN)
8192 OP_CASE(FSQRT)
8193 OP_CASE(SMIN)
8194 OP_CASE(SMAX)
8195 OP_CASE(UMIN)
8196 OP_CASE(UMAX)
8197 OP_CASE(ABDS)
8198 OP_CASE(ABDU)
8199 OP_CASE(STRICT_FADD)
8200 OP_CASE(STRICT_FSUB)
8201 OP_CASE(STRICT_FMUL)
8202 OP_CASE(STRICT_FDIV)
8203 OP_CASE(STRICT_FSQRT)
8204 VP_CASE(SDIV) // VP_SDIV
8205 VP_CASE(SREM) // VP_SREM
8206 VP_CASE(UDIV) // VP_UDIV
8207 VP_CASE(UREM) // VP_UREM
8209 return RISCVISD::CTLZ_VL;
8211 return RISCVISD::CTTZ_VL;
8212 case ISD::FMA:
8213 return RISCVISD::VFMADD_VL;
8214 case ISD::STRICT_FMA:
8215 return RISCVISD::STRICT_VFMADD_VL;
8216 case ISD::AND:
8217 if (Op.getSimpleValueType().getVectorElementType() == MVT::i1)
8218 return RISCVISD::VMAND_VL;
8219 return RISCVISD::AND_VL;
8220 case ISD::OR:
8221 if (Op.getSimpleValueType().getVectorElementType() == MVT::i1)
8222 return RISCVISD::VMOR_VL;
8223 return RISCVISD::OR_VL;
8224 case ISD::XOR:
8225 if (Op.getSimpleValueType().getVectorElementType() == MVT::i1)
8226 return RISCVISD::VMXOR_VL;
8227 return RISCVISD::XOR_VL;
8228 case ISD::ANY_EXTEND:
8229 case ISD::ZERO_EXTEND:
8230 return RISCVISD::VZEXT_VL;
8231 case ISD::SIGN_EXTEND:
8232 return RISCVISD::VSEXT_VL;
8233 case ISD::SETCC:
8234 return RISCVISD::SETCC_VL;
8235 case ISD::VSELECT:
8236 return RISCVISD::VMERGE_VL;
8237 case ISD::VP_MERGE:
8238 return RISCVISD::VMERGE_VL;
8239 case ISD::FMINNUM:
8240 case ISD::FMINIMUMNUM:
8241 return RISCVISD::VFMIN_VL;
8242 case ISD::FMAXNUM:
8243 case ISD::FMAXIMUMNUM:
8244 return RISCVISD::VFMAX_VL;
8245 case ISD::LRINT:
8246 case ISD::LLRINT:
8247 return RISCVISD::VFCVT_RM_X_F_VL;
8248 case ISD::MASKED_UDIV:
8249 return RISCVISD::UDIV_VL;
8250 case ISD::MASKED_UREM:
8251 return RISCVISD::UREM_VL;
8252 case ISD::MASKED_SDIV:
8253 return RISCVISD::SDIV_VL;
8254 case ISD::MASKED_SREM:
8255 return RISCVISD::SREM_VL;
8256 }
8257 // clang-format on
8258#undef OP_CASE
8259#undef VP_CASE
8260}
8261
8264 const TargetLowering &TLI) {
8265 MVT OpVT = Op.getSimpleValueType();
8266 if (!OpVT.isVector())
8267 return false;
8268 MVT EltVT = OpVT.getVectorElementType();
8269 if (!(EltVT == MVT::f16 && Subtarget.hasVInstructionsF16Minimal() &&
8270 !Subtarget.hasVInstructionsF16()) &&
8271 !(EltVT == MVT::bf16 && Subtarget.hasVInstructionsBF16Minimal() &&
8272 (!Subtarget.hasVInstructionsBF16() ||
8273 !llvm::is_contained(ZvfbfaOps, Op.getOpcode()))))
8274 return false;
8275 // Need to split when the same width f32 vector type isn't legal.
8276 return !TLI.isTypeLegal(
8277 MVT::getVectorVT(MVT::f32, OpVT.getVectorElementCount()));
8278}
8279
8281 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(Op.getValueType());
8282 SDLoc DL(Op);
8283
8284 SmallVector<SDValue, 4> LoOperands(Op.getNumOperands());
8285 SmallVector<SDValue, 4> HiOperands(Op.getNumOperands());
8286
8287 for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
8288 if (!Op.getOperand(j).getValueType().isVector()) {
8289 LoOperands[j] = Op.getOperand(j);
8290 HiOperands[j] = Op.getOperand(j);
8291 continue;
8292 }
8293 std::tie(LoOperands[j], HiOperands[j]) =
8294 DAG.SplitVector(Op.getOperand(j), DL);
8295 }
8296
8297 SDValue LoRes =
8298 DAG.getNode(Op.getOpcode(), DL, LoVT, LoOperands, Op->getFlags());
8299 SDValue HiRes =
8300 DAG.getNode(Op.getOpcode(), DL, HiVT, HiOperands, Op->getFlags());
8301
8302 return DAG.getNode(ISD::CONCAT_VECTORS, DL, Op.getValueType(), LoRes, HiRes);
8303}
8304
8306 bool IsVP) {
8307 SDLoc DL(Op);
8308
8309 if (IsVP) {
8310 auto [Lo, Hi] = DAG.SplitVector(Op.getOperand(1), DL);
8311 auto [MaskLo, MaskHi] = DAG.SplitVector(Op.getOperand(2), DL);
8312 auto [EVLLo, EVLHi] =
8313 DAG.SplitEVL(Op.getOperand(3), Op.getOperand(1).getValueType(), DL);
8314
8315 SDValue ResLo =
8316 DAG.getNode(Op.getOpcode(), DL, Op.getValueType(),
8317 {Op.getOperand(0), Lo, MaskLo, EVLLo}, Op->getFlags());
8318 return DAG.getNode(Op.getOpcode(), DL, Op.getValueType(),
8319 {ResLo, Hi, MaskHi, EVLHi}, Op->getFlags());
8320 }
8321
8322 unsigned Opcode = Op.getOpcode();
8323 unsigned OpNo = Opcode == ISD::VECREDUCE_SEQ_FADD ? 1 : 0;
8324
8325 auto [Lo, Hi] = DAG.SplitVector(Op.getOperand(OpNo), DL);
8326 if (Opcode == ISD::VECREDUCE_SEQ_FADD) {
8327 SDValue ResLo = DAG.getNode(Op.getOpcode(), DL, Op.getValueType(),
8328 Op.getOperand(0), Lo, Op->getFlags());
8329 return DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), ResLo, Hi,
8330 Op->getFlags());
8331 }
8332
8333 SDValue ResLo =
8334 DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), Lo, Op->getFlags());
8335 SDValue ResHi =
8336 DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), Hi, Op->getFlags());
8337 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
8338 return DAG.getNode(BaseOpc, DL, Op.getValueType(), ResLo, ResHi,
8339 Op->getFlags());
8340}
8341
8343
8344 assert(Op->isStrictFPOpcode());
8345
8346 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(Op->getValueType(0));
8347
8348 SDVTList LoVTs = DAG.getVTList(LoVT, Op->getValueType(1));
8349 SDVTList HiVTs = DAG.getVTList(HiVT, Op->getValueType(1));
8350
8351 SDLoc DL(Op);
8352
8353 SmallVector<SDValue, 4> LoOperands(Op.getNumOperands());
8354 SmallVector<SDValue, 4> HiOperands(Op.getNumOperands());
8355
8356 for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
8357 if (!Op.getOperand(j).getValueType().isVector()) {
8358 LoOperands[j] = Op.getOperand(j);
8359 HiOperands[j] = Op.getOperand(j);
8360 continue;
8361 }
8362 std::tie(LoOperands[j], HiOperands[j]) =
8363 DAG.SplitVector(Op.getOperand(j), DL);
8364 }
8365
8366 SDValue LoRes =
8367 DAG.getNode(Op.getOpcode(), DL, LoVTs, LoOperands, Op->getFlags());
8368 HiOperands[0] = LoRes.getValue(1);
8369 SDValue HiRes =
8370 DAG.getNode(Op.getOpcode(), DL, HiVTs, HiOperands, Op->getFlags());
8371
8372 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, Op->getValueType(0),
8373 LoRes.getValue(0), HiRes.getValue(0));
8374 return DAG.getMergeValues({V, HiRes.getValue(1)}, DL);
8375}
8376
8377SDValue
8378RISCVTargetLowering::lowerXAndesBfHCvtBFloat16Load(SDValue Op,
8379 SelectionDAG &DAG) const {
8380 assert(Subtarget.hasVendorXAndesBFHCvt() && !Subtarget.hasStdExtZfh() &&
8381 "Unexpected bfloat16 load lowering");
8382
8383 SDLoc DL(Op);
8384 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
8385 EVT MemVT = LD->getMemoryVT();
8386 SDValue Load = DAG.getExtLoad(
8387 ISD::ZEXTLOAD, DL, Subtarget.getXLenVT(), LD->getChain(),
8388 LD->getBasePtr(),
8390 LD->getMemOperand());
8391 // Using mask to make bf16 nan-boxing valid when we don't have flh
8392 // instruction. -65536 would be treat as a small number and thus it can be
8393 // directly used lui to get the constant.
8394 SDValue mask = DAG.getSignedConstant(-65536, DL, Subtarget.getXLenVT());
8395 SDValue OrSixteenOne =
8396 DAG.getNode(ISD::OR, DL, Load.getValueType(), {Load, mask});
8397 SDValue ConvertedResult =
8398 DAG.getNode(RISCVISD::NDS_FMV_BF16_X, DL, MVT::bf16, OrSixteenOne);
8399 return DAG.getMergeValues({ConvertedResult, Load.getValue(1)}, DL);
8400}
8401
8402SDValue
8403RISCVTargetLowering::lowerXAndesBfHCvtBFloat16Store(SDValue Op,
8404 SelectionDAG &DAG) const {
8405 assert(Subtarget.hasVendorXAndesBFHCvt() && !Subtarget.hasStdExtZfh() &&
8406 "Unexpected bfloat16 store lowering");
8407
8408 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
8409 SDLoc DL(Op);
8410 SDValue FMV = DAG.getNode(RISCVISD::NDS_FMV_X_ANYEXTBF16, DL,
8411 Subtarget.getXLenVT(), ST->getValue());
8412 return DAG.getTruncStore(
8413 ST->getChain(), DL, FMV, ST->getBasePtr(),
8414 EVT::getIntegerVT(*DAG.getContext(), ST->getMemoryVT().getSizeInBits()),
8415 ST->getMemOperand());
8416}
8417
8419 const RISCVSubtarget &Subtarget);
8420
8422 const RISCVSubtarget &Subtarget);
8423
8425 SelectionDAG &DAG) const {
8426 switch (Op.getOpcode()) {
8427 default:
8429 "Unimplemented RISCVTargetLowering::LowerOperation Case");
8430 case ISD::PREFETCH:
8431 return LowerPREFETCH(Op, Subtarget, DAG);
8432 case ISD::ATOMIC_FENCE:
8433 return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8434 case ISD::GlobalAddress:
8435 return lowerGlobalAddress(Op, DAG);
8436 case ISD::BlockAddress:
8437 return lowerBlockAddress(Op, DAG);
8438 case ISD::ConstantPool:
8439 return lowerConstantPool(Op, DAG);
8440 case ISD::JumpTable:
8441 return lowerJumpTable(Op, DAG);
8443 return lowerGlobalTLSAddress(Op, DAG);
8444 case ISD::Constant:
8445 return lowerConstant(Op, DAG, Subtarget);
8446 case ISD::ConstantFP:
8447 return lowerConstantFP(Op, DAG);
8448 case ISD::SELECT:
8449 return lowerSELECT(Op, DAG);
8450 case ISD::BRCOND:
8451 return lowerBRCOND(Op, DAG);
8452 case ISD::VASTART:
8453 return lowerVASTART(Op, DAG);
8454 case ISD::FRAMEADDR:
8455 return lowerFRAMEADDR(Op, DAG);
8456 case ISD::RETURNADDR:
8457 return lowerRETURNADDR(Op, DAG);
8458 case ISD::SHL_PARTS:
8459 return lowerShiftLeftParts(Op, DAG);
8460 case ISD::SRA_PARTS:
8461 return lowerShiftRightParts(Op, DAG, true);
8462 case ISD::SRL_PARTS:
8463 return lowerShiftRightParts(Op, DAG, false);
8464 case ISD::ROTL:
8465 case ISD::ROTR:
8466 if (Op.getValueType().isFixedLengthVector()) {
8467 assert(Subtarget.hasStdExtZvkb());
8468 return lowerToScalableOp(Op, DAG);
8469 }
8470 assert(Subtarget.hasVendorXTHeadBb() &&
8471 !(Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) &&
8472 "Unexpected custom legalization");
8473 // XTHeadBb only supports rotate by constant.
8474 if (!isa<ConstantSDNode>(Op.getOperand(1)))
8475 return SDValue();
8476 return Op;
8477 case ISD::BITCAST: {
8478 SDLoc DL(Op);
8479 EVT VT = Op.getValueType();
8480 SDValue Op0 = Op.getOperand(0);
8481 EVT Op0VT = Op0.getValueType();
8482 MVT XLenVT = Subtarget.getXLenVT();
8483 if (Op0VT == MVT::i16 &&
8484 ((VT == MVT::f16 && Subtarget.hasStdExtZfhminOrZhinxmin()) ||
8485 (VT == MVT::bf16 && Subtarget.hasStdExtZfbfmin()))) {
8486 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
8487 return DAG.getNode(RISCVISD::FMV_H_X, DL, VT, NewOp0);
8488 }
8489 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
8490 Subtarget.hasStdExtFOrZfinx()) {
8491 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
8492 return DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
8493 }
8494 if (VT == MVT::f64 && Op0VT == MVT::i64 && !Subtarget.is64Bit() &&
8495 Subtarget.hasStdExtDOrZdinx()) {
8496 SDValue Lo, Hi;
8497 std::tie(Lo, Hi) = DAG.SplitScalar(Op0, DL, MVT::i32, MVT::i32);
8498 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8499 }
8500
8501 if (Subtarget.hasStdExtP() && VT.isSimple() && Op0VT.isSimple()) {
8502 if (VT.getSimpleVT() == Subtarget.getXLenVT() &&
8503 Subtarget.isPExtPackedType(Op0VT.getSimpleVT()))
8504 return Op;
8505 if (Op0VT.getSimpleVT() == Subtarget.getXLenVT() &&
8506 Subtarget.isPExtPackedType(VT.getSimpleVT()))
8507 return Op;
8508 }
8509
8510 // Consider other scalar<->scalar casts as legal if the types are legal.
8511 // Otherwise expand them.
8512 if (!VT.isVector() && !Op0VT.isVector()) {
8513 if (isTypeLegal(VT) && isTypeLegal(Op0VT))
8514 return Op;
8515 return SDValue();
8516 }
8517
8518 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() &&
8519 "Unexpected types");
8520
8521 if (VT.isFixedLengthVector()) {
8522 // We can handle fixed length vector bitcasts with a simple replacement
8523 // in isel.
8524 if (Op0VT.isFixedLengthVector())
8525 return Op;
8526 // When bitcasting from scalar to fixed-length vector, insert the scalar
8527 // into a one-element vector of the result type, and perform a vector
8528 // bitcast.
8529 if (!Op0VT.isVector()) {
8530 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
8531 if (!isTypeLegal(BVT))
8532 return SDValue();
8533 return DAG.getBitcast(
8534 VT, DAG.getInsertVectorElt(DL, DAG.getUNDEF(BVT), Op0, 0));
8535 }
8536 return SDValue();
8537 }
8538 // Custom-legalize bitcasts from fixed-length vector types to scalar types
8539 // thus: bitcast the vector to a one-element vector type whose element type
8540 // is the same as the result type, and extract the first element.
8541 if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
8542 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
8543 if (!isTypeLegal(BVT))
8544 return SDValue();
8545 SDValue BVec = DAG.getBitcast(BVT, Op0);
8546 return DAG.getExtractVectorElt(DL, VT, BVec, 0);
8547 }
8548 return SDValue();
8549 }
8551 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8553 return LowerINTRINSIC_W_CHAIN(Op, DAG);
8555 return LowerINTRINSIC_VOID(Op, DAG);
8556 case ISD::IS_FPCLASS:
8557 return LowerIS_FPCLASS(Op, DAG);
8558 case ISD::BITREVERSE: {
8559 MVT VT = Op.getSimpleValueType();
8560 if (VT == MVT::v8i8 && !Subtarget.is64Bit() && Subtarget.hasStdExtP()) {
8561 // Split into two v4i8 bitreverses, each of which fits in a GPR.
8562 SDLoc DL(Op);
8563 auto [Lo, Hi] = DAG.SplitVectorOperand(Op.getNode(), 0);
8564 Lo = DAG.getNode(ISD::BITREVERSE, DL, MVT::v4i8, Lo);
8565 Hi = DAG.getNode(ISD::BITREVERSE, DL, MVT::v4i8, Hi);
8566 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8567 }
8568 if (VT.isFixedLengthVector()) {
8569 assert(Subtarget.hasStdExtZvbb());
8570 return lowerToScalableOp(Op, DAG);
8571 }
8572 SDLoc DL(Op);
8573 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
8574 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
8575 // Expand bitreverse to a bswap(rev8) followed by brev8.
8576 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
8577 return DAG.getNode(RISCVISD::BREV8, DL, VT, BSwap);
8578 }
8579 case ISD::TRUNCATE:
8582 // Only custom-lower vector truncates
8583 if (!Op.getSimpleValueType().isVector())
8584 return Op;
8585 return lowerVectorTrunc(Op, DAG);
8586 case ISD::ANY_EXTEND:
8587 case ISD::ZERO_EXTEND:
8588 if (Op.getOperand(0).getValueType().isVector() &&
8589 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
8590 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
8591 if (Op.getValueType().isScalableVector())
8592 return Op;
8593 return lowerToScalableOp(Op, DAG);
8594 case ISD::SIGN_EXTEND:
8595 if (Op.getOperand(0).getValueType().isVector() &&
8596 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
8597 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
8598 if (Op.getValueType().isScalableVector())
8599 return Op;
8600 return lowerToScalableOp(Op, DAG);
8602 return lowerSPLAT_VECTOR_PARTS(Op, DAG);
8604 return lowerINSERT_VECTOR_ELT(Op, DAG);
8606 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
8607 case ISD::SCALAR_TO_VECTOR: {
8608 MVT VT = Op.getSimpleValueType();
8609 SDLoc DL(Op);
8610 SDValue Scalar = Op.getOperand(0);
8611 if (VT.getVectorElementType() == MVT::i1) {
8612 MVT WideVT = VT.changeVectorElementType(MVT::i8);
8613 SDValue V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, WideVT, Scalar);
8614 return DAG.getNode(ISD::TRUNCATE, DL, VT, V);
8615 }
8616 MVT ContainerVT = VT;
8617 if (VT.isFixedLengthVector())
8619 SDValue VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
8620
8621 SDValue V;
8622 if (VT.isFloatingPoint()) {
8623 V = DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, ContainerVT,
8624 DAG.getUNDEF(ContainerVT), Scalar, VL);
8625 } else {
8626 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), Scalar);
8627 V = DAG.getNode(RISCVISD::VMV_S_X_VL, DL, ContainerVT,
8628 DAG.getUNDEF(ContainerVT), Scalar, VL);
8629 }
8630 if (VT.isFixedLengthVector())
8631 V = convertFromScalableVector(VT, V, DAG, Subtarget);
8632 return V;
8633 }
8634 case ISD::VSCALE: {
8635 MVT XLenVT = Subtarget.getXLenVT();
8636 MVT VT = Op.getSimpleValueType();
8637 SDLoc DL(Op);
8638 SDValue Res = DAG.getNode(RISCVISD::READ_VLENB, DL, XLenVT);
8639 // We define our scalable vector types for lmul=1 to use a 64 bit known
8640 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
8641 // vscale as VLENB / 8.
8642 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
8643 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock)
8644 reportFatalInternalError("Support for VLEN==32 is incomplete.");
8645 // We assume VLENB is a multiple of 8. We manually choose the best shift
8646 // here because SimplifyDemandedBits isn't always able to simplify it.
8647 uint64_t Val = Op.getConstantOperandVal(0);
8648 if (isPowerOf2_64(Val)) {
8649 uint64_t Log2 = Log2_64(Val);
8650 if (Log2 < 3) {
8651 SDNodeFlags Flags;
8652 Flags.setExact(true);
8653 Res = DAG.getNode(ISD::SRL, DL, XLenVT, Res,
8654 DAG.getConstant(3 - Log2, DL, XLenVT), Flags);
8655 } else if (Log2 > 3) {
8656 Res = DAG.getNode(ISD::SHL, DL, XLenVT, Res,
8657 DAG.getConstant(Log2 - 3, DL, XLenVT));
8658 }
8659 } else if ((Val % 8) == 0) {
8660 // If the multiplier is a multiple of 8, scale it down to avoid needing
8661 // to shift the VLENB value.
8662 Res = DAG.getNode(ISD::MUL, DL, XLenVT, Res,
8663 DAG.getConstant(Val / 8, DL, XLenVT));
8664 } else {
8665 SDNodeFlags Flags;
8666 Flags.setExact(true);
8667 SDValue VScale = DAG.getNode(ISD::SRL, DL, XLenVT, Res,
8668 DAG.getConstant(3, DL, XLenVT), Flags);
8669 Res = DAG.getNode(ISD::MUL, DL, XLenVT, VScale,
8670 DAG.getConstant(Val, DL, XLenVT));
8671 }
8672 return DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
8673 }
8674 case ISD::FPOWI: {
8675 // Custom promote f16 powi with illegal i32 integer type on RV64. Once
8676 // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
8677 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
8678 Op.getOperand(1).getValueType() == MVT::i32) {
8679 SDLoc DL(Op);
8680 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
8681 SDValue Powi =
8682 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
8683 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
8684 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
8685 }
8686 return SDValue();
8687 }
8688 case ISD::FMAXIMUM:
8689 case ISD::FMINIMUM:
8690 if (isPromotedOpNeedingSplit(Op, Subtarget, *this))
8691 return SplitVectorOp(Op, DAG);
8692 return lowerFMAXIMUM_FMINIMUM(Op, DAG, Subtarget);
8693 case ISD::FP_EXTEND:
8694 case ISD::FP_ROUND:
8695 return lowerVectorFPExtendOrRound(Op, DAG);
8698 return lowerStrictFPExtendOrRoundLike(Op, DAG);
8699 case ISD::SINT_TO_FP:
8700 case ISD::UINT_TO_FP:
8701 // An i1-to-fp conversion is equivalent to selecting between 1.0/-1.0 and
8702 // 0.0 for unsigned/signed conversion, respectively. This avoids extending
8703 // the mask before converting it.
8704 if (Op.getValueType().isVector() &&
8705 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) {
8706 SDLoc DL(Op);
8707 EVT VT = Op.getValueType();
8708 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8709 double TrueVal = Op.getOpcode() == ISD::UINT_TO_FP ? 1.0 : -1.0;
8710 SDValue True = DAG.getConstantFP(TrueVal, DL, VT);
8711 return DAG.getNode(ISD::VSELECT, DL, VT, Op.getOperand(0), True, Zero);
8712 }
8713 // Fall back to zvfbfmin for bf16 case if source type is wider than 8 bits.
8714 if (SDValue Op1 = Op.getOperand(0);
8715 Op.getValueType().isVector() &&
8716 ((Op.getValueType().getScalarType() == MVT::f16 &&
8717 (Subtarget.hasVInstructionsF16Minimal() &&
8718 !Subtarget.hasVInstructionsF16())) ||
8719 (Op.getValueType().getScalarType() == MVT::bf16 &&
8720 (Subtarget.hasVInstructionsBF16Minimal() &&
8721 (!Subtarget.hasVInstructionsBF16() ||
8722 Op1.getValueType().getScalarSizeInBits() > 8))))) {
8723 MVT NVT =
8724 MVT::getVectorVT(MVT::f32, Op.getValueType().getVectorElementCount());
8725 if (!isTypeLegal(NVT))
8726 return SplitVectorOp(Op, DAG);
8727 // int -> f32
8728 SDLoc DL(Op);
8729 SDValue NC = DAG.getNode(Op.getOpcode(), DL, NVT, Op->ops());
8730 // f32 -> [b]f16
8731 return DAG.getNode(ISD::FP_ROUND, DL, Op.getValueType(), NC,
8732 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
8733 }
8734 [[fallthrough]];
8735 case ISD::FP_TO_SINT:
8736 case ISD::FP_TO_UINT:
8737 // Fall back to zvfbfmin for bf16 case if destination type is wider than 8
8738 // bits.
8739 if (SDValue Op1 = Op.getOperand(0);
8740 Op1.getValueType().isVector() &&
8741 ((Op1.getValueType().getScalarType() == MVT::f16 &&
8742 (Subtarget.hasVInstructionsF16Minimal() &&
8743 !Subtarget.hasVInstructionsF16())) ||
8744 (Op1.getValueType().getScalarType() == MVT::bf16 &&
8745 (Subtarget.hasVInstructionsBF16Minimal() &&
8746 (!Subtarget.hasVInstructionsBF16() ||
8747 Op.getValueType().getScalarSizeInBits() > 8))))) {
8748 MVT NVT = MVT::getVectorVT(MVT::f32,
8749 Op1.getValueType().getVectorElementCount());
8750 if (!isTypeLegal(NVT))
8751 return SplitVectorOp(Op, DAG);
8752 // [b]f16 -> f32
8753 SDLoc DL(Op);
8754 SDValue WidenVec = DAG.getNode(ISD::FP_EXTEND, DL, NVT, Op1);
8755 // f32 -> int
8756 return DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), WidenVec);
8757 }
8758 [[fallthrough]];
8763 // RVV can only do fp<->int conversions to types half/double the size as
8764 // the source. We custom-lower any conversions that do two hops into
8765 // sequences.
8766 MVT VT = Op.getSimpleValueType();
8767 if (VT.isScalarInteger())
8768 return lowerFP_TO_INT(Op, DAG, Subtarget);
8769 bool IsStrict = Op->isStrictFPOpcode();
8770 SDValue Src = Op.getOperand(0 + IsStrict);
8771 MVT SrcVT = Src.getSimpleValueType();
8772 if (SrcVT.isScalarInteger())
8773 return lowerINT_TO_FP(Op, DAG, Subtarget);
8774 if (!VT.isVector())
8775 return Op;
8776 SDLoc DL(Op);
8777 MVT EltVT = VT.getVectorElementType();
8778 MVT SrcEltVT = SrcVT.getVectorElementType();
8779 unsigned EltSize = EltVT.getSizeInBits();
8780 unsigned SrcEltSize = SrcEltVT.getSizeInBits();
8781 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
8782 "Unexpected vector element types");
8783
8784 bool IsInt2FP = SrcEltVT.isInteger();
8785 // Widening conversions
8786 if (EltSize > (2 * SrcEltSize)) {
8787 if (IsInt2FP) {
8788 // Do a regular integer sign/zero extension then convert to float.
8789 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize / 2),
8791 unsigned ExtOpcode = (Op.getOpcode() == ISD::UINT_TO_FP ||
8792 Op.getOpcode() == ISD::STRICT_UINT_TO_FP)
8795 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
8796 if (IsStrict)
8797 return DAG.getNode(Op.getOpcode(), DL, Op->getVTList(),
8798 Op.getOperand(0), Ext);
8799 return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
8800 }
8801 // FP2Int
8802 assert((SrcEltVT == MVT::f16 || SrcEltVT == MVT::bf16) &&
8803 "Unexpected FP_TO_[US]INT lowering");
8804 // Do one doubling fp_extend then complete the operation by converting
8805 // to int.
8806 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
8807 if (IsStrict) {
8808 auto [FExt, Chain] =
8809 DAG.getStrictFPExtendOrRound(Src, Op.getOperand(0), DL, InterimFVT);
8810 return DAG.getNode(Op.getOpcode(), DL, Op->getVTList(), Chain, FExt);
8811 }
8812 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
8813 return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
8814 }
8815
8816 // Narrowing conversions
8817 if (SrcEltSize > (2 * EltSize)) {
8818 if (IsInt2FP) {
8819 // One narrowing int_to_fp, then an fp_round.
8820 assert((EltVT == MVT::f16 || EltVT == MVT::bf16) &&
8821 "Unexpected [US]_TO_FP lowering");
8822 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
8823 if (IsStrict) {
8824 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL,
8825 DAG.getVTList(InterimFVT, MVT::Other),
8826 Op.getOperand(0), Src);
8827 SDValue Chain = Int2FP.getValue(1);
8828 return DAG.getStrictFPExtendOrRound(Int2FP, Chain, DL, VT).first;
8829 }
8830 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
8831 return DAG.getFPExtendOrRound(Int2FP, DL, VT);
8832 }
8833 // FP2Int
8834 // One narrowing fp_to_int, then truncate the integer. If the float isn't
8835 // representable by the integer, the result is poison.
8836 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
8838 if (IsStrict) {
8839 SDValue FP2Int =
8840 DAG.getNode(Op.getOpcode(), DL, DAG.getVTList(IVecVT, MVT::Other),
8841 Op.getOperand(0), Src);
8842 SDValue Res = DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
8843 return DAG.getMergeValues({Res, FP2Int.getValue(1)}, DL);
8844 }
8845 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
8846 if (EltSize == 1)
8847 // The integer should be 0 or 1/-1, so compare the integer result to 0.
8848 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, IVecVT), FP2Int,
8849 ISD::SETNE);
8850 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
8851 }
8852
8853 // Scalable vectors can exit here. Patterns will handle equally-sized
8854 // conversions halving/doubling ones.
8855 if (!VT.isFixedLengthVector())
8856 return Op;
8857
8858 // For fixed-length vectors we lower to a custom "VL" node.
8859 unsigned RVVOpc = 0;
8860 switch (Op.getOpcode()) {
8861 default:
8862 llvm_unreachable("Impossible opcode");
8863 case ISD::FP_TO_SINT:
8864 RVVOpc = RISCVISD::VFCVT_RTZ_X_F_VL;
8865 break;
8866 case ISD::FP_TO_UINT:
8867 RVVOpc = RISCVISD::VFCVT_RTZ_XU_F_VL;
8868 break;
8869 case ISD::SINT_TO_FP:
8870 RVVOpc = RISCVISD::SINT_TO_FP_VL;
8871 break;
8872 case ISD::UINT_TO_FP:
8873 RVVOpc = RISCVISD::UINT_TO_FP_VL;
8874 break;
8876 RVVOpc = RISCVISD::STRICT_VFCVT_RTZ_X_F_VL;
8877 break;
8879 RVVOpc = RISCVISD::STRICT_VFCVT_RTZ_XU_F_VL;
8880 break;
8882 RVVOpc = RISCVISD::STRICT_SINT_TO_FP_VL;
8883 break;
8885 RVVOpc = RISCVISD::STRICT_UINT_TO_FP_VL;
8886 break;
8887 }
8888
8890 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
8891 assert(ContainerVT.getVectorElementCount() == SrcContainerVT.getVectorElementCount() &&
8892 "Expected same element count");
8893
8894 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
8895
8896 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
8897 if (IsStrict) {
8898 Src = DAG.getNode(RVVOpc, DL, DAG.getVTList(ContainerVT, MVT::Other),
8899 Op.getOperand(0), Src, Mask, VL);
8900 SDValue SubVec = convertFromScalableVector(VT, Src, DAG, Subtarget);
8901 return DAG.getMergeValues({SubVec, Src.getValue(1)}, DL);
8902 }
8903 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
8904 return convertFromScalableVector(VT, Src, DAG, Subtarget);
8905 }
8908 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
8909 case ISD::FP_TO_BF16: {
8910 // Custom lower to ensure the libcall return is passed in an FPR on hard
8911 // float ABIs.
8912 assert(!Subtarget.isSoftFPABI() && "Unexpected custom legalization");
8913 SDLoc DL(Op);
8914 MakeLibCallOptions CallOptions;
8915 RTLIB::Libcall LC =
8916 RTLIB::getFPROUND(Op.getOperand(0).getValueType(), MVT::bf16);
8917 SDValue Res =
8918 makeLibCall(DAG, LC, MVT::f32, Op.getOperand(0), CallOptions, DL).first;
8919 if (Subtarget.is64Bit())
8920 return DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Res);
8921 return DAG.getBitcast(MVT::i32, Res);
8922 }
8923 case ISD::BF16_TO_FP: {
8924 assert(Subtarget.hasStdExtFOrZfinx() && "Unexpected custom legalization");
8925 MVT VT = Op.getSimpleValueType();
8926 SDLoc DL(Op);
8927 Op = DAG.getNode(
8928 ISD::SHL, DL, Op.getOperand(0).getValueType(), Op.getOperand(0),
8929 DAG.getShiftAmountConstant(16, Op.getOperand(0).getValueType(), DL));
8930 SDValue Res = Subtarget.is64Bit()
8931 ? DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Op)
8932 : DAG.getBitcast(MVT::f32, Op);
8933 // fp_extend if the target VT is bigger than f32.
8934 if (VT != MVT::f32)
8935 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Res);
8936 return Res;
8937 }
8939 case ISD::FP_TO_FP16: {
8940 // Custom lower to ensure the libcall return is passed in an FPR on hard
8941 // float ABIs.
8942 assert(Subtarget.hasStdExtFOrZfinx() && "Unexpected custom legalisation");
8943 SDLoc DL(Op);
8944 MakeLibCallOptions CallOptions;
8945 bool IsStrict = Op->isStrictFPOpcode();
8946 SDValue Op0 = IsStrict ? Op.getOperand(1) : Op.getOperand(0);
8947 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8948 RTLIB::Libcall LC = RTLIB::getFPROUND(Op0.getValueType(), MVT::f16);
8949 SDValue Res;
8950 std::tie(Res, Chain) =
8951 makeLibCall(DAG, LC, MVT::f32, Op0, CallOptions, DL, Chain);
8952 SDValue Result =
8953 Subtarget.is64Bit()
8954 ? DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Res)
8955 : DAG.getBitcast(MVT::i32, Res);
8956 if (IsStrict)
8957 return DAG.getMergeValues({Result, Chain}, DL);
8958 return Result;
8959 }
8961 case ISD::FP16_TO_FP: {
8962 // Custom lower to ensure the libcall argument is passed in an FPR on hard
8963 // float ABIs.
8964 assert(Subtarget.hasStdExtFOrZfinx() && "Unexpected custom legalisation");
8965 SDLoc DL(Op);
8966 MakeLibCallOptions CallOptions;
8967 bool IsStrict = Op->isStrictFPOpcode();
8968 SDValue Op0 = IsStrict ? Op.getOperand(1) : Op.getOperand(0);
8969 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8970 SDValue Arg = Subtarget.is64Bit()
8971 ? DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Op0)
8972 : DAG.getBitcast(MVT::f32, Op0);
8973 SDValue Res;
8974 std::tie(Res, Chain) = makeLibCall(DAG, RTLIB::FPEXT_F16_F32, MVT::f32, Arg,
8975 CallOptions, DL, Chain);
8976 if (IsStrict)
8977 return DAG.getMergeValues({Res, Chain}, DL);
8978 return Res;
8979 }
8980 case ISD::FTRUNC:
8981 case ISD::FCEIL:
8982 case ISD::FFLOOR:
8983 case ISD::FNEARBYINT:
8984 case ISD::FRINT:
8985 case ISD::FROUND:
8986 case ISD::FROUNDEVEN:
8987 if (isPromotedOpNeedingSplit(Op, Subtarget, *this))
8988 return SplitVectorOp(Op, DAG);
8989 return lowerFTRUNC_FCEIL_FFLOOR_FROUND(Op, DAG, Subtarget);
8990 case ISD::FCANONICALIZE:
8991 case ISD::MASK_BEFOREFIRST: {
8992 MVT VT = Op.getSimpleValueType();
8993 assert(VT.isFixedLengthVector() && "Unexpected type");
8994 SDLoc DL(Op);
8996 SDValue Src =
8997 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
8998 SDValue Res = DAG.getNode(Op.getOpcode(), DL, ContainerVT, Src);
8999 return convertFromScalableVector(VT, Res, DAG, Subtarget);
9000 }
9001 case ISD::LRINT:
9002 case ISD::LLRINT:
9003 case ISD::LROUND:
9004 case ISD::LLROUND: {
9005 if (Op.getValueType().isVector())
9006 return lowerVectorXRINT_XROUND(Op, DAG, Subtarget);
9007 assert(Op.getOperand(0).getValueType() == MVT::f16 &&
9008 "Unexpected custom legalisation");
9009 SDLoc DL(Op);
9010 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
9011 return DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), Ext);
9012 }
9013 case ISD::STRICT_LRINT:
9014 case ISD::STRICT_LLRINT:
9015 case ISD::STRICT_LROUND:
9016 case ISD::STRICT_LLROUND: {
9017 assert(Op.getOperand(1).getValueType() == MVT::f16 &&
9018 "Unexpected custom legalisation");
9019 SDLoc DL(Op);
9020 SDValue Ext = DAG.getNode(ISD::STRICT_FP_EXTEND, DL, {MVT::f32, MVT::Other},
9021 {Op.getOperand(0), Op.getOperand(1)});
9022 return DAG.getNode(Op.getOpcode(), DL, {Op.getValueType(), MVT::Other},
9023 {Ext.getValue(1), Ext.getValue(0)});
9024 }
9025 case ISD::VECREDUCE_ADD:
9030 return lowerVECREDUCE(Op, DAG);
9031 case ISD::VECREDUCE_AND:
9032 case ISD::VECREDUCE_OR:
9033 case ISD::VECREDUCE_XOR:
9034 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
9035 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
9036 return lowerVECREDUCE(Op, DAG);
9038 if (isPromotedOpNeedingSplit(Op.getOperand(1), Subtarget, *this))
9039 return SplitVectorReductionOp(Op, DAG, /*IsVP*/ false);
9040 return lowerFPVECREDUCE(Op, DAG);
9046 if (isPromotedOpNeedingSplit(Op.getOperand(0), Subtarget, *this))
9047 return SplitVectorReductionOp(Op, DAG, /*IsVP*/ false);
9048 return lowerFPVECREDUCE(Op, DAG);
9049 case ISD::VP_REDUCE_ADD:
9050 case ISD::VP_REDUCE_UMAX:
9051 case ISD::VP_REDUCE_SMAX:
9052 case ISD::VP_REDUCE_UMIN:
9053 case ISD::VP_REDUCE_SMIN:
9054 case ISD::VP_REDUCE_FADD:
9055 case ISD::VP_REDUCE_SEQ_FADD:
9056 case ISD::VP_REDUCE_FMIN:
9057 case ISD::VP_REDUCE_FMAX:
9058 case ISD::VP_REDUCE_FMINIMUM:
9059 case ISD::VP_REDUCE_FMAXIMUM:
9060 if (isPromotedOpNeedingSplit(Op.getOperand(1), Subtarget, *this))
9061 return SplitVectorReductionOp(Op, DAG, /*IsVP*/ true);
9062 return lowerVPREDUCE(Op, DAG);
9063 case ISD::VP_REDUCE_AND:
9064 case ISD::VP_REDUCE_OR:
9065 case ISD::VP_REDUCE_XOR:
9066 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
9067 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
9068 return lowerVPREDUCE(Op, DAG);
9069 case ISD::VP_CTTZ_ELTS:
9070 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
9071 return lowerVPCttzElements(Op, DAG);
9072 case ISD::UNDEF:
9073 case ISD::POISON: {
9074 MVT ContainerVT = getContainerForFixedLengthVector(Op.getSimpleValueType());
9075 SDValue Passthru = Op.getOpcode() == ISD::POISON
9076 ? DAG.getPOISON(ContainerVT)
9077 : DAG.getUNDEF(ContainerVT);
9078 return convertFromScalableVector(Op.getSimpleValueType(), Passthru, DAG,
9079 Subtarget);
9080 }
9082 return lowerINSERT_SUBVECTOR(Op, DAG);
9084 return lowerEXTRACT_SUBVECTOR(Op, DAG);
9086 return lowerVECTOR_DEINTERLEAVE(Op, DAG);
9088 return lowerVECTOR_INTERLEAVE(Op, DAG);
9089 case ISD::STEP_VECTOR:
9090 return lowerSTEP_VECTOR(Op, DAG);
9092 return lowerVECTOR_REVERSE(Op, DAG);
9095 return lowerVECTOR_SPLICE(Op, DAG);
9096 case ISD::BUILD_VECTOR: {
9097 MVT VT = Op.getSimpleValueType();
9098 MVT EltVT = VT.getVectorElementType();
9099 if (!Subtarget.is64Bit() && EltVT == MVT::i64)
9100 return lowerBuildVectorViaVID(Op, DAG, Subtarget);
9101 return lowerBUILD_VECTOR(Op, DAG, Subtarget);
9102 }
9103 case ISD::SPLAT_VECTOR: {
9104 MVT VT = Op.getSimpleValueType();
9105 MVT EltVT = VT.getVectorElementType();
9106 if ((EltVT == MVT::f16 && !Subtarget.hasVInstructionsF16()) ||
9107 EltVT == MVT::bf16) {
9108 SDLoc DL(Op);
9109 SDValue Elt;
9110 if ((EltVT == MVT::bf16 && Subtarget.hasStdExtZfbfmin()) ||
9111 (EltVT == MVT::f16 && Subtarget.hasStdExtZfhmin()))
9112 Elt = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, Subtarget.getXLenVT(),
9113 Op.getOperand(0));
9114 else
9115 Elt = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Op.getOperand(0));
9116 MVT IVT = VT.changeVectorElementType(MVT::i16);
9117 return DAG.getNode(ISD::BITCAST, DL, VT,
9118 DAG.getNode(ISD::SPLAT_VECTOR, DL, IVT, Elt));
9119 }
9120
9121 if (EltVT == MVT::i1)
9122 return lowerVectorMaskSplat(Op, DAG);
9123 return SDValue();
9124 }
9126 return lowerVECTOR_SHUFFLE(Op, DAG);
9127 case ISD::CONCAT_VECTORS: {
9128 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
9129 // better than going through the stack, as the default expansion does.
9130 SDLoc DL(Op);
9131 MVT VT = Op.getSimpleValueType();
9132 MVT ContainerVT = VT;
9133 if (VT.isFixedLengthVector())
9135
9136 // Recursively split concat_vectors with more than 2 operands:
9137 //
9138 // concat_vector op1, op2, op3, op4
9139 // ->
9140 // concat_vector (concat_vector op1, op2), (concat_vector op3, op4)
9141 //
9142 // This reduces the length of the chain of vslideups and allows us to
9143 // perform the vslideups at a smaller LMUL, limited to MF2.
9144 if (Op.getNumOperands() > 2 &&
9146 MVT HalfVT = VT.getHalfNumVectorElementsVT();
9147 assert(isPowerOf2_32(Op.getNumOperands()));
9148 size_t HalfNumOps = Op.getNumOperands() / 2;
9149 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT,
9150 Op->ops().take_front(HalfNumOps));
9151 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT,
9152 Op->ops().drop_front(HalfNumOps));
9153 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9154 }
9155
9156 unsigned NumOpElts =
9157 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
9158 SDValue Vec = DAG.getUNDEF(VT);
9159 for (const auto &OpIdx : enumerate(Op->ops())) {
9160 SDValue SubVec = OpIdx.value();
9161 // Don't insert undef subvectors.
9162 if (SubVec.isUndef())
9163 continue;
9164 Vec = DAG.getInsertSubvector(DL, Vec, SubVec, OpIdx.index() * NumOpElts);
9165 }
9166 return Vec;
9167 }
9168 case ISD::LOAD: {
9169 auto *Load = cast<LoadSDNode>(Op);
9170 EVT VT = Load->getValueType(0);
9171 if (VT == MVT::f64) {
9172 assert(Subtarget.hasStdExtZdinx() && !Subtarget.hasStdExtZilsd() &&
9173 !Subtarget.is64Bit() && "Unexpected custom legalisation");
9174
9175 // Replace a double precision load with two i32 loads and a BuildPairF64.
9176 SDLoc DL(Op);
9177 SDValue BasePtr = Load->getBasePtr();
9178 SDValue Chain = Load->getChain();
9179
9180 SDValue Lo =
9181 DAG.getLoad(MVT::i32, DL, Chain, BasePtr, Load->getPointerInfo(),
9182 Load->getBaseAlign(), Load->getMemOperand()->getFlags());
9183 BasePtr = DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(4));
9184 SDValue Hi = DAG.getLoad(
9185 MVT::i32, DL, Chain, BasePtr, Load->getPointerInfo().getWithOffset(4),
9186 Load->getBaseAlign(), Load->getMemOperand()->getFlags());
9187 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
9188 Hi.getValue(1));
9189
9190 // For big-endian, swap the order of Lo and Hi.
9191 if (!Subtarget.isLittleEndian())
9192 std::swap(Lo, Hi);
9193
9194 SDValue Pair = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9195 return DAG.getMergeValues({Pair, Chain}, DL);
9196 }
9197
9198 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() &&
9199 (VT == MVT::v2i32 || VT == MVT::v4i16 || VT == MVT::v8i8)) {
9200 assert(!Subtarget.is64Bit() && "Unexpected custom legalisation");
9201
9202 // Determine the half-size type
9203 MVT HalfVT;
9204 if (VT == MVT::v2i32)
9205 HalfVT = MVT::i32;
9206 else if (VT == MVT::v4i16)
9207 HalfVT = MVT::v2i16;
9208 else // VT == MVT::v8i8
9209 HalfVT = MVT::v4i8;
9210
9211 SDLoc DL(Op);
9212 SDValue BasePtr = Load->getBasePtr();
9213 SDValue Chain = Load->getChain();
9214
9215 // Create two loads for the lower and upper halves
9216 SDValue Lo =
9217 DAG.getLoad(HalfVT, DL, Chain, BasePtr, Load->getPointerInfo(),
9218 Load->getBaseAlign(), Load->getMemOperand()->getFlags());
9219 unsigned HalfSize = HalfVT.getStoreSize();
9220 BasePtr =
9221 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(HalfSize));
9222 SDValue Hi =
9223 DAG.getLoad(HalfVT, DL, Chain, BasePtr,
9224 Load->getPointerInfo().getWithOffset(HalfSize),
9225 Load->getBaseAlign(), Load->getMemOperand()->getFlags());
9226 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
9227 Hi.getValue(1));
9228
9229 // Combine the two halves into the result vector
9230 SDValue Result;
9231 if (VT == MVT::v2i32) {
9232 // For v2i32, build vector from two i32 scalars
9233 Result = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Lo, Hi);
9234 } else {
9235 // For v4i16 and v8i8, use CONCAT_VECTORS
9236 Result = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9237 }
9238
9239 return DAG.getMergeValues({Result, Chain}, DL);
9240 }
9241
9242 if (VT == MVT::bf16)
9243 return lowerXAndesBfHCvtBFloat16Load(Op, DAG);
9244
9245 // Handle normal vector tuple load.
9246 if (VT.isRISCVVectorTuple()) {
9247 SDLoc DL(Op);
9248 MVT XLenVT = Subtarget.getXLenVT();
9249 unsigned NF = VT.getRISCVVectorTupleNumFields();
9250 unsigned Sz = VT.getSizeInBits().getKnownMinValue();
9251 unsigned NumElts = Sz / (NF * 8);
9252 int Log2LMUL = Log2_64(NumElts) - 3;
9253
9254 auto Flag = SDNodeFlags();
9255 Flag.setNoUnsignedWrap(true);
9256 SDValue Ret = DAG.getUNDEF(VT);
9257 SDValue BasePtr = Load->getBasePtr();
9258 SDValue VROffset = DAG.getNode(RISCVISD::READ_VLENB, DL, XLenVT);
9259 VROffset =
9260 DAG.getNode(ISD::SHL, DL, XLenVT, VROffset,
9261 DAG.getConstant(std::max(Log2LMUL, 0), DL, XLenVT));
9262 SmallVector<SDValue, 8> OutChains;
9263
9264 // Load NF vector registers and combine them to a vector tuple.
9265 for (unsigned i = 0; i < NF; ++i) {
9266 SDValue LoadVal = DAG.getLoad(
9267 MVT::getScalableVectorVT(MVT::i8, NumElts), DL, Load->getChain(),
9268 BasePtr, MachinePointerInfo(Load->getAddressSpace()), Align(8));
9269 OutChains.push_back(LoadVal.getValue(1));
9270 Ret = DAG.getNode(RISCVISD::TUPLE_INSERT, DL, VT, Ret, LoadVal,
9271 DAG.getTargetConstant(i, DL, MVT::i32));
9272 BasePtr = DAG.getNode(ISD::ADD, DL, XLenVT, BasePtr, VROffset, Flag);
9273 }
9274 return DAG.getMergeValues(
9275 {Ret, DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains)}, DL);
9276 }
9277
9278 if (auto V = expandUnalignedRVVLoad(Op, DAG))
9279 return V;
9280 if (Op.getValueType().isFixedLengthVector())
9281 return lowerFixedLengthVectorLoadToRVV(Op, DAG);
9282 return Op;
9283 }
9284 case ISD::STORE: {
9285 auto *Store = cast<StoreSDNode>(Op);
9286 SDValue StoredVal = Store->getValue();
9287 EVT VT = StoredVal.getValueType();
9288
9289 if (VT == MVT::f64) {
9290 assert(Subtarget.hasStdExtZdinx() && !Subtarget.hasStdExtZilsd() &&
9291 !Subtarget.is64Bit() && "Unexpected custom legalisation");
9292
9293 // Replace a double precision store with a SplitF64 and i32 stores.
9294 SDValue DL(Op);
9295 SDValue BasePtr = Store->getBasePtr();
9296 SDValue Chain = Store->getChain();
9297 SDValue Split = DAG.getNode(RISCVISD::SplitF64, DL,
9298 DAG.getVTList(MVT::i32, MVT::i32), StoredVal);
9299
9300 SDValue Lo = Split.getValue(0);
9301 SDValue Hi = Split.getValue(1);
9302
9303 // For big-endian, swap the order of Lo and Hi before storing.
9304 if (!Subtarget.isLittleEndian())
9305 std::swap(Lo, Hi);
9306
9307 SDValue LoStore = DAG.getStore(
9308 Chain, DL, Lo, BasePtr, Store->getPointerInfo(),
9309 Store->getBaseAlign(), Store->getMemOperand()->getFlags());
9310 BasePtr = DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(4));
9311 SDValue HiStore = DAG.getStore(
9312 Chain, DL, Hi, BasePtr, Store->getPointerInfo().getWithOffset(4),
9313 Store->getBaseAlign(), Store->getMemOperand()->getFlags());
9314 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, LoStore, HiStore);
9315 }
9316 if (VT == MVT::i64) {
9317 assert(Subtarget.hasStdExtZilsd() && !Subtarget.is64Bit() &&
9318 "Unexpected custom legalisation");
9319 if (Store->isTruncatingStore())
9320 return SDValue();
9321
9322 if (Store->getAlign() < Subtarget.getZilsdAlign())
9323 return SDValue();
9324
9325 SDLoc DL(Op);
9326 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, StoredVal,
9327 DAG.getTargetConstant(0, DL, MVT::i32));
9328 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, StoredVal,
9329 DAG.getTargetConstant(1, DL, MVT::i32));
9330
9331 return DAG.getMemIntrinsicNode(
9332 RISCVISD::SD_RV32, DL, DAG.getVTList(MVT::Other),
9333 {Store->getChain(), Lo, Hi, Store->getBasePtr()}, MVT::i64,
9334 Store->getMemOperand());
9335 }
9336
9337 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() &&
9338 (VT == MVT::v2i32 || VT == MVT::v4i16 || VT == MVT::v8i8)) {
9339 assert(!Subtarget.is64Bit() && "Unexpected custom legalisation");
9340
9341 auto *Store = cast<StoreSDNode>(Op);
9342 SDValue Val = Store->getValue();
9343
9344 // Determine the half-size type
9345 MVT HalfVT;
9346 if (VT == MVT::v2i32)
9347 HalfVT = MVT::i32;
9348 else if (VT == MVT::v4i16)
9349 HalfVT = MVT::v2i16;
9350 else // VT == MVT::v8i8
9351 HalfVT = MVT::v4i8;
9352
9353 SDLoc DL(Op);
9354 SDValue BasePtr = Store->getBasePtr();
9355 SDValue Chain = Store->getChain();
9356
9357 // Extract the two halves from the vector
9358 SDValue Lo, Hi;
9359 if (VT == MVT::v2i32) {
9360 // For v2i32, extract two i32 scalars
9361 Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Val,
9362 DAG.getVectorIdxConstant(0, DL));
9363 Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Val,
9364 DAG.getVectorIdxConstant(1, DL));
9365 } else {
9366 // For v4i16 and v8i8, extract two vector halves
9367 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, Val,
9368 DAG.getVectorIdxConstant(0, DL));
9369 unsigned HalfNumElts = HalfVT.getVectorNumElements();
9370 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, Val,
9371 DAG.getVectorIdxConstant(HalfNumElts, DL));
9372 }
9373
9374 // Create two stores for the lower and upper halves
9375 SDValue LoStore = DAG.getStore(
9376 Chain, DL, Lo, BasePtr, Store->getPointerInfo(),
9377 Store->getBaseAlign(), Store->getMemOperand()->getFlags());
9378 unsigned HalfSize = HalfVT.getStoreSize();
9379 BasePtr =
9380 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(HalfSize));
9381 SDValue HiStore = DAG.getStore(
9382 Chain, DL, Hi, BasePtr,
9383 Store->getPointerInfo().getWithOffset(HalfSize),
9384 Store->getBaseAlign(), Store->getMemOperand()->getFlags());
9385
9386 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, LoStore, HiStore);
9387 }
9388
9389 if (VT == MVT::bf16)
9390 return lowerXAndesBfHCvtBFloat16Store(Op, DAG);
9391
9392 // Handle normal vector tuple store.
9393 if (VT.isRISCVVectorTuple()) {
9394 SDLoc DL(Op);
9395 MVT XLenVT = Subtarget.getXLenVT();
9396 unsigned NF = VT.getRISCVVectorTupleNumFields();
9397 unsigned Sz = VT.getSizeInBits().getKnownMinValue();
9398 unsigned NumElts = Sz / (NF * 8);
9399 int Log2LMUL = Log2_64(NumElts) - 3;
9400
9401 auto Flag = SDNodeFlags();
9402 Flag.setNoUnsignedWrap(true);
9403 SDValue Ret;
9404 SDValue Chain = Store->getChain();
9405 SDValue BasePtr = Store->getBasePtr();
9406 SDValue VROffset = DAG.getNode(RISCVISD::READ_VLENB, DL, XLenVT);
9407 VROffset =
9408 DAG.getNode(ISD::SHL, DL, XLenVT, VROffset,
9409 DAG.getConstant(std::max(Log2LMUL, 0), DL, XLenVT));
9410
9411 // Extract subregisters in a vector tuple and store them individually.
9412 for (unsigned i = 0; i < NF; ++i) {
9413 auto Extract =
9414 DAG.getNode(RISCVISD::TUPLE_EXTRACT, DL,
9415 MVT::getScalableVectorVT(MVT::i8, NumElts), StoredVal,
9416 DAG.getTargetConstant(i, DL, MVT::i32));
9417 Ret = DAG.getStore(Chain, DL, Extract, BasePtr,
9418 MachinePointerInfo(Store->getAddressSpace()),
9419 Store->getBaseAlign(),
9420 Store->getMemOperand()->getFlags());
9421 Chain = Ret.getValue(0);
9422 BasePtr = DAG.getNode(ISD::ADD, DL, XLenVT, BasePtr, VROffset, Flag);
9423 }
9424 return Ret;
9425 }
9426
9427 if (auto V = expandUnalignedRVVStore(Op, DAG))
9428 return V;
9429 if (Op.getOperand(1).getValueType().isFixedLengthVector())
9430 return lowerFixedLengthVectorStoreToRVV(Op, DAG);
9431 return Op;
9432 }
9433 case ISD::VP_LOAD:
9434 if (SDValue V = expandUnalignedVPLoad(Op, DAG))
9435 return V;
9436 [[fallthrough]];
9437 case ISD::MLOAD:
9438 return lowerMaskedLoad(Op, DAG);
9439 case ISD::VP_LOAD_FF:
9440 return lowerLoadFF(Op, DAG);
9441 case ISD::VP_STORE:
9442 if (SDValue V = expandUnalignedVPStore(Op, DAG))
9443 return V;
9444 [[fallthrough]];
9445 case ISD::MSTORE:
9446 return lowerMaskedStore(Op, DAG);
9448 return lowerVectorCompress(Op, DAG);
9449 case ISD::SELECT_CC: {
9450 // This occurs because we custom legalize SETGT and SETUGT for setcc. That
9451 // causes LegalizeDAG to think we need to custom legalize select_cc. Expand
9452 // into separate SETCC+SELECT just like LegalizeDAG.
9453 SDValue Tmp1 = Op.getOperand(0);
9454 SDValue Tmp2 = Op.getOperand(1);
9455 SDValue True = Op.getOperand(2);
9456 SDValue False = Op.getOperand(3);
9457 EVT VT = Op.getValueType();
9458 SDValue CC = Op.getOperand(4);
9459 EVT CmpVT = Tmp1.getValueType();
9460 EVT CCVT =
9461 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
9462 SDLoc DL(Op);
9463 SDValue Cond =
9464 DAG.getNode(ISD::SETCC, DL, CCVT, Tmp1, Tmp2, CC, Op->getFlags());
9465 return DAG.getSelect(DL, VT, Cond, True, False);
9466 }
9467 case ISD::SETCC: {
9468 MVT OpVT = Op.getOperand(0).getSimpleValueType();
9469 if (OpVT.isScalarInteger()) {
9470 MVT VT = Op.getSimpleValueType();
9471 SDValue LHS = Op.getOperand(0);
9472 SDValue RHS = Op.getOperand(1);
9473 ISD::CondCode CCVal = Op.getOperandCondCode(2);
9474 assert((CCVal == ISD::SETGT || CCVal == ISD::SETUGT) &&
9475 "Unexpected CondCode");
9476
9477 SDLoc DL(Op);
9478
9479 // If the RHS is a constant in the range [-2049, 0) or (0, 2046], we can
9480 // convert this to the equivalent of (set(u)ge X, C+1) by using
9481 // (xori (slti(u) X, C+1), 1). This avoids materializing a small constant
9482 // in a register.
9483 if (isa<ConstantSDNode>(RHS)) {
9484 int64_t Imm = cast<ConstantSDNode>(RHS)->getSExtValue();
9485 if (Imm != 0 && isInt<12>((uint64_t)Imm + 1)) {
9486 // If this is an unsigned compare and the constant is -1, incrementing
9487 // the constant would change behavior. The result should be false.
9488 if (CCVal == ISD::SETUGT && Imm == -1)
9489 return DAG.getConstant(0, DL, VT);
9490 // Using getSetCCSwappedOperands will convert SET(U)GT->SET(U)LT.
9491 CCVal = ISD::getSetCCSwappedOperands(CCVal);
9492 SDValue SetCC = DAG.getSetCC(
9493 DL, VT, LHS, DAG.getSignedConstant(Imm + 1, DL, OpVT), CCVal);
9494 return DAG.getLogicalNOT(DL, SetCC, VT);
9495 }
9496 // Lower (setugt X, 2047) as (setne (srl X, 11), 0).
9497 if (CCVal == ISD::SETUGT && Imm == 2047) {
9498 SDValue Shift = DAG.getNode(ISD::SRL, DL, OpVT, LHS,
9499 DAG.getShiftAmountConstant(11, OpVT, DL));
9500 return DAG.getSetCC(DL, VT, Shift, DAG.getConstant(0, DL, OpVT),
9501 ISD::SETNE);
9502 }
9503 }
9504
9505 // Not a constant we could handle, swap the operands and condition code to
9506 // SETLT/SETULT.
9507 CCVal = ISD::getSetCCSwappedOperands(CCVal);
9508 return DAG.getSetCC(DL, VT, RHS, LHS, CCVal);
9509 }
9510
9511 MVT VT = Op.getSimpleValueType();
9512 if (Subtarget.hasStdExtP() && VT.isFixedLengthVector()) {
9513 ISD::CondCode CCVal = Op.getOperandCondCode(2);
9514 SDValue LHS = Op.getOperand(0);
9515 SDValue RHS = Op.getOperand(1);
9516 SDLoc DL(Op);
9517 if (CCVal == ISD::SETNE) {
9518 // Convert setne X, 0 to setult 0, X.
9520 return DAG.getSetCC(DL, VT, RHS, LHS, ISD::SETULT);
9521 }
9522
9523 // Not a constant we could handle, convert to SETEQ+Invert
9524 SDValue SetCC = DAG.getSetCC(DL, VT, LHS, RHS, ISD::SETEQ);
9525 return DAG.getLogicalNOT(DL, SetCC, VT);
9526 }
9527
9528 if (CCVal == ISD::SETGT) {
9530 SDValue SetCC =
9531 DAG.getSetCC(DL, VT, LHS, DAG.getConstant(0, DL, VT), ISD::SETLT);
9532 return DAG.getLogicalNOT(DL, SetCC, VT);
9533 }
9534
9535 // Not a constant we could handle, swap the operands and condition code
9536 // to SETLT.
9537 CCVal = ISD::getSetCCSwappedOperands(CCVal);
9538 return DAG.getSetCC(DL, VT, RHS, LHS, CCVal);
9539 }
9540
9541 return SDValue();
9542 }
9543
9544 if (isPromotedOpNeedingSplit(Op.getOperand(0), Subtarget, *this))
9545 return SplitVectorOp(Op, DAG);
9546
9547 return lowerToScalableOp(Op, DAG);
9548 }
9549 case ISD::ADD:
9550 case ISD::SUB:
9551 case ISD::SDIV:
9552 case ISD::SREM:
9553 case ISD::UDIV:
9554 case ISD::UREM:
9555 case ISD::BSWAP:
9556 case ISD::CTPOP:
9557 return lowerToScalableOp(Op, DAG);
9558 case ISD::VSELECT: {
9559 EVT VT = Op.getValueType();
9560 // Split 64-bit vector VSELECT on RV32 with P extension for v4i16 and v8i8
9561 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() &&
9562 (VT == MVT::v4i16 || VT == MVT::v8i8)) {
9563 SDLoc DL(Op);
9564 SDValue Mask = Op.getOperand(0);
9565 SDValue TrueVal = Op.getOperand(1);
9566 SDValue FalseVal = Op.getOperand(2);
9567
9568 // Split all three operands into two halves
9569 auto [MaskLo, MaskHi] = DAG.SplitVector(Mask, DL);
9570 auto [TrueLo, TrueHi] = DAG.SplitVector(TrueVal, DL);
9571 auto [FalseLo, FalseHi] = DAG.SplitVector(FalseVal, DL);
9572
9573 // Perform VSELECT on each half
9574 SDValue ResLo = DAG.getNode(ISD::VSELECT, DL, TrueLo.getValueType(),
9575 MaskLo, TrueLo, FalseLo);
9576 SDValue ResHi = DAG.getNode(ISD::VSELECT, DL, TrueHi.getValueType(),
9577 MaskHi, TrueHi, FalseHi);
9578
9579 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
9580 }
9581 return lowerToScalableOp(Op, DAG);
9582 }
9583 case ISD::AND:
9584 case ISD::OR:
9585 case ISD::XOR:
9586 case ISD::MUL:
9587 case ISD::MULHS:
9588 case ISD::MULHU: {
9589 EVT VT = Op.getValueType();
9590 unsigned Opc = Op.getOpcode();
9591 // Split 64-bit vector AND/OR/XOR/MUL/MULHS/MULHU on RV32 with P extension
9592 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() &&
9593 (VT == MVT::v4i16 || VT == MVT::v8i8)) {
9594 SDLoc DL(Op);
9595 SDValue LHS = Op.getOperand(0);
9596 SDValue RHS = Op.getOperand(1);
9597
9598 // Determine the half-size type
9599 MVT HalfVT = (VT == MVT::v4i16) ? MVT::v2i16 : MVT::v4i8;
9600
9601 // Extract the two halves from LHS
9602 auto [LHSLo, LHSHi] = DAG.SplitVector(LHS, DL, HalfVT, HalfVT);
9603
9604 // Extract the two halves from RHS
9605 auto [RHSLo, RHSHi] = DAG.SplitVector(RHS, DL, HalfVT, HalfVT);
9606
9607 // Perform the operation on each half
9608 SDValue ResLo = DAG.getNode(Opc, DL, HalfVT, LHSLo, RHSLo);
9609 SDValue ResHi = DAG.getNode(Opc, DL, HalfVT, LHSHi, RHSHi);
9610
9611 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
9612 }
9613 // Lower v4i8/v2i16 MUL/MULHS/MULHU via widening multiply + srl + truncate.
9614 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() &&
9615 (Opc == ISD::MUL || Opc == ISD::MULHS || Opc == ISD::MULHU) &&
9616 (VT == MVT::v4i8 || VT == MVT::v2i16)) {
9617 assert((VT == MVT::v4i8 || Opc == ISD::MUL) &&
9618 "Unexpected custom legalisation");
9619 SDLoc DL(Op);
9620 MVT WideVT = (VT == MVT::v4i8) ? MVT::v4i16 : MVT::v2i32;
9621 unsigned WMulOpc =
9622 (Opc == ISD::MULHU) ? RISCVISD::PWMULU : RISCVISD::PWMUL;
9623 SDValue Res =
9624 DAG.getNode(WMulOpc, DL, WideVT, Op.getOperand(0), Op.getOperand(1));
9625 if (Opc != ISD::MUL) {
9626 unsigned EltBits = VT.getVectorElementType().getSizeInBits();
9627 Res = DAG.getNode(ISD::SRL, DL, WideVT, Res,
9628 DAG.getConstant(EltBits, DL, WideVT));
9629 }
9630 return DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
9631 }
9632 // Lower packed MUL and byte MULHS/MULHU on RV64 via a pair of widening
9633 // multiplies, selecting the low/high halves with PPAIRE/PPAIRO.
9634 if (Subtarget.hasStdExtP() && Subtarget.is64Bit() &&
9635 ((Opc == ISD::MUL && (VT == MVT::v8i8 || VT == MVT::v4i16)) ||
9636 (VT == MVT::v8i8 && (Opc == ISD::MULHS || Opc == ISD::MULHU)))) {
9637 SDLoc DL(Op);
9638 SDValue LHS = Op.getOperand(0);
9639 SDValue RHS = Op.getOperand(1);
9640 unsigned LoOpc = Opc == ISD::MULHU ? RISCVISD::PMULU_HALVES_00
9641 : RISCVISD::PMUL_HALVES_00;
9642 unsigned HiOpc = Opc == ISD::MULHU ? RISCVISD::PMULU_HALVES_11
9643 : RISCVISD::PMUL_HALVES_11;
9644 MVT WideVT = VT == MVT::v8i8 ? MVT::v4i16 : MVT::v2i32;
9645 SDValue Lo = DAG.getNode(LoOpc, DL, WideVT, LHS, RHS);
9646 SDValue Hi = DAG.getNode(HiOpc, DL, WideVT, LHS, RHS);
9647 unsigned PairOpc = Opc == ISD::MUL ? RISCVISD::PPAIRE : RISCVISD::PPAIRO;
9648 return DAG.getNode(PairOpc, DL, VT, DAG.getBitcast(VT, Lo),
9649 DAG.getBitcast(VT, Hi));
9650 }
9651 return lowerToScalableOp(Op, DAG);
9652 }
9654 EVT VT = Op.getValueType();
9655 assert(Subtarget.hasStdExtP() && Subtarget.is64Bit() &&
9656 (VT == MVT::v2i32 || VT == MVT::v4i16) &&
9657 "Unexpected custom legalisation");
9659 Op.getOperand(0));
9660 }
9661 case ISD::SHL:
9662 case ISD::SRL:
9663 case ISD::SRA:
9664 case ISD::SSHLSAT:
9665 if (Op.getSimpleValueType().isFixedLengthVector()) {
9666 if (Subtarget.hasStdExtP()) {
9667 SDValue ShAmtVec = Op.getOperand(1);
9668 SDValue SplatVal = DAG.getSplatValue(ShAmtVec, /*LegalTypes=*/true);
9669
9670 if (!SplatVal)
9671 return SDValue();
9672
9673 unsigned Opc;
9674 switch (Op.getOpcode()) {
9675 default:
9676 llvm_unreachable("Unexpected opcode");
9677 case ISD::SHL:
9678 Opc = RISCVISD::PSLL;
9679 break;
9680 case ISD::SRL:
9681 Opc = RISCVISD::PSRL;
9682 break;
9683 case ISD::SRA:
9684 Opc = RISCVISD::PSRA;
9685 break;
9686 case ISD::SSHLSAT:
9687 Opc = RISCVISD::PSSHA;
9688 break;
9689 }
9690 return DAG.getNode(Opc, SDLoc(Op), Op.getValueType(), Op.getOperand(0),
9691 SplatVal);
9692 }
9693 return lowerToScalableOp(Op, DAG);
9694 }
9695 assert(Op.getOpcode() != ISD::SSHLSAT);
9696 // This can be called for an i32 shift amount that needs to be promoted on
9697 // RV64 or an i64 shift amount that needs to be expanded on RV32+P.
9698 assert(
9699 ((Subtarget.is64Bit() && Op.getOperand(1).getValueType() == MVT::i32) ||
9700 (!Subtarget.is64Bit() && Subtarget.hasStdExtP() &&
9701 Op.getOperand(1).getValueType() == MVT::i64)) &&
9702 "Unexpected custom legalisation");
9703 return SDValue();
9704 case ISD::MASKED_UDIV:
9705 case ISD::MASKED_SDIV:
9706 case ISD::MASKED_UREM:
9707 case ISD::MASKED_SREM: {
9708 SDLoc DL(Op);
9709 MVT VT = Op.getSimpleValueType();
9711 SDValue VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
9712 SDValue Res = DAG.getNode(
9714 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget),
9715 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget),
9716 DAG.getUNDEF(ContainerVT),
9718 DAG, Subtarget),
9719 VL);
9720 return convertFromScalableVector(VT, Res, DAG, Subtarget);
9721 }
9722 case ISD::FABS:
9723 case ISD::FNEG:
9724 if (Op.getValueType() == MVT::f16 || Op.getValueType() == MVT::bf16)
9725 return lowerFABSorFNEG(Op, DAG, Subtarget);
9726 [[fallthrough]];
9727 case ISD::FADD:
9728 case ISD::FSUB:
9729 case ISD::FMUL:
9730 case ISD::FDIV:
9731 case ISD::FSQRT:
9732 case ISD::FMA:
9733 case ISD::FMINNUM:
9734 case ISD::FMAXNUM:
9735 case ISD::FMINIMUMNUM:
9736 case ISD::FMAXIMUMNUM:
9737 if (isPromotedOpNeedingSplit(Op, Subtarget, *this))
9738 return SplitVectorOp(Op, DAG);
9739 [[fallthrough]];
9740 case ISD::AVGFLOORS:
9741 case ISD::AVGFLOORU:
9742 case ISD::AVGCEILS:
9743 case ISD::AVGCEILU:
9744 case ISD::SMIN:
9745 case ISD::SMAX:
9746 case ISD::UMIN:
9747 case ISD::UMAX:
9748 case ISD::UADDSAT:
9749 case ISD::USUBSAT:
9750 case ISD::SADDSAT:
9751 case ISD::SSUBSAT:
9752 return lowerToScalableOp(Op, DAG);
9753 case ISD::ABDS:
9754 case ISD::ABDU: {
9755 EVT VT = Op->getValueType(0);
9756 if (Subtarget.hasStdExtZvabd() && VT.isVector())
9757 return lowerToScalableOp(Op, DAG);
9758
9759 SDLoc dl(Op);
9760 SDValue LHS = DAG.getFreeze(Op->getOperand(0));
9761 SDValue RHS = DAG.getFreeze(Op->getOperand(1));
9762 bool IsSigned = Op->getOpcode() == ISD::ABDS;
9763
9764 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
9765 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
9766 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
9767 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
9768 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
9769 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
9770 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
9771 }
9772 case ISD::ABS:
9774 return lowerABS(Op, DAG);
9775 case ISD::CTLZ:
9777 case ISD::CTTZ:
9779 if (Subtarget.hasStdExtZvbb())
9780 return lowerToScalableOp(Op, DAG);
9781 assert(Op.getOpcode() != ISD::CTTZ);
9782 return lowerCTLZ_CTTZ_ZERO_POISON(Op, DAG);
9783 case ISD::CLMUL:
9784 case ISD::CLMULH: {
9785 SDLoc DL(Op);
9786 MVT VT = Op.getSimpleValueType();
9787 MVT XLenVT = Subtarget.getXLenVT();
9788
9789 if (!VT.isVector()) {
9790 // The op needs to be performed in a vector register.
9791 assert(Subtarget.hasStdExtZvbc() && Subtarget.is64Bit() && VT == XLenVT &&
9792 "Unexpected custom legalisation");
9793 // We can't implicitly use vector registers with noimplicitfloat.
9795 Attribute::NoImplicitFloat))
9796 return SDValue();
9797 MVT VecVT = MVT::getScalableVectorVT(VT, 1);
9798 SDValue VL = DAG.getConstant(1, DL, XLenVT);
9799 SDValue Op0 =
9800 lowerScalarInsert(Op.getOperand(0), VL, VecVT, DL, DAG, Subtarget);
9801 SDValue Op1 =
9802 lowerScalarInsert(Op.getOperand(1), VL, VecVT, DL, DAG, Subtarget);
9803 SDValue Res = DAG.getNode(Op.getOpcode(), DL, VecVT, Op0, Op1);
9804 return DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Res);
9805 }
9806
9807 // If the scalable vector version of this op is Legal, convert to scalable.
9808 if (VT.isFixedLengthVector() &&
9809 (VT.getVectorElementType() == MVT::i64 || Subtarget.hasStdExtZvbc32e()))
9810 return lowerToScalableOp(Op, DAG);
9811
9812 assert(Op.getOpcode() == ISD::CLMUL && Subtarget.hasStdExtZvbc() &&
9813 "Unexpected custom legalisation");
9814 // Promote to i64 vector.
9815 MVT I64VecVT = VT.changeVectorElementType(MVT::i64);
9816 SDValue Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, I64VecVT, Op.getOperand(0));
9817 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, I64VecVT, Op.getOperand(1));
9818 SDValue CLMUL = DAG.getNode(ISD::CLMUL, DL, I64VecVT, Op0, Op1);
9819 return DAG.getNode(ISD::TRUNCATE, DL, VT, CLMUL);
9820 }
9821 case ISD::FCOPYSIGN:
9822 if (Op.getValueType() == MVT::f16 || Op.getValueType() == MVT::bf16)
9823 return lowerFCOPYSIGN(Op, DAG, Subtarget);
9824 if (isPromotedOpNeedingSplit(Op, Subtarget, *this))
9825 return SplitVectorOp(Op, DAG);
9826 return lowerToScalableOp(Op, DAG);
9827 case ISD::STRICT_FADD:
9828 case ISD::STRICT_FSUB:
9829 case ISD::STRICT_FMUL:
9830 case ISD::STRICT_FDIV:
9831 case ISD::STRICT_FSQRT:
9832 case ISD::STRICT_FMA:
9833 if (isPromotedOpNeedingSplit(Op, Subtarget, *this))
9834 return SplitStrictFPVectorOp(Op, DAG);
9835 return lowerToScalableOp(Op, DAG);
9836 case ISD::STRICT_FSETCC:
9838 return lowerVectorStrictFSetcc(Op, DAG);
9839 case ISD::STRICT_FCEIL:
9840 case ISD::STRICT_FRINT:
9841 case ISD::STRICT_FFLOOR:
9842 case ISD::STRICT_FTRUNC:
9844 case ISD::STRICT_FROUND:
9846 return lowerVectorStrictFTRUNC_FCEIL_FFLOOR_FROUND(Op, DAG, Subtarget);
9847 case ISD::MGATHER:
9848 case ISD::VP_GATHER:
9849 return lowerMaskedGather(Op, DAG);
9850 case ISD::MSCATTER:
9851 case ISD::VP_SCATTER:
9852 return lowerMaskedScatter(Op, DAG);
9853 case ISD::GET_ROUNDING:
9854 return lowerGET_ROUNDING(Op, DAG);
9855 case ISD::SET_ROUNDING:
9856 return lowerSET_ROUNDING(Op, DAG);
9857 case ISD::GET_FPENV:
9858 return lowerGET_FPENV(Op, DAG);
9859 case ISD::SET_FPENV:
9860 return lowerSET_FPENV(Op, DAG);
9861 case ISD::RESET_FPENV:
9862 return lowerRESET_FPENV(Op, DAG);
9863 case ISD::GET_FPMODE:
9864 return lowerGET_FPMODE(Op, DAG);
9865 case ISD::SET_FPMODE:
9866 return lowerSET_FPMODE(Op, DAG);
9867 case ISD::RESET_FPMODE:
9868 return lowerRESET_FPMODE(Op, DAG);
9869 case ISD::EH_DWARF_CFA:
9870 return lowerEH_DWARF_CFA(Op, DAG);
9871 case ISD::VP_MERGE:
9872 if (Op.getSimpleValueType().getVectorElementType() == MVT::i1)
9873 return lowerVPMergeMask(Op, DAG);
9874 [[fallthrough]];
9875 case ISD::VP_SDIV:
9876 case ISD::VP_UDIV:
9877 case ISD::VP_SREM:
9878 case ISD::VP_UREM:
9879 return lowerVPOp(Op, DAG);
9880 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
9881 return lowerVPStridedLoad(Op, DAG);
9882 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
9883 return lowerVPStridedStore(Op, DAG);
9884 case ISD::EXPERIMENTAL_VP_SPLICE:
9885 return lowerVPSpliceExperimental(Op, DAG);
9886 case ISD::EXPERIMENTAL_VP_REVERSE:
9887 return lowerVPReverseExperimental(Op, DAG);
9888 case ISD::CLEAR_CACHE: {
9889 assert(getTargetMachine().getTargetTriple().isOSLinux() &&
9890 "llvm.clear_cache only needs custom lower on Linux targets");
9891 SDLoc DL(Op);
9892 SDValue Flags = DAG.getConstant(0, DL, Subtarget.getXLenVT());
9893 return emitFlushICache(DAG, Op.getOperand(0), Op.getOperand(1),
9894 Op.getOperand(2), Flags, DL);
9895 }
9897 return lowerDYNAMIC_STACKALLOC(Op, DAG);
9899 return lowerINIT_TRAMPOLINE(Op, DAG);
9901 return lowerADJUST_TRAMPOLINE(Op, DAG);
9905 return lowerPARTIAL_REDUCE_MLA(Op, DAG);
9906 case ISD::CTTZ_ELTS:
9908 return lowerCttzElts(Op, DAG, Subtarget);
9910 return lowerCONVERT_FROM_ARBITRARY_FP(Op, DAG, Subtarget);
9911 }
9912}
9913
9914SDValue RISCVTargetLowering::emitFlushICache(SelectionDAG &DAG, SDValue InChain,
9915 SDValue Start, SDValue End,
9916 SDValue Flags, SDLoc DL) const {
9917 MakeLibCallOptions CallOptions;
9918 std::pair<SDValue, SDValue> CallResult =
9919 makeLibCall(DAG, RTLIB::RISCV_FLUSH_ICACHE, MVT::isVoid,
9920 {Start, End, Flags}, CallOptions, DL, InChain);
9921
9922 // This function returns void so only the out chain matters.
9923 return CallResult.second;
9924}
9925
9926SDValue RISCVTargetLowering::lowerINIT_TRAMPOLINE(SDValue Op,
9927 SelectionDAG &DAG) const {
9928 if (!Subtarget.is64Bit())
9929 llvm::reportFatalUsageError("Trampolines only implemented for RV64");
9930
9931 // Create an MCCodeEmitter to encode instructions.
9932 TargetLoweringObjectFile *TLO = getTargetMachine().getObjFileLowering();
9933 assert(TLO);
9934 MCContext &MCCtx = TLO->getContext();
9935
9936 std::unique_ptr<MCCodeEmitter> CodeEmitter(
9937 createRISCVMCCodeEmitter(*getTargetMachine().getMCInstrInfo(), MCCtx));
9938
9939 SDValue Root = Op.getOperand(0);
9940 SDValue Trmp = Op.getOperand(1); // trampoline
9941 SDLoc dl(Op);
9942
9943 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9944
9945 // We store in the trampoline buffer the following instructions and data.
9946 // Offset:
9947 // 0: auipc t2, 0
9948 // 4: ld t0, 24(t2)
9949 // 8: ld t2, 16(t2)
9950 // 12: jalr t0
9951 // 16: <StaticChainOffset>
9952 // 24: <FunctionAddressOffset>
9953 // 32:
9954 // Offset with branch control flow protection enabled:
9955 // 0: lpad <imm20>
9956 // 4: auipc t3, 0
9957 // 8: ld t2, 28(t3)
9958 // 12: ld t3, 20(t3)
9959 // 16: jalr t2
9960 // 20: <StaticChainOffset>
9961 // 28: <FunctionAddressOffset>
9962 // 36:
9963
9964 const MachineFunction &MF = DAG.getMachineFunction();
9965 const bool HasCFBranch =
9966 MF.getInfo<RISCVMachineFunctionInfo>()->hasCFProtectionBranch();
9967 const unsigned StaticChainIdx = HasCFBranch ? 5 : 4;
9968 const unsigned StaticChainOffset = StaticChainIdx * 4;
9969 const unsigned FunctionAddressOffset = StaticChainOffset + 8;
9970
9971 const MCSubtargetInfo &STI = getTargetMachine().getMCSubtargetInfo();
9972 auto GetEncoding = [&](const MCInst &MC) {
9975 CodeEmitter->encodeInstruction(MC, CB, Fixups, STI);
9976 uint32_t Encoding = support::endian::read32le(CB.data());
9977 return Encoding;
9978 };
9979
9980 SmallVector<SDValue> OutChains;
9981
9982 SmallVector<uint32_t> Encodings;
9983 if (!HasCFBranch) {
9984 Encodings.append(
9985 {// auipc t2, 0
9986 // Loads the current PC into t2.
9987 GetEncoding(MCInstBuilder(RISCV::AUIPC).addReg(RISCV::X7).addImm(0)),
9988 // ld t0, 24(t2)
9989 // Loads the function address into t0. Note that we are using offsets
9990 // pc-relative to the first instruction of the trampoline.
9991 GetEncoding(MCInstBuilder(RISCV::LD)
9992 .addReg(RISCV::X5)
9993 .addReg(RISCV::X7)
9994 .addImm(FunctionAddressOffset)),
9995 // ld t2, 16(t2)
9996 // Load the value of the static chain.
9997 GetEncoding(MCInstBuilder(RISCV::LD)
9998 .addReg(RISCV::X7)
9999 .addReg(RISCV::X7)
10000 .addImm(StaticChainOffset)),
10001 // jalr t0
10002 // Jump to the function.
10003 GetEncoding(MCInstBuilder(RISCV::JALR)
10004 .addReg(RISCV::X0)
10005 .addReg(RISCV::X5)
10006 .addImm(0))});
10007 } else {
10008 Encodings.append(
10009 {// auipc x0, <imm20> (lpad <imm20>)
10010 // Landing pad.
10011 GetEncoding(MCInstBuilder(RISCV::AUIPC).addReg(RISCV::X0).addImm(0)),
10012 // auipc t3, 0
10013 // Loads the current PC into t3.
10014 GetEncoding(MCInstBuilder(RISCV::AUIPC).addReg(RISCV::X28).addImm(0)),
10015 // ld t2, (FunctionAddressOffset - 4)(t3)
10016 // Loads the function address into t2. Note that we are using offsets
10017 // pc-relative to the SECOND instruction of the trampoline.
10018 GetEncoding(MCInstBuilder(RISCV::LD)
10019 .addReg(RISCV::X7)
10020 .addReg(RISCV::X28)
10021 .addImm(FunctionAddressOffset - 4)),
10022 // ld t3, (StaticChainOffset - 4)(t3)
10023 // Load the value of the static chain.
10024 GetEncoding(MCInstBuilder(RISCV::LD)
10025 .addReg(RISCV::X28)
10026 .addReg(RISCV::X28)
10027 .addImm(StaticChainOffset - 4)),
10028 // jalr t2
10029 // Software-guarded jump to the function.
10030 GetEncoding(MCInstBuilder(RISCV::JALR)
10031 .addReg(RISCV::X0)
10032 .addReg(RISCV::X7)
10033 .addImm(0))});
10034 }
10035
10036 // Store encoded instructions.
10037 for (auto [Idx, Encoding] : llvm::enumerate(Encodings)) {
10038 SDValue Addr = Idx > 0 ? DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10039 DAG.getConstant(Idx * 4, dl, MVT::i64))
10040 : Trmp;
10041 OutChains.push_back(DAG.getTruncStore(
10042 Root, dl, DAG.getConstant(Encoding, dl, MVT::i64), Addr,
10043 MachinePointerInfo(TrmpAddr, Idx * 4), MVT::i32));
10044 }
10045
10046 // Now store the variable part of the trampoline.
10047 SDValue FunctionAddress = Op.getOperand(2);
10048 SDValue StaticChain = Op.getOperand(3);
10049
10050 // Store the given static chain and function pointer in the trampoline buffer.
10051 struct OffsetValuePair {
10052 const unsigned Offset;
10053 const SDValue Value;
10054 SDValue Addr = SDValue(); // Used to cache the address.
10055 } OffsetValues[] = {
10056 {StaticChainOffset, StaticChain},
10057 {FunctionAddressOffset, FunctionAddress},
10058 };
10059 for (auto &OffsetValue : OffsetValues) {
10060 SDValue Addr =
10061 DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10062 DAG.getConstant(OffsetValue.Offset, dl, MVT::i64));
10063 OffsetValue.Addr = Addr;
10064 OutChains.push_back(
10065 DAG.getStore(Root, dl, OffsetValue.Value, Addr,
10066 MachinePointerInfo(TrmpAddr, OffsetValue.Offset)));
10067 }
10068
10069 assert(OutChains.size() == StaticChainIdx + 2 &&
10070 "Size of OutChains mismatch");
10071 SDValue StoreToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
10072
10073 // The end of instructions of trampoline is the same as the static chain
10074 // address that we computed earlier.
10075 SDValue EndOfTrmp = OffsetValues[0].Addr;
10076
10077 // Call clear cache on the trampoline instructions.
10078 SDValue Chain = DAG.getNode(ISD::CLEAR_CACHE, dl, MVT::Other, StoreToken,
10079 Trmp, EndOfTrmp);
10080
10081 return Chain;
10082}
10083
10084SDValue RISCVTargetLowering::lowerADJUST_TRAMPOLINE(SDValue Op,
10085 SelectionDAG &DAG) const {
10086 if (!Subtarget.is64Bit())
10087 llvm::reportFatalUsageError("Trampolines only implemented for RV64");
10088
10089 return Op.getOperand(0);
10090}
10091
10092SDValue RISCVTargetLowering::lowerPARTIAL_REDUCE_MLA(SDValue Op,
10093 SelectionDAG &DAG) const {
10094 // Currently, only the vdot4a and vdot4au case (from zvdot4a8i) should be
10095 // legal.
10096 // TODO: There are many other sub-cases we could potentially lower, are
10097 // any of them worthwhile? Ex: via vredsum, vwredsum, vwwmaccu, etc..
10098 SDLoc DL(Op);
10099 MVT VT = Op.getSimpleValueType();
10100 SDValue Accum = Op.getOperand(0);
10101 SDValue A = Op.getOperand(1);
10102 SDValue B = Op.getOperand(2);
10103 MVT ArgVT = A.getSimpleValueType();
10104 assert(ArgVT == B.getSimpleValueType() &&
10105 ArgVT.getVectorElementType() == MVT::i8);
10106 (void)ArgVT;
10107
10108 // vdot4a* only produces an i32 result. For an i64 accumulator, perform the
10109 // dot product into a fresh i32 accumulator (each result is the sum of four
10110 // i8 products, which cannot overflow i32), reduce those i32 partial sums
10111 // down to the accumulator's element count while still in i32 (a sum of eight
10112 // i8 products still cannot overflow i32), and only then extend to i64 and add
10113 // to the accumulator.
10114 if (VT.getVectorElementType() == MVT::i64) {
10115 assert(Accum.getSimpleValueType() == VT);
10116 // vdot4a* reduces each group of four i8 lanes into one i32 lane, so the
10117 // intermediate i32 result has 1/4 the element count of the i8 inputs.
10118 MVT DotVT = MVT::getVectorVT(
10119 MVT::i32, ArgVT.getVectorElementCount().divideCoefficientBy(4));
10120 SDValue Dot = DAG.getNode(Op.getOpcode(), DL, DotVT,
10121 {DAG.getConstant(0, DL, DotVT), A, B});
10122 // The reduced i32 sums are signed for SMLA/SUMLA and unsigned for UMLA.
10123 unsigned ExtOpc = Op.getOpcode() == ISD::PARTIAL_REDUCE_UMLA
10126
10127 MVT NarrowVT = VT.changeVectorElementType(MVT::i32);
10128 if (VT.isScalableVector() &&
10130 .second) {
10131 // When the accumulator is a single vector (LMUL 1), the i32 subvectors
10132 // are a fractional LMUL, so extracting the high subvector would need a
10133 // vslidedown. Widen the i32 sums to i64 first instead; the i64
10134 // subvectors are then register-aligned and the reduction is a plain add.
10135 MVT WideVT = DotVT.changeVectorElementType(MVT::i64);
10136 SDValue Wide = DAG.getNode(ExtOpc, DL, WideVT, Dot);
10137 unsigned Stride = VT.getVectorMinNumElements();
10138 SDValue Sum = DAG.getExtractSubvector(DL, VT, Wide, 0);
10139 for (unsigned I = 1, E = WideVT.getVectorMinNumElements() / Stride;
10140 I != E; ++I)
10141 Sum = DAG.getNode(ISD::ADD, DL, VT, Sum,
10142 DAG.getExtractSubvector(DL, VT, Wide, I * Stride));
10143 return DAG.getNode(ISD::ADD, DL, VT, Accum, Sum);
10144 }
10145
10146 // Add the i32 partial sums down to the accumulator's element count by
10147 // extracting and summing the subvectors (still in i32 to avoid a wider
10148 // extend), then extend once to i64 and accumulate.
10149 unsigned Stride = NarrowVT.getVectorMinNumElements();
10150 SDValue Sum = DAG.getExtractSubvector(DL, NarrowVT, Dot, 0);
10151 for (unsigned I = 1, E = DotVT.getVectorMinNumElements() / Stride; I != E;
10152 ++I)
10153 Sum = DAG.getNode(ISD::ADD, DL, NarrowVT, Sum,
10154 DAG.getExtractSubvector(DL, NarrowVT, Dot, I * Stride));
10155 return DAG.getNode(ISD::ADD, DL, VT, Accum,
10156 DAG.getNode(ExtOpc, DL, VT, Sum));
10157 }
10158
10159 assert(Accum.getSimpleValueType() == VT &&
10160 VT.getVectorElementType() == MVT::i32);
10161
10162 // The zvdot4a8i pseudos are defined with sources and destination both
10163 // being i32. This cast is needed for correctness to avoid incorrect
10164 // .vx matching of i8 splats.
10165 A = DAG.getBitcast(VT, A);
10166 B = DAG.getBitcast(VT, B);
10167
10168 MVT ContainerVT = VT;
10169 if (VT.isFixedLengthVector()) {
10171 Accum = convertToScalableVector(ContainerVT, Accum, DAG, Subtarget);
10172 A = convertToScalableVector(ContainerVT, A, DAG, Subtarget);
10173 B = convertToScalableVector(ContainerVT, B, DAG, Subtarget);
10174 }
10175
10176 unsigned Opc;
10177 switch (Op.getOpcode()) {
10179 Opc = RISCVISD::VDOT4A_VL;
10180 break;
10182 Opc = RISCVISD::VDOT4AU_VL;
10183 break;
10185 Opc = RISCVISD::VDOT4ASU_VL;
10186 break;
10187 default:
10188 llvm_unreachable("Unexpected opcode");
10189 }
10190 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
10191 SDValue Res = DAG.getNode(Opc, DL, ContainerVT, {A, B, Accum, Mask, VL});
10192 if (VT.isFixedLengthVector())
10193 Res = convertFromScalableVector(VT, Res, DAG, Subtarget);
10194 return Res;
10195}
10196
10198 SelectionDAG &DAG, unsigned Flags) {
10199 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
10200}
10201
10203 SelectionDAG &DAG, unsigned Flags) {
10204 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
10205 Flags);
10206}
10207
10209 SelectionDAG &DAG, unsigned Flags) {
10210 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
10211 N->getOffset(), Flags);
10212}
10213
10215 SelectionDAG &DAG, unsigned Flags) {
10216 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
10217}
10218
10220 EVT Ty, SelectionDAG &DAG) {
10222 SDValue CPAddr = DAG.getTargetConstantPool(CPV, Ty, Align(8));
10223 SDValue LC = DAG.getNode(RISCVISD::LLA, DL, Ty, CPAddr);
10224 return DAG.getLoad(
10225 Ty, DL, DAG.getEntryNode(), LC,
10227}
10228
10230 EVT Ty, SelectionDAG &DAG) {
10232 RISCVConstantPoolValue::Create(*DAG.getContext(), N->getSymbol());
10233 SDValue CPAddr = DAG.getTargetConstantPool(CPV, Ty, Align(8));
10234 SDValue LC = DAG.getNode(RISCVISD::LLA, DL, Ty, CPAddr);
10235 return DAG.getLoad(
10236 Ty, DL, DAG.getEntryNode(), LC,
10238}
10239
10240template <class NodeTy>
10241SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
10242 bool IsLocal, bool IsExternWeak) const {
10243 SDLoc DL(N);
10244 EVT Ty = getPointerTy(DAG.getDataLayout());
10245
10246 // When HWASAN is used and tagging of global variables is enabled
10247 // they should be accessed via the GOT, since the tagged address of a global
10248 // is incompatible with existing code models. This also applies to non-pic
10249 // mode.
10250 if (isPositionIndependent() || Subtarget.allowTaggedGlobals()) {
10251 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
10252 if (IsLocal && !Subtarget.allowTaggedGlobals())
10253 // Use PC-relative addressing to access the symbol. This generates the
10254 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
10255 // %pcrel_lo(auipc)).
10256 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
10257
10258 // Use PC-relative addressing to access the GOT for this symbol, then load
10259 // the address from the GOT. This generates the pattern (PseudoLGA sym),
10260 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
10261 SDValue Load =
10262 SDValue(DAG.getMachineNode(RISCV::PseudoLGA, DL, Ty, Addr), 0);
10264 MachineMemOperand *MemOp = MF.getMachineMemOperand(
10268 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
10269 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
10270 return Load;
10271 }
10272
10273 switch (getTargetMachine().getCodeModel()) {
10274 default:
10275 reportFatalUsageError("Unsupported code model for lowering");
10276 case CodeModel::Small: {
10277 // Generate a sequence for accessing addresses within the first 2 GiB of
10278 // address space.
10279 if (Subtarget.hasVendorXqcili()) {
10280 // Use QC.E.LI to generate the address, as this is easier to relax than
10281 // LUI/ADDI.
10282 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
10283 return DAG.getNode(RISCVISD::QC_E_LI, DL, Ty, Addr);
10284 }
10285
10286 // This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
10287 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
10288 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
10289 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
10290 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo);
10291 }
10292 case CodeModel::Medium: {
10293 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
10294 if (IsExternWeak) {
10295 // An extern weak symbol may be undefined, i.e. have value 0, which may
10296 // not be within 2GiB of PC, so use GOT-indirect addressing to access the
10297 // symbol. This generates the pattern (PseudoLGA sym), which expands to
10298 // (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
10299 SDValue Load =
10300 SDValue(DAG.getMachineNode(RISCV::PseudoLGA, DL, Ty, Addr), 0);
10302 MachineMemOperand *MemOp = MF.getMachineMemOperand(
10306 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
10307 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
10308 return Load;
10309 }
10310
10311 // Generate a sequence for accessing addresses within any 2GiB range within
10312 // the address space. This generates the pattern (PseudoLLA sym), which
10313 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
10314 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
10315 }
10316 case CodeModel::Large: {
10317 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N))
10318 return getLargeGlobalAddress(G, DL, Ty, DAG);
10319
10320 // Using pc-relative mode for other node type.
10321 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
10322 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
10323 }
10324 }
10325}
10326
10327SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
10328 SelectionDAG &DAG) const {
10329 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
10330 assert(N->getOffset() == 0 && "unexpected offset in global node");
10331 const GlobalValue *GV = N->getGlobal();
10332 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(GV);
10333 return getAddr(N, DAG, IsLocal, GV->hasExternalWeakLinkage());
10334}
10335
10336SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
10337 SelectionDAG &DAG) const {
10338 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
10339
10340 return getAddr(N, DAG);
10341}
10342
10343SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
10344 SelectionDAG &DAG) const {
10345 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
10346
10347 return getAddr(N, DAG);
10348}
10349
10350SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
10351 SelectionDAG &DAG) const {
10352 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
10353
10354 return getAddr(N, DAG);
10355}
10356
10357SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
10358 SelectionDAG &DAG,
10359 bool UseGOT) const {
10360 SDLoc DL(N);
10361 EVT Ty = getPointerTy(DAG.getDataLayout());
10362 const GlobalValue *GV = N->getGlobal();
10363 MVT XLenVT = Subtarget.getXLenVT();
10364
10365 if (UseGOT) {
10366 // Use PC-relative addressing to access the GOT for this TLS symbol, then
10367 // load the address from the GOT and add the thread pointer. This generates
10368 // the pattern (PseudoLA_TLS_IE sym), which expands to
10369 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
10370 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
10371 SDValue Load =
10372 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
10374 MachineMemOperand *MemOp = MF.getMachineMemOperand(
10378 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
10379 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
10380
10381 // Add the thread pointer.
10382 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
10383 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
10384 }
10385
10386 // Generate a sequence for accessing the address relative to the thread
10387 // pointer, with the appropriate adjustment for the thread pointer offset.
10388 // This generates the pattern
10389 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
10390 SDValue AddrHi =
10392 SDValue AddrAdd =
10394 SDValue AddrLo =
10396
10397 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
10398 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
10399 SDValue MNAdd =
10400 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd);
10401 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo);
10402}
10403
10404SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
10405 SelectionDAG &DAG) const {
10406 SDLoc DL(N);
10407 EVT Ty = getPointerTy(DAG.getDataLayout());
10408 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
10409 const GlobalValue *GV = N->getGlobal();
10410
10411 // Use a PC-relative addressing mode to access the global dynamic GOT address.
10412 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
10413 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
10414 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
10415 SDValue Load =
10416 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
10417
10418 // Prepare argument list to generate call.
10420 Args.emplace_back(Load, CallTy);
10421
10422 // Setup call to __tls_get_addr.
10423 TargetLowering::CallLoweringInfo CLI(DAG);
10424 CLI.setDebugLoc(DL)
10425 .setChain(DAG.getEntryNode())
10426 .setLibCallee(CallingConv::C, CallTy,
10427 DAG.getExternalSymbol("__tls_get_addr", Ty),
10428 std::move(Args));
10429
10430 return LowerCallTo(CLI).first;
10431}
10432
10433SDValue RISCVTargetLowering::getTLSDescAddr(GlobalAddressSDNode *N,
10434 SelectionDAG &DAG) const {
10435 SDLoc DL(N);
10436 EVT Ty = getPointerTy(DAG.getDataLayout());
10437 const GlobalValue *GV = N->getGlobal();
10438
10439 // Use a PC-relative addressing mode to access the global dynamic GOT address.
10440 // This generates the pattern (PseudoLA_TLSDESC sym), which expands to
10441 //
10442 // auipc tX, %tlsdesc_hi(symbol) // R_RISCV_TLSDESC_HI20(symbol)
10443 // lw tY, tX, %tlsdesc_load_lo(label) // R_RISCV_TLSDESC_LOAD_LO12(label)
10444 // addi a0, tX, %tlsdesc_add_lo(label) // R_RISCV_TLSDESC_ADD_LO12(label)
10445 // jalr t0, tY // R_RISCV_TLSDESC_CALL(label)
10446 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
10447 return SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLSDESC, DL, Ty, Addr), 0);
10448}
10449
10450SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
10451 SelectionDAG &DAG) const {
10452 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
10453 assert(N->getOffset() == 0 && "unexpected offset in global node");
10454
10455 if (DAG.getTarget().useEmulatedTLS())
10456 return LowerToTLSEmulatedModel(N, DAG);
10457
10459
10462 reportFatalUsageError("In GHC calling convention TLS is not supported");
10463
10464 SDValue Addr;
10465 switch (Model) {
10467 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
10468 break;
10470 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
10471 break;
10474 Addr = DAG.getTarget().useTLSDESC() ? getTLSDescAddr(N, DAG)
10475 : getDynamicTLSAddr(N, DAG);
10476 break;
10477 }
10478
10479 return Addr;
10480}
10481
10482// Return true if Val is equal to (setcc LHS, RHS, CC).
10483// Return false if Val is the inverse of (setcc LHS, RHS, CC).
10484// Otherwise, return std::nullopt.
10485static std::optional<bool> matchSetCC(SDValue LHS, SDValue RHS,
10486 ISD::CondCode CC, SDValue Val) {
10487 assert(Val->getOpcode() == ISD::SETCC);
10488 SDValue LHS2 = Val.getOperand(0);
10489 SDValue RHS2 = Val.getOperand(1);
10490 ISD::CondCode CC2 = Val.getOperandCondCode(2);
10491
10492 if (LHS == LHS2 && RHS == RHS2) {
10493 if (CC == CC2)
10494 return true;
10495 if (CC == ISD::getSetCCInverse(CC2, LHS2.getValueType()))
10496 return false;
10497 } else if (LHS == RHS2 && RHS == LHS2) {
10499 if (CC == CC2)
10500 return true;
10501 if (CC == ISD::getSetCCInverse(CC2, LHS2.getValueType()))
10502 return false;
10503 }
10504
10505 return std::nullopt;
10506}
10507
10509 return isa<ConstantSDNode>(V) && V->getAsAPIntVal().isSignedIntN(12);
10510}
10511
10513 const RISCVSubtarget &Subtarget) {
10514 SDValue CondV = N->getOperand(0);
10515 SDValue TrueV = N->getOperand(1);
10516 SDValue FalseV = N->getOperand(2);
10517 MVT VT = N->getSimpleValueType(0);
10518 SDLoc DL(N);
10519
10520 if (!Subtarget.hasConditionalMoveFusion()) {
10521 // (select c, -1, y) -> -c | y
10522 if (isAllOnesConstant(TrueV)) {
10523 SDValue Neg = DAG.getNegative(CondV, DL, VT);
10524 return DAG.getNode(ISD::OR, DL, VT, Neg, DAG.getFreeze(FalseV));
10525 }
10526 // (select c, y, -1) -> (c-1) | y
10527 if (isAllOnesConstant(FalseV)) {
10528 SDValue Neg = DAG.getNode(ISD::ADD, DL, VT, CondV,
10529 DAG.getAllOnesConstant(DL, VT));
10530 return DAG.getNode(ISD::OR, DL, VT, Neg, DAG.getFreeze(TrueV));
10531 }
10532
10533 const bool HasZicond = VT.isScalarInteger() && Subtarget.hasStdExtZicond();
10534
10535 // (select c, 0, y) -> (c-1) & y
10536 if (isNullConstant(TrueV) && (!HasZicond || isSimm12Constant(FalseV))) {
10537 SDValue Neg =
10538 DAG.getNode(ISD::ADD, DL, VT, CondV, DAG.getAllOnesConstant(DL, VT));
10539 return DAG.getNode(ISD::AND, DL, VT, Neg, DAG.getFreeze(FalseV));
10540 }
10541 if (isNullConstant(FalseV)) {
10542 if (auto *TrueC = dyn_cast<ConstantSDNode>(TrueV)) {
10543 // (select c, y, 0) -> (c * (y - 1)) + c
10544 int64_t MulImm = TrueC->getSExtValue();
10545 if (MulImm != INT64_MIN && isInt<12>(MulImm - 1) &&
10546 Subtarget.hasVendorXqciac())
10547 return DAG.getNode(RISCVISD::QC_MULIADD, DL, VT, CondV, CondV,
10548 DAG.getSignedTargetConstant(MulImm - 1, DL, VT));
10549
10550 // (select c, (1 << ShAmount), 0) -> c << ShAmount
10551 uint64_t TrueVal = TrueC->getZExtValue();
10552 if (isPowerOf2_64(TrueVal))
10553 return DAG.getNode(
10554 ISD::SHL, DL, VT, CondV,
10555 DAG.getShiftAmountConstant(Log2_64(TrueVal), VT, DL));
10556
10557 // (select c, (1 << ShAmount) + 1, 0) -> (c << ShAmount) + c
10558 uint64_t TrueM1 = TrueVal - 1;
10559 if (isPowerOf2_64(TrueM1)) {
10560 unsigned ShAmount = Log2_64(TrueM1);
10561 if (Subtarget.hasShlAdd(ShAmount))
10562 return DAG.getNode(RISCVISD::SHL_ADD, DL, VT, CondV,
10563 DAG.getTargetConstant(ShAmount, DL, VT), CondV);
10564 }
10565 }
10566 // (select c, y, 0) -> -c & y
10567 if (!HasZicond || isSimm12Constant(TrueV)) {
10568 SDValue Neg = DAG.getNegative(CondV, DL, VT);
10569 return DAG.getNode(ISD::AND, DL, VT, Neg, DAG.getFreeze(TrueV));
10570 }
10571 }
10572 }
10573
10574 // select c, ~x, x --> xor -c, x
10575 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV)) {
10576 const APInt &TrueVal = TrueV->getAsAPIntVal();
10577 const APInt &FalseVal = FalseV->getAsAPIntVal();
10578 if (~TrueVal == FalseVal) {
10579 SDValue Neg = DAG.getNegative(CondV, DL, VT);
10580 return DAG.getNode(ISD::XOR, DL, VT, Neg, FalseV);
10581 }
10582 }
10583
10584 // Try to fold (select (setcc lhs, rhs, cc), truev, falsev) into bitwise ops
10585 // when both truev and falsev are also setcc.
10586 if (CondV.getOpcode() == ISD::SETCC && TrueV.getOpcode() == ISD::SETCC &&
10587 FalseV.getOpcode() == ISD::SETCC) {
10588 SDValue LHS = CondV.getOperand(0);
10589 SDValue RHS = CondV.getOperand(1);
10591
10592 // (select x, x, y) -> x | y
10593 // (select !x, x, y) -> x & y
10594 if (std::optional<bool> MatchResult = matchSetCC(LHS, RHS, CC, TrueV)) {
10595 return DAG.getNode(*MatchResult ? ISD::OR : ISD::AND, DL, VT, TrueV,
10596 DAG.getFreeze(FalseV));
10597 }
10598 // (select x, y, x) -> x & y
10599 // (select !x, y, x) -> x | y
10600 if (std::optional<bool> MatchResult = matchSetCC(LHS, RHS, CC, FalseV)) {
10601 return DAG.getNode(*MatchResult ? ISD::AND : ISD::OR, DL, VT,
10602 DAG.getFreeze(TrueV), FalseV);
10603 }
10604 }
10605
10606 return SDValue();
10607}
10608
10609// Transform `binOp (select cond, x, c0), c1` where `c0` and `c1` are constants
10610// into `select cond, binOp(x, c1), binOp(c0, c1)` if profitable.
10611// For now we only consider transformation profitable if `binOp(c0, c1)` ends up
10612// being `0` or `-1`. In such cases we can replace `select` with `and`.
10613// TODO: Should we also do this if `binOp(c0, c1)` is cheaper to materialize
10614// than `c0`?
10615static SDValue
10617 const RISCVSubtarget &Subtarget) {
10618 if (Subtarget.hasShortForwardBranchIALU())
10619 return SDValue();
10620
10621 unsigned SelOpNo = 0;
10622 SDValue Sel = BO->getOperand(0);
10623 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
10624 SelOpNo = 1;
10625 Sel = BO->getOperand(1);
10626 }
10627
10628 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
10629 return SDValue();
10630
10631 unsigned ConstSelOpNo = 1;
10632 unsigned OtherSelOpNo = 2;
10633 if (!isa<ConstantSDNode>(Sel->getOperand(ConstSelOpNo))) {
10634 ConstSelOpNo = 2;
10635 OtherSelOpNo = 1;
10636 }
10637 SDValue ConstSelOp = Sel->getOperand(ConstSelOpNo);
10638 ConstantSDNode *ConstSelOpNode = dyn_cast<ConstantSDNode>(ConstSelOp);
10639 if (!ConstSelOpNode || ConstSelOpNode->isOpaque())
10640 return SDValue();
10641
10642 SDValue ConstBinOp = BO->getOperand(SelOpNo ^ 1);
10643 ConstantSDNode *ConstBinOpNode = dyn_cast<ConstantSDNode>(ConstBinOp);
10644 if (!ConstBinOpNode || ConstBinOpNode->isOpaque())
10645 return SDValue();
10646
10647 SDLoc DL(Sel);
10648 EVT VT = BO->getValueType(0);
10649
10650 SDValue NewConstOps[2] = {ConstSelOp, ConstBinOp};
10651 if (SelOpNo == 1)
10652 std::swap(NewConstOps[0], NewConstOps[1]);
10653
10654 SDValue NewConstOp =
10655 DAG.FoldConstantArithmetic(BO->getOpcode(), DL, VT, NewConstOps);
10656 if (!NewConstOp)
10657 return SDValue();
10658
10659 const APInt &NewConstAPInt = NewConstOp->getAsAPIntVal();
10660 if (!NewConstAPInt.isZero() && !NewConstAPInt.isAllOnes())
10661 return SDValue();
10662
10663 SDValue OtherSelOp = Sel->getOperand(OtherSelOpNo);
10664 SDValue NewNonConstOps[2] = {OtherSelOp, ConstBinOp};
10665 if (SelOpNo == 1)
10666 std::swap(NewNonConstOps[0], NewNonConstOps[1]);
10667 SDValue NewNonConstOp = DAG.getNode(BO->getOpcode(), DL, VT, NewNonConstOps);
10668
10669 SDValue NewT = (ConstSelOpNo == 1) ? NewConstOp : NewNonConstOp;
10670 SDValue NewF = (ConstSelOpNo == 1) ? NewNonConstOp : NewConstOp;
10671 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewT, NewF);
10672}
10673
10674SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10675 SDValue CondV = Op.getOperand(0);
10676 SDValue TrueV = Op.getOperand(1);
10677 SDValue FalseV = Op.getOperand(2);
10678 SDLoc DL(Op);
10679 MVT VT = Op.getSimpleValueType();
10680 MVT XLenVT = Subtarget.getXLenVT();
10681
10682 // Handle P extension packed types by bitcasting to an integer of
10683 // matching width and reusing the scalar selection mechanism.
10684 // Reachable cases:
10685 // RV32: v4i8/v2i16 -> select on i32
10686 // RV32: v8i8/v4i16 -> select on i64 (legalizes to two i32 selects)
10687 // RV64: v8i8/v4i16/v2i32 -> select on i64
10688 if (Subtarget.isPExtPackedType(VT)) {
10689 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
10690 SDValue TrueVInt = DAG.getBitcast(IntVT, TrueV);
10691 SDValue FalseVInt = DAG.getBitcast(IntVT, FalseV);
10692 SDValue ResultInt =
10693 DAG.getNode(ISD::SELECT, DL, IntVT, CondV, TrueVInt, FalseVInt);
10694 return DAG.getBitcast(VT, ResultInt);
10695 }
10696
10697 // Lower vector SELECTs to VSELECTs by splatting the condition.
10698 if (VT.isVector()) {
10699 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
10700 SDValue CondSplat = DAG.getSplat(SplatCondVT, DL, CondV);
10701 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
10702 }
10703
10704 // Try some other optimizations before falling back to generic lowering.
10705 if (SDValue V = lowerSelectToBinOp(Op.getNode(), DAG, Subtarget))
10706 return V;
10707
10708 // When there is no cost for GPR <-> FPR, we can use zicond select for
10709 // floating value when CondV is int type
10710 bool FPinGPR = Subtarget.hasStdExtZfinx();
10711
10712 // We can handle FGPR without spliting into hi/lo parts
10713 bool FitsInGPR = TypeSize::isKnownLE(VT.getSizeInBits(),
10714 Subtarget.getXLenVT().getSizeInBits());
10715
10716 bool UseZicondForFPSel = Subtarget.hasStdExtZicond() && FPinGPR &&
10717 VT.isFloatingPoint() && FitsInGPR;
10718
10719 if (UseZicondForFPSel) {
10720
10721 auto CastToInt = [&](SDValue V) -> SDValue {
10722 // Treat +0.0 as int 0 to enable single 'czero' instruction generation.
10723 if (isNullFPConstant(V))
10724 return DAG.getConstant(0, DL, XLenVT);
10725
10726 if (VT == MVT::f16)
10727 return DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, V);
10728
10729 if (VT == MVT::f32 && Subtarget.is64Bit())
10730 return DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, XLenVT, V);
10731
10732 return DAG.getBitcast(XLenVT, V);
10733 };
10734
10735 SDValue TrueVInt = CastToInt(TrueV);
10736 SDValue FalseVInt = CastToInt(FalseV);
10737
10738 // Emit integer SELECT (lowers to Zicond)
10739 SDValue ResultInt =
10740 DAG.getNode(ISD::SELECT, DL, XLenVT, CondV, TrueVInt, FalseVInt);
10741
10742 // Convert back to floating VT
10743 if (VT == MVT::f32 && Subtarget.is64Bit())
10744 return DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, VT, ResultInt);
10745
10746 if (VT == MVT::f16)
10747 return DAG.getNode(RISCVISD::FMV_H_X, DL, VT, ResultInt);
10748
10749 return DAG.getBitcast(VT, ResultInt);
10750 }
10751
10752 // When Zicond is present, emit CZERO_EQZ and CZERO_NEZ
10753 // nodes to implement the SELECT. Performing the lowering here allows for
10754 // greater control over when CZERO_{EQZ/NEZ} are used vs another branchless
10755 // sequence or RISCVISD::SELECT_CC node (branch-based select).
10756 if (Subtarget.hasStdExtZicond() && VT.isScalarInteger()) {
10757
10758 // (select c, t, 0) -> (czero_eqz t, c)
10759 if (isNullConstant(FalseV))
10760 return DAG.getNode(RISCVISD::CZERO_EQZ, DL, VT, TrueV, CondV);
10761 // (select c, 0, f) -> (czero_nez f, c)
10762 if (isNullConstant(TrueV))
10763 return DAG.getNode(RISCVISD::CZERO_NEZ, DL, VT, FalseV, CondV);
10764
10765 // Check to see if a given operation is a 'NOT', if so return the negated
10766 // operand
10767 auto getNotOperand = [](const SDValue &Op) -> std::optional<const SDValue> {
10768 using namespace llvm::SDPatternMatch;
10769 SDValue Xor;
10770 if (sd_match(Op, m_OneUse(m_Not(m_Value(Xor))))) {
10771 return Xor;
10772 }
10773 return std::nullopt;
10774 };
10775 // (select c, (and f, x), f) -> (or (and f, x), (czero_nez f, c))
10776 // (select c, (and f, ~x), f) -> (andn f, (czero_eqz x, c))
10777 if (TrueV.getOpcode() == ISD::AND &&
10778 (TrueV.getOperand(0) == FalseV || TrueV.getOperand(1) == FalseV)) {
10779 auto NotOperand = (TrueV.getOperand(0) == FalseV)
10780 ? getNotOperand(TrueV.getOperand(1))
10781 : getNotOperand(TrueV.getOperand(0));
10782 if (NotOperand) {
10783 SDValue CMOV =
10784 DAG.getNode(RISCVISD::CZERO_EQZ, DL, VT, *NotOperand, CondV);
10785 SDValue NOT = DAG.getNOT(DL, CMOV, VT);
10786 return DAG.getNode(ISD::AND, DL, VT, FalseV, NOT);
10787 }
10788 return DAG.getNode(
10789 ISD::OR, DL, VT, TrueV,
10790 DAG.getNode(RISCVISD::CZERO_NEZ, DL, VT, FalseV, CondV));
10791 }
10792
10793 // (select c, t, (and t, x)) -> (or (czero_eqz t, c), (and t, x))
10794 // (select c, t, (and t, ~x)) -> (andn t, (czero_nez x, c))
10795 if (FalseV.getOpcode() == ISD::AND &&
10796 (FalseV.getOperand(0) == TrueV || FalseV.getOperand(1) == TrueV)) {
10797 auto NotOperand = (FalseV.getOperand(0) == TrueV)
10798 ? getNotOperand(FalseV.getOperand(1))
10799 : getNotOperand(FalseV.getOperand(0));
10800 if (NotOperand) {
10801 SDValue CMOV =
10802 DAG.getNode(RISCVISD::CZERO_NEZ, DL, VT, *NotOperand, CondV);
10803 SDValue NOT = DAG.getNOT(DL, CMOV, VT);
10804 return DAG.getNode(ISD::AND, DL, VT, TrueV, NOT);
10805 }
10806 return DAG.getNode(
10807 ISD::OR, DL, VT, FalseV,
10808 DAG.getNode(RISCVISD::CZERO_EQZ, DL, VT, TrueV, CondV));
10809 }
10810
10811 // (select c, c1, c2) -> (add (czero_nez c2 - c1, c), c1)
10812 // (select c, c1, c2) -> (add (czero_eqz c1 - c2, c), c2)
10813 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV)) {
10814 const APInt &TrueVal = TrueV->getAsAPIntVal();
10815 const APInt &FalseVal = FalseV->getAsAPIntVal();
10816
10817 // Prefer these over Zicond to avoid materializing an immediate:
10818 // (select (x < 0), y, z) -> x >> (XLEN - 1) & (y - z) + z
10819 // (select (x > -1), z, y) -> x >> (XLEN - 1) & (y - z) + z
10820 if (CondV.getOpcode() == ISD::SETCC &&
10821 CondV.getOperand(0).getValueType() == VT && CondV.hasOneUse()) {
10822 ISD::CondCode CCVal = CondV.getOperandCondCode(2);
10823 if ((CCVal == ISD::SETLT && isNullConstant(CondV.getOperand(1))) ||
10824 (CCVal == ISD::SETGT && isAllOnesConstant(CondV.getOperand(1)))) {
10825 int64_t TrueImm = TrueVal.getSExtValue();
10826 int64_t FalseImm = FalseVal.getSExtValue();
10827 if (CCVal == ISD::SETGT)
10828 std::swap(TrueImm, FalseImm);
10829 if (isInt<12>(TrueImm) && isInt<12>(FalseImm) &&
10830 isInt<12>(TrueImm - FalseImm)) {
10831 SDValue SRA =
10832 DAG.getNode(ISD::SRA, DL, VT, CondV.getOperand(0),
10833 DAG.getConstant(Subtarget.getXLen() - 1, DL, VT));
10834 SDValue AND =
10835 DAG.getNode(ISD::AND, DL, VT, SRA,
10836 DAG.getSignedConstant(TrueImm - FalseImm, DL, VT));
10837 return DAG.getNode(ISD::ADD, DL, VT, AND,
10838 DAG.getSignedConstant(FalseImm, DL, VT));
10839 }
10840 }
10841 }
10842
10843 // Use SLLI/ADDI (and possible XORI) to avoid having to materialize
10844 // a constant in register
10845 if ((TrueVal - FalseVal).isPowerOf2() && FalseVal.isSignedIntN(12)) {
10846 SDValue Log2 = DAG.getConstant((TrueVal - FalseVal).logBase2(), DL, VT);
10847 SDValue BitDiff = DAG.getNode(ISD::SHL, DL, VT, CondV, Log2);
10848 return DAG.getNode(ISD::ADD, DL, VT, BitDiff, FalseV);
10849 }
10850 if ((FalseVal - TrueVal).isPowerOf2() && TrueVal.isSignedIntN(12)) {
10851 SDValue Log2 = DAG.getConstant((FalseVal - TrueVal).logBase2(), DL, VT);
10852 CondV = DAG.getLogicalNOT(DL, CondV, CondV.getValueType());
10853 SDValue BitDiff = DAG.getNode(ISD::SHL, DL, VT, CondV, Log2);
10854 return DAG.getNode(ISD::ADD, DL, VT, BitDiff, TrueV);
10855 }
10856
10857 // If we can't use ADDI, it might still be profitable to use SLLI/ADD or
10858 // SLLI/SUB. We need to materialize a large constant for the czero+add
10859 // sequence below anyway. Using SLLI avoids materializing the delta.
10860 // Don't do this if the condition is an equality comparison since czero
10861 // allows us to fold part of the compare.
10862 if ((TrueVal - FalseVal).isPowerOf2() &&
10863 !(CondV.getOpcode() == ISD::SETCC &&
10865 SDValue Log2 = DAG.getConstant((TrueVal - FalseVal).logBase2(), DL, VT);
10866 SDValue BitDiff = DAG.getNode(ISD::SHL, DL, VT, CondV, Log2);
10867 return DAG.getNode(ISD::ADD, DL, VT, FalseV, BitDiff);
10868 }
10869 if ((FalseVal - TrueVal).isPowerOf2() && !FalseVal.isSignedIntN(12) &&
10870 !(CondV.getOpcode() == ISD::SETCC &&
10872 SDValue Log2 = DAG.getConstant((FalseVal - TrueVal).logBase2(), DL, VT);
10873 SDValue BitDiff = DAG.getNode(ISD::SHL, DL, VT, CondV, Log2);
10874 return DAG.getNode(ISD::SUB, DL, VT, FalseV, BitDiff);
10875 }
10876
10877 auto getCost = [&](const APInt &Delta, const APInt &Addend) {
10878 const int DeltaCost = RISCVMatInt::getIntMatCost(
10879 Delta, Subtarget.getXLen(), Subtarget, /*CompressionCost=*/true);
10880 // Does the addend fold into an ADDI
10881 if (Addend.isSignedIntN(12))
10882 return DeltaCost;
10883 const int AddendCost = RISCVMatInt::getIntMatCost(
10884 Addend, Subtarget.getXLen(), Subtarget, /*CompressionCost=*/true);
10885 return AddendCost + DeltaCost;
10886 };
10887 bool IsCZERO_NEZ = getCost(FalseVal - TrueVal, TrueVal) <=
10888 getCost(TrueVal - FalseVal, FalseVal);
10889 SDValue LHSVal = DAG.getConstant(
10890 IsCZERO_NEZ ? FalseVal - TrueVal : TrueVal - FalseVal, DL, VT);
10891 SDValue CMOV =
10892 DAG.getNode(IsCZERO_NEZ ? RISCVISD::CZERO_NEZ : RISCVISD::CZERO_EQZ,
10893 DL, VT, LHSVal, CondV);
10894 return DAG.getNode(ISD::ADD, DL, VT, CMOV, IsCZERO_NEZ ? TrueV : FalseV);
10895 }
10896
10897 // (select c, c1, t) -> (add (czero_nez t - c1, c), c1)
10898 // (select c, t, c1) -> (add (czero_eqz t - c1, c), c1)
10899 if (isa<ConstantSDNode>(TrueV) != isa<ConstantSDNode>(FalseV)) {
10900 bool IsCZERO_NEZ = isa<ConstantSDNode>(TrueV);
10901 SDValue ConstVal = IsCZERO_NEZ ? TrueV : FalseV;
10902 SDValue RegV = IsCZERO_NEZ ? FalseV : TrueV;
10903 int64_t RawConstVal = cast<ConstantSDNode>(ConstVal)->getSExtValue();
10904 // Efficient only if the constant and its negation fit into `ADDI`
10905 // Prefer Add/Sub over Xor since can be compressed for small immediates
10906 if (isInt<12>(RawConstVal)) {
10907 // Fall back to XORI if Const == -0x800 since we don't have SUBI.
10908 unsigned SubOpc = (RawConstVal == -0x800) ? ISD::XOR : ISD::SUB;
10909 unsigned AddOpc = (RawConstVal == -0x800) ? ISD::XOR : ISD::ADD;
10910 SDValue SubOp = DAG.getNode(SubOpc, DL, VT, RegV, ConstVal);
10911 SDValue CZERO =
10912 DAG.getNode(IsCZERO_NEZ ? RISCVISD::CZERO_NEZ : RISCVISD::CZERO_EQZ,
10913 DL, VT, SubOp, CondV);
10914 return DAG.getNode(AddOpc, DL, VT, CZERO, ConstVal);
10915 }
10916 }
10917
10918 // Unless we have the short forward branch optimization, or we are
10919 // optimizing for size.
10920 if (!Subtarget.hasConditionalMoveFusion() && !DAG.shouldOptForSize()) {
10921 using namespace llvm::SDPatternMatch;
10922
10923 // (select c, x, -x) -> (sub (czero_eqz x, c), (czero_nez x, c))
10924 if (sd_match(FalseV, m_Neg(m_Specific(TrueV)))) {
10925 TrueV = DAG.getFreeze(TrueV);
10926 return DAG.getNode(
10927 ISD::SUB, DL, VT,
10928 DAG.getNode(RISCVISD::CZERO_EQZ, DL, VT, TrueV, CondV),
10929 DAG.getNode(RISCVISD::CZERO_NEZ, DL, VT, TrueV, CondV));
10930 }
10931 // (select c, -x, x) -> (sub (czero_nez x, c), (czero_eqz x, c))
10932 if (sd_match(TrueV, m_Neg(m_Specific(FalseV)))) {
10933 FalseV = DAG.getFreeze(FalseV);
10934 return DAG.getNode(
10935 ISD::SUB, DL, VT,
10936 DAG.getNode(RISCVISD::CZERO_NEZ, DL, VT, FalseV, CondV),
10937 DAG.getNode(RISCVISD::CZERO_EQZ, DL, VT, FalseV, CondV));
10938 }
10939
10940 // (select c, t, f) -> (or (czero_eqz t, c), (czero_nez f, c))
10941 return DAG.getNode(
10942 ISD::OR, DL, VT,
10943 DAG.getNode(RISCVISD::CZERO_EQZ, DL, VT, TrueV, CondV),
10944 DAG.getNode(RISCVISD::CZERO_NEZ, DL, VT, FalseV, CondV),
10946 }
10947 }
10948
10949 if (Op.hasOneUse()) {
10950 unsigned UseOpc = Op->user_begin()->getOpcode();
10951 if (isBinOp(UseOpc) && DAG.isSafeToSpeculativelyExecute(UseOpc)) {
10952 SDNode *BinOp = *Op->user_begin();
10953 if (SDValue NewSel = foldBinOpIntoSelectIfProfitable(*Op->user_begin(),
10954 DAG, Subtarget)) {
10955 DAG.ReplaceAllUsesWith(BinOp, &NewSel);
10956 // Opcode check is necessary because foldBinOpIntoSelectIfProfitable
10957 // may return a constant node and cause crash in lowerSELECT.
10958 if (NewSel.getOpcode() == ISD::SELECT)
10959 return lowerSELECT(NewSel, DAG);
10960 return NewSel;
10961 }
10962 }
10963 }
10964
10965 // (select cc, 1.0, 0.0) -> (sint_to_fp (zext cc))
10966 // (select cc, 0.0, 1.0) -> (sint_to_fp (zext (xor cc, 1)))
10967 const ConstantFPSDNode *FPTV = dyn_cast<ConstantFPSDNode>(TrueV);
10968 const ConstantFPSDNode *FPFV = dyn_cast<ConstantFPSDNode>(FalseV);
10969 if (FPTV && FPFV) {
10970 if (FPTV->isOne() && FPFV->isPosZero())
10971 return DAG.getNode(ISD::SINT_TO_FP, DL, VT, CondV);
10972 if (FPTV->isPosZero() && FPFV->isOne()) {
10973 SDValue XOR = DAG.getNode(ISD::XOR, DL, XLenVT, CondV,
10974 DAG.getConstant(1, DL, XLenVT));
10975 return DAG.getNode(ISD::SINT_TO_FP, DL, VT, XOR);
10976 }
10977 }
10978
10979 // If the condition is not an integer SETCC which operates on XLenVT, we need
10980 // to emit a RISCVISD::SELECT_CC comparing the condition to zero. i.e.:
10981 // (select condv, truev, falsev)
10982 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
10983 if (CondV.getOpcode() != ISD::SETCC ||
10984 CondV.getOperand(0).getSimpleValueType() != XLenVT) {
10985 SDValue Zero = DAG.getConstant(0, DL, XLenVT);
10986 SDValue SetNE = DAG.getCondCode(ISD::SETNE);
10987
10988 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
10989
10990 return DAG.getNode(RISCVISD::SELECT_CC, DL, VT, Ops);
10991 }
10992
10993 // If the CondV is the output of a SETCC node which operates on XLenVT inputs,
10994 // then merge the SETCC node into the lowered RISCVISD::SELECT_CC to take
10995 // advantage of the integer compare+branch instructions. i.e.:
10996 // (select (setcc lhs, rhs, cc), truev, falsev)
10997 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
10998 SDValue LHS = CondV.getOperand(0);
10999 SDValue RHS = CondV.getOperand(1);
11000 ISD::CondCode CCVal = CondV.getOperandCondCode(2);
11001
11002 // Special case for a select of 2 constants that have a difference of 1.
11003 // Normally this is done by DAGCombine, but if the select is introduced by
11004 // type legalization or op legalization, we miss it. Restricting to SETLT
11005 // case for now because that is what signed saturating add/sub need.
11006 // FIXME: We don't need the condition to be SETLT or even a SETCC,
11007 // but we would probably want to swap the true/false values if the condition
11008 // is SETGE/SETLE to avoid an XORI.
11009 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
11010 CCVal == ISD::SETLT) {
11011 const APInt &TrueVal = TrueV->getAsAPIntVal();
11012 const APInt &FalseVal = FalseV->getAsAPIntVal();
11013 if (TrueVal - 1 == FalseVal)
11014 return DAG.getNode(ISD::ADD, DL, VT, CondV, FalseV);
11015 if (TrueVal + 1 == FalseVal)
11016 return DAG.getNode(ISD::SUB, DL, VT, FalseV, CondV);
11017 }
11018
11019 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG, Subtarget);
11020 // 1 < x ? x : 1 -> 0 < x ? x : 1
11021 if (isOneConstant(LHS) && (CCVal == ISD::SETLT || CCVal == ISD::SETULT) &&
11022 RHS == TrueV && LHS == FalseV) {
11023 LHS = DAG.getConstant(0, DL, VT);
11024 // 0 <u x is the same as x != 0.
11025 if (CCVal == ISD::SETULT) {
11026 std::swap(LHS, RHS);
11027 CCVal = ISD::SETNE;
11028 }
11029 }
11030
11031 // x <s -1 ? x : -1 -> x <s 0 ? x : -1
11032 if (isAllOnesConstant(RHS) && CCVal == ISD::SETLT && LHS == TrueV &&
11033 RHS == FalseV) {
11034 RHS = DAG.getConstant(0, DL, VT);
11035 }
11036
11037 SDValue TargetCC = DAG.getCondCode(CCVal);
11038
11039 if (isa<ConstantSDNode>(TrueV) && !isa<ConstantSDNode>(FalseV)) {
11040 // (select (setcc lhs, rhs, CC), constant, falsev)
11041 // -> (select (setcc lhs, rhs, InverseCC), falsev, constant)
11042 std::swap(TrueV, FalseV);
11043 TargetCC = DAG.getCondCode(ISD::getSetCCInverse(CCVal, LHS.getValueType()));
11044 }
11045
11046 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
11047 return DAG.getNode(RISCVISD::SELECT_CC, DL, VT, Ops);
11048}
11049
11050SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11051 SDValue CondV = Op.getOperand(1);
11052 SDLoc DL(Op);
11053 MVT XLenVT = Subtarget.getXLenVT();
11054
11055 if (CondV.getOpcode() == ISD::SETCC &&
11056 CondV.getOperand(0).getValueType() == XLenVT) {
11057 SDValue LHS = CondV.getOperand(0);
11058 SDValue RHS = CondV.getOperand(1);
11059 ISD::CondCode CCVal = CondV.getOperandCondCode(2);
11060
11061 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG, Subtarget);
11062
11063 SDValue TargetCC = DAG.getCondCode(CCVal);
11064 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
11065 LHS, RHS, TargetCC, Op.getOperand(2));
11066 }
11067
11068 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
11069 CondV, DAG.getConstant(0, DL, XLenVT),
11070 DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
11071}
11072
11073SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11075 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
11076
11077 SDLoc DL(Op);
11078 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11080
11081 // vastart just stores the address of the VarArgsFrameIndex slot into the
11082 // memory location argument.
11083 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11084 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
11085 MachinePointerInfo(SV));
11086}
11087
11088SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
11089 SelectionDAG &DAG) const {
11090 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
11092 MachineFrameInfo &MFI = MF.getFrameInfo();
11093 MFI.setFrameAddressIsTaken(true);
11094 Register FrameReg = RI.getFrameRegister(MF);
11095 int XLenInBytes = Subtarget.getXLen() / 8;
11096
11097 EVT VT = Op.getValueType();
11098 SDLoc DL(Op);
11099 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
11100 unsigned Depth = Op.getConstantOperandVal(0);
11101 while (Depth--) {
11102 int Offset = -(XLenInBytes * 2);
11103 SDValue Ptr = DAG.getNode(
11104 ISD::ADD, DL, VT, FrameAddr,
11106 FrameAddr =
11107 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
11108 }
11109 return FrameAddr;
11110}
11111
11112SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
11113 SelectionDAG &DAG) const {
11114 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
11116 MachineFrameInfo &MFI = MF.getFrameInfo();
11117 MFI.setReturnAddressIsTaken(true);
11118 MVT XLenVT = Subtarget.getXLenVT();
11119 int XLenInBytes = Subtarget.getXLen() / 8;
11120
11121 EVT VT = Op.getValueType();
11122 SDLoc DL(Op);
11123 unsigned Depth = Op.getConstantOperandVal(0);
11124 if (Depth) {
11125 int Off = -XLenInBytes;
11126 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
11128 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
11129 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
11130 MachinePointerInfo());
11131 }
11132
11133 // Return the value of the return address register, marking it an implicit
11134 // live-in.
11135 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
11136 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
11137}
11138
11139SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
11140 SelectionDAG &DAG) const {
11141 SDLoc DL(Op);
11142 SDValue Lo = Op.getOperand(0);
11143 SDValue Hi = Op.getOperand(1);
11144 SDValue Shamt = Op.getOperand(2);
11145 EVT VT = Lo.getValueType();
11146 unsigned XLen = Subtarget.getXLen();
11147
11148 // With P extension, use SLX (FSHL) for the high part.
11149 if (Subtarget.hasStdExtP()) {
11150 // HiRes = fshl(Hi, Lo, Shamt) - correct when Shamt < XLen
11151 SDValue HiRes = DAG.getNode(ISD::FSHL, DL, VT, Hi, Lo, Shamt);
11152 // LoRes = Lo << Shamt - correct Lo when Shamt < XLen,
11153 // Mask shift amount to avoid UB when Shamt >= XLen.
11154 SDValue ShamtMasked =
11155 DAG.getNode(ISD::AND, DL, VT, Shamt, DAG.getConstant(XLen - 1, DL, VT));
11156 SDValue LoRes = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMasked);
11157
11158 // Create a mask that is -1 when Shamt >= XLen, 0 otherwise.
11159 // FIXME: We should use a select and let LowerSelect make the
11160 // optimizations.
11161 SDValue ShAmtExt =
11162 DAG.getNode(ISD::SHL, DL, VT, Shamt,
11163 DAG.getConstant(XLen - Log2_32(XLen) - 1, DL, VT));
11164 SDValue Mask = DAG.getNode(ISD::SRA, DL, VT, ShAmtExt,
11165 DAG.getConstant(XLen - 1, DL, VT));
11166
11167 // When Shamt >= XLen: HiRes = LoRes, LoRes = 0
11168 // HiRes = (HiRes & ~Mask) | (LoRes & Mask)
11169 SDValue HiMasked =
11170 DAG.getNode(ISD::AND, DL, VT, HiRes, DAG.getNOT(DL, Mask, VT));
11171 SDValue LoMasked = DAG.getNode(ISD::AND, DL, VT, LoRes, Mask);
11172 HiRes =
11173 DAG.getNode(ISD::OR, DL, VT, HiMasked, LoMasked, SDNodeFlags::Disjoint);
11174
11175 // LoRes = LoRes & ~Mask (clear when Shamt >= XLen)
11176 LoRes = DAG.getNode(ISD::AND, DL, VT, LoRes, DAG.getNOT(DL, Mask, VT));
11177
11178 return DAG.getMergeValues({LoRes, HiRes}, DL);
11179 }
11180
11181 // if Shamt-XLEN < 0: // Shamt < XLEN
11182 // Lo = Lo << Shamt
11183 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
11184 // else:
11185 // Lo = 0
11186 // Hi = Lo << (Shamt-XLEN)
11187
11188 SDValue Zero = DAG.getConstant(0, DL, VT);
11189 SDValue One = DAG.getConstant(1, DL, VT);
11190 SDValue MinusXLen = DAG.getSignedConstant(-(int)XLen, DL, VT);
11191 SDValue XLenMinus1 = DAG.getConstant(XLen - 1, DL, VT);
11192 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
11193 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
11194
11195 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
11196 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
11197 SDValue ShiftRightLo =
11198 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
11199 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
11200 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
11201 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
11202
11203 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
11204
11205 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
11206 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
11207
11208 SDValue Parts[2] = {Lo, Hi};
11209 return DAG.getMergeValues(Parts, DL);
11210}
11211
11212SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
11213 bool IsSRA) const {
11214 SDLoc DL(Op);
11215 SDValue Lo = Op.getOperand(0);
11216 SDValue Hi = Op.getOperand(1);
11217 SDValue Shamt = Op.getOperand(2);
11218 EVT VT = Lo.getValueType();
11219
11220 // With P extension, use NSRL/NSRA for RV32 or FSHR (SRX) for RV64.
11221 if (Subtarget.hasStdExtP()) {
11222 unsigned XLen = Subtarget.getXLen();
11223
11224 SDValue LoRes;
11225 if (Subtarget.is64Bit()) {
11226 // On RV64, use FSHR (SRX instruction) for the low part. We will need
11227 // to fix this later if ShAmt >= 64.
11228 LoRes = DAG.getNode(ISD::FSHR, DL, VT, Hi, Lo, Shamt);
11229 } else {
11230 // On RV32, use NSRL/NSRA for the low part.
11231 // NSRL/NSRA read 6 bits of shift amount, so they handle Shamt >= 32
11232 // correctly.
11233 LoRes = DAG.getNode(IsSRA ? RISCVISD::NSRA : RISCVISD::NSRL, DL, VT, Lo,
11234 Hi, Shamt);
11235 }
11236
11237 // Mask shift amount to avoid UB when Shamt >= XLen.
11238 SDValue ShamtMasked =
11239 DAG.getNode(ISD::AND, DL, VT, Shamt, DAG.getConstant(XLen - 1, DL, VT));
11240 SDValue HiRes =
11241 DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, VT, Hi, ShamtMasked);
11242
11243 // Create a mask that is -1 when Shamt >= XLen, 0 otherwise.
11244 // FIXME: We should use a select and let LowerSelect make the
11245 // optimizations.
11246 SDValue ShAmtExt =
11247 DAG.getNode(ISD::SHL, DL, VT, Shamt,
11248 DAG.getConstant(XLen - Log2_32(XLen) - 1, DL, VT));
11249 SDValue Mask = DAG.getNode(ISD::SRA, DL, VT, ShAmtExt,
11250 DAG.getConstant(XLen - 1, DL, VT));
11251
11252 if (Subtarget.is64Bit()) {
11253 // On RV64, FSHR masks shift amount to 63. We need to replace LoRes
11254 // with HiRes when Shamt >= 64.
11255 // LoRes = (LoRes & ~Mask) | (HiRes & Mask)
11256 SDValue LoMasked =
11257 DAG.getNode(ISD::AND, DL, VT, LoRes, DAG.getNOT(DL, Mask, VT));
11258 SDValue HiMasked = DAG.getNode(ISD::AND, DL, VT, HiRes, Mask);
11259 LoRes = DAG.getNode(ISD::OR, DL, VT, LoMasked, HiMasked,
11261 }
11262
11263 // If ShAmt >= XLen, we need to replace HiRes with 0 or sign bits.
11264 if (IsSRA) {
11265 // sra hi, hi, (mask & (XLen-1)) - shifts by XLen-1 when shamt >= XLen
11266 SDValue MaskAmt = DAG.getNode(ISD::AND, DL, VT, Mask,
11267 DAG.getConstant(XLen - 1, DL, VT));
11268 HiRes = DAG.getNode(ISD::SRA, DL, VT, HiRes, MaskAmt);
11269 } else {
11270 // andn hi, hi, mask - clears hi when shamt >= XLen
11271 HiRes = DAG.getNode(ISD::AND, DL, VT, HiRes, DAG.getNOT(DL, Mask, VT));
11272 }
11273
11274 return DAG.getMergeValues({LoRes, HiRes}, DL);
11275 }
11276
11277 // SRA expansion:
11278 // if Shamt-XLEN < 0: // Shamt < XLEN
11279 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - ShAmt))
11280 // Hi = Hi >>s Shamt
11281 // else:
11282 // Lo = Hi >>s (Shamt-XLEN);
11283 // Hi = Hi >>s (XLEN-1)
11284 //
11285 // SRL expansion:
11286 // if Shamt-XLEN < 0: // Shamt < XLEN
11287 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - ShAmt))
11288 // Hi = Hi >>u Shamt
11289 // else:
11290 // Lo = Hi >>u (Shamt-XLEN);
11291 // Hi = 0;
11292
11293 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
11294
11295 SDValue Zero = DAG.getConstant(0, DL, VT);
11296 SDValue One = DAG.getConstant(1, DL, VT);
11297 SDValue MinusXLen = DAG.getSignedConstant(-(int)Subtarget.getXLen(), DL, VT);
11298 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
11299 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
11300 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
11301
11302 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
11303 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
11304 SDValue ShiftLeftHi =
11305 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
11306 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
11307 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
11308 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
11309 SDValue HiFalse =
11310 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
11311
11312 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
11313
11314 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
11315 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
11316
11317 SDValue Parts[2] = {Lo, Hi};
11318 return DAG.getMergeValues(Parts, DL);
11319}
11320
11321// Lower splats of i1 types to SETCC. For each mask vector type, we have a
11322// legal equivalently-sized i8 type, so we can use that as a go-between.
11323SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
11324 SelectionDAG &DAG) const {
11325 SDLoc DL(Op);
11326 MVT VT = Op.getSimpleValueType();
11327 SDValue SplatVal = Op.getOperand(0);
11328 // All-zeros or all-ones splats are handled specially.
11330 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
11331 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
11332 }
11334 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
11335 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
11336 }
11337 MVT InterVT = VT.changeVectorElementType(MVT::i8);
11338 SplatVal = DAG.getNode(ISD::AND, DL, SplatVal.getValueType(), SplatVal,
11339 DAG.getConstant(1, DL, SplatVal.getValueType()));
11340 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
11341 SDValue Zero = DAG.getConstant(0, DL, InterVT);
11342 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
11343}
11344
11345// Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
11346// illegal (currently only vXi64 RV32).
11347// FIXME: We could also catch non-constant sign-extended i32 values and lower
11348// them to VMV_V_X_VL.
11349SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
11350 SelectionDAG &DAG) const {
11351 SDLoc DL(Op);
11352 MVT VecVT = Op.getSimpleValueType();
11353 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
11354 "Unexpected SPLAT_VECTOR_PARTS lowering");
11355
11356 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
11357 SDValue Lo = Op.getOperand(0);
11358 SDValue Hi = Op.getOperand(1);
11359
11360 MVT ContainerVT = VecVT;
11361 if (VecVT.isFixedLengthVector())
11363
11364 auto VL = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).second;
11365
11366 SDValue Res =
11368
11369 if (VecVT.isFixedLengthVector())
11370 Res = convertFromScalableVector(VecVT, Res, DAG, Subtarget);
11371
11372 return Res;
11373}
11374
11375// Custom-lower extensions from mask vectors by using a vselect either with 1
11376// for zero/any-extension or -1 for sign-extension:
11377// (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
11378// Note that any-extension is lowered identically to zero-extension.
11379SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
11380 int64_t ExtTrueVal) const {
11381 SDLoc DL(Op);
11382 MVT VecVT = Op.getSimpleValueType();
11383 SDValue Src = Op.getOperand(0);
11384 // Only custom-lower extensions from mask types
11385 assert(Src.getValueType().isVector() &&
11386 Src.getValueType().getVectorElementType() == MVT::i1);
11387
11388 if (VecVT.isScalableVector()) {
11389 SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
11390 SDValue SplatTrueVal = DAG.getSignedConstant(ExtTrueVal, DL, VecVT);
11391 if (Src.getOpcode() == ISD::XOR &&
11392 ISD::isConstantSplatVectorAllOnes(Src.getOperand(1)))
11393 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src.getOperand(0), SplatZero,
11394 SplatTrueVal);
11395 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
11396 }
11397
11399 MVT I1ContainerVT =
11401
11402 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
11403
11404 SDValue VL = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).second;
11405
11406 MVT XLenVT = Subtarget.getXLenVT();
11407 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
11408 SDValue SplatTrueVal = DAG.getSignedConstant(ExtTrueVal, DL, XLenVT);
11409
11410 if (Src.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
11411 SDValue Xor = Src.getOperand(0);
11412 if (Xor.getOpcode() == RISCVISD::VMXOR_VL) {
11413 SDValue ScalableOnes = Xor.getOperand(1);
11414 if (ScalableOnes.getOpcode() == ISD::INSERT_SUBVECTOR &&
11415 ScalableOnes.getOperand(0).isUndef() &&
11417 CC = Xor.getOperand(0);
11418 std::swap(SplatZero, SplatTrueVal);
11419 }
11420 }
11421 }
11422
11423 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
11424 DAG.getUNDEF(ContainerVT), SplatZero, VL);
11425 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
11426 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
11427 SDValue Select =
11428 DAG.getNode(RISCVISD::VMERGE_VL, DL, ContainerVT, CC, SplatTrueVal,
11429 SplatZero, DAG.getUNDEF(ContainerVT), VL);
11430
11431 return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
11432}
11433
11434// Custom-lower truncations from vectors to mask vectors by using a mask and a
11435// setcc operation:
11436// (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
11437SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
11438 SelectionDAG &DAG) const {
11439 SDLoc DL(Op);
11440 EVT MaskVT = Op.getValueType();
11441 // Only expect to custom-lower truncations to mask types
11442 assert(MaskVT.isVectorOf(MVT::i1) &&
11443 "Unexpected type for vector mask lowering");
11444 SDValue Src = Op.getOperand(0);
11445 MVT VecVT = Src.getSimpleValueType();
11446 // If this is a fixed vector, we need to convert it to a scalable vector.
11447 MVT ContainerVT = VecVT;
11448
11449 if (VecVT.isFixedLengthVector()) {
11451 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
11452 }
11453
11454 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
11455
11456 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
11457 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
11458
11459 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
11460 DAG.getUNDEF(ContainerVT), SplatOne, VL);
11461 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
11462 DAG.getUNDEF(ContainerVT), SplatZero, VL);
11463
11464 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
11465 SDValue Trunc = DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne,
11466 DAG.getUNDEF(ContainerVT), Mask, VL);
11467 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT,
11468 {Trunc, SplatZero, DAG.getCondCode(ISD::SETNE),
11469 DAG.getUNDEF(MaskContainerVT), Mask, VL});
11470 if (MaskVT.isFixedLengthVector())
11471 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
11472 return Trunc;
11473}
11474
11475SDValue RISCVTargetLowering::lowerVectorTrunc(SDValue Op,
11476 SelectionDAG &DAG) const {
11477 unsigned Opc = Op.getOpcode();
11478 SDLoc DL(Op);
11479
11480 MVT VT = Op.getSimpleValueType();
11481 // Only custom-lower vector truncates
11482 assert(VT.isVector() && "Unexpected type for vector truncate lowering");
11483
11484 // Truncates to mask types are handled differently
11485 if (VT.getVectorElementType() == MVT::i1)
11486 return lowerVectorMaskTrunc(Op, DAG);
11487
11488 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
11489 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
11490 // truncate by one power of two at a time.
11491 MVT DstEltVT = VT.getVectorElementType();
11492
11493 SDValue Src = Op.getOperand(0);
11494 MVT SrcVT = Src.getSimpleValueType();
11495 MVT SrcEltVT = SrcVT.getVectorElementType();
11496
11497 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
11498 isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
11499 "Unexpected vector truncate lowering");
11500
11501 MVT ContainerVT = SrcVT;
11502 if (SrcVT.isFixedLengthVector()) {
11504 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
11505 }
11506
11507 SDValue Result = Src;
11508 auto [Mask, VL] = getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
11509
11510 unsigned NewOpc;
11512 NewOpc = RISCVISD::TRUNCATE_VECTOR_VL_SSAT;
11513 else if (Opc == ISD::TRUNCATE_USAT_U)
11514 NewOpc = RISCVISD::TRUNCATE_VECTOR_VL_USAT;
11515 else
11516 NewOpc = RISCVISD::TRUNCATE_VECTOR_VL;
11517
11518 do {
11519 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
11520 MVT ResultVT = ContainerVT.changeVectorElementType(SrcEltVT);
11521 Result = DAG.getNode(NewOpc, DL, ResultVT, Result, Mask, VL);
11522 } while (SrcEltVT != DstEltVT);
11523
11524 if (SrcVT.isFixedLengthVector())
11525 Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
11526
11527 return Result;
11528}
11529
11530SDValue
11531RISCVTargetLowering::lowerStrictFPExtendOrRoundLike(SDValue Op,
11532 SelectionDAG &DAG) const {
11533 SDLoc DL(Op);
11534 SDValue Chain = Op.getOperand(0);
11535 SDValue Src = Op.getOperand(1);
11536 MVT VT = Op.getSimpleValueType();
11537 MVT SrcVT = Src.getSimpleValueType();
11538 MVT ContainerVT = VT;
11539 if (VT.isFixedLengthVector()) {
11540 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
11541 ContainerVT =
11542 SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
11543 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
11544 }
11545
11546 auto [Mask, VL] = getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
11547
11548 // RVV can only widen/truncate fp to types double/half the size as the source.
11549 if ((VT.getVectorElementType() == MVT::f64 &&
11550 (SrcVT.getVectorElementType() == MVT::f16 ||
11551 SrcVT.getVectorElementType() == MVT::bf16)) ||
11552 ((VT.getVectorElementType() == MVT::f16 ||
11553 VT.getVectorElementType() == MVT::bf16) &&
11554 SrcVT.getVectorElementType() == MVT::f64)) {
11555 // For double rounding, the intermediate rounding should be round-to-odd.
11556 unsigned InterConvOpc = Op.getOpcode() == ISD::STRICT_FP_EXTEND
11557 ? RISCVISD::STRICT_FP_EXTEND_VL
11558 : RISCVISD::STRICT_VFNCVT_ROD_VL;
11559 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
11560 Src = DAG.getNode(InterConvOpc, DL, DAG.getVTList(InterVT, MVT::Other),
11561 Chain, Src, Mask, VL);
11562 Chain = Src.getValue(1);
11563 }
11564
11565 unsigned ConvOpc = Op.getOpcode() == ISD::STRICT_FP_EXTEND
11566 ? RISCVISD::STRICT_FP_EXTEND_VL
11567 : RISCVISD::STRICT_FP_ROUND_VL;
11568 SDValue Res = DAG.getNode(ConvOpc, DL, DAG.getVTList(ContainerVT, MVT::Other),
11569 Chain, Src, Mask, VL);
11570 if (VT.isFixedLengthVector()) {
11571 // StrictFP operations have two result values. Their lowered result should
11572 // have same result count.
11573 SDValue SubVec = convertFromScalableVector(VT, Res, DAG, Subtarget);
11574 Res = DAG.getMergeValues({SubVec, Res.getValue(1)}, DL);
11575 }
11576 return Res;
11577}
11578
11579SDValue
11580RISCVTargetLowering::lowerVectorFPExtendOrRound(SDValue Op,
11581 SelectionDAG &DAG) const {
11582 bool IsExtend = Op.getOpcode() == ISD::FP_EXTEND;
11583 // RVV can only do truncate fp to types half the size as the source. We
11584 // custom-lower f64->f16 rounds via RVV's round-to-odd float
11585 // conversion instruction.
11586 SDLoc DL(Op);
11587 MVT VT = Op.getSimpleValueType();
11588
11589 assert(VT.isVector() && "Unexpected type for vector truncate lowering");
11590
11591 SDValue Src = Op.getOperand(0);
11592 MVT SrcVT = Src.getSimpleValueType();
11593
11594 bool IsDirectExtend =
11595 IsExtend && (VT.getVectorElementType() != MVT::f64 ||
11596 (SrcVT.getVectorElementType() != MVT::f16 &&
11597 SrcVT.getVectorElementType() != MVT::bf16));
11598 bool IsDirectTrunc = !IsExtend && ((VT.getVectorElementType() != MVT::f16 &&
11599 VT.getVectorElementType() != MVT::bf16) ||
11600 SrcVT.getVectorElementType() != MVT::f64);
11601
11602 bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
11603
11604 // We have regular SD node patterns for direct non-VL extends.
11605 if (VT.isScalableVector() && IsDirectConv)
11606 return Op;
11607
11608 // Prepare any fixed-length vector operands.
11609 MVT ContainerVT = VT;
11610 if (VT.isFixedLengthVector()) {
11611 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
11612 ContainerVT =
11613 SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
11614 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
11615 }
11616
11617 auto [Mask, VL] = getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
11618
11619 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
11620
11621 if (IsDirectConv) {
11622 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
11623 if (VT.isFixedLengthVector())
11624 Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
11625 return Src;
11626 }
11627
11628 unsigned InterConvOpc =
11629 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
11630
11631 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
11632 SDValue IntermediateConv =
11633 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
11634 SDValue Result =
11635 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
11636 if (VT.isFixedLengthVector())
11637 return convertFromScalableVector(VT, Result, DAG, Subtarget);
11638 return Result;
11639}
11640
11641// Given a scalable vector type and an index into it, returns the type for the
11642// smallest subvector that the index fits in. This can be used to reduce LMUL
11643// for operations like vslidedown.
11644//
11645// E.g. With Zvl128b, index 3 in a nxv4i32 fits within the first nxv2i32.
11646static std::optional<MVT>
11647getSmallestVTForIndex(MVT VecVT, unsigned MaxIdx, SDLoc DL, SelectionDAG &DAG,
11648 const RISCVSubtarget &Subtarget) {
11649 assert(VecVT.isScalableVector());
11650 const unsigned EltSize = VecVT.getScalarSizeInBits();
11651 const unsigned VectorBitsMin = Subtarget.getRealMinVLen();
11652 const unsigned MinVLMAX = VectorBitsMin / EltSize;
11653 MVT SmallerVT;
11654 if (MaxIdx < MinVLMAX)
11655 SmallerVT = RISCVTargetLowering::getM1VT(VecVT);
11656 else if (MaxIdx < MinVLMAX * 2)
11657 SmallerVT =
11659 else if (MaxIdx < MinVLMAX * 4)
11660 SmallerVT = RISCVTargetLowering::getM1VT(VecVT)
11663 if (!SmallerVT.isValid() || !VecVT.bitsGT(SmallerVT))
11664 return std::nullopt;
11665 return SmallerVT;
11666}
11667
11668// Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
11669// first position of a vector, and that vector is slid up to the insert index.
11670// By limiting the active vector length to index+1 and merging with the
11671// original vector (with an undisturbed tail policy for elements >= VL), we
11672// achieve the desired result of leaving all elements untouched except the one
11673// at VL-1, which is replaced with the desired value.
11674SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
11675 SelectionDAG &DAG) const {
11676 SDLoc DL(Op);
11677 MVT VecVT = Op.getSimpleValueType();
11678 MVT XLenVT = Subtarget.getXLenVT();
11679 SDValue Vec = Op.getOperand(0);
11680 SDValue Val = Op.getOperand(1);
11681 MVT ValVT = Val.getSimpleValueType();
11682 SDValue Idx = Op.getOperand(2);
11683
11684 if (VecVT.getVectorElementType() == MVT::i1) {
11685 // FIXME: For now we just promote to an i8 vector and insert into that,
11686 // but this is probably not optimal.
11687 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
11688 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
11689 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
11690 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
11691 }
11692
11693 if ((ValVT == MVT::f16 && !Subtarget.hasVInstructionsF16()) ||
11694 (ValVT == MVT::bf16 && !Subtarget.hasVInstructionsBF16())) {
11695 // If we don't have vfmv.s.f for f16/bf16, use fmv.x.h first.
11696 MVT IntVT = VecVT.changeTypeToInteger();
11697 SDValue IntInsert = DAG.getNode(
11698 ISD::INSERT_VECTOR_ELT, DL, IntVT, DAG.getBitcast(IntVT, Vec),
11699 DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Val), Idx);
11700 return DAG.getBitcast(VecVT, IntInsert);
11701 }
11702
11703 if (Subtarget.hasStdExtP() && VecVT.isFixedLengthVector()) {
11704 auto *IdxC = dyn_cast<ConstantSDNode>(Idx);
11705 if (!IdxC)
11706 return SDValue();
11707
11708 unsigned IdxVal = IdxC->getZExtValue();
11709 unsigned NumElts = VecVT.getVectorNumElements();
11710 MVT EltVT = VecVT.getVectorElementType();
11711
11712 // v2i32 on RV32 lives in a GPR pair; constant index inserts are selected
11713 // with INSERT_SUBREG.
11714 if (!Subtarget.is64Bit() && VecVT == MVT::v2i32)
11715 return Op;
11716
11717 if (!Subtarget.is64Bit() && (VecVT == MVT::v4i16 || VecVT == MVT::v8i8)) {
11718 unsigned HalfNumElts = NumElts / 2;
11719 auto [Lo, Hi] = DAG.SplitVector(Vec, DL);
11720 MVT HalfVT = Lo.getSimpleValueType();
11721 if (IdxVal < HalfNumElts) {
11722 SDValue NewLo =
11723 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, HalfVT, Lo, Val, Idx);
11724 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, NewLo, Hi);
11725 }
11726 SDValue NewHi =
11727 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, HalfVT, Hi, Val,
11728 DAG.getVectorIdxConstant(IdxVal - HalfNumElts, DL));
11729 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, NewHi);
11730 }
11731
11732 SDValue ExtVal = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Val);
11733
11734 // A 2-element vector is a single PPAIR of the old vector and the new
11735 // element.
11736 if (NumElts == 2) {
11737 SDValue NewElt = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, ExtVal);
11738 // Index 0: take element 0 from NewElt and element 1 from Vec.
11739 if (IdxVal == 0)
11740 return DAG.getNode(RISCVISD::PPAIREO, DL, VecVT, NewElt, Vec);
11741 // Index 1: take element 0 from Vec and element 0 of NewElt.
11742 return DAG.getNode(RISCVISD::PPAIRE, DL, VecVT, Vec, NewElt);
11743 }
11744
11745 // For 4/8-element vectors, use MVM(or MERGE) instruction which does bitwise
11746 // select: rd = (~mask & rd) | (mask & rs1).
11747 // This generates: slli + lui/li + mvm
11748 if (NumElts == 4 || NumElts == 8) {
11749 unsigned EltBits = EltVT.getSizeInBits();
11750 unsigned ShiftAmt = IdxVal * EltBits;
11751 uint64_t PosMask = ((1ULL << EltBits) - 1) << ShiftAmt;
11752
11753 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, XLenVT, ExtVal,
11754 DAG.getConstant(ShiftAmt, DL, XLenVT));
11755 SDValue Mask = DAG.getConstant(PosMask, DL, XLenVT);
11756 Vec = DAG.getBitcast(XLenVT, Vec);
11757 SDValue Result =
11758 DAG.getNode(RISCVISD::MERGE, DL, XLenVT, Mask, Vec, ShiftedVal);
11759 return DAG.getBitcast(VecVT, Result);
11760 }
11761
11762 return SDValue();
11763 }
11764
11765 MVT ContainerVT = VecVT;
11766 // If the operand is a fixed-length vector, convert to a scalable one.
11767 if (VecVT.isFixedLengthVector()) {
11769 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
11770 }
11771
11772 // If we know the index we're going to insert at, we can shrink Vec so that
11773 // we're performing the scalar inserts and slideup on a smaller LMUL.
11774 SDValue OrigVec = Vec;
11775 std::optional<unsigned> AlignedIdx;
11776 if (auto *IdxC = dyn_cast<ConstantSDNode>(Idx)) {
11777 const unsigned OrigIdx = IdxC->getZExtValue();
11778 // Do we know an upper bound on LMUL?
11779 if (auto ShrunkVT = getSmallestVTForIndex(ContainerVT, OrigIdx,
11780 DL, DAG, Subtarget)) {
11781 ContainerVT = *ShrunkVT;
11782 AlignedIdx = 0;
11783 }
11784
11785 // If we're compiling for an exact VLEN value, we can always perform
11786 // the insert in m1 as we can determine the register corresponding to
11787 // the index in the register group.
11788 const MVT M1VT = RISCVTargetLowering::getM1VT(ContainerVT);
11789 if (auto VLEN = Subtarget.getRealVLen(); VLEN && ContainerVT.bitsGT(M1VT)) {
11790 EVT ElemVT = VecVT.getVectorElementType();
11791 unsigned ElemsPerVReg = *VLEN / ElemVT.getFixedSizeInBits();
11792 unsigned RemIdx = OrigIdx % ElemsPerVReg;
11793 unsigned SubRegIdx = OrigIdx / ElemsPerVReg;
11794 AlignedIdx = SubRegIdx * M1VT.getVectorElementCount().getKnownMinValue();
11795 Idx = DAG.getVectorIdxConstant(RemIdx, DL);
11796 ContainerVT = M1VT;
11797 }
11798
11799 if (AlignedIdx)
11800 Vec = DAG.getExtractSubvector(DL, ContainerVT, Vec, *AlignedIdx);
11801 }
11802
11803 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
11804 // Even i64-element vectors on RV32 can be lowered without scalar
11805 // legalization if the most-significant 32 bits of the value are not affected
11806 // by the sign-extension of the lower 32 bits. This applies to i32 constants
11807 // and sign_extend of i32 values.
11808 if (!IsLegalInsert) {
11809 if (isa<ConstantSDNode>(Val)) {
11810 const auto *CVal = cast<ConstantSDNode>(Val);
11811 if (isInt<32>(CVal->getSExtValue())) {
11812 IsLegalInsert = true;
11813 Val = DAG.getSignedConstant(CVal->getSExtValue(), DL, MVT::i32);
11814 }
11815 } else if (Val.getOpcode() == ISD::SIGN_EXTEND &&
11816 Val.getOperand(0).getValueType() == MVT::i32) {
11817 IsLegalInsert = true;
11818 Val = Val.getOperand(0);
11819 }
11820 }
11821
11822 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
11823
11824 SDValue ValInVec;
11825
11826 if (IsLegalInsert) {
11827 unsigned Opc =
11828 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
11829 if (isNullConstant(Idx)) {
11830 if (!VecVT.isFloatingPoint())
11831 Val = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Val);
11832 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
11833
11834 if (AlignedIdx)
11835 Vec = DAG.getInsertSubvector(DL, OrigVec, Vec, *AlignedIdx);
11836 if (!VecVT.isFixedLengthVector())
11837 return Vec;
11838 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
11839 }
11840
11841 ValInVec = lowerScalarInsert(Val, VL, ContainerVT, DL, DAG, Subtarget);
11842 } else {
11843 // On RV32, i64-element vectors must be specially handled to place the
11844 // value at element 0, by using two vslide1down instructions in sequence on
11845 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
11846 // this.
11847 SDValue ValLo, ValHi;
11848 std::tie(ValLo, ValHi) = DAG.SplitScalar(Val, DL, MVT::i32, MVT::i32);
11849 MVT I32ContainerVT =
11851 SDValue I32Mask =
11852 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
11853 // Limit the active VL to two.
11854 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
11855 // If the Idx is 0 we can insert directly into the vector.
11856 if (isNullConstant(Idx)) {
11857 // First slide in the lo value, then the hi in above it. We use slide1down
11858 // to avoid the register group overlap constraint of vslide1up.
11859 SDValue I32Vec = DAG.getBitcast(I32ContainerVT, Vec);
11860 ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT,
11861 I32Vec, I32Vec, ValLo, I32Mask, InsertI64VL);
11862 // If the source vector is undef don't pass along the tail elements from
11863 // the previous slide1down.
11864 SDValue Tail = Vec.isUndef() ? I32Vec : ValInVec;
11865 ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT,
11866 Tail, ValInVec, ValHi, I32Mask, InsertI64VL);
11867 // Bitcast back to the right container type.
11868 ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
11869
11870 if (AlignedIdx)
11871 ValInVec = DAG.getInsertSubvector(DL, OrigVec, ValInVec, *AlignedIdx);
11872 if (!VecVT.isFixedLengthVector())
11873 return ValInVec;
11874 return convertFromScalableVector(VecVT, ValInVec, DAG, Subtarget);
11875 }
11876
11877 // First slide in the lo value, then the hi in above it. We use slide1down
11878 // to avoid the register group overlap constraint of vslide1up.
11879 ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT,
11880 DAG.getUNDEF(I32ContainerVT),
11881 DAG.getUNDEF(I32ContainerVT), ValLo,
11882 I32Mask, InsertI64VL);
11883 ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT,
11884 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
11885 I32Mask, InsertI64VL);
11886 // Bitcast back to the right container type.
11887 ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
11888 }
11889
11890 // Now that the value is in a vector, slide it into position.
11891 SDValue InsertVL =
11892 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
11893
11894 // Use tail agnostic policy if Idx is the last index of Vec.
11896 if (VecVT.isFixedLengthVector() && isa<ConstantSDNode>(Idx) &&
11897 Idx->getAsZExtVal() + 1 == VecVT.getVectorNumElements())
11899 SDValue Slideup = getVSlideup(DAG, Subtarget, DL, ContainerVT, Vec, ValInVec,
11900 Idx, Mask, InsertVL, Policy);
11901
11902 if (AlignedIdx)
11903 Slideup = DAG.getInsertSubvector(DL, OrigVec, Slideup, *AlignedIdx);
11904 if (!VecVT.isFixedLengthVector())
11905 return Slideup;
11906 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
11907}
11908
11909// Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
11910// extract the first element: (extractelt (slidedown vec, idx), 0). For integer
11911// types this is done using VMV_X_S to allow us to glean information about the
11912// sign bits of the result.
11913SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
11914 SelectionDAG &DAG) const {
11915 SDLoc DL(Op);
11916 SDValue Idx = Op.getOperand(1);
11917 SDValue Vec = Op.getOperand(0);
11918 EVT EltVT = Op.getValueType();
11919 MVT VecVT = Vec.getSimpleValueType();
11920 MVT XLenVT = Subtarget.getXLenVT();
11921
11922 if (VecVT.getVectorElementType() == MVT::i1) {
11923 // Use vfirst.m to extract the first bit.
11924 if (isNullConstant(Idx)) {
11925 MVT ContainerVT = VecVT;
11926 if (VecVT.isFixedLengthVector()) {
11928 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
11929 }
11930 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
11931 SDValue Vfirst =
11932 DAG.getNode(RISCVISD::VFIRST_VL, DL, XLenVT, Vec, Mask, VL);
11933 SDValue Res = DAG.getSetCC(DL, XLenVT, Vfirst,
11934 DAG.getConstant(0, DL, XLenVT), ISD::SETEQ);
11935 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Res);
11936 }
11937 if (VecVT.isFixedLengthVector()) {
11938 unsigned NumElts = VecVT.getVectorNumElements();
11939 if (NumElts >= 8) {
11940 MVT WideEltVT;
11941 unsigned WidenVecLen;
11942 SDValue ExtractElementIdx;
11943 SDValue ExtractBitIdx;
11944 unsigned MaxEEW = Subtarget.getELen();
11945 MVT LargestEltVT = MVT::getIntegerVT(
11946 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
11947 if (NumElts <= LargestEltVT.getSizeInBits()) {
11948 assert(isPowerOf2_32(NumElts) &&
11949 "the number of elements should be power of 2");
11950 WideEltVT = MVT::getIntegerVT(NumElts);
11951 WidenVecLen = 1;
11952 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
11953 ExtractBitIdx = Idx;
11954 } else {
11955 WideEltVT = LargestEltVT;
11956 WidenVecLen = NumElts / WideEltVT.getSizeInBits();
11957 // extract element index = index / element width
11958 ExtractElementIdx = DAG.getNode(
11959 ISD::SRL, DL, XLenVT, Idx,
11960 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
11961 // mask bit index = index % element width
11962 ExtractBitIdx = DAG.getNode(
11963 ISD::AND, DL, XLenVT, Idx,
11964 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
11965 }
11966 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
11967 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
11968 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
11969 Vec, ExtractElementIdx);
11970 // Extract the bit from GPR.
11971 SDValue ShiftRight =
11972 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
11973 SDValue Res = DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
11974 DAG.getConstant(1, DL, XLenVT));
11975 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Res);
11976 }
11977 }
11978 // Otherwise, promote to an i8 vector and extract from that.
11979 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
11980 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
11981 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
11982 }
11983
11984 if ((EltVT == MVT::f16 && !Subtarget.hasVInstructionsF16()) ||
11985 (EltVT == MVT::bf16 && !Subtarget.hasVInstructionsBF16())) {
11986 // If we don't have vfmv.f.s for f16/bf16, extract to a gpr then use fmv.h.x
11987 MVT IntVT = VecVT.changeTypeToInteger();
11988 SDValue IntVec = DAG.getBitcast(IntVT, Vec);
11989 SDValue IntExtract =
11990 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, IntVec, Idx);
11991 return DAG.getNode(RISCVISD::FMV_H_X, DL, EltVT, IntExtract);
11992 }
11993
11994 if (Subtarget.hasStdExtP() && VecVT.isFixedLengthVector()) {
11995 if (VecVT != MVT::v4i16 && VecVT != MVT::v2i16 && VecVT != MVT::v8i8 &&
11996 VecVT != MVT::v4i8 && VecVT != MVT::v2i32)
11997 return SDValue();
11998
11999 // v2i32 on RV32 lives in a GPR pair; constant index extracts are selected
12000 // with EXTRACT_SUBREG.
12001 if (!Subtarget.is64Bit() && VecVT.getSizeInBits() == 64) {
12002 auto *IdxC = dyn_cast<ConstantSDNode>(Idx);
12003 if (!IdxC) {
12004 // Shift the pair right by the bit offset of the element. NSRL reads 6
12005 // bits of shift amount so it handles offsets >= 32.
12006 SDValue Lo, Hi;
12007 if (VecVT == MVT::v2i32) {
12008 Lo = DAG.getExtractVectorElt(DL, MVT::i32, Vec, 0);
12009 Hi = DAG.getExtractVectorElt(DL, MVT::i32, Vec, 1);
12010 } else {
12011 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
12012 Lo = DAG.getBitcast(XLenVT, Lo);
12013 Hi = DAG.getBitcast(XLenVT, Hi);
12014 }
12015 unsigned ElemWidth = VecVT.getVectorElementType().getSizeInBits();
12016 SDValue Shamt = DAG.getNode(ISD::MUL, DL, XLenVT, Idx,
12017 DAG.getConstant(ElemWidth, DL, XLenVT));
12018 return DAG.getNode(RISCVISD::NSRL, DL, XLenVT, Lo, Hi, Shamt);
12019 }
12020 // v2i32 constant index extracts are selected with EXTRACT_SUBREG.
12021 if (VecVT == MVT::v2i32)
12022 return Op;
12023 unsigned IdxVal = IdxC->getZExtValue();
12024 unsigned HalfNumElts = VecVT.getVectorNumElements() / 2;
12025 auto [Lo, Hi] = DAG.SplitVector(Vec, DL);
12026 if (IdxVal < HalfNumElts)
12027 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Lo, Idx);
12028 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Hi,
12029 DAG.getVectorIdxConstant(IdxVal - HalfNumElts, DL));
12030 }
12031
12032 SDValue Extracted = DAG.getBitcast(XLenVT, Vec);
12033 unsigned ElemWidth = VecVT.getVectorElementType().getSizeInBits();
12034 SDValue Shamt = DAG.getNode(ISD::MUL, DL, XLenVT, Idx,
12035 DAG.getConstant(ElemWidth, DL, XLenVT));
12036 return DAG.getNode(ISD::SRL, DL, XLenVT, Extracted, Shamt);
12037 }
12038
12039 // If this is a fixed vector, we need to convert it to a scalable vector.
12040 MVT ContainerVT = VecVT;
12041 if (VecVT.isFixedLengthVector()) {
12043 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
12044 }
12045
12046 // If we're compiling for an exact VLEN value and we have a known
12047 // constant index, we can always perform the extract in m1 (or
12048 // smaller) as we can determine the register corresponding to
12049 // the index in the register group.
12050 const auto VLen = Subtarget.getRealVLen();
12051 if (auto *IdxC = dyn_cast<ConstantSDNode>(Idx);
12052 IdxC && VLen && VecVT.getSizeInBits().getKnownMinValue() > *VLen) {
12054 unsigned OrigIdx = IdxC->getZExtValue();
12055 EVT ElemVT = VecVT.getVectorElementType();
12056 unsigned ElemsPerVReg = *VLen / ElemVT.getFixedSizeInBits();
12057 unsigned RemIdx = OrigIdx % ElemsPerVReg;
12058 unsigned SubRegIdx = OrigIdx / ElemsPerVReg;
12059 unsigned ExtractIdx =
12060 SubRegIdx * M1VT.getVectorElementCount().getKnownMinValue();
12061 Vec = DAG.getExtractSubvector(DL, M1VT, Vec, ExtractIdx);
12062 Idx = DAG.getVectorIdxConstant(RemIdx, DL);
12063 ContainerVT = M1VT;
12064 }
12065
12066 // Reduce the LMUL of our slidedown and vmv.x.s to the smallest LMUL which
12067 // contains our index.
12068 std::optional<uint64_t> MaxIdx;
12069 if (VecVT.isFixedLengthVector())
12070 MaxIdx = VecVT.getVectorNumElements() - 1;
12071 if (auto *IdxC = dyn_cast<ConstantSDNode>(Idx))
12072 MaxIdx = IdxC->getZExtValue();
12073 if (MaxIdx) {
12074 if (auto SmallerVT =
12075 getSmallestVTForIndex(ContainerVT, *MaxIdx, DL, DAG, Subtarget)) {
12076 ContainerVT = *SmallerVT;
12077 Vec = DAG.getExtractSubvector(DL, ContainerVT, Vec, 0);
12078 }
12079 }
12080
12081 // If after narrowing, the required slide is still greater than LMUL2,
12082 // fallback to generic expansion and go through the stack. This is done
12083 // for a subtle reason: extracting *all* elements out of a vector is
12084 // widely expected to be linear in vector size, but because vslidedown
12085 // is linear in LMUL, performing N extracts using vslidedown becomes
12086 // O(n^2) / (VLEN/ETYPE) work. On the surface, going through the stack
12087 // seems to have the same problem (the store is linear in LMUL), but the
12088 // generic expansion *memoizes* the store, and thus for many extracts of
12089 // the same vector we end up with one store and a bunch of loads.
12090 // TODO: We don't have the same code for insert_vector_elt because we
12091 // have BUILD_VECTOR and handle the degenerate case there. Should we
12092 // consider adding an inverse BUILD_VECTOR node?
12093 MVT LMUL2VT =
12095 if (ContainerVT.bitsGT(LMUL2VT) && VecVT.isFixedLengthVector())
12096 return SDValue();
12097
12098 // If the index is 0, the vector is already in the right position.
12099 if (!isNullConstant(Idx)) {
12100 // Use a VL of 1 to avoid processing more elements than we need.
12101 auto [Mask, VL] = getDefaultVLOps(1, ContainerVT, DL, DAG, Subtarget);
12102 Vec = getVSlidedown(DAG, Subtarget, DL, ContainerVT,
12103 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
12104 }
12105
12106 if (!EltVT.isInteger()) {
12107 // Floating-point extracts are handled in TableGen.
12108 return DAG.getExtractVectorElt(DL, EltVT, Vec, 0);
12109 }
12110
12111 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
12112 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
12113}
12114
12115// Some RVV intrinsics may claim that they want an integer operand to be
12116// promoted or expanded.
12118 const RISCVSubtarget &Subtarget) {
12119 assert((Op.getOpcode() == ISD::INTRINSIC_VOID ||
12120 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
12121 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
12122 "Unexpected opcode");
12123
12124 if (!Subtarget.hasVInstructions())
12125 return SDValue();
12126
12127 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_VOID ||
12128 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
12129 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
12130
12131 SDLoc DL(Op);
12132
12134 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
12135 if (!II || !II->hasScalarOperand())
12136 return SDValue();
12137
12138 unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
12139 assert(SplatOp < Op.getNumOperands());
12140
12142 SDValue &ScalarOp = Operands[SplatOp];
12143 MVT OpVT = ScalarOp.getSimpleValueType();
12144 MVT XLenVT = Subtarget.getXLenVT();
12145
12146 // If this isn't a scalar, or its type is XLenVT we're done.
12147 if (!OpVT.isScalarInteger() || OpVT == XLenVT)
12148 return SDValue();
12149
12150 // Simplest case is that the operand needs to be promoted to XLenVT.
12151 if (OpVT.bitsLT(XLenVT)) {
12152 // If the operand is a constant, sign extend to increase our chances
12153 // of being able to use a .vi instruction. ANY_EXTEND would become a
12154 // a zero extend and the simm5 check in isel would fail.
12155 // FIXME: Should we ignore the upper bits in isel instead?
12156 unsigned ExtOpc =
12158 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
12159 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
12160 }
12161
12162 // Use the previous operand to get the vXi64 VT. The result might be a mask
12163 // VT for compares. Using the previous operand assumes that the previous
12164 // operand will never have a smaller element size than a scalar operand and
12165 // that a widening operation never uses SEW=64.
12166 // NOTE: If this fails the below assert, we can probably just find the
12167 // element count from any operand or result and use it to construct the VT.
12168 assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
12169 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
12170
12171 // The more complex case is when the scalar is larger than XLenVT.
12172 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
12173 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
12174
12175 // If this is a sign-extended 32-bit value, we can truncate it and rely on the
12176 // instruction to sign-extend since SEW>XLEN.
12177 if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
12178 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
12179 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
12180 }
12181
12182 switch (IntNo) {
12183 case Intrinsic::riscv_vslide1up:
12184 case Intrinsic::riscv_vslide1down:
12185 case Intrinsic::riscv_vslide1up_mask:
12186 case Intrinsic::riscv_vslide1down_mask: {
12187 // We need to special case these when the scalar is larger than XLen.
12188 unsigned NumOps = Op.getNumOperands();
12189 bool IsMasked = NumOps == 7;
12190
12191 // Convert the vector source to the equivalent nxvXi32 vector.
12192 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
12193 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
12194 SDValue ScalarLo, ScalarHi;
12195 std::tie(ScalarLo, ScalarHi) =
12196 DAG.SplitScalar(ScalarOp, DL, MVT::i32, MVT::i32);
12197
12198 // Double the VL since we halved SEW.
12199 SDValue AVL = getVLOperand(Op);
12200 SDValue I32VL;
12201
12202 // Optimize for constant AVL
12203 if (isa<ConstantSDNode>(AVL)) {
12204 const auto [MinVLMAX, MaxVLMAX] =
12206
12207 uint64_t AVLInt = AVL->getAsZExtVal();
12208 if (AVLInt <= MinVLMAX) {
12209 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
12210 } else if (AVLInt >= 2 * MaxVLMAX) {
12211 // Just set vl to VLMAX in this situation
12212 I32VL = DAG.getRegister(RISCV::X0, XLenVT);
12213 } else {
12214 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
12215 // is related to the hardware implementation.
12216 // So let the following code handle
12217 }
12218 }
12219 if (!I32VL) {
12221 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
12222 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
12223 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
12224 SDValue SETVL =
12225 DAG.getTargetConstant(Intrinsic::riscv_vsetvli, DL, MVT::i32);
12226 // Using vsetvli instruction to get actually used length which related to
12227 // the hardware implementation
12228 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
12229 SEW, LMUL);
12230 I32VL =
12231 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
12232 }
12233
12234 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
12235
12236 // Shift the two scalar parts in using SEW=32 slide1up/slide1down
12237 // instructions.
12238 SDValue Passthru;
12239 if (IsMasked)
12240 Passthru = DAG.getUNDEF(I32VT);
12241 else
12242 Passthru = DAG.getBitcast(I32VT, Operands[1]);
12243
12244 if (IntNo == Intrinsic::riscv_vslide1up ||
12245 IntNo == Intrinsic::riscv_vslide1up_mask) {
12246 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
12247 ScalarHi, I32Mask, I32VL);
12248 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
12249 ScalarLo, I32Mask, I32VL);
12250 } else {
12251 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
12252 ScalarLo, I32Mask, I32VL);
12253 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
12254 ScalarHi, I32Mask, I32VL);
12255 }
12256
12257 // Convert back to nxvXi64.
12258 Vec = DAG.getBitcast(VT, Vec);
12259
12260 if (!IsMasked)
12261 return Vec;
12262 // Apply mask after the operation.
12263 SDValue Mask = Operands[NumOps - 3];
12264 SDValue MaskedOff = Operands[1];
12265 // Assume Policy operand is the last operand.
12266 uint64_t Policy = Operands[NumOps - 1]->getAsZExtVal();
12267 // We don't need to select maskedoff if it's undef.
12268 if (MaskedOff.isUndef())
12269 return Vec;
12270 // TAMU
12271 if (Policy == RISCVVType::TAIL_AGNOSTIC)
12272 return DAG.getNode(RISCVISD::VMERGE_VL, DL, VT, Mask, Vec, MaskedOff,
12273 DAG.getUNDEF(VT), AVL);
12274 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
12275 // It's fine because vmerge does not care mask policy.
12276 return DAG.getNode(RISCVISD::VMERGE_VL, DL, VT, Mask, Vec, MaskedOff,
12277 MaskedOff, AVL);
12278 }
12279 }
12280
12281 // We need to convert the scalar to a splat vector.
12282 SDValue VL = getVLOperand(Op);
12283 assert(VL.getValueType() == XLenVT);
12284 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
12285 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
12286}
12287
12288// Lower the llvm.get.vector.length intrinsic to vsetvli. We only support
12289// scalable vector llvm.get.vector.length for now.
12290//
12291// We need to convert from a scalable VF to a vsetvli with VLMax equal to
12292// (vscale * VF). The vscale and VF are independent of element width. We use
12293// SEW=8 for the vsetvli because it is the only element width that supports all
12294// fractional LMULs. The LMUL is chosen so that with SEW=8 the VLMax is
12295// (vscale * VF). Where vscale is defined as VLEN/RVVBitsPerBlock. The
12296// InsertVSETVLI pass can fix up the vtype of the vsetvli if a different
12297// SEW and LMUL are better for the surrounding vector instructions.
12299 const RISCVSubtarget &Subtarget) {
12300 MVT XLenVT = Subtarget.getXLenVT();
12301
12302 // The smallest LMUL is only valid for the smallest element width.
12303 const unsigned ElementWidth = 8;
12304
12305 // Determine the VF that corresponds to LMUL 1 for ElementWidth.
12306 unsigned LMul1VF = RISCV::RVVBitsPerBlock / ElementWidth;
12307 // We don't support VF==1 with ELEN==32.
12308 [[maybe_unused]] unsigned MinVF =
12310
12311 [[maybe_unused]] unsigned VF = N->getConstantOperandVal(2);
12312 assert(VF >= MinVF && VF <= (LMul1VF * 8) && isPowerOf2_32(VF) &&
12313 "Unexpected VF");
12314
12315 bool Fractional = VF < LMul1VF;
12316 unsigned LMulVal = Fractional ? LMul1VF / VF : VF / LMul1VF;
12317 unsigned VLMUL = (unsigned)RISCVVType::encodeLMUL(LMulVal, Fractional);
12318 unsigned VSEW = RISCVVType::encodeSEW(ElementWidth);
12319
12320 SDLoc DL(N);
12321
12322 SDValue LMul = DAG.getTargetConstant(VLMUL, DL, XLenVT);
12323 SDValue Sew = DAG.getTargetConstant(VSEW, DL, XLenVT);
12324
12325 SDValue AVL = DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
12326
12327 SDValue ID = DAG.getTargetConstant(Intrinsic::riscv_vsetvli, DL, XLenVT);
12328 SDValue Res =
12329 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, ID, AVL, Sew, LMul);
12330 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), Res);
12331}
12332
12334 const RISCVSubtarget &Subtarget) {
12335 SDValue Op0 = Op.getOperand(0);
12336 MVT OpVT = Op0.getSimpleValueType();
12337 MVT ContainerVT = OpVT;
12338 if (OpVT.isFixedLengthVector()) {
12341 }
12342 MVT XLenVT = Subtarget.getXLenVT();
12343 SDLoc DL(Op);
12344 auto [Mask, VL] = getDefaultVLOps(OpVT, ContainerVT, DL, DAG, Subtarget);
12345 SDValue Res = DAG.getNode(RISCVISD::VFIRST_VL, DL, XLenVT, Op0, Mask, VL);
12346 if (Op.getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON)
12347 return Res;
12348
12349 // Convert -1 to VL.
12350 SDValue Setcc =
12351 DAG.getSetCC(DL, XLenVT, Res, DAG.getConstant(0, DL, XLenVT), ISD::SETLT);
12352 VL = DAG.getElementCount(DL, XLenVT, OpVT.getVectorElementCount());
12353 return DAG.getSelect(DL, XLenVT, Setcc, VL, Res);
12354}
12355
12357 const RISCVSubtarget &Subtarget) {
12359 const uint64_t SemEnum = Op->getConstantOperandVal(1);
12360 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
12361
12362 if (Sem != APFloatBase::S_Float8E5M2)
12363 return SDValue();
12364
12365 SDValue Src = Op.getOperand(0);
12366 EVT SrcEVT = Src.getValueType();
12367 if (!SrcEVT.isSimple() || SrcEVT.getVectorElementType() != MVT::i8)
12368 return SDValue();
12369 MVT SrcVT = SrcEVT.getSimpleVT();
12370 MVT DstVT = Op.getSimpleValueType();
12371 assert(DstVT.getVectorElementType() == MVT::bf16);
12372 SDLoc DL(Op);
12373
12374 MVT SrcContainerVT = SrcVT;
12375 MVT DstContainerVT = DstVT;
12376 if (SrcVT.isFixedLengthVector()) {
12377 SrcContainerVT = getContainerForFixedLengthVector(SrcVT, Subtarget);
12378 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
12379 DstContainerVT = getContainerForFixedLengthVector(DstVT, Subtarget);
12380 }
12381 SDValue VL =
12382 getDefaultVLOps(SrcVT, SrcContainerVT, DL, DAG, Subtarget).second;
12383
12384 SDValue Ops[] = {DAG.getTargetConstant(Intrinsic::riscv_vfwcvt_f_f_v_alt, DL,
12385 Subtarget.getXLenVT()),
12386 DAG.getPOISON(DstContainerVT), // Passthru
12387 Src, VL};
12388 SDValue NewVal =
12389 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, DstContainerVT, Ops);
12390 if (SrcVT.isFixedLengthVector())
12391 NewVal = convertFromScalableVector(DstVT, NewVal, DAG, Subtarget);
12392 return NewVal;
12393}
12394
12395static inline void promoteVCIXScalar(SDValue Op,
12397 SelectionDAG &DAG) {
12398 const RISCVSubtarget &Subtarget =
12400
12401 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_VOID ||
12402 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
12403 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
12404 SDLoc DL(Op);
12405
12407 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
12408 if (!II || !II->hasScalarOperand())
12409 return;
12410
12411 unsigned SplatOp = II->ScalarOperand + 1;
12412 assert(SplatOp < Op.getNumOperands());
12413
12414 SDValue &ScalarOp = Operands[SplatOp];
12415 MVT OpVT = ScalarOp.getSimpleValueType();
12416 MVT XLenVT = Subtarget.getXLenVT();
12417
12418 // The code below is partially copied from lowerVectorIntrinsicScalars.
12419 // If this isn't a scalar, or its type is XLenVT we're done.
12420 if (!OpVT.isScalarInteger() || OpVT == XLenVT)
12421 return;
12422
12423 // Manually emit promote operation for scalar operation.
12424 if (OpVT.bitsLT(XLenVT)) {
12425 unsigned ExtOpc =
12427 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
12428 }
12429}
12430
12431static void processVCIXOperands(SDValue OrigOp,
12433 SelectionDAG &DAG) {
12434 promoteVCIXScalar(OrigOp, Operands, DAG);
12435 const RISCVSubtarget &Subtarget =
12437 for (SDValue &V : Operands) {
12438 EVT ValType = V.getValueType();
12439 if (ValType.isVector() && ValType.isFloatingPoint()) {
12440 MVT InterimIVT =
12441 MVT::getVectorVT(MVT::getIntegerVT(ValType.getScalarSizeInBits()),
12442 ValType.getVectorElementCount());
12443 V = DAG.getBitcast(InterimIVT, V);
12444 }
12445 if (ValType.isFixedLengthVector()) {
12446 MVT OpContainerVT =
12447 getContainerForFixedLengthVector(V.getSimpleValueType(), Subtarget);
12448 V = convertToScalableVector(OpContainerVT, V, DAG, Subtarget);
12449 }
12450 }
12451}
12452
12453// LMUL * VLEN should be greater than or equal to EGS * SEW
12454static inline bool isValidEGW(int EGS, EVT VT,
12455 const RISCVSubtarget &Subtarget) {
12456 return (Subtarget.getRealMinVLen() *
12458 EGS * VT.getScalarSizeInBits();
12459}
12460
12461static unsigned getRVPShiftOpcode(Intrinsic::ID IntNo) {
12462 switch (IntNo) {
12463 default:
12465 "Unexpected RISC-V packed saturating and rounding shift intrinsic");
12466 case Intrinsic::riscv_psll:
12467 return RISCVISD::PSLL;
12468 case Intrinsic::riscv_psrl:
12469 return RISCVISD::PSRL;
12470 case Intrinsic::riscv_psra:
12471 return RISCVISD::PSRA;
12472 case Intrinsic::riscv_pssha:
12473 return RISCVISD::PSSHA;
12474 case Intrinsic::riscv_psshar:
12475 return RISCVISD::PSSHAR;
12476 case Intrinsic::riscv_psshl:
12477 return RISCVISD::PSSHL;
12478 case Intrinsic::riscv_psshlr:
12479 return RISCVISD::PSSHLR;
12480 }
12481}
12482
12483static unsigned getRVPNarrowingOpcode(Intrinsic::ID IntNo) {
12484 switch (IntNo) {
12485 default:
12486 llvm_unreachable("Unexpected RISC-V packed narrowing intrinsic");
12487 case Intrinsic::riscv_pnsrl:
12488 return RISCVISD::PNSRL;
12489 case Intrinsic::riscv_pnsra:
12490 return RISCVISD::PNSRA;
12491 case Intrinsic::riscv_pnsrar:
12492 return RISCVISD::PNSRAR;
12493 case Intrinsic::riscv_pnclipu:
12494 return RISCVISD::PNCLIPU;
12495 case Intrinsic::riscv_pnclipru:
12496 return RISCVISD::PNCLIPRU;
12497 case Intrinsic::riscv_pnclip:
12498 return RISCVISD::PNCLIP;
12499 case Intrinsic::riscv_pnclipr:
12500 return RISCVISD::PNCLIPR;
12501 }
12502}
12503
12505 switch (IntNo) {
12506 default:
12507 llvm_unreachable("Unexpected RISC-V scalar narrowing intrinsic");
12508 case Intrinsic::riscv_nclipu_u32:
12509 return RISCVISD::NCLIPU;
12510 case Intrinsic::riscv_nclipru_u32:
12511 return RISCVISD::NCLIPRU;
12512 case Intrinsic::riscv_nsrar_i32:
12513 return RISCVISD::NSRAR;
12514 case Intrinsic::riscv_nclip_i32:
12515 return RISCVISD::NCLIP;
12516 case Intrinsic::riscv_nclipr_i32:
12517 return RISCVISD::NCLIPR;
12518 }
12519}
12520
12522 MVT VT, SelectionDAG &DAG) {
12523 ShAmt = DAG.getAnyExtOrTrunc(ShAmt, DL, VT);
12524 return DAG.getNode(ISD::AND, DL, VT, ShAmt, DAG.getConstant(63, DL, VT));
12525}
12526
12528 const RISCVSubtarget &Subtarget) {
12529 MVT VT = Src.getSimpleValueType();
12530 MVT PPairVT =
12532 VT.getVectorNumElements() * 2);
12533 Src = DAG.getBitcast(PPairVT, Src);
12534 SDValue Zero = DAG.getNode(ISD::SPLAT_VECTOR, DL, PPairVT,
12535 DAG.getConstant(0, DL, Subtarget.getXLenVT()));
12536 SDValue Res = DAG.getNode(RISCVISD::PPAIRE, DL, PPairVT, Src, Zero);
12537 return DAG.getBitcast(VT, Res);
12538}
12539
12540static unsigned getRVPMulHighOpcode(unsigned IntNo) {
12541 switch (IntNo) {
12542 default:
12543 llvm_unreachable("Unexpected RISC-V packed multiply high intrinsic");
12544 case Intrinsic::riscv_pmulhr:
12545 return RISCVISD::MULHR;
12546 case Intrinsic::riscv_pmulhru:
12547 return RISCVISD::MULHRU;
12548 case Intrinsic::riscv_pmulhsu:
12549 return RISCVISD::MULHSU;
12550 case Intrinsic::riscv_pmulhrsu:
12551 return RISCVISD::MULHRSU;
12552 }
12553}
12554
12555static unsigned getRVPScalarOpcode(unsigned IntNo) {
12556 switch (IntNo) {
12557 default:
12559 "Unexpected RISC-V scalar averaging, multiply high, Q-format "
12560 "multiply or multiply high accumulate intrinsic");
12561 case Intrinsic::riscv_aadd_i32:
12562 return ISD::AVGFLOORS;
12563 case Intrinsic::riscv_aaddu_u32:
12564 return ISD::AVGFLOORU;
12565 case Intrinsic::riscv_asub_i32:
12566 return ISD::AVGSUBFLOORS;
12567 case Intrinsic::riscv_asubu_u32:
12568 return ISD::AVGSUBFLOORU;
12569 case Intrinsic::riscv_ssh1sadd_i32:
12570 return RISCVISD::SSH1SADD;
12571 case Intrinsic::riscv_mseq_u32:
12572 return RISCVISD::MSEQ;
12573 case Intrinsic::riscv_mslt_i32:
12574 return RISCVISD::MSLT;
12575 case Intrinsic::riscv_msltu_u32:
12576 return RISCVISD::MSLTU;
12577 case Intrinsic::riscv_mulhr_i32:
12578 return RISCVISD::MULHR;
12579 case Intrinsic::riscv_mulhru_u32:
12580 return RISCVISD::MULHRU;
12581 case Intrinsic::riscv_mulhsu_i32:
12582 return RISCVISD::MULHSU;
12583 case Intrinsic::riscv_mulhrsu_i32:
12584 return RISCVISD::MULHRSU;
12585 case Intrinsic::riscv_mulq_i32:
12586 return RISCVISD::MULQ;
12587 case Intrinsic::riscv_mulqr_i32:
12588 return RISCVISD::MULQR;
12589 case Intrinsic::riscv_mhacc_i32:
12590 return RISCVISD::MHACC;
12591 case Intrinsic::riscv_mhracc_i32:
12592 return RISCVISD::MHRACC;
12593 case Intrinsic::riscv_mhaccu_u32:
12594 return RISCVISD::MHACCU;
12595 case Intrinsic::riscv_mhraccu_u32:
12596 return RISCVISD::MHRACCU;
12597 case Intrinsic::riscv_mhaccsu_i32:
12598 return RISCVISD::MHACCSU;
12599 case Intrinsic::riscv_mhraccsu_i32:
12600 return RISCVISD::MHRACCSU;
12601 }
12602}
12603
12604static unsigned getRVPMulHighAccumulateOpcode(unsigned IntNo) {
12605 switch (IntNo) {
12606 default:
12608 "Unexpected RISC-V packed multiply high accumulate intrinsic");
12609 case Intrinsic::riscv_pmhacc:
12610 return RISCVISD::MHACC;
12611 case Intrinsic::riscv_pmhracc:
12612 return RISCVISD::MHRACC;
12613 case Intrinsic::riscv_pmhaccu:
12614 return RISCVISD::MHACCU;
12615 case Intrinsic::riscv_pmhraccu:
12616 return RISCVISD::MHRACCU;
12617 case Intrinsic::riscv_pmhaccsu:
12618 return RISCVISD::MHACCSU;
12619 case Intrinsic::riscv_pmhraccsu:
12620 return RISCVISD::MHRACCSU;
12621 }
12622}
12623
12624/// Return the multiply high accumulate node for \p IntNo.
12625static unsigned getRVPMulHighAccumulateHalfOpcode(unsigned IntNo) {
12626 switch (IntNo) {
12627 default:
12628 llvm_unreachable("Unexpected RISC-V packed multiply high accumulate half "
12629 "intrinsic");
12630 case Intrinsic::riscv_pmhacc_half_0:
12631 return RISCVISD::MHACC_HALF_0;
12632 case Intrinsic::riscv_pmhacc_half_1:
12633 return RISCVISD::MHACC_HALF_1;
12634 case Intrinsic::riscv_pmhaccsu_half_0:
12635 return RISCVISD::MHACCSU_HALF_0;
12636 case Intrinsic::riscv_pmhaccsu_half_1:
12637 return RISCVISD::MHACCSU_HALF_1;
12638 }
12639}
12640
12641/// Return the multiply-high-parts node for a multiply-high-parts intrinsic.
12642/// The scalar spelling maps to the same node; its product is the first
12643/// element.
12644static unsigned getRVPMulHighHalfOpcode(unsigned IntNo) {
12645 switch (IntNo) {
12646 default:
12647 llvm_unreachable("Unexpected RISC-V multiply high half intrinsic");
12648 case Intrinsic::riscv_pmulh_half_0:
12649 case Intrinsic::riscv_mulh_h0:
12650 return RISCVISD::MULH_HALF_0;
12651 case Intrinsic::riscv_pmulh_half_1:
12652 case Intrinsic::riscv_mulh_h1:
12653 return RISCVISD::MULH_HALF_1;
12654 case Intrinsic::riscv_pmulhsu_half_0:
12655 case Intrinsic::riscv_mulhsu_h0:
12656 return RISCVISD::MULHSU_HALF_0;
12657 case Intrinsic::riscv_pmulhsu_half_1:
12658 case Intrinsic::riscv_mulhsu_h1:
12659 return RISCVISD::MULHSU_HALF_1;
12660 }
12661}
12662
12664 switch (IntNo) {
12665 default:
12666 llvm_unreachable("Unexpected RISC-V packed Q-format accumulate intrinsic");
12667 case Intrinsic::riscv_mqacc_00:
12668 case Intrinsic::riscv_pmqacc_h00:
12669 return RISCVISD::MQACC_HALVES_00;
12670 case Intrinsic::riscv_mqacc_01:
12671 case Intrinsic::riscv_pmqacc_h01:
12672 return RISCVISD::MQACC_HALVES_01;
12673 case Intrinsic::riscv_mqacc_11:
12674 case Intrinsic::riscv_pmqacc_h11:
12675 return RISCVISD::MQACC_HALVES_11;
12676 case Intrinsic::riscv_mqracc_00:
12677 case Intrinsic::riscv_pmqracc_h00:
12678 return RISCVISD::MQRACC_HALVES_00;
12679 case Intrinsic::riscv_mqracc_01:
12680 case Intrinsic::riscv_pmqracc_h01:
12681 return RISCVISD::MQRACC_HALVES_01;
12682 case Intrinsic::riscv_mqracc_11:
12683 case Intrinsic::riscv_pmqracc_h11:
12684 return RISCVISD::MQRACC_HALVES_11;
12685 }
12686}
12687
12688static unsigned getRVPHorizontalMulOpcode(unsigned IntNo) {
12689 switch (IntNo) {
12690 default:
12691 llvm_unreachable("Unexpected RISC-V packed horizontal multiply intrinsic");
12692 case Intrinsic::riscv_pm4add:
12693 return RISCVISD::PM4ADD;
12694 case Intrinsic::riscv_pm2add:
12695 return RISCVISD::PM2ADD;
12696 case Intrinsic::riscv_pm2add_x:
12697 return RISCVISD::PM2ADD_X;
12698 case Intrinsic::riscv_pm4addu:
12699 return RISCVISD::PM4ADDU;
12700 case Intrinsic::riscv_pm2addu:
12701 return RISCVISD::PM2ADDU;
12702 case Intrinsic::riscv_pmq2add:
12703 return RISCVISD::PMQ2ADD;
12704 case Intrinsic::riscv_pmqr2add:
12705 return RISCVISD::PMQR2ADD;
12706 case Intrinsic::riscv_pm2sadd:
12707 return RISCVISD::PM2SADD;
12708 case Intrinsic::riscv_pm2sadd_x:
12709 return RISCVISD::PM2SADD_X;
12710 case Intrinsic::riscv_pm2sub:
12711 return RISCVISD::PM2SUB;
12712 case Intrinsic::riscv_pm2sub_x:
12713 return RISCVISD::PM2SUB_X;
12714 case Intrinsic::riscv_pm4addsu:
12715 return RISCVISD::PM4ADDSU;
12716 case Intrinsic::riscv_pm2addsu:
12717 return RISCVISD::PM2ADDSU;
12718 case Intrinsic::riscv_pm2wadd:
12719 return RISCVISD::PM2WADD;
12720 case Intrinsic::riscv_pm2wadd_x:
12721 return RISCVISD::PM2WADD_X;
12722 case Intrinsic::riscv_pm2waddu:
12723 return RISCVISD::PM2WADDU;
12724 case Intrinsic::riscv_pm2wsub:
12725 return RISCVISD::PM2WSUB;
12726 case Intrinsic::riscv_pm2wsub_x:
12727 return RISCVISD::PM2WSUB_X;
12728 case Intrinsic::riscv_pm2waddsu:
12729 return RISCVISD::PM2WADDSU;
12730 }
12731}
12732
12733static unsigned getRVPWideningMulAccOpcode(unsigned IntNo) {
12734 switch (IntNo) {
12735 default:
12736 llvm_unreachable("Unexpected RISC-V packed pwmacc intrinsic");
12737 case Intrinsic::riscv_pwmacc_i32x2:
12738 return RISCVISD::PWMACC_H;
12739 case Intrinsic::riscv_pwmaccu_u32x2:
12740 return RISCVISD::PWMACCU_H;
12741 case Intrinsic::riscv_pwmaccsu_i32x2:
12742 return RISCVISD::PWMACCSU_H;
12743 }
12744}
12745
12746static unsigned getRVPHorizontalMulAccOpcode(unsigned IntNo) {
12747 switch (IntNo) {
12748 default:
12750 "Unexpected RISC-V packed horizontal multiply-accumulate intrinsic");
12751 case Intrinsic::riscv_pm2wadda:
12752 return RISCVISD::PM2WADDA;
12753 case Intrinsic::riscv_pm2wadda_x:
12754 return RISCVISD::PM2WADDA_X;
12755 case Intrinsic::riscv_pm2waddau:
12756 return RISCVISD::PM2WADDAU;
12757 case Intrinsic::riscv_pm2wsuba:
12758 return RISCVISD::PM2WSUBA;
12759 case Intrinsic::riscv_pm2wsuba_x:
12760 return RISCVISD::PM2WSUBA_X;
12761 case Intrinsic::riscv_pm2waddasu:
12762 return RISCVISD::PM2WADDASU;
12763 }
12764}
12765
12766static unsigned getRVPMulAddAccOpcode(unsigned IntNo) {
12767 switch (IntNo) {
12768 default:
12769 llvm_unreachable("Unexpected RISC-V packed multiplication with horizontal "
12770 "addition/subtraction accumulate intrinsic");
12771 case Intrinsic::riscv_pm2adda:
12772 return RISCVISD::PM2ADDA;
12773 case Intrinsic::riscv_pm2adda_x:
12774 return RISCVISD::PM2ADDA_X;
12775 case Intrinsic::riscv_pm2addau:
12776 return RISCVISD::PM2ADDAU;
12777 case Intrinsic::riscv_pmq2adda:
12778 return RISCVISD::PMQ2ADDA;
12779 case Intrinsic::riscv_pmqr2adda:
12780 return RISCVISD::PMQR2ADDA;
12781 case Intrinsic::riscv_pm2suba:
12782 return RISCVISD::PM2SUBA;
12783 case Intrinsic::riscv_pm2suba_x:
12784 return RISCVISD::PM2SUBA_X;
12785 case Intrinsic::riscv_pm2addasu:
12786 return RISCVISD::PM2ADDASU;
12787 case Intrinsic::riscv_pm4adda:
12788 return RISCVISD::PM4ADDA;
12789 case Intrinsic::riscv_pm4addau:
12790 return RISCVISD::PM4ADDAU;
12791 case Intrinsic::riscv_pm4addasu:
12792 return RISCVISD::PM4ADDASU;
12793 }
12794}
12795
12796static SDValue lowerRV32HorizontalMul64(unsigned IntNo, SDValue Rs1,
12797 SDValue Rs2, const SDLoc &DL,
12798 SelectionDAG &DAG) {
12799 auto Extract = [&](SDValue V, unsigned Idx) {
12800 return DAG.getExtractVectorElt(DL, MVT::i32, V, Idx);
12801 };
12802
12803 if (Rs1.getSimpleValueType() == MVT::v2i16) {
12804 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
12805 SDValue Res =
12806 DAG.getNode(getRVPHorizontalMulOpcode(IntNo), DL, VTs, Rs1, Rs2);
12807 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Res, Res.getValue(1));
12808 }
12809
12810 if (Rs1.getSimpleValueType() == MVT::v4i16) {
12811 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
12812 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
12813 unsigned MulOpc, AccOpc;
12814 switch (IntNo) {
12815 default:
12816 llvm_unreachable("Unexpected RV32 horizontal multiply intrinsic");
12817 case Intrinsic::riscv_pm4add:
12818 MulOpc = RISCVISD::PM2WADD;
12819 AccOpc = RISCVISD::PM2WADDA;
12820 break;
12821 case Intrinsic::riscv_pm4addu:
12822 MulOpc = RISCVISD::PM2WADDU;
12823 AccOpc = RISCVISD::PM2WADDAU;
12824 break;
12825 case Intrinsic::riscv_pm4addsu:
12826 MulOpc = RISCVISD::PM2WADDSU;
12827 AccOpc = RISCVISD::PM2WADDASU;
12828 break;
12829 }
12830 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
12831 SDValue Acc = DAG.getNode(MulOpc, DL, VTs, Rs1Lo, Rs2Lo);
12832 Acc = DAG.getNode(AccOpc, DL, VTs, Acc, Acc.getValue(1), Rs1Hi, Rs2Hi);
12833 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Acc, Acc.getValue(1));
12834 }
12835
12836 assert(Rs1.getSimpleValueType() == MVT::v2i32 &&
12837 "Unexpected RV32 horizontal multiply source type");
12838 SDValue Rs1Lo = Extract(Rs1, 0);
12839 SDValue Rs1Hi = Extract(Rs1, 1);
12840 SDValue Rs2Lo = Extract(Rs2, 0);
12841 SDValue Rs2Hi = Extract(Rs2, 1);
12842
12843 if (IntNo == Intrinsic::riscv_pmq2add || IntNo == Intrinsic::riscv_pmqr2add) {
12844 unsigned AccOpc = IntNo == Intrinsic::riscv_pmq2add ? RISCVISD::MQWACC
12845 : RISCVISD::MQRWACC;
12846 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
12847 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
12848 SDValue Acc = DAG.getNode(AccOpc, DL, VTs, {Zero, Zero, Rs1Lo, Rs2Lo});
12849 Acc = DAG.getNode(AccOpc, DL, VTs, {Acc, Acc.getValue(1), Rs1Hi, Rs2Hi});
12850 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Acc, Acc.getValue(1));
12851 }
12852
12853 unsigned MulOpc = ISD::SMUL_LOHI;
12854 if (IntNo == Intrinsic::riscv_pm2addu)
12855 MulOpc = ISD::UMUL_LOHI;
12856 else if (IntNo == Intrinsic::riscv_pm2addsu)
12857 MulOpc = RISCVISD::WMULSU;
12858 bool IsSub =
12859 IntNo == Intrinsic::riscv_pm2sub || IntNo == Intrinsic::riscv_pm2sub_x;
12860 if (IntNo == Intrinsic::riscv_pm2add_x || IntNo == Intrinsic::riscv_pm2sub_x)
12861 std::swap(Rs2Lo, Rs2Hi);
12862
12863 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
12864 SDValue LoMul = DAG.getNode(MulOpc, DL, VTs, Rs1Lo, Rs2Lo);
12865 SDValue HiMul = DAG.getNode(MulOpc, DL, VTs, Rs1Hi, Rs2Hi);
12866 unsigned Opc = IsSub ? RISCVISD::SUBD : RISCVISD::ADDD;
12867 SDValue Res = DAG.getNode(Opc, DL, VTs, LoMul, LoMul.getValue(1), HiMul,
12868 HiMul.getValue(1));
12869 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Res, Res.getValue(1));
12870}
12871
12872/// Return the packed multiply-halves node for a multiply-parts intrinsic. The
12873/// scalar spelling maps to the same node; its product is the first element.
12874static unsigned getRVPMulHalvesOpcode(unsigned IntNo) {
12875 switch (IntNo) {
12876 default:
12877 llvm_unreachable("Unexpected RISC-V multiply-parts intrinsic");
12878 case Intrinsic::riscv_pmul_00:
12879 case Intrinsic::riscv_mul_00:
12880 return RISCVISD::PMUL_HALVES_00;
12881 case Intrinsic::riscv_pmul_01:
12882 case Intrinsic::riscv_mul_01:
12883 return RISCVISD::PMUL_HALVES_01;
12884 case Intrinsic::riscv_pmul_11:
12885 case Intrinsic::riscv_mul_11:
12886 return RISCVISD::PMUL_HALVES_11;
12887 case Intrinsic::riscv_pmulu_00:
12888 case Intrinsic::riscv_mulu_00:
12889 return RISCVISD::PMULU_HALVES_00;
12890 case Intrinsic::riscv_pmulu_01:
12891 case Intrinsic::riscv_mulu_01:
12892 return RISCVISD::PMULU_HALVES_01;
12893 case Intrinsic::riscv_pmulu_11:
12894 case Intrinsic::riscv_mulu_11:
12895 return RISCVISD::PMULU_HALVES_11;
12896 case Intrinsic::riscv_pmulsu_00:
12897 case Intrinsic::riscv_mulsu_00:
12898 return RISCVISD::PMULSU_HALVES_00;
12899 case Intrinsic::riscv_pmulsu_11:
12900 case Intrinsic::riscv_mulsu_11:
12901 return RISCVISD::PMULSU_HALVES_11;
12902 }
12903}
12904
12905/// Return the scalar multiply-parts intrinsic computing the first product of
12906/// packed intrinsic \p IntNo.
12908 switch (IntNo) {
12909 default:
12910 llvm_unreachable("Unexpected RISC-V packed multiply-parts intrinsic");
12911 case Intrinsic::riscv_pmul_00:
12912 return Intrinsic::riscv_mul_00;
12913 case Intrinsic::riscv_pmul_01:
12914 return Intrinsic::riscv_mul_01;
12915 case Intrinsic::riscv_pmul_11:
12916 return Intrinsic::riscv_mul_11;
12917 case Intrinsic::riscv_pmulu_00:
12918 return Intrinsic::riscv_mulu_00;
12919 case Intrinsic::riscv_pmulu_01:
12920 return Intrinsic::riscv_mulu_01;
12921 case Intrinsic::riscv_pmulu_11:
12922 return Intrinsic::riscv_mulu_11;
12923 case Intrinsic::riscv_pmulsu_00:
12924 return Intrinsic::riscv_mulsu_00;
12925 case Intrinsic::riscv_pmulsu_11:
12926 return Intrinsic::riscv_mulsu_11;
12927 }
12928}
12929
12930/// Return the accumulate form of multiply-parts intrinsic \p IntNo, or
12931/// Intrinsic::not_intrinsic if there is none.
12933 switch (IntNo) {
12934 default:
12936 case Intrinsic::riscv_mul_00:
12937 return Intrinsic::riscv_macc_00;
12938 case Intrinsic::riscv_pmul_00:
12939 return Intrinsic::riscv_pmacc_00;
12940 case Intrinsic::riscv_mul_01:
12941 return Intrinsic::riscv_macc_01;
12942 case Intrinsic::riscv_pmul_01:
12943 return Intrinsic::riscv_pmacc_01;
12944 case Intrinsic::riscv_mul_11:
12945 return Intrinsic::riscv_macc_11;
12946 case Intrinsic::riscv_pmul_11:
12947 return Intrinsic::riscv_pmacc_11;
12948 case Intrinsic::riscv_mulu_00:
12949 return Intrinsic::riscv_maccu_00;
12950 case Intrinsic::riscv_pmulu_00:
12951 return Intrinsic::riscv_pmaccu_00;
12952 case Intrinsic::riscv_mulu_01:
12953 return Intrinsic::riscv_maccu_01;
12954 case Intrinsic::riscv_pmulu_01:
12955 return Intrinsic::riscv_pmaccu_01;
12956 case Intrinsic::riscv_mulu_11:
12957 return Intrinsic::riscv_maccu_11;
12958 case Intrinsic::riscv_pmulu_11:
12959 return Intrinsic::riscv_pmaccu_11;
12960 case Intrinsic::riscv_mulsu_00:
12961 return Intrinsic::riscv_maccsu_00;
12962 case Intrinsic::riscv_pmulsu_00:
12963 return Intrinsic::riscv_pmaccsu_00;
12964 case Intrinsic::riscv_mulsu_11:
12965 return Intrinsic::riscv_maccsu_11;
12966 case Intrinsic::riscv_pmulsu_11:
12967 return Intrinsic::riscv_pmaccsu_11;
12968 }
12969}
12970
12971/// Return the multiply-parts accumulate node for \p IntNo.
12972static unsigned getRVPMulAccHalvesOpcode(unsigned IntNo) {
12973 switch (IntNo) {
12974 default:
12975 llvm_unreachable("Unexpected RISC-V multiply-parts accumulate intrinsic");
12976 case Intrinsic::riscv_pmacc_00:
12977 case Intrinsic::riscv_macc_00:
12978 return RISCVISD::PMACC_HALVES_00;
12979 case Intrinsic::riscv_pmacc_01:
12980 case Intrinsic::riscv_macc_01:
12981 return RISCVISD::PMACC_HALVES_01;
12982 case Intrinsic::riscv_pmacc_11:
12983 case Intrinsic::riscv_macc_11:
12984 return RISCVISD::PMACC_HALVES_11;
12985 case Intrinsic::riscv_pmaccu_00:
12986 case Intrinsic::riscv_maccu_00:
12987 return RISCVISD::PMACCU_HALVES_00;
12988 case Intrinsic::riscv_pmaccu_01:
12989 case Intrinsic::riscv_maccu_01:
12990 return RISCVISD::PMACCU_HALVES_01;
12991 case Intrinsic::riscv_pmaccu_11:
12992 case Intrinsic::riscv_maccu_11:
12993 return RISCVISD::PMACCU_HALVES_11;
12994 case Intrinsic::riscv_pmaccsu_00:
12995 case Intrinsic::riscv_maccsu_00:
12996 return RISCVISD::PMACCSU_HALVES_00;
12997 case Intrinsic::riscv_pmaccsu_11:
12998 case Intrinsic::riscv_maccsu_11:
12999 return RISCVISD::PMACCSU_HALVES_11;
13000 }
13001}
13002
13003/// Return {opcode, rs1 lane, rs2 lane} for the word form of \p IntNo.
13004static std::tuple<unsigned, unsigned, unsigned>
13006 switch (IntNo) {
13007 default:
13008 llvm_unreachable("Unexpected RISC-V multiply-parts intrinsic");
13009 case Intrinsic::riscv_mul_00:
13010 return {ISD::SMUL_LOHI, 0, 0};
13011 case Intrinsic::riscv_mul_01:
13012 return {ISD::SMUL_LOHI, 0, 1};
13013 case Intrinsic::riscv_mul_11:
13014 return {ISD::SMUL_LOHI, 1, 1};
13015 case Intrinsic::riscv_mulu_00:
13016 return {ISD::UMUL_LOHI, 0, 0};
13017 case Intrinsic::riscv_mulu_01:
13018 return {ISD::UMUL_LOHI, 0, 1};
13019 case Intrinsic::riscv_mulu_11:
13020 return {ISD::UMUL_LOHI, 1, 1};
13021 case Intrinsic::riscv_mulsu_00:
13022 return {RISCVISD::WMULSU, 0, 0};
13023 case Intrinsic::riscv_mulsu_11:
13024 return {RISCVISD::WMULSU, 1, 1};
13025 }
13026}
13027
13028/// Return {opcode, rs1 lane, rs2 lane} for the word form of accumulate
13029/// intrinsic \p IntNo.
13030static std::tuple<unsigned, unsigned, unsigned>
13032 switch (IntNo) {
13033 default:
13034 llvm_unreachable("Unexpected RISC-V multiply-parts accumulate intrinsic");
13035 case Intrinsic::riscv_macc_00:
13036 return {RISCVISD::WMACC, 0, 0};
13037 case Intrinsic::riscv_macc_01:
13038 return {RISCVISD::WMACC, 0, 1};
13039 case Intrinsic::riscv_macc_11:
13040 return {RISCVISD::WMACC, 1, 1};
13041 case Intrinsic::riscv_maccu_00:
13042 return {RISCVISD::WMACCU, 0, 0};
13043 case Intrinsic::riscv_maccu_01:
13044 return {RISCVISD::WMACCU, 0, 1};
13045 case Intrinsic::riscv_maccu_11:
13046 return {RISCVISD::WMACCU, 1, 1};
13047 case Intrinsic::riscv_maccsu_00:
13048 return {RISCVISD::WMACCSU, 0, 0};
13049 case Intrinsic::riscv_maccsu_11:
13050 return {RISCVISD::WMACCSU, 1, 1};
13051 }
13052}
13053
13055 SDValue V, MVT WideVT);
13056
13057SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
13058 SelectionDAG &DAG) const {
13059 unsigned IntNo = Op.getConstantOperandVal(0);
13060 SDLoc DL(Op);
13061 MVT XLenVT = Subtarget.getXLenVT();
13062
13063 switch (IntNo) {
13064 default:
13065 break; // Don't custom lower most intrinsics.
13066 case Intrinsic::riscv_tuple_insert: {
13067 SDValue Vec = Op.getOperand(1);
13068 SDValue SubVec = Op.getOperand(2);
13069 SDValue Index = Op.getOperand(3);
13070
13071 return DAG.getNode(RISCVISD::TUPLE_INSERT, DL, Op.getValueType(), Vec,
13072 SubVec, Index);
13073 }
13074 case Intrinsic::riscv_tuple_extract: {
13075 SDValue Vec = Op.getOperand(1);
13076 SDValue Index = Op.getOperand(2);
13077
13078 return DAG.getNode(RISCVISD::TUPLE_EXTRACT, DL, Op.getValueType(), Vec,
13079 Index);
13080 }
13081 case Intrinsic::thread_pointer: {
13082 EVT PtrVT = getPointerTy(DAG.getDataLayout());
13083 return DAG.getRegister(RISCV::X4, PtrVT);
13084 }
13085 case Intrinsic::riscv_pmul_00:
13086 case Intrinsic::riscv_pmul_01:
13087 case Intrinsic::riscv_pmul_11:
13088 case Intrinsic::riscv_pmulu_00:
13089 case Intrinsic::riscv_pmulu_01:
13090 case Intrinsic::riscv_pmulu_11:
13091 case Intrinsic::riscv_pmulsu_00:
13092 case Intrinsic::riscv_pmulsu_11: {
13093 MVT VT = Op.getSimpleValueType();
13094 SDValue Rs1 = Op.getOperand(1);
13095 SDValue Rs2 = Op.getOperand(2);
13096 unsigned Opc = getRVPMulHalvesOpcode(IntNo);
13097 if (!Subtarget.isPExtPackedDoubleType(VT))
13098 return DAG.getNode(Opc, DL, VT, Rs1, Rs2);
13099
13100 // On RV32 a 64-bit result lives in a GPR pair; compute each half with the
13101 // 32-bit form of the same product.
13102 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
13103 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13104 if (VT == MVT::v2i32) {
13105 // Each half is a single product, described by the scalar intrinsic.
13107 DL, MVT::i32);
13108 SDValue Lo =
13109 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, Id, Rs1Lo, Rs2Lo);
13110 SDValue Hi =
13111 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, Id, Rs1Hi, Rs2Hi);
13112 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Lo, Hi);
13113 }
13114 MVT HalfVT = VT.getHalfNumVectorElementsVT();
13115 SDValue Lo = DAG.getNode(Opc, DL, HalfVT, Rs1Lo, Rs2Lo);
13116 SDValue Hi = DAG.getNode(Opc, DL, HalfVT, Rs1Hi, Rs2Hi);
13117 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
13118 }
13119 case Intrinsic::riscv_pmacc_00:
13120 case Intrinsic::riscv_pmacc_01:
13121 case Intrinsic::riscv_pmacc_11:
13122 case Intrinsic::riscv_pmaccu_00:
13123 case Intrinsic::riscv_pmaccu_01:
13124 case Intrinsic::riscv_pmaccu_11:
13125 case Intrinsic::riscv_pmaccsu_00:
13126 case Intrinsic::riscv_pmaccsu_11:
13127 case Intrinsic::riscv_macc_00:
13128 case Intrinsic::riscv_macc_01:
13129 case Intrinsic::riscv_macc_11:
13130 case Intrinsic::riscv_maccu_00:
13131 case Intrinsic::riscv_maccu_01:
13132 case Intrinsic::riscv_maccu_11:
13133 case Intrinsic::riscv_maccsu_00:
13134 case Intrinsic::riscv_maccsu_11: {
13135 MVT VT = Op.getSimpleValueType();
13136 SDValue Rd = Op.getOperand(1);
13137 SDValue Rs1 = Op.getOperand(2);
13138 SDValue Rs2 = Op.getOperand(3);
13139 unsigned Opc = getRVPMulAccHalvesOpcode(IntNo);
13140 if (VT != MVT::v2i32 || !Subtarget.isPExtPackedDoubleType(VT))
13141 return DAG.getNode(Opc, DL, VT, Rd, Rs1, Rs2);
13142
13143 // On RV32 a 64-bit result lives in a GPR pair; accumulate each half with
13144 // the 32-bit form of the same product.
13145 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
13146 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13147 SDValue Lo =
13148 DAG.getNode(Opc, DL, MVT::i32,
13149 DAG.getExtractVectorElt(DL, MVT::i32, Rd, 0), Rs1Lo, Rs2Lo);
13150 SDValue Hi =
13151 DAG.getNode(Opc, DL, MVT::i32,
13152 DAG.getExtractVectorElt(DL, MVT::i32, Rd, 1), Rs1Hi, Rs2Hi);
13153 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Lo, Hi);
13154 }
13155 case Intrinsic::riscv_pas:
13156 case Intrinsic::riscv_psa:
13157 case Intrinsic::riscv_psas:
13158 case Intrinsic::riscv_pssa:
13159 case Intrinsic::riscv_paas:
13160 case Intrinsic::riscv_pasa: {
13161 // v2i32 has no paired instruction on RV32; split into a pair of i32 ops
13162 // with cross-lane operands. The exchange shape is: even result uses
13163 // (S1[0], S2[1]); odd result uses (S1[1], S2[0]).
13164 if (Subtarget.is64Bit() || Op.getSimpleValueType() != MVT::v2i32)
13165 break;
13166
13167 unsigned EvenOpc, OddOpc;
13168 switch (IntNo) {
13169 case Intrinsic::riscv_pas:
13170 EvenOpc = ISD::SUB;
13171 OddOpc = ISD::ADD;
13172 break;
13173 case Intrinsic::riscv_psa:
13174 EvenOpc = ISD::ADD;
13175 OddOpc = ISD::SUB;
13176 break;
13177 case Intrinsic::riscv_psas:
13178 EvenOpc = ISD::SSUBSAT;
13179 OddOpc = ISD::SADDSAT;
13180 break;
13181 case Intrinsic::riscv_pssa:
13182 EvenOpc = ISD::SADDSAT;
13183 OddOpc = ISD::SSUBSAT;
13184 break;
13185 case Intrinsic::riscv_paas:
13186 EvenOpc = ISD::AVGSUBFLOORS;
13187 OddOpc = ISD::AVGFLOORS;
13188 break;
13189 case Intrinsic::riscv_pasa:
13190 EvenOpc = ISD::AVGFLOORS;
13191 OddOpc = ISD::AVGSUBFLOORS;
13192 break;
13193 default:
13194 llvm_unreachable("Unexpected exchanged add/sub intrinsic");
13195 }
13196
13197 SDValue S1 = Op.getOperand(1);
13198 SDValue S2 = Op.getOperand(2);
13199 SDValue S1Even = DAG.getExtractVectorElt(DL, MVT::i32, S1, 0);
13200 SDValue S1Odd = DAG.getExtractVectorElt(DL, MVT::i32, S1, 1);
13201 SDValue S2Even = DAG.getExtractVectorElt(DL, MVT::i32, S2, 0);
13202 SDValue S2Odd = DAG.getExtractVectorElt(DL, MVT::i32, S2, 1);
13203
13204 SDValue REven = DAG.getNode(EvenOpc, DL, MVT::i32, S1Even, S2Odd);
13205 SDValue ROdd = DAG.getNode(OddOpc, DL, MVT::i32, S1Odd, S2Even);
13206 return DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, REven, ROdd);
13207 }
13208 case Intrinsic::riscv_orc_b:
13209 case Intrinsic::riscv_brev8:
13210 case Intrinsic::riscv_sha256sig0:
13211 case Intrinsic::riscv_sha256sig1:
13212 case Intrinsic::riscv_sha256sum0:
13213 case Intrinsic::riscv_sha256sum1:
13214 case Intrinsic::riscv_sm3p0:
13215 case Intrinsic::riscv_sm3p1: {
13216 unsigned Opc;
13217 switch (IntNo) {
13218 case Intrinsic::riscv_orc_b: Opc = RISCVISD::ORC_B; break;
13219 case Intrinsic::riscv_brev8: Opc = RISCVISD::BREV8; break;
13220 case Intrinsic::riscv_sha256sig0: Opc = RISCVISD::SHA256SIG0; break;
13221 case Intrinsic::riscv_sha256sig1: Opc = RISCVISD::SHA256SIG1; break;
13222 case Intrinsic::riscv_sha256sum0: Opc = RISCVISD::SHA256SUM0; break;
13223 case Intrinsic::riscv_sha256sum1: Opc = RISCVISD::SHA256SUM1; break;
13224 case Intrinsic::riscv_sm3p0: Opc = RISCVISD::SM3P0; break;
13225 case Intrinsic::riscv_sm3p1: Opc = RISCVISD::SM3P1; break;
13226 }
13227
13228 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1));
13229 }
13230 case Intrinsic::riscv_sm4ks:
13231 case Intrinsic::riscv_sm4ed: {
13232 unsigned Opc =
13233 IntNo == Intrinsic::riscv_sm4ks ? RISCVISD::SM4KS : RISCVISD::SM4ED;
13234
13235 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2),
13236 Op.getOperand(3));
13237 }
13238 case Intrinsic::riscv_zip:
13239 case Intrinsic::riscv_unzip: {
13240 unsigned Opc =
13241 IntNo == Intrinsic::riscv_zip ? RISCVISD::ZIP : RISCVISD::UNZIP;
13242 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1));
13243 }
13244 case Intrinsic::riscv_mopr:
13245 return DAG.getNode(RISCVISD::MOP_R, DL, XLenVT, Op.getOperand(1),
13246 Op.getOperand(2));
13247
13248 case Intrinsic::riscv_moprr: {
13249 return DAG.getNode(RISCVISD::MOP_RR, DL, XLenVT, Op.getOperand(1),
13250 Op.getOperand(2), Op.getOperand(3));
13251 }
13252 case Intrinsic::riscv_clmulh:
13253 case Intrinsic::riscv_clmulr: {
13254 unsigned Opc = IntNo == Intrinsic::riscv_clmulh ? ISD::CLMULH : ISD::CLMULR;
13255 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
13256 }
13257 case Intrinsic::riscv_paadd:
13258 case Intrinsic::riscv_paaddu:
13259 case Intrinsic::riscv_pasub:
13260 case Intrinsic::riscv_pasubu:
13261 case Intrinsic::riscv_pabd:
13262 case Intrinsic::riscv_pabdu:
13263 case Intrinsic::riscv_psabs: {
13264 unsigned Opc;
13265 switch (IntNo) {
13266 case Intrinsic::riscv_paadd:
13268 break;
13269 case Intrinsic::riscv_paaddu:
13271 break;
13272 case Intrinsic::riscv_pasub:
13274 break;
13275 case Intrinsic::riscv_pasubu:
13277 break;
13278 case Intrinsic::riscv_pabd:
13279 Opc = ISD::ABDS;
13280 break;
13281 case Intrinsic::riscv_pabdu:
13282 Opc = ISD::ABDU;
13283 break;
13284 case Intrinsic::riscv_psabs:
13285 Opc = RISCVISD::PSABS;
13286 break;
13287 }
13288
13289 if (IntNo == Intrinsic::riscv_psabs)
13290 return DAG.getNode(Opc, DL, Op.getValueType(), Op.getOperand(1));
13291
13292 return DAG.getNode(Opc, DL, Op.getValueType(), Op.getOperand(1),
13293 Op.getOperand(2));
13294 }
13295 case Intrinsic::riscv_pnclipp:
13296 case Intrinsic::riscv_pnclipup: {
13297 bool IsSigned = IntNo == Intrinsic::riscv_pnclipp;
13298 EVT VT = Op.getValueType();
13299 SDValue Rs1 = Op.getOperand(1);
13300 SDValue Rs2 = Op.getOperand(2);
13301 if (Subtarget.is64Bit()) {
13302 unsigned Opc = IsSigned ? RISCVISD::PNCLIPP : RISCVISD::PNCLIPUP;
13303 return DAG.getNode(Opc, DL, VT, Rs1, Rs2);
13304 }
13305
13306 SDValue Shift = DAG.getConstant(0, DL, XLenVT);
13307 if (VT == MVT::v4i8) {
13308 unsigned ClipOpc = IsSigned ? RISCVISD::PNCLIP : RISCVISD::PNCLIPU;
13309 SDValue Pair = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16, Rs1, Rs2);
13310 return DAG.getNode(ClipOpc, DL, VT, Pair, Shift);
13311 }
13312 if (VT == MVT::v2i16) {
13313 unsigned ClipOpc = IsSigned ? RISCVISD::PNCLIP : RISCVISD::PNCLIPU;
13314 SDValue Pair = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Rs1, Rs2);
13315 return DAG.getNode(ClipOpc, DL, VT, Pair, Shift);
13316 }
13317 if (VT == MVT::v2i32) {
13318 unsigned ClipOpc = IsSigned ? RISCVISD::NCLIP : RISCVISD::NCLIPU;
13319 auto [Rs1Lo, Rs1Hi] = DAG.SplitScalar(Rs1, DL, XLenVT, XLenVT);
13320 auto [Rs2Lo, Rs2Hi] = DAG.SplitScalar(Rs2, DL, XLenVT, XLenVT);
13321 SDValue Lo = DAG.getNode(ClipOpc, DL, XLenVT, Rs1Lo, Rs1Hi, Shift);
13322 SDValue Hi = DAG.getNode(ClipOpc, DL, XLenVT, Rs2Lo, Rs2Hi, Shift);
13323 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Lo, Hi);
13324 }
13325 if (VT == MVT::v8i8 || VT == MVT::v4i16) {
13326 unsigned ClipOpc = IsSigned ? RISCVISD::PNCLIP : RISCVISD::PNCLIPU;
13327 MVT HalfVT = VT == MVT::v8i8 ? MVT::v4i8 : MVT::v2i16;
13328 SDValue Lo = DAG.getNode(ClipOpc, DL, HalfVT, Rs1, Shift);
13329 SDValue Hi = DAG.getNode(ClipOpc, DL, HalfVT, Rs2, Shift);
13330 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
13331 }
13332
13333 llvm_unreachable("unexpected VT for pnclipp/pnclipup on RV32");
13334 }
13335 case Intrinsic::riscv_mqacc_00:
13336 case Intrinsic::riscv_mqacc_01:
13337 case Intrinsic::riscv_mqacc_11:
13338 case Intrinsic::riscv_mqracc_00:
13339 case Intrinsic::riscv_mqracc_01:
13340 case Intrinsic::riscv_mqracc_11:
13341 case Intrinsic::riscv_pmqacc_h00:
13342 case Intrinsic::riscv_pmqacc_h01:
13343 case Intrinsic::riscv_pmqacc_h11:
13344 case Intrinsic::riscv_pmqracc_h00:
13345 case Intrinsic::riscv_pmqracc_h01:
13346 case Intrinsic::riscv_pmqracc_h11: {
13347 EVT VT = Op.getValueType();
13348 SDValue Rd = Op.getOperand(1);
13349 SDValue Rs1 = Op.getOperand(2);
13350 SDValue Rs2 = Op.getOperand(3);
13351
13352 if (VT == MVT::v2i32 && Rs1.getSimpleValueType() == MVT::v4i16) {
13353 if (Subtarget.is64Bit()) {
13354 unsigned Opc = getRVPQFormatAccOpcode(IntNo);
13355 return DAG.getNode(Opc, DL, VT, Rd, Rs1, Rs2);
13356 }
13357
13358 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
13359 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13360 SDValue RdLo = DAG.getExtractVectorElt(DL, XLenVT, Rd, 0);
13361 SDValue RdHi = DAG.getExtractVectorElt(DL, XLenVT, Rd, 1);
13362 unsigned ScalarOpc = getRVPQFormatAccOpcode(IntNo);
13363 SDValue Lo = DAG.getNode(ScalarOpc, DL, XLenVT, RdLo, Rs1Lo, Rs2Lo);
13364 SDValue Hi = DAG.getNode(ScalarOpc, DL, XLenVT, RdHi, Rs1Hi, Rs2Hi);
13365 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Lo, Hi);
13366 }
13367
13368 if (VT == XLenVT) {
13369 unsigned Opc = getRVPQFormatAccOpcode(IntNo);
13370 return DAG.getNode(Opc, DL, XLenVT, Rd, Rs1, Rs2);
13371 }
13372
13373 return SDValue();
13374 }
13375 case Intrinsic::riscv_pmulq:
13376 case Intrinsic::riscv_pmulqr: {
13377 unsigned Opc;
13378 switch (IntNo) {
13379 case Intrinsic::riscv_pmulq:
13380 Opc = RISCVISD::MULQ;
13381 break;
13382 case Intrinsic::riscv_pmulqr:
13383 Opc = RISCVISD::MULQR;
13384 break;
13385 }
13386
13387 EVT VT = Op.getValueType();
13388 SDValue Rs1 = Op.getOperand(1);
13389 SDValue Rs2 = Op.getOperand(2);
13390
13391 // On RV32 the 64-bit packed vectors (v2i32, v4i16) have no single Q-format
13392 // multiply instruction. Split v4i16 into two v2i16 halves (each lowered to
13393 // a single pmulq.h/pmulqr.h via the existing patterns), and v2i32 into two
13394 // scalar mulq/mulqr (matched by the RV32 PatGprGpr patterns).
13395 if (!Subtarget.is64Bit()) {
13396 if (VT == MVT::v2i32) {
13397 SDValue Lo1 = DAG.getExtractVectorElt(DL, XLenVT, Rs1, 0);
13398 SDValue Lo2 = DAG.getExtractVectorElt(DL, XLenVT, Rs2, 0);
13399 SDValue Hi1 = DAG.getExtractVectorElt(DL, XLenVT, Rs1, 1);
13400 SDValue Hi2 = DAG.getExtractVectorElt(DL, XLenVT, Rs2, 1);
13401 SDValue LoRes = DAG.getNode(Opc, DL, XLenVT, Lo1, Lo2);
13402 SDValue HiRes = DAG.getNode(Opc, DL, XLenVT, Hi1, Hi2);
13403 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, LoRes, HiRes);
13404 }
13405 if (VT == MVT::v4i16) {
13406 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
13407 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13408 SDValue LoRes = DAG.getNode(Opc, DL, MVT::v2i16, Rs1Lo, Rs2Lo);
13409 SDValue HiRes = DAG.getNode(Opc, DL, MVT::v2i16, Rs1Hi, Rs2Hi);
13410 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoRes, HiRes);
13411 }
13412 }
13413
13414 return DAG.getNode(Opc, DL, VT, Rs1, Rs2);
13415 }
13416 case Intrinsic::riscv_psll:
13417 case Intrinsic::riscv_psrl:
13418 case Intrinsic::riscv_psra:
13419 case Intrinsic::riscv_pssha:
13420 case Intrinsic::riscv_psshar:
13421 case Intrinsic::riscv_psshl:
13422 case Intrinsic::riscv_psshlr: {
13423 SDValue ShAmt = Op.getOperand(2);
13424 ShAmt = DAG.getAnyExtOrTrunc(ShAmt, DL, XLenVT);
13425 return DAG.getNode(getRVPShiftOpcode(IntNo), DL, Op.getValueType(),
13426 Op.getOperand(1), ShAmt);
13427 }
13428 case Intrinsic::riscv_pwsll:
13429 case Intrinsic::riscv_pwsla: {
13430 MVT VT = Op.getSimpleValueType();
13431 SDValue Src = Op.getOperand(1);
13432 MVT SrcVT = Src.getSimpleValueType();
13433 if (!((VT == MVT::v4i16 && SrcVT == MVT::v4i8) ||
13434 (VT == MVT::v2i32 && SrcVT == MVT::v2i16)))
13435 reportFatalUsageError("unsupported packed widening shift intrinsic");
13436
13437 SDValue ShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op.getOperand(2));
13438 bool IsSigned = IntNo == Intrinsic::riscv_pwsla;
13439 if (!Subtarget.is64Bit()) {
13440 unsigned Opc = IsSigned ? RISCVISD::PWSLA : RISCVISD::PWSLL;
13441 return DAG.getNode(Opc, DL, VT, Src, ShAmt);
13442 }
13443
13444 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13445 SDValue Wide = DAG.getNode(ExtOpc, DL, VT, Src);
13446 return DAG.getNode(RISCVISD::PSLL, DL, VT, Wide, ShAmt);
13447 }
13448 case Intrinsic::riscv_pnsrl:
13449 case Intrinsic::riscv_pnsra:
13450 case Intrinsic::riscv_pnsrar:
13451 case Intrinsic::riscv_pnclipu:
13452 case Intrinsic::riscv_pnclipru:
13453 case Intrinsic::riscv_pnclip:
13454 case Intrinsic::riscv_pnclipr: {
13455 MVT VT = Op.getSimpleValueType();
13456 MVT SrcVT = Op.getOperand(1).getSimpleValueType();
13457 if (!((VT == MVT::v4i8 && SrcVT == MVT::v4i16) ||
13458 (VT == MVT::v2i16 && SrcVT == MVT::v2i32)))
13459 reportFatalUsageError("unsupported packed narrowing intrinsic");
13460
13461 SDValue ShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op.getOperand(2));
13462 return DAG.getNode(getRVPNarrowingOpcode(IntNo), DL, VT, Op.getOperand(1),
13463 ShAmt);
13464 }
13465 case Intrinsic::riscv_nclipu_u32:
13466 case Intrinsic::riscv_nclipru_u32:
13467 case Intrinsic::riscv_nsrar_i32:
13468 case Intrinsic::riscv_nclip_i32:
13469 case Intrinsic::riscv_nclipr_i32: {
13470 assert(!Subtarget.is64Bit() &&
13471 "RV64 should be handled during type legalization");
13472 auto [Lo, Hi] = DAG.SplitScalar(Op.getOperand(1), DL, MVT::i32, MVT::i32);
13473 SDValue ShAmt =
13474 getRVPScalarNarrowingShiftAmount(Op.getOperand(2), DL, MVT::i32, DAG);
13475 return DAG.getNode(getRVPScalarNarrowingOpcode(IntNo), DL, MVT::i32, Lo, Hi,
13476 ShAmt);
13477 }
13478 case Intrinsic::riscv_psati:
13479 case Intrinsic::riscv_pusati:
13480 case Intrinsic::riscv_sati:
13481 case Intrinsic::riscv_usati: {
13482 bool IsSigned =
13483 IntNo == Intrinsic::riscv_psati || IntNo == Intrinsic::riscv_sati;
13484 unsigned Opc = IsSigned ? RISCVISD::SATI : RISCVISD::USATI;
13485 return DAG.getNode(
13486 Opc, DL, Op.getValueType(), Op.getOperand(1),
13487 DAG.getTargetConstant(Op.getConstantOperandVal(2), DL, XLenVT));
13488 }
13489 case Intrinsic::riscv_psext_b:
13490 case Intrinsic::riscv_psext_h: {
13491 EVT VT = Op.getValueType();
13492 if (!VT.isSimple() || !Subtarget.isPExtPackedType(VT.getSimpleVT()))
13493 reportFatalUsageError("unsupported llvm.riscv.psext intrinsic");
13494
13495 MVT SimpleVT = VT.getSimpleVT();
13496 unsigned SrcEltBits = IntNo == Intrinsic::riscv_psext_b ? 8 : 16;
13497 if (SrcEltBits >= SimpleVT.getScalarSizeInBits())
13498 reportFatalUsageError("unsupported llvm.riscv.psext intrinsic");
13499
13500 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltBits),
13501 SimpleVT.getVectorElementCount());
13502 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, SimpleVT, Op.getOperand(1),
13503 DAG.getValueType(ExtVT));
13504 }
13505 case Intrinsic::riscv_pzext_b:
13506 case Intrinsic::riscv_pzext_h: {
13507 EVT VT = Op.getValueType();
13508 if (!VT.isSimple() || !Subtarget.isPExtPackedType(VT.getSimpleVT()))
13509 reportFatalUsageError("unsupported llvm.riscv.pzext intrinsic");
13510
13511 MVT SimpleVT = VT.getSimpleVT();
13512 unsigned SrcEltBits = IntNo == Intrinsic::riscv_pzext_b ? 8 : 16;
13513 if (SimpleVT.getScalarSizeInBits() != SrcEltBits * 2)
13514 reportFatalUsageError("unsupported llvm.riscv.pzext intrinsic");
13515
13516 return lowerPZExt(Op.getOperand(1), DL, DAG, Subtarget);
13517 }
13518 case Intrinsic::riscv_pabdsumu:
13519 case Intrinsic::riscv_pabdsumau: {
13520 // On RV32 an i32-result absolute difference sum over a 64-bit (GPRPair)
13521 // source has no paired instruction. Split into two v4i8 halves: reduce the
13522 // low half (folding in rd when accumulating), then accumulate the high half
13523 // into that partial sum.
13524 SDValue Rs1 = Op.getOperand(Op.getNumOperands() - 2);
13525 SDValue Rs2 = Op.getOperand(Op.getNumOperands() - 1);
13526 if (Subtarget.is64Bit() || Rs1.getSimpleValueType() != MVT::v8i8)
13527 return SDValue();
13528 bool IsAcc = IntNo == Intrinsic::riscv_pabdsumau;
13529 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
13530 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13531 SDValue AbdsumuId =
13532 DAG.getTargetConstant(Intrinsic::riscv_pabdsumu, DL, MVT::i32);
13533 SDValue AbdsumauId =
13534 DAG.getTargetConstant(Intrinsic::riscv_pabdsumau, DL, MVT::i32);
13535 SDValue Lo = IsAcc ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
13536 AbdsumauId, Op.getOperand(1), Rs1Lo, Rs2Lo)
13537 : DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
13538 AbdsumuId, Rs1Lo, Rs2Lo);
13539 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, AbdsumauId, Lo,
13540 Rs1Hi, Rs2Hi);
13541 }
13542 case Intrinsic::riscv_pmulhr:
13543 case Intrinsic::riscv_pmulhru:
13544 case Intrinsic::riscv_pmulhsu:
13545 case Intrinsic::riscv_pmulhrsu: {
13546 EVT VT = Op.getValueType();
13547 unsigned Opc = getRVPMulHighOpcode(IntNo);
13548
13549 // RV32 has no single instruction for 64-bit packed multiply high. Split
13550 // v4i16 into two v2i16 packed operations, and split v2i32 into scalar i32
13551 // operations so isel can use MULH*.
13552 if (!Subtarget.is64Bit() && VT == MVT::v4i16) {
13553 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Op.getOperand(1), DL);
13554 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Op.getOperand(2), DL);
13555 SDValue Lo = DAG.getNode(Opc, DL, MVT::v2i16, Rs1Lo, Rs2Lo);
13556 SDValue Hi = DAG.getNode(Opc, DL, MVT::v2i16, Rs1Hi, Rs2Hi);
13557 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
13558 }
13559
13560 if (!Subtarget.is64Bit() && VT == MVT::v2i32) {
13561 auto Extract = [&](SDValue V, unsigned Idx) {
13562 return DAG.getExtractVectorElt(DL, MVT::i32, V, Idx);
13563 };
13564 SDValue Rs1 = Op.getOperand(1);
13565 SDValue Rs2 = Op.getOperand(2);
13566 SDValue Lo =
13567 DAG.getNode(Opc, DL, MVT::i32, Extract(Rs1, 0), Extract(Rs2, 0));
13568 SDValue Hi =
13569 DAG.getNode(Opc, DL, MVT::i32, Extract(Rs1, 1), Extract(Rs2, 1));
13570 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Lo, Hi);
13571 }
13572
13573 return DAG.getNode(Opc, DL, VT, Op.getOperand(1), Op.getOperand(2));
13574 }
13575 case Intrinsic::riscv_aadd_i32:
13576 case Intrinsic::riscv_aaddu_u32:
13577 case Intrinsic::riscv_asub_i32:
13578 case Intrinsic::riscv_asubu_u32:
13579 case Intrinsic::riscv_ssh1sadd_i32:
13580 case Intrinsic::riscv_mseq_u32:
13581 case Intrinsic::riscv_mslt_i32:
13582 case Intrinsic::riscv_msltu_u32:
13583 case Intrinsic::riscv_mulhr_i32:
13584 case Intrinsic::riscv_mulhru_u32:
13585 case Intrinsic::riscv_mulhsu_i32:
13586 case Intrinsic::riscv_mulhrsu_i32:
13587 case Intrinsic::riscv_mulq_i32:
13588 case Intrinsic::riscv_mulqr_i32:
13589 case Intrinsic::riscv_mhacc_i32:
13590 case Intrinsic::riscv_mhracc_i32:
13591 case Intrinsic::riscv_mhaccu_u32:
13592 case Intrinsic::riscv_mhraccu_u32:
13593 case Intrinsic::riscv_mhaccsu_i32:
13594 case Intrinsic::riscv_mhraccsu_i32: {
13595 // RV32 selects the scalar P instructions directly. RV64 goes via
13596 // ReplaceNodeResults.
13597 unsigned Opc = getRVPScalarOpcode(IntNo);
13599 return DAG.getNode(Opc, DL, MVT::i32, Ops);
13600 }
13601 case Intrinsic::riscv_mqwacc_i64:
13602 case Intrinsic::riscv_mqrwacc_i64: {
13603 // RV32 goes via ReplaceNodeResults. RV64 uses mqacc.w00 on the low words.
13604 unsigned Opc = IntNo == Intrinsic::riscv_mqwacc_i64
13605 ? RISCVISD::MQACC_HALVES_00
13606 : RISCVISD::MQRACC_HALVES_00;
13607 SDValue Rs1 =
13608 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32, Op.getOperand(2));
13609 SDValue Rs2 =
13610 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32, Op.getOperand(3));
13611 return DAG.getNode(Opc, DL, MVT::i64, Op.getOperand(1), Rs1, Rs2);
13612 }
13613 case Intrinsic::riscv_pmhacc:
13614 case Intrinsic::riscv_pmhracc:
13615 case Intrinsic::riscv_pmhaccu:
13616 case Intrinsic::riscv_pmhraccu:
13617 case Intrinsic::riscv_pmhaccsu:
13618 case Intrinsic::riscv_pmhraccsu: {
13619 EVT VT = Op.getValueType();
13620 unsigned MulOpc = getRVPMulHighAccumulateOpcode(IntNo);
13621 SDValue Rd = Op.getOperand(1);
13622 SDValue Rs1 = Op.getOperand(2);
13623 SDValue Rs2 = Op.getOperand(3);
13624
13625 // RV32 has no single instruction for 64-bit packed multiply high
13626 // accumulate. Split v4i16 into two v2i16 packed operations, and split
13627 // v2i32 into scalar i32 operations.
13628 if (!Subtarget.is64Bit() && VT == MVT::v4i16) {
13629 auto [RdLo, RdHi] = DAG.SplitVector(Rd, DL);
13630 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
13631 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13632 SDValue Lo = DAG.getNode(MulOpc, DL, MVT::v2i16, RdLo, Rs1Lo, Rs2Lo);
13633 SDValue Hi = DAG.getNode(MulOpc, DL, MVT::v2i16, RdHi, Rs1Hi, Rs2Hi);
13634 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
13635 }
13636
13637 if (!Subtarget.is64Bit() && VT == MVT::v2i32) {
13638 auto Extract = [&](SDValue V, unsigned Idx) {
13639 return DAG.getExtractVectorElt(DL, MVT::i32, V, Idx);
13640 };
13641 SDValue Lo = DAG.getNode(MulOpc, DL, MVT::i32, Extract(Rd, 0),
13642 Extract(Rs1, 0), Extract(Rs2, 0));
13643 SDValue Hi = DAG.getNode(MulOpc, DL, MVT::i32, Extract(Rd, 1),
13644 Extract(Rs1, 1), Extract(Rs2, 1));
13645 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Lo, Hi);
13646 }
13647
13648 return DAG.getNode(MulOpc, DL, VT, Rd, Rs1, Rs2);
13649 }
13650 case Intrinsic::riscv_pmhacc_half_0:
13651 case Intrinsic::riscv_pmhacc_half_1:
13652 case Intrinsic::riscv_pmhaccsu_half_0:
13653 case Intrinsic::riscv_pmhaccsu_half_1: {
13654 EVT VT = Op.getValueType();
13655 unsigned Opc = getRVPMulHighAccumulateHalfOpcode(IntNo);
13656 SDValue Rd = Op.getOperand(1);
13657 SDValue Rs1 = Op.getOperand(2);
13658 SDValue Rs2 = Op.getOperand(3);
13659
13660 // RV32: split v4i16 into two v2i16 operations
13661 if (!Subtarget.is64Bit() && VT == MVT::v4i16) {
13662 auto [RdLo, RdHi] = DAG.SplitVector(Rd, DL);
13663 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
13664 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13665 SDValue Lo = DAG.getNode(Opc, DL, MVT::v2i16, RdLo, Rs1Lo, Rs2Lo);
13666 SDValue Hi = DAG.getNode(Opc, DL, MVT::v2i16, RdHi, Rs1Hi, Rs2Hi);
13667 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
13668 }
13669
13670 // RV32 has no 64-bit packed form: split into two scalar operations, each
13671 // accumulating one word of the result.
13672 if (!Subtarget.is64Bit() && VT == MVT::v2i32) {
13673 auto Extract = [&](SDValue V, unsigned Idx) {
13674 return DAG.getExtractVectorElt(DL, MVT::i32, V, Idx);
13675 };
13676 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13677 SDValue Lo = DAG.getNode(Opc, DL, MVT::i32, Extract(Rd, 0),
13678 Extract(Rs1, 0), Rs2Lo);
13679 SDValue Hi = DAG.getNode(Opc, DL, MVT::i32, Extract(Rd, 1),
13680 Extract(Rs1, 1), Rs2Hi);
13681 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Lo, Hi);
13682 }
13683
13684 return DAG.getNode(Opc, DL, VT, Rd, Rs1, Rs2);
13685 }
13686 case Intrinsic::riscv_pmulh_half_0:
13687 case Intrinsic::riscv_pmulh_half_1:
13688 case Intrinsic::riscv_pmulhsu_half_0:
13689 case Intrinsic::riscv_pmulhsu_half_1: {
13690 EVT VT = Op.getValueType();
13691 SDValue Rs1 = Op.getOperand(1);
13692 SDValue Rs2 = Op.getOperand(2);
13693 unsigned Opc = getRVPMulHighHalfOpcode(IntNo);
13694
13695 // RV32 has no single instruction for a 64-bit packed multiply-high parts.
13696 // Split v4i16 into two v2i16 packed operations.
13697 if (!Subtarget.is64Bit() && VT == MVT::v4i16) {
13698 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
13699 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13700 SDValue Lo = DAG.getNode(Opc, DL, MVT::v2i16, Rs1Lo, Rs2Lo);
13701 SDValue Hi = DAG.getNode(Opc, DL, MVT::v2i16, Rs1Hi, Rs2Hi);
13702 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
13703 }
13704
13705 // RV32 has no single instruction for a 64-bit packed word multiply-high
13706 // parts. Split v2i32 into two scalar operations, one per result word.
13707 if (!Subtarget.is64Bit() && VT == MVT::v2i32) {
13708 auto Extract = [&](SDValue V, unsigned Idx) {
13709 return DAG.getExtractVectorElt(DL, MVT::i32, V, Idx);
13710 };
13711 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13712 SDValue Lo = DAG.getNode(Opc, DL, MVT::i32, Extract(Rs1, 0), Rs2Lo);
13713 SDValue Hi = DAG.getNode(Opc, DL, MVT::i32, Extract(Rs1, 1), Rs2Hi);
13714 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Lo, Hi);
13715 }
13716
13717 return DAG.getNode(Opc, DL, VT, Rs1, Rs2);
13718 }
13719 case Intrinsic::riscv_pmqwacc_i32x2:
13720 case Intrinsic::riscv_pmqrwacc_i32x2: {
13721 EVT VT = Op.getValueType();
13722 SDValue Acc = Op.getOperand(1);
13723 SDValue Rs1 = Op.getOperand(2);
13724 SDValue Rs2 = Op.getOperand(3);
13725
13726 if (!Subtarget.is64Bit()) {
13727 unsigned Opc = IntNo == Intrinsic::riscv_pmqwacc_i32x2
13728 ? RISCVISD::PMQWACC_H
13729 : RISCVISD::PMQRWACC_H;
13730 return DAG.getNode(Opc, DL, VT, Acc, Rs1, Rs2);
13731 }
13732
13733 Rs1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16, Rs1,
13734 DAG.getUNDEF(MVT::v2i16));
13735 Rs2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16, Rs2,
13736 DAG.getUNDEF(MVT::v2i16));
13737 SDValue Zip = DAG.getNode(RISCVISD::PZIP, DL, MVT::v4i16, Rs1, Rs2);
13738 unsigned Opc = IntNo == Intrinsic::riscv_pmqwacc_i32x2
13739 ? RISCVISD::MQACC_HALVES_01
13740 : RISCVISD::MQRACC_HALVES_01;
13741 return DAG.getNode(Opc, DL, VT, Acc, Zip, Zip);
13742 }
13743 case Intrinsic::riscv_mulh_h0:
13744 case Intrinsic::riscv_mulh_h1:
13745 case Intrinsic::riscv_mulhsu_h0:
13746 case Intrinsic::riscv_mulhsu_h1: {
13747 // mulh.h0/h1 exist only on RV32 and pmulh.w.h0/h1 only on RV64; the
13748 // other XLEN lowers the scalar intrinsic via the packed form in
13749 // ReplaceNodeResults.
13750 EVT VT = Op.getValueType();
13751 if (VT != MVT::i32 || Subtarget.is64Bit())
13752 return SDValue();
13753
13754 SDValue Rs1 = Op.getOperand(1);
13755 SDValue Rs2 = Op.getOperand(2);
13756 unsigned Opc = getRVPMulHighHalfOpcode(IntNo);
13757 return DAG.getNode(Opc, DL, VT, Rs1, Rs2);
13758 }
13759 case Intrinsic::riscv_pm4add:
13760 case Intrinsic::riscv_pm2add:
13761 case Intrinsic::riscv_pm2add_x:
13762 case Intrinsic::riscv_pm4addu:
13763 case Intrinsic::riscv_pm2addu:
13764 case Intrinsic::riscv_pmq2add:
13765 case Intrinsic::riscv_pmqr2add:
13766 case Intrinsic::riscv_pm2sadd:
13767 case Intrinsic::riscv_pm2sadd_x:
13768 case Intrinsic::riscv_pm2sub:
13769 case Intrinsic::riscv_pm2sub_x:
13770 case Intrinsic::riscv_pm4addsu:
13771 case Intrinsic::riscv_pm2addsu: {
13772 EVT VT = Op.getValueType();
13773 unsigned Opc = getRVPHorizontalMulOpcode(IntNo);
13774 SDValue Rs1 = Op.getOperand(1);
13775 SDValue Rs2 = Op.getOperand(2);
13776
13777 // RV32 applies the 32-bit instruction independently to both halves of a
13778 // 64-bit packed input.
13779 if (!Subtarget.is64Bit() && VT == MVT::v2i32) {
13780 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
13781 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13782 SDValue Lo = DAG.getNode(Opc, DL, MVT::i32, Rs1Lo, Rs2Lo);
13783 SDValue Hi = DAG.getNode(Opc, DL, MVT::i32, Rs1Hi, Rs2Hi);
13784 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Lo, Hi);
13785 }
13786
13787 return DAG.getNode(Opc, DL, VT, Rs1, Rs2);
13788 }
13789 case Intrinsic::riscv_pwmacc_i32x2:
13790 case Intrinsic::riscv_pwmaccu_u32x2:
13791 case Intrinsic::riscv_pwmaccsu_i32x2: {
13792 EVT VT = Op.getValueType();
13793 SDValue Acc = Op.getOperand(1);
13794 SDValue Rs1 = Op.getOperand(2);
13795 SDValue Rs2 = Op.getOperand(3);
13796
13797 if (Subtarget.is64Bit()) {
13798 // Per the spec decomposition table: a single zip16p puts the
13799 // halfwords of Rs1 in the even elements and those of Rs2 in the odd
13800 // elements (the su form uses the pwcvtu.wh spelling, zip16p with x0).
13801 // pmacc.w.h01 then multiplies the even elements of the first source
13802 // by the odd elements of the second source into rd. RV32 selects the
13803 // pwmacc.h family on the register pair instead.
13804 Rs1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16, Rs1,
13805 DAG.getUNDEF(MVT::v2i16));
13806 Rs2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16, Rs2,
13807 DAG.getUNDEF(MVT::v2i16));
13808 if (IntNo == Intrinsic::riscv_pwmaccsu_i32x2) {
13809 SDValue Zero = DAG.getConstant(0, DL, MVT::v4i16);
13810 Rs1 = DAG.getNode(RISCVISD::PZIP, DL, MVT::v4i16, Rs1, Zero);
13811 Rs2 = DAG.getNode(RISCVISD::PZIP, DL, MVT::v4i16, Rs2, Zero);
13812 return DAG.getNode(RISCVISD::PMACCSU_HALVES_00, DL, VT, Acc, Rs1, Rs2);
13813 }
13814 SDValue Zip = DAG.getNode(RISCVISD::PZIP, DL, MVT::v4i16, Rs1, Rs2);
13815 unsigned Opc = IntNo == Intrinsic::riscv_pwmaccu_u32x2
13816 ? RISCVISD::PMACCU_HALVES_01
13817 : RISCVISD::PMACC_HALVES_01;
13818 return DAG.getNode(Opc, DL, VT, Acc, Zip, Zip);
13819 }
13820
13821 // RV32 uses pwmacc.h/pwmaccsu.h on the 64-bit accumulator register
13822 // pair, represented as a single v2i32 value.
13823 return DAG.getNode(getRVPWideningMulAccOpcode(IntNo), DL, VT, Acc, Rs1,
13824 Rs2);
13825 }
13826 case Intrinsic::riscv_pm2wadd:
13827 case Intrinsic::riscv_pm2wadd_x:
13828 case Intrinsic::riscv_pm2waddu:
13829 case Intrinsic::riscv_pm2wsub:
13830 case Intrinsic::riscv_pm2wsub_x:
13831 case Intrinsic::riscv_pm2waddsu: {
13832 // These intrinsics only have a dedicated widening instruction on RV32
13833 // (handled in ReplaceNodeResults). On RV64 the i64 result type is legal,
13834 // so synthesize the equivalent value directly at i64 width: the add forms
13835 // zero-extend their operands to v4i16 and reuse pm4add(u/su).h, relying on
13836 // zero lanes contributing zero products (the "_x" exchanged form
13837 // additionally swaps rs2's halfwords via ppairoe.h first); the sub forms
13838 // extract and sign-extend each halfword lane and compute the product
13839 // difference with plain i64 arithmetic. A custom RISCVISD opcode must
13840 // never be the direct result of an i32-producing DAG.getNode here: i32 is
13841 // not a legal type on RV64 (only i64 has a register class), and the
13842 // generic legalizer's post-hoc promotion of such a "naked" custom-opcode
13843 // node mis-widens its vector operands instead of leaving the node alone.
13844 assert(Subtarget.is64Bit() && Op.getValueType() == MVT::i64 &&
13845 "Unexpected widening horizontal multiply-add legalization");
13846 SDValue Rs1 = Op.getOperand(1);
13847 SDValue Rs2 = Op.getOperand(2);
13848
13849 if (IntNo == Intrinsic::riscv_pm2wsub ||
13850 IntNo == Intrinsic::riscv_pm2wsub_x) {
13851 // Route through the existing riscv_pm2sub(_x) intrinsic (a plain
13852 // ISD::INTRINSIC_WO_CHAIN, which is registered Custom for i32 on RV64)
13853 // rather than calling RISCVISD::PM2SUB(_X) directly: a "naked" custom
13854 // opcode freshly materialized here with an i32 result hits the same
13855 // legalizer trap described above, but INTRINSIC_WO_CHAIN's i32 action
13856 // is a recognized Custom target that correctly re-enters LowerOperation.
13857 unsigned SubIntNo = IntNo == Intrinsic::riscv_pm2wsub
13858 ? Intrinsic::riscv_pm2sub
13859 : Intrinsic::riscv_pm2sub_x;
13860 SDValue IntrId = DAG.getTargetConstant(SubIntNo, DL, MVT::i64);
13861 SDValue Res =
13862 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, IntrId, Rs1, Rs2);
13863 return DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Res);
13864 }
13865
13866 auto WidenAny = [&](SDValue V) {
13867 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16, V,
13868 DAG.getUNDEF(MVT::v2i16));
13869 };
13870
13871 SDValue A = WidenAny(Rs1);
13872 SDValue B;
13873 if (IntNo == Intrinsic::riscv_pm2wadd_x) {
13874 SDValue Rs2Wide = widenPackedVectorWithZeros(DAG, DL, Rs2, MVT::v4i16);
13875 B = DAG.getNode(RISCVISD::PPAIROE, DL, MVT::v4i16, Rs2Wide, Rs2Wide);
13876 } else {
13877 B = widenPackedVectorWithZeros(DAG, DL, Rs2, MVT::v4i16);
13878 }
13879
13880 unsigned MulOpc = IntNo == Intrinsic::riscv_pm2waddu ? RISCVISD::PM4ADDU
13881 : IntNo == Intrinsic::riscv_pm2waddsu ? RISCVISD::PM4ADDSU
13882 : RISCVISD::PM4ADD;
13883 return DAG.getNode(MulOpc, DL, MVT::i64, A, B);
13884 }
13885 case Intrinsic::riscv_pm2wadda:
13886 case Intrinsic::riscv_pm2wadda_x:
13887 case Intrinsic::riscv_pm2waddau:
13888 case Intrinsic::riscv_pm2wsuba:
13889 case Intrinsic::riscv_pm2wsuba_x:
13890 case Intrinsic::riscv_pm2waddasu: {
13891
13892 assert(Subtarget.is64Bit() && Op.getValueType() == MVT::i64 &&
13893 "Unexpected widening horizontal multiply-accumulate legalization");
13894 SDValue Rd = Op.getOperand(1);
13895 SDValue Rs1 = Op.getOperand(2);
13896 SDValue Rs2 = Op.getOperand(3);
13897
13898 auto WidenAnyAcc = [&](SDValue V) {
13899 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16, V,
13900 DAG.getUNDEF(MVT::v2i16));
13901 };
13902 SDValue A = WidenAnyAcc(Rs1);
13903
13904 if (IntNo == Intrinsic::riscv_pm2wsuba ||
13905 IntNo == Intrinsic::riscv_pm2wsuba_x) {
13906
13907 SDValue B = widenPackedVectorWithZeros(DAG, DL, Rs2, MVT::v4i16);
13908 unsigned SubOpc = IntNo == Intrinsic::riscv_pm2wsuba ? RISCVISD::PM2SUB
13909 : RISCVISD::PM2SUB_X;
13910 SDValue Packed = DAG.getNode(SubOpc, DL, MVT::v2i32, A, B);
13911 SDValue SumId =
13912 DAG.getTargetConstant(Intrinsic::riscv_predsum, DL, MVT::i64);
13913 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, SumId, Packed,
13914 Rd);
13915 }
13916
13917 SDValue B;
13918 if (IntNo == Intrinsic::riscv_pm2wadda_x) {
13919 SDValue Rs2Wide = widenPackedVectorWithZeros(DAG, DL, Rs2, MVT::v4i16);
13920 B = DAG.getNode(RISCVISD::PPAIROE, DL, MVT::v4i16, Rs2Wide, Rs2Wide);
13921 } else {
13922 B = widenPackedVectorWithZeros(DAG, DL, Rs2, MVT::v4i16);
13923 }
13924
13925 unsigned AccOpc = IntNo == Intrinsic::riscv_pm2waddau ? RISCVISD::PM4ADDAU
13926 : IntNo == Intrinsic::riscv_pm2waddasu
13927 ? RISCVISD::PM4ADDASU
13928 : RISCVISD::PM4ADDA;
13929 return DAG.getNode(AccOpc, DL, MVT::i64, Rd, A, B);
13930 }
13931 case Intrinsic::riscv_pm2adda:
13932 case Intrinsic::riscv_pm2adda_x:
13933 case Intrinsic::riscv_pm2addau:
13934 case Intrinsic::riscv_pmq2adda:
13935 case Intrinsic::riscv_pmqr2adda:
13936 case Intrinsic::riscv_pm2suba:
13937 case Intrinsic::riscv_pm2suba_x:
13938 case Intrinsic::riscv_pm2addasu:
13939 case Intrinsic::riscv_pm4adda:
13940 case Intrinsic::riscv_pm4addau:
13941 case Intrinsic::riscv_pm4addasu: {
13942 MVT VT = Op.getSimpleValueType();
13943 SDValue Rd = Op.getOperand(1);
13944 SDValue Rs1 = Op.getOperand(2);
13945 SDValue Rs2 = Op.getOperand(3);
13946 unsigned Opc = getRVPMulAddAccOpcode(IntNo);
13947
13948 if (VT == Subtarget.getXLenVT())
13949 return DAG.getNode(Opc, DL, VT, Rd, Rs1, Rs2);
13950
13951 assert(VT == MVT::v2i32 &&
13952 "Unexpected packed multiply-horizontal-add-accumulate result");
13953 if (Subtarget.is64Bit())
13954 return DAG.getNode(Opc, DL, VT, Rd, Rs1, Rs2);
13955
13956 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
13957 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
13958 SDValue RdLo = DAG.getExtractVectorElt(DL, MVT::i32, Rd, 0);
13959 SDValue RdHi = DAG.getExtractVectorElt(DL, MVT::i32, Rd, 1);
13960 SDValue Lo = DAG.getNode(Opc, DL, MVT::i32, RdLo, Rs1Lo, Rs2Lo);
13961 SDValue Hi = DAG.getNode(Opc, DL, MVT::i32, RdHi, Rs1Hi, Rs2Hi);
13962 return DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
13963 }
13964 case Intrinsic::riscv_pmerge: {
13965 EVT VT = Op.getValueType();
13966 // 64-bit packed types on RV32: split into two 32-bit halves.
13967 if (!Subtarget.is64Bit() && (VT == MVT::v8i8 || VT == MVT::v4i16)) {
13968 MVT HalfVT = VT == MVT::v8i8 ? MVT::v4i8 : MVT::v2i16;
13969 auto [Rs1Lo, Rs1Hi] =
13970 DAG.SplitVector(Op.getOperand(1), DL, HalfVT, HalfVT);
13971 auto [Rs2Lo, Rs2Hi] =
13972 DAG.SplitVector(Op.getOperand(2), DL, HalfVT, HalfVT);
13973 auto [MaskLo, MaskHi] =
13974 DAG.SplitVector(Op.getOperand(3), DL, HalfVT, HalfVT);
13975 SDValue ResLo =
13976 DAG.getNode(RISCVISD::MERGE, DL, HalfVT, MaskLo, Rs1Lo, Rs2Lo);
13977 SDValue ResHi =
13978 DAG.getNode(RISCVISD::MERGE, DL, HalfVT, MaskHi, Rs1Hi, Rs2Hi);
13979 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
13980 }
13981
13982 // v2i32 has no legal 32-bit vector half, so merge each i32 element.
13983 if (!Subtarget.is64Bit() && VT == MVT::v2i32) {
13984 SDValue Elts[2];
13985 for (unsigned I = 0; I != 2; ++I) {
13986 SDValue Rs1 =
13987 DAG.getExtractVectorElt(DL, MVT::i32, Op.getOperand(1), I);
13988 SDValue Rs2 =
13989 DAG.getExtractVectorElt(DL, MVT::i32, Op.getOperand(2), I);
13990 SDValue Mask =
13991 DAG.getExtractVectorElt(DL, MVT::i32, Op.getOperand(3), I);
13992 Elts[I] = DAG.getNode(RISCVISD::MERGE, DL, MVT::i32, Mask, Rs1, Rs2);
13993 }
13994 return DAG.getBuildVector(VT, DL, Elts);
13995 }
13996
13997 return DAG.getNode(RISCVISD::MERGE, DL, VT, Op.getOperand(3),
13998 Op.getOperand(1), Op.getOperand(2));
13999 }
14000 case Intrinsic::experimental_get_vector_length:
14001 return lowerGetVectorLength(Op.getNode(), DAG, Subtarget);
14002 case Intrinsic::riscv_vmv_x_s: {
14003 SDValue Res = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Op.getOperand(1));
14004 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Res);
14005 }
14006 case Intrinsic::riscv_vfmv_f_s:
14007 return DAG.getExtractVectorElt(DL, Op.getValueType(), Op.getOperand(1), 0);
14008 case Intrinsic::riscv_vmv_v_x:
14009 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
14010 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
14011 Subtarget);
14012 case Intrinsic::riscv_vfmv_v_f:
14013 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
14014 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14015 case Intrinsic::riscv_vmv_s_x: {
14016 SDValue Scalar = Op.getOperand(2);
14017
14018 if (Scalar.getValueType().bitsLE(XLenVT)) {
14019 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
14020 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
14021 Op.getOperand(1), Scalar, Op.getOperand(3));
14022 }
14023
14024 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
14025
14026 // This is an i64 value that lives in two scalar registers. We have to
14027 // insert this in a convoluted way. First we build vXi64 splat containing
14028 // the two values that we assemble using some bit math. Next we'll use
14029 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
14030 // to merge element 0 from our splat into the source vector.
14031 // FIXME: This is probably not the best way to do this, but it is
14032 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
14033 // point.
14034 // sw lo, (a0)
14035 // sw hi, 4(a0)
14036 // vlse vX, (a0)
14037 //
14038 // vid.v vVid
14039 // vmseq.vx mMask, vVid, 0
14040 // vmerge.vvm vDest, vSrc, vVal, mMask
14041 MVT VT = Op.getSimpleValueType();
14042 SDValue Vec = Op.getOperand(1);
14043 SDValue VL = getVLOperand(Op);
14044
14045 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
14046 if (Op.getOperand(1).isUndef())
14047 return SplattedVal;
14048 SDValue SplattedIdx =
14049 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
14050 DAG.getConstant(0, DL, MVT::i32), VL);
14051
14052 MVT MaskVT = getMaskTypeFor(VT);
14053 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
14054 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
14055 SDValue SelectCond =
14056 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT,
14057 {VID, SplattedIdx, DAG.getCondCode(ISD::SETEQ),
14058 DAG.getUNDEF(MaskVT), Mask, VL});
14059 return DAG.getNode(RISCVISD::VMERGE_VL, DL, VT, SelectCond, SplattedVal,
14060 Vec, DAG.getUNDEF(VT), VL);
14061 }
14062 case Intrinsic::riscv_vfmv_s_f:
14063 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, Op.getValueType(),
14064 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14065 // EGS * EEW >= 128 bits
14066 case Intrinsic::riscv_vaesdf_vv:
14067 case Intrinsic::riscv_vaesdf_vs:
14068 case Intrinsic::riscv_vaesdm_vv:
14069 case Intrinsic::riscv_vaesdm_vs:
14070 case Intrinsic::riscv_vaesef_vv:
14071 case Intrinsic::riscv_vaesef_vs:
14072 case Intrinsic::riscv_vaesem_vv:
14073 case Intrinsic::riscv_vaesem_vs:
14074 case Intrinsic::riscv_vaeskf1:
14075 case Intrinsic::riscv_vaeskf2:
14076 case Intrinsic::riscv_vaesz_vs:
14077 case Intrinsic::riscv_vsm4k:
14078 case Intrinsic::riscv_vsm4r_vv:
14079 case Intrinsic::riscv_vsm4r_vs: {
14080 if (!isValidEGW(4, Op.getSimpleValueType(), Subtarget) ||
14081 !isValidEGW(4, Op->getOperand(1).getSimpleValueType(), Subtarget) ||
14082 !isValidEGW(4, Op->getOperand(2).getSimpleValueType(), Subtarget))
14083 reportFatalUsageError("EGW should be greater than or equal to 4 * SEW.");
14084 return Op;
14085 }
14086 // EGS * EEW >= 256 bits
14087 case Intrinsic::riscv_vsm3c:
14088 case Intrinsic::riscv_vsm3me: {
14089 if (!isValidEGW(8, Op.getSimpleValueType(), Subtarget) ||
14090 !isValidEGW(8, Op->getOperand(1).getSimpleValueType(), Subtarget))
14091 reportFatalUsageError("EGW should be greater than or equal to 8 * SEW.");
14092 return Op;
14093 }
14094 // zvknha(SEW=32)/zvknhb(SEW=[32|64])
14095 case Intrinsic::riscv_vsha2ch:
14096 case Intrinsic::riscv_vsha2cl:
14097 case Intrinsic::riscv_vsha2ms: {
14098 if (Op->getSimpleValueType(0).getScalarSizeInBits() == 64 &&
14099 !Subtarget.hasStdExtZvknhb())
14100 reportFatalUsageError("SEW=64 needs Zvknhb to be enabled.");
14101 if (!isValidEGW(4, Op.getSimpleValueType(), Subtarget) ||
14102 !isValidEGW(4, Op->getOperand(1).getSimpleValueType(), Subtarget) ||
14103 !isValidEGW(4, Op->getOperand(2).getSimpleValueType(), Subtarget))
14104 reportFatalUsageError("EGW should be greater than or equal to 4 * SEW.");
14105 return Op;
14106 }
14107 case Intrinsic::riscv_sf_vc_v_x:
14108 case Intrinsic::riscv_sf_vc_v_i:
14109 case Intrinsic::riscv_sf_vc_v_xv:
14110 case Intrinsic::riscv_sf_vc_v_iv:
14111 case Intrinsic::riscv_sf_vc_v_vv:
14112 case Intrinsic::riscv_sf_vc_v_fv:
14113 case Intrinsic::riscv_sf_vc_v_xvv:
14114 case Intrinsic::riscv_sf_vc_v_ivv:
14115 case Intrinsic::riscv_sf_vc_v_vvv:
14116 case Intrinsic::riscv_sf_vc_v_fvv:
14117 case Intrinsic::riscv_sf_vc_v_xvw:
14118 case Intrinsic::riscv_sf_vc_v_ivw:
14119 case Intrinsic::riscv_sf_vc_v_vvw:
14120 case Intrinsic::riscv_sf_vc_v_fvw: {
14121 MVT VT = Op.getSimpleValueType();
14122
14123 SmallVector<SDValue> Operands{Op->op_values()};
14125
14126 MVT RetVT = VT;
14127 if (VT.isFixedLengthVector())
14129 else if (VT.isFloatingPoint())
14132
14133 SDValue NewNode = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, RetVT, Operands);
14134
14135 if (VT.isFixedLengthVector())
14136 NewNode = convertFromScalableVector(VT, NewNode, DAG, Subtarget);
14137 else if (VT.isFloatingPoint())
14138 NewNode = DAG.getBitcast(VT, NewNode);
14139
14140 if (Op == NewNode)
14141 break;
14142
14143 return NewNode;
14144 }
14145 }
14146
14147 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
14148}
14149
14151 unsigned Type) {
14152 SDLoc DL(Op);
14153 SmallVector<SDValue> Operands{Op->op_values()};
14154 Operands.erase(Operands.begin() + 1);
14155
14156 const RISCVSubtarget &Subtarget =
14158 MVT VT = Op.getSimpleValueType();
14159 MVT RetVT = VT;
14160 MVT FloatVT = VT;
14161
14162 if (VT.isFloatingPoint()) {
14163 RetVT = MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits()),
14164 VT.getVectorElementCount());
14165 FloatVT = RetVT;
14166 }
14167 if (VT.isFixedLengthVector())
14169
14171
14172 SDVTList VTs = DAG.getVTList({RetVT, MVT::Other});
14173 SDValue NewNode = DAG.getNode(Type, DL, VTs, Operands);
14174 SDValue Chain = NewNode.getValue(1);
14175
14176 if (VT.isFixedLengthVector())
14177 NewNode = convertFromScalableVector(FloatVT, NewNode, DAG, Subtarget);
14178 if (VT.isFloatingPoint())
14179 NewNode = DAG.getBitcast(VT, NewNode);
14180
14181 NewNode = DAG.getMergeValues({NewNode, Chain}, DL);
14182
14183 return NewNode;
14184}
14185
14187 unsigned Type) {
14188 SmallVector<SDValue> Operands{Op->op_values()};
14189 Operands.erase(Operands.begin() + 1);
14191
14192 return DAG.getNode(Type, SDLoc(Op), Op.getValueType(), Operands);
14193}
14194
14195static SDValue
14198 SelectionDAG &DAG) {
14199 bool IsStrided;
14200 switch (IntNo) {
14201 case Intrinsic::riscv_seg2_load_mask:
14202 case Intrinsic::riscv_seg3_load_mask:
14203 case Intrinsic::riscv_seg4_load_mask:
14204 case Intrinsic::riscv_seg5_load_mask:
14205 case Intrinsic::riscv_seg6_load_mask:
14206 case Intrinsic::riscv_seg7_load_mask:
14207 case Intrinsic::riscv_seg8_load_mask:
14208 IsStrided = false;
14209 break;
14210 case Intrinsic::riscv_sseg2_load_mask:
14211 case Intrinsic::riscv_sseg3_load_mask:
14212 case Intrinsic::riscv_sseg4_load_mask:
14213 case Intrinsic::riscv_sseg5_load_mask:
14214 case Intrinsic::riscv_sseg6_load_mask:
14215 case Intrinsic::riscv_sseg7_load_mask:
14216 case Intrinsic::riscv_sseg8_load_mask:
14217 IsStrided = true;
14218 break;
14219 default:
14220 llvm_unreachable("unexpected intrinsic ID");
14221 };
14222
14223 static const Intrinsic::ID VlsegInts[7] = {
14224 Intrinsic::riscv_vlseg2_mask, Intrinsic::riscv_vlseg3_mask,
14225 Intrinsic::riscv_vlseg4_mask, Intrinsic::riscv_vlseg5_mask,
14226 Intrinsic::riscv_vlseg6_mask, Intrinsic::riscv_vlseg7_mask,
14227 Intrinsic::riscv_vlseg8_mask};
14228 static const Intrinsic::ID VlssegInts[7] = {
14229 Intrinsic::riscv_vlsseg2_mask, Intrinsic::riscv_vlsseg3_mask,
14230 Intrinsic::riscv_vlsseg4_mask, Intrinsic::riscv_vlsseg5_mask,
14231 Intrinsic::riscv_vlsseg6_mask, Intrinsic::riscv_vlsseg7_mask,
14232 Intrinsic::riscv_vlsseg8_mask};
14233
14234 SDLoc DL(Op);
14235 unsigned NF = Op->getNumValues() - 1;
14236 assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
14237 MVT XLenVT = Subtarget.getXLenVT();
14238 MVT VT = Op->getSimpleValueType(0);
14240 unsigned Sz = NF * ContainerVT.getVectorMinNumElements() *
14241 ContainerVT.getScalarSizeInBits();
14242 EVT VecTupTy = MVT::getRISCVVectorTupleVT(Sz, NF);
14243
14244 // Operands: (chain, int_id, pointer, mask, vl) or
14245 // (chain, int_id, pointer, offset, mask, vl)
14246 SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
14247 SDValue Mask = Op.getOperand(Op.getNumOperands() - 2);
14248 MVT MaskVT = Mask.getSimpleValueType();
14249 MVT MaskContainerVT = ::getContainerForFixedLengthVector(MaskVT, Subtarget);
14250 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
14251
14252 SDValue IntID = DAG.getTargetConstant(
14253 IsStrided ? VlssegInts[NF - 2] : VlsegInts[NF - 2], DL, XLenVT);
14255
14256 SDVTList VTs = DAG.getVTList({VecTupTy, MVT::Other});
14258 Load->getChain(),
14259 IntID,
14260 DAG.getUNDEF(VecTupTy),
14261 Op.getOperand(2),
14262 Mask,
14263 VL,
14266 DAG.getTargetConstant(Log2_64(VT.getScalarSizeInBits()), DL, XLenVT)};
14267 // Insert the stride operand.
14268 if (IsStrided)
14269 Ops.insert(std::next(Ops.begin(), 4), Op.getOperand(3));
14270
14271 SDValue Result =
14273 Load->getMemoryVT(), Load->getMemOperand());
14275 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) {
14276 SDValue SubVec = DAG.getNode(RISCVISD::TUPLE_EXTRACT, DL, ContainerVT,
14277 Result.getValue(0),
14278 DAG.getTargetConstant(RetIdx, DL, MVT::i32));
14279 Results.push_back(convertFromScalableVector(VT, SubVec, DAG, Subtarget));
14280 }
14281 Results.push_back(Result.getValue(1));
14282 return DAG.getMergeValues(Results, DL);
14283}
14284
14285SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
14286 SelectionDAG &DAG) const {
14287 unsigned IntNo = Op.getConstantOperandVal(1);
14288 switch (IntNo) {
14289 default:
14290 break;
14291 case Intrinsic::riscv_seg2_load_mask:
14292 case Intrinsic::riscv_seg3_load_mask:
14293 case Intrinsic::riscv_seg4_load_mask:
14294 case Intrinsic::riscv_seg5_load_mask:
14295 case Intrinsic::riscv_seg6_load_mask:
14296 case Intrinsic::riscv_seg7_load_mask:
14297 case Intrinsic::riscv_seg8_load_mask:
14298 case Intrinsic::riscv_sseg2_load_mask:
14299 case Intrinsic::riscv_sseg3_load_mask:
14300 case Intrinsic::riscv_sseg4_load_mask:
14301 case Intrinsic::riscv_sseg5_load_mask:
14302 case Intrinsic::riscv_sseg6_load_mask:
14303 case Intrinsic::riscv_sseg7_load_mask:
14304 case Intrinsic::riscv_sseg8_load_mask:
14305 return lowerFixedVectorSegLoadIntrinsics(IntNo, Op, Subtarget, DAG);
14306
14307 case Intrinsic::riscv_sf_vc_v_x_se:
14308 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_X_SE);
14309 case Intrinsic::riscv_sf_vc_v_i_se:
14310 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_I_SE);
14311 case Intrinsic::riscv_sf_vc_v_xv_se:
14312 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_XV_SE);
14313 case Intrinsic::riscv_sf_vc_v_iv_se:
14314 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_IV_SE);
14315 case Intrinsic::riscv_sf_vc_v_vv_se:
14316 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_VV_SE);
14317 case Intrinsic::riscv_sf_vc_v_fv_se:
14318 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_FV_SE);
14319 case Intrinsic::riscv_sf_vc_v_xvv_se:
14320 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_XVV_SE);
14321 case Intrinsic::riscv_sf_vc_v_ivv_se:
14322 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_IVV_SE);
14323 case Intrinsic::riscv_sf_vc_v_vvv_se:
14324 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_VVV_SE);
14325 case Intrinsic::riscv_sf_vc_v_fvv_se:
14326 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_FVV_SE);
14327 case Intrinsic::riscv_sf_vc_v_xvw_se:
14328 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_XVW_SE);
14329 case Intrinsic::riscv_sf_vc_v_ivw_se:
14330 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_IVW_SE);
14331 case Intrinsic::riscv_sf_vc_v_vvw_se:
14332 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_VVW_SE);
14333 case Intrinsic::riscv_sf_vc_v_fvw_se:
14334 return getVCIXISDNodeWCHAIN(Op, DAG, RISCVISD::SF_VC_V_FVW_SE);
14335 }
14336
14337 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
14338}
14339
14340static SDValue
14343 SelectionDAG &DAG) {
14344 bool IsStrided;
14345 switch (IntNo) {
14346 case Intrinsic::riscv_seg2_store_mask:
14347 case Intrinsic::riscv_seg3_store_mask:
14348 case Intrinsic::riscv_seg4_store_mask:
14349 case Intrinsic::riscv_seg5_store_mask:
14350 case Intrinsic::riscv_seg6_store_mask:
14351 case Intrinsic::riscv_seg7_store_mask:
14352 case Intrinsic::riscv_seg8_store_mask:
14353 IsStrided = false;
14354 break;
14355 case Intrinsic::riscv_sseg2_store_mask:
14356 case Intrinsic::riscv_sseg3_store_mask:
14357 case Intrinsic::riscv_sseg4_store_mask:
14358 case Intrinsic::riscv_sseg5_store_mask:
14359 case Intrinsic::riscv_sseg6_store_mask:
14360 case Intrinsic::riscv_sseg7_store_mask:
14361 case Intrinsic::riscv_sseg8_store_mask:
14362 IsStrided = true;
14363 break;
14364 default:
14365 llvm_unreachable("unexpected intrinsic ID");
14366 }
14367
14368 SDLoc DL(Op);
14369 static const Intrinsic::ID VssegInts[] = {
14370 Intrinsic::riscv_vsseg2_mask, Intrinsic::riscv_vsseg3_mask,
14371 Intrinsic::riscv_vsseg4_mask, Intrinsic::riscv_vsseg5_mask,
14372 Intrinsic::riscv_vsseg6_mask, Intrinsic::riscv_vsseg7_mask,
14373 Intrinsic::riscv_vsseg8_mask};
14374 static const Intrinsic::ID VsssegInts[] = {
14375 Intrinsic::riscv_vssseg2_mask, Intrinsic::riscv_vssseg3_mask,
14376 Intrinsic::riscv_vssseg4_mask, Intrinsic::riscv_vssseg5_mask,
14377 Intrinsic::riscv_vssseg6_mask, Intrinsic::riscv_vssseg7_mask,
14378 Intrinsic::riscv_vssseg8_mask};
14379
14380 // Operands: (chain, int_id, vec*, ptr, mask, vl) or
14381 // (chain, int_id, vec*, ptr, stride, mask, vl)
14382 unsigned NF = Op->getNumOperands() - (IsStrided ? 6 : 5);
14383 assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
14384 MVT XLenVT = Subtarget.getXLenVT();
14385 MVT VT = Op->getOperand(2).getSimpleValueType();
14387 unsigned Sz = NF * ContainerVT.getVectorMinNumElements() *
14388 ContainerVT.getScalarSizeInBits();
14389 EVT VecTupTy = MVT::getRISCVVectorTupleVT(Sz, NF);
14390
14391 SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
14392 SDValue Mask = Op.getOperand(Op.getNumOperands() - 2);
14393 MVT MaskVT = Mask.getSimpleValueType();
14394 MVT MaskContainerVT = ::getContainerForFixedLengthVector(MaskVT, Subtarget);
14395 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
14396
14397 SDValue IntID = DAG.getTargetConstant(
14398 IsStrided ? VsssegInts[NF - 2] : VssegInts[NF - 2], DL, XLenVT);
14399 SDValue Ptr = Op->getOperand(NF + 2);
14400
14401 auto *FixedIntrinsic = cast<MemIntrinsicSDNode>(Op);
14402
14403 SDValue StoredVal = DAG.getUNDEF(VecTupTy);
14404 for (unsigned i = 0; i < NF; i++)
14405 StoredVal = DAG.getNode(
14406 RISCVISD::TUPLE_INSERT, DL, VecTupTy, StoredVal,
14407 convertToScalableVector(ContainerVT, FixedIntrinsic->getOperand(2 + i),
14408 DAG, Subtarget),
14409 DAG.getTargetConstant(i, DL, MVT::i32));
14410
14412 FixedIntrinsic->getChain(),
14413 IntID,
14414 StoredVal,
14415 Ptr,
14416 Mask,
14417 VL,
14418 DAG.getTargetConstant(Log2_64(VT.getScalarSizeInBits()), DL, XLenVT)};
14419 // Insert the stride operand.
14420 if (IsStrided)
14421 Ops.insert(std::next(Ops.begin(), 4),
14422 Op.getOperand(Op.getNumOperands() - 3));
14423
14424 return DAG.getMemIntrinsicNode(
14425 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Ops,
14426 FixedIntrinsic->getMemoryVT(), FixedIntrinsic->getMemOperand());
14427}
14428
14429SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
14430 SelectionDAG &DAG) const {
14431 unsigned IntNo = Op.getConstantOperandVal(1);
14432 switch (IntNo) {
14433 default:
14434 break;
14435 case Intrinsic::riscv_seg2_store_mask:
14436 case Intrinsic::riscv_seg3_store_mask:
14437 case Intrinsic::riscv_seg4_store_mask:
14438 case Intrinsic::riscv_seg5_store_mask:
14439 case Intrinsic::riscv_seg6_store_mask:
14440 case Intrinsic::riscv_seg7_store_mask:
14441 case Intrinsic::riscv_seg8_store_mask:
14442 case Intrinsic::riscv_sseg2_store_mask:
14443 case Intrinsic::riscv_sseg3_store_mask:
14444 case Intrinsic::riscv_sseg4_store_mask:
14445 case Intrinsic::riscv_sseg5_store_mask:
14446 case Intrinsic::riscv_sseg6_store_mask:
14447 case Intrinsic::riscv_sseg7_store_mask:
14448 case Intrinsic::riscv_sseg8_store_mask:
14449 return lowerFixedVectorSegStoreIntrinsics(IntNo, Op, Subtarget, DAG);
14450
14451 case Intrinsic::riscv_sf_vc_xv_se:
14452 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_XV_SE);
14453 case Intrinsic::riscv_sf_vc_iv_se:
14454 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_IV_SE);
14455 case Intrinsic::riscv_sf_vc_vv_se:
14456 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_VV_SE);
14457 case Intrinsic::riscv_sf_vc_fv_se:
14458 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_FV_SE);
14459 case Intrinsic::riscv_sf_vc_xvv_se:
14460 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_XVV_SE);
14461 case Intrinsic::riscv_sf_vc_ivv_se:
14462 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_IVV_SE);
14463 case Intrinsic::riscv_sf_vc_vvv_se:
14464 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_VVV_SE);
14465 case Intrinsic::riscv_sf_vc_fvv_se:
14466 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_FVV_SE);
14467 case Intrinsic::riscv_sf_vc_xvw_se:
14468 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_XVW_SE);
14469 case Intrinsic::riscv_sf_vc_ivw_se:
14470 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_IVW_SE);
14471 case Intrinsic::riscv_sf_vc_vvw_se:
14472 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_VVW_SE);
14473 case Intrinsic::riscv_sf_vc_fvw_se:
14474 return getVCIXISDNodeVOID(Op, DAG, RISCVISD::SF_VC_FVW_SE);
14475 }
14476
14477 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
14478}
14479
14480static unsigned getRVVReductionOp(unsigned ISDOpcode) {
14481 switch (ISDOpcode) {
14482 default:
14483 llvm_unreachable("Unhandled reduction");
14484 case ISD::VP_REDUCE_ADD:
14485 case ISD::VECREDUCE_ADD:
14486 return RISCVISD::VECREDUCE_ADD_VL;
14487 case ISD::VP_REDUCE_UMAX:
14489 return RISCVISD::VECREDUCE_UMAX_VL;
14490 case ISD::VP_REDUCE_SMAX:
14492 return RISCVISD::VECREDUCE_SMAX_VL;
14493 case ISD::VP_REDUCE_UMIN:
14495 return RISCVISD::VECREDUCE_UMIN_VL;
14496 case ISD::VP_REDUCE_SMIN:
14498 return RISCVISD::VECREDUCE_SMIN_VL;
14499 case ISD::VP_REDUCE_AND:
14500 case ISD::VECREDUCE_AND:
14501 return RISCVISD::VECREDUCE_AND_VL;
14502 case ISD::VP_REDUCE_OR:
14503 case ISD::VECREDUCE_OR:
14504 return RISCVISD::VECREDUCE_OR_VL;
14505 case ISD::VP_REDUCE_XOR:
14506 case ISD::VECREDUCE_XOR:
14507 return RISCVISD::VECREDUCE_XOR_VL;
14508 case ISD::VP_REDUCE_FADD:
14509 return RISCVISD::VECREDUCE_FADD_VL;
14510 case ISD::VP_REDUCE_SEQ_FADD:
14511 return RISCVISD::VECREDUCE_SEQ_FADD_VL;
14512 case ISD::VP_REDUCE_FMAX:
14513 case ISD::VP_REDUCE_FMAXIMUM:
14514 return RISCVISD::VECREDUCE_FMAX_VL;
14515 case ISD::VP_REDUCE_FMIN:
14516 case ISD::VP_REDUCE_FMINIMUM:
14517 return RISCVISD::VECREDUCE_FMIN_VL;
14518 }
14519
14520}
14521
14522SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
14523 SelectionDAG &DAG,
14524 bool IsVP) const {
14525 SDLoc DL(Op);
14526 SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
14527 MVT VecVT = Vec.getSimpleValueType();
14528 assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
14529 Op.getOpcode() == ISD::VECREDUCE_OR ||
14530 Op.getOpcode() == ISD::VECREDUCE_XOR ||
14531 Op.getOpcode() == ISD::VP_REDUCE_AND ||
14532 Op.getOpcode() == ISD::VP_REDUCE_OR ||
14533 Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
14534 "Unexpected reduction lowering");
14535
14536 MVT XLenVT = Subtarget.getXLenVT();
14537
14538 MVT ContainerVT = VecVT;
14539 if (VecVT.isFixedLengthVector()) {
14541 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
14542 }
14543
14544 SDValue Mask, VL;
14545 if (IsVP) {
14546 Mask = Op.getOperand(2);
14547 if (VecVT.isFixedLengthVector())
14548 Mask = convertToScalableVector(ContainerVT, Mask, DAG, Subtarget);
14549 VL = Op.getOperand(3);
14550 } else {
14551 std::tie(Mask, VL) =
14552 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
14553 }
14554
14556 switch (Op.getOpcode()) {
14557 default:
14558 llvm_unreachable("Unhandled reduction");
14559 case ISD::VECREDUCE_AND:
14560 case ISD::VP_REDUCE_AND: {
14561 // vcpop ~x == 0
14562 if (VecVT.isFixedLengthVector())
14563 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec,
14565 else
14566 Vec = DAG.getNOT(DL, Vec, ContainerVT);
14567 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
14568 CC = ISD::SETEQ;
14569 break;
14570 }
14571 case ISD::VECREDUCE_OR:
14572 case ISD::VP_REDUCE_OR:
14573 // vcpop x != 0
14574 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
14575 CC = ISD::SETNE;
14576 break;
14577 case ISD::VECREDUCE_XOR:
14578 case ISD::VP_REDUCE_XOR: {
14579 // ((vcpop x) & 1) != 0
14580 SDValue One = DAG.getConstant(1, DL, XLenVT);
14581 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
14582 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
14583 CC = ISD::SETNE;
14584 break;
14585 }
14586 }
14587
14588 SDValue Zero = DAG.getConstant(0, DL, XLenVT);
14589 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
14590 SetCC = DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), SetCC);
14591
14592 if (!IsVP)
14593 return SetCC;
14594
14595 // Now include the start value in the operation.
14596 // Note that we must return the start value when no elements are operated
14597 // upon. The vcpop instructions we've emitted in each case above will return
14598 // 0 for an inactive vector, and so we've already received the neutral value:
14599 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
14600 // can simply include the start value.
14601 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
14602 return DAG.getNode(BaseOpc, DL, Op.getValueType(), SetCC, Op.getOperand(0));
14603}
14604
14605static bool isNonZeroAVL(SDValue AVL) {
14606 auto *RegisterAVL = dyn_cast<RegisterSDNode>(AVL);
14607 auto *ImmAVL = dyn_cast<ConstantSDNode>(AVL);
14608 return (RegisterAVL && RegisterAVL->getReg() == RISCV::X0) ||
14609 (ImmAVL && ImmAVL->getZExtValue() >= 1);
14610}
14611
14612/// Helper to lower a reduction sequence of the form:
14613/// scalar = reduce_op vec, scalar_start
14614static SDValue lowerReductionSeq(unsigned RVVOpcode, MVT ResVT,
14615 SDValue StartValue, SDValue Vec, SDValue Mask,
14616 SDValue VL, const SDLoc &DL, SelectionDAG &DAG,
14617 const RISCVSubtarget &Subtarget) {
14618 const MVT VecVT = Vec.getSimpleValueType();
14619 const MVT M1VT = RISCVTargetLowering::getM1VT(VecVT);
14620 const MVT XLenVT = Subtarget.getXLenVT();
14621 const bool NonZeroAVL = isNonZeroAVL(VL);
14622
14623 // The reduction needs an LMUL1 input; do the splat at either LMUL1
14624 // or the original VT if fractional.
14625 auto InnerVT = VecVT.bitsLE(M1VT) ? VecVT : M1VT;
14626 // We reuse the VL of the reduction to reduce vsetvli toggles if we can
14627 // prove it is non-zero. For the AVL=0 case, we need the scalar to
14628 // be the result of the reduction operation.
14629 auto InnerVL = NonZeroAVL ? VL : DAG.getConstant(1, DL, XLenVT);
14630 SDValue InitialValue =
14631 lowerScalarInsert(StartValue, InnerVL, InnerVT, DL, DAG, Subtarget);
14632 if (M1VT != InnerVT)
14633 InitialValue =
14634 DAG.getInsertSubvector(DL, DAG.getUNDEF(M1VT), InitialValue, 0);
14635 SDValue PassThru = NonZeroAVL ? DAG.getUNDEF(M1VT) : InitialValue;
14637 SDValue Ops[] = {PassThru, Vec, InitialValue, Mask, VL, Policy};
14638 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, Ops);
14639 return DAG.getExtractVectorElt(DL, ResVT, Reduction, 0);
14640}
14641
14642SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
14643 SelectionDAG &DAG) const {
14644 SDLoc DL(Op);
14645 SDValue Vec = Op.getOperand(0);
14646 EVT VecEVT = Vec.getValueType();
14647
14648 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
14649
14650 // Due to ordering in legalize types we may have a vector type that needs to
14651 // be split. Do that manually so we can get down to a legal type.
14652 while (getTypeAction(*DAG.getContext(), VecEVT) ==
14654 auto [Lo, Hi] = DAG.SplitVector(Vec, DL);
14655 VecEVT = Lo.getValueType();
14656 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
14657 }
14658
14659 // TODO: The type may need to be widened rather than split. Or widened before
14660 // it can be split.
14661 if (!isTypeLegal(VecEVT))
14662 return SDValue();
14663
14664 MVT VecVT = VecEVT.getSimpleVT();
14665 MVT VecEltVT = VecVT.getVectorElementType();
14666 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
14667
14668 MVT ContainerVT = VecVT;
14669 if (VecVT.isFixedLengthVector()) {
14671 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
14672 }
14673
14674 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
14675
14676 SDValue StartV;
14677 switch (BaseOpc) {
14678 default:
14679 StartV = DAG.getIdentityElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
14680 break;
14681 case ISD::AND:
14682 case ISD::OR:
14683 case ISD::UMAX:
14684 case ISD::UMIN:
14685 case ISD::SMAX:
14686 case ISD::SMIN:
14687 StartV = DAG.getExtractVectorElt(DL, VecEltVT, Vec, 0);
14688 break;
14689 }
14690 return lowerReductionSeq(RVVOpcode, Op.getSimpleValueType(), StartV, Vec,
14691 Mask, VL, DL, DAG, Subtarget);
14692}
14693
14694// Given a reduction op, this function returns the matching reduction opcode,
14695// the vector SDValue and the scalar SDValue required to lower this to a
14696// RISCVISD node.
14697static std::tuple<unsigned, SDValue, SDValue>
14699 const RISCVSubtarget &Subtarget) {
14700 SDLoc DL(Op);
14701 auto Flags = Op->getFlags();
14702 unsigned Opcode = Op.getOpcode();
14703 switch (Opcode) {
14704 default:
14705 llvm_unreachable("Unhandled reduction");
14706 case ISD::VECREDUCE_FADD: {
14707 // Use positive zero if we can. It is cheaper to materialize.
14708 SDValue Zero =
14709 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
14710 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
14711 }
14713 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
14714 Op.getOperand(0));
14718 case ISD::VECREDUCE_FMAX: {
14719 SDValue Front = DAG.getExtractVectorElt(DL, EltVT, Op.getOperand(0), 0);
14720 unsigned RVVOpc =
14721 (Opcode == ISD::VECREDUCE_FMIN || Opcode == ISD::VECREDUCE_FMINIMUM)
14722 ? RISCVISD::VECREDUCE_FMIN_VL
14723 : RISCVISD::VECREDUCE_FMAX_VL;
14724 return std::make_tuple(RVVOpc, Op.getOperand(0), Front);
14725 }
14726 }
14727}
14728
14729SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
14730 SelectionDAG &DAG) const {
14731 SDLoc DL(Op);
14732 MVT VecEltVT = Op.getSimpleValueType();
14733
14734 unsigned RVVOpcode;
14735 SDValue VectorVal, ScalarVal;
14736 std::tie(RVVOpcode, VectorVal, ScalarVal) =
14737 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT, Subtarget);
14738 MVT VecVT = VectorVal.getSimpleValueType();
14739
14740 MVT ContainerVT = VecVT;
14741 if (VecVT.isFixedLengthVector()) {
14743 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
14744 }
14745
14746 MVT ResVT = Op.getSimpleValueType();
14747 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
14748 SDValue Res = lowerReductionSeq(RVVOpcode, ResVT, ScalarVal, VectorVal, Mask,
14749 VL, DL, DAG, Subtarget);
14750 if (Op.getOpcode() != ISD::VECREDUCE_FMINIMUM &&
14751 Op.getOpcode() != ISD::VECREDUCE_FMAXIMUM)
14752 return Res;
14753
14754 if (Op->getFlags().hasNoNaNs())
14755 return Res;
14756
14757 // Force output to NaN if any element is Nan.
14758 SDValue IsNan =
14759 DAG.getNode(RISCVISD::SETCC_VL, DL, Mask.getValueType(),
14760 {VectorVal, VectorVal, DAG.getCondCode(ISD::SETNE),
14761 DAG.getUNDEF(Mask.getValueType()), Mask, VL});
14762 MVT XLenVT = Subtarget.getXLenVT();
14763 SDValue CPop = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, IsNan, Mask, VL);
14764 SDValue NoNaNs = DAG.getSetCC(DL, XLenVT, CPop,
14765 DAG.getConstant(0, DL, XLenVT), ISD::SETEQ);
14766 return DAG.getSelect(
14767 DL, ResVT, NoNaNs, Res,
14768 DAG.getConstantFP(APFloat::getNaN(ResVT.getFltSemantics()), DL, ResVT));
14769}
14770
14771SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
14772 SelectionDAG &DAG) const {
14773 SDLoc DL(Op);
14774 unsigned Opc = Op.getOpcode();
14775 SDValue Start = Op.getOperand(0);
14776 SDValue Vec = Op.getOperand(1);
14777 EVT VecEVT = Vec.getValueType();
14778 MVT XLenVT = Subtarget.getXLenVT();
14779
14780 // TODO: The type may need to be widened rather than split. Or widened before
14781 // it can be split.
14782 if (!isTypeLegal(VecEVT))
14783 return SDValue();
14784
14785 MVT VecVT = VecEVT.getSimpleVT();
14786 unsigned RVVOpcode = getRVVReductionOp(Opc);
14787
14788 SDValue VL = Op.getOperand(3);
14789 SDValue Mask = Op.getOperand(2);
14790 if (VecVT.isFixedLengthVector()) {
14792 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
14794 Subtarget);
14795 }
14796 SDValue Res =
14797 lowerReductionSeq(RVVOpcode, Op.getSimpleValueType(), Op.getOperand(0),
14798 Vec, Mask, VL, DL, DAG, Subtarget);
14799 if ((Opc != ISD::VP_REDUCE_FMINIMUM && Opc != ISD::VP_REDUCE_FMAXIMUM) ||
14800 Op->getFlags().hasNoNaNs())
14801 return Res;
14802
14803 // Propagate NaNs.
14804 MVT PredVT = getMaskTypeFor(Vec.getSimpleValueType());
14805 // Check if any of the elements in Vec is NaN.
14806 SDValue IsNaN = DAG.getNode(
14807 RISCVISD::SETCC_VL, DL, PredVT,
14808 {Vec, Vec, DAG.getCondCode(ISD::SETNE), DAG.getUNDEF(PredVT), Mask, VL});
14809 SDValue VCPop = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, IsNaN, Mask, VL);
14810 // Check if the start value is NaN.
14811 SDValue StartIsNaN = DAG.getSetCC(DL, XLenVT, Start, Start, ISD::SETUO);
14812 VCPop = DAG.getNode(ISD::OR, DL, XLenVT, VCPop, StartIsNaN);
14813 SDValue NoNaNs = DAG.getSetCC(DL, XLenVT, VCPop,
14814 DAG.getConstant(0, DL, XLenVT), ISD::SETEQ);
14815 MVT ResVT = Res.getSimpleValueType();
14816 return DAG.getSelect(
14817 DL, ResVT, NoNaNs, Res,
14818 DAG.getConstantFP(APFloat::getNaN(ResVT.getFltSemantics()), DL, ResVT));
14819}
14820
14821SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
14822 SelectionDAG &DAG) const {
14823 SDValue Vec = Op.getOperand(0);
14824 SDValue SubVec = Op.getOperand(1);
14825 MVT VecVT = Vec.getSimpleValueType();
14826 MVT SubVecVT = SubVec.getSimpleValueType();
14827
14828 SDLoc DL(Op);
14829 MVT XLenVT = Subtarget.getXLenVT();
14830 unsigned OrigIdx = Op.getConstantOperandVal(2);
14831 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
14832
14833 // Lower a 32-bit insert into a 64-bit packed vector on RV32 to an
14834 // extract_subvector of the other half and a concat_vectors.
14835 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() &&
14836 (VecVT == MVT::v4i16 || VecVT == MVT::v8i8)) {
14837 unsigned HalfElts = VecVT.getVectorNumElements() / 2;
14838 if (SubVecVT.getSizeInBits() != 32 || (OrigIdx != 0 && OrigIdx != HalfElts))
14839 return SDValue();
14840 SDValue Other =
14841 DAG.getExtractSubvector(DL, SubVecVT, Vec, OrigIdx == 0 ? HalfElts : 0);
14842 return OrigIdx == 0
14843 ? DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, SubVec, Other)
14844 : DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Other, SubVec);
14845 }
14846
14847 if (OrigIdx == 0 && Vec.isUndef())
14848 return Op;
14849
14850 // We don't have the ability to slide mask vectors up indexed by their i1
14851 // elements; the smallest we can do is i8. Often we are able to bitcast to
14852 // equivalent i8 vectors. Note that when inserting a fixed-length vector
14853 // into a scalable one, we might not necessarily have enough scalable
14854 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
14855 if (SubVecVT.getVectorElementType() == MVT::i1) {
14856 if (VecVT.getVectorMinNumElements() >= 8 &&
14857 SubVecVT.getVectorMinNumElements() >= 8) {
14858 assert(OrigIdx % 8 == 0 && "Invalid index");
14859 assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
14860 SubVecVT.getVectorMinNumElements() % 8 == 0 &&
14861 "Unexpected mask vector lowering");
14862 OrigIdx /= 8;
14863 SubVecVT =
14864 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
14865 SubVecVT.isScalableVector());
14866 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
14867 VecVT.isScalableVector());
14868 Vec = DAG.getBitcast(VecVT, Vec);
14869 SubVec = DAG.getBitcast(SubVecVT, SubVec);
14870 } else {
14871 // We can't slide this mask vector up indexed by its i1 elements.
14872 // This poses a problem when we wish to insert a scalable vector which
14873 // can't be re-expressed as a larger type. Just choose the slow path and
14874 // extend to a larger type, then truncate back down.
14875 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
14876 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
14877 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
14878 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
14879 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
14880 Op.getOperand(2));
14881 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
14882 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
14883 }
14884 }
14885
14886 // If the subvector vector is a fixed-length type and we don't know VLEN
14887 // exactly, we cannot use subregister manipulation to simplify the codegen; we
14888 // don't know which register of a LMUL group contains the specific subvector
14889 // as we only know the minimum register size. Therefore we must slide the
14890 // vector group up the full amount.
14891 const auto VLen = Subtarget.getRealVLen();
14892 if (SubVecVT.isFixedLengthVector() && !VLen) {
14893 MVT ContainerVT = VecVT;
14894 if (VecVT.isFixedLengthVector()) {
14896 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
14897 }
14898
14899 SubVec = DAG.getInsertSubvector(DL, DAG.getUNDEF(ContainerVT), SubVec, 0);
14900
14901 SDValue Mask =
14902 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
14903 // Set the vector length to only the number of elements we care about. Note
14904 // that for slideup this includes the offset.
14905 unsigned EndIndex = OrigIdx + SubVecVT.getVectorNumElements();
14906 SDValue VL = DAG.getConstant(EndIndex, DL, XLenVT);
14907
14908 // Use tail agnostic policy if we're inserting over Vec's tail.
14910 if (VecVT.isFixedLengthVector() && EndIndex == VecVT.getVectorNumElements())
14912
14913 // If we're inserting into the lowest elements, use a tail undisturbed
14914 // vmv.v.v.
14915 if (OrigIdx == 0) {
14916 SubVec =
14917 DAG.getNode(RISCVISD::VMV_V_V_VL, DL, ContainerVT, Vec, SubVec, VL);
14918 } else {
14919 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
14920 SubVec = getVSlideup(DAG, Subtarget, DL, ContainerVT, Vec, SubVec,
14921 SlideupAmt, Mask, VL, Policy);
14922 }
14923
14924 if (VecVT.isFixedLengthVector())
14925 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
14926 return DAG.getBitcast(Op.getValueType(), SubVec);
14927 }
14928
14929 MVT ContainerVecVT = VecVT;
14930 if (VecVT.isFixedLengthVector()) {
14931 ContainerVecVT = getContainerForFixedLengthVector(VecVT);
14932 Vec = convertToScalableVector(ContainerVecVT, Vec, DAG, Subtarget);
14933 }
14934
14935 MVT ContainerSubVecVT = SubVecVT;
14936 if (SubVecVT.isFixedLengthVector()) {
14937 ContainerSubVecVT = getContainerForFixedLengthVector(SubVecVT);
14938 SubVec = convertToScalableVector(ContainerSubVecVT, SubVec, DAG, Subtarget);
14939 }
14940
14941 unsigned SubRegIdx;
14942 ElementCount RemIdx;
14943 // insert_subvector scales the index by vscale if the subvector is scalable,
14944 // and decomposeSubvectorInsertExtractToSubRegs takes this into account. So if
14945 // we have a fixed length subvector, we need to adjust the index by 1/vscale.
14946 if (SubVecVT.isFixedLengthVector()) {
14947 assert(VLen);
14948 unsigned Vscale = *VLen / RISCV::RVVBitsPerBlock;
14949 auto Decompose =
14951 ContainerVecVT, ContainerSubVecVT, OrigIdx / Vscale, TRI);
14952 SubRegIdx = Decompose.first;
14953 RemIdx = ElementCount::getFixed((Decompose.second * Vscale) +
14954 (OrigIdx % Vscale));
14955 } else {
14956 auto Decompose =
14958 ContainerVecVT, ContainerSubVecVT, OrigIdx, TRI);
14959 SubRegIdx = Decompose.first;
14960 RemIdx = ElementCount::getScalable(Decompose.second);
14961 }
14962
14963 TypeSize VecRegSize = TypeSize::getScalable(RISCV::RVVBitsPerBlock);
14965 Subtarget.expandVScale(SubVecVT.getSizeInBits()).getKnownMinValue()));
14966 bool ExactlyVecRegSized =
14967 Subtarget.expandVScale(SubVecVT.getSizeInBits())
14968 .isKnownMultipleOf(Subtarget.expandVScale(VecRegSize));
14969
14970 // 1. If the Idx has been completely eliminated and this subvector's size is
14971 // a vector register or a multiple thereof, or the surrounding elements are
14972 // undef, then this is a subvector insert which naturally aligns to a vector
14973 // register. These can easily be handled using subregister manipulation.
14974 // 2. If the subvector isn't an exact multiple of a valid register group size,
14975 // then the insertion must preserve the undisturbed elements of the register.
14976 // We do this by lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1
14977 // vector type (which resolves to a subregister copy), performing a VSLIDEUP
14978 // to place the subvector within the vector register, and an INSERT_SUBVECTOR
14979 // of that LMUL=1 type back into the larger vector (resolving to another
14980 // subregister operation). See below for how our VSLIDEUP works. We go via a
14981 // LMUL=1 type to avoid allocating a large register group to hold our
14982 // subvector.
14983 if (RemIdx.isZero() && (ExactlyVecRegSized || Vec.isUndef())) {
14984 if (SubVecVT.isFixedLengthVector()) {
14985 // We may get NoSubRegister if inserting at index 0 and the subvec
14986 // container is the same as the vector, e.g. vec=v4i32,subvec=v4i32,idx=0
14987 if (SubRegIdx == RISCV::NoSubRegister) {
14988 assert(OrigIdx == 0);
14989 return Op;
14990 }
14991
14992 // Use a insert_subvector that will resolve to an insert subreg.
14993 assert(VLen);
14994 unsigned Vscale = *VLen / RISCV::RVVBitsPerBlock;
14995 SDValue Insert =
14996 DAG.getInsertSubvector(DL, Vec, SubVec, OrigIdx / Vscale);
14997 if (VecVT.isFixedLengthVector())
14998 Insert = convertFromScalableVector(VecVT, Insert, DAG, Subtarget);
14999 return Insert;
15000 }
15001 return Op;
15002 }
15003
15004 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
15005 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
15006 // (in our case undisturbed). This means we can set up a subvector insertion
15007 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
15008 // size of the subvector.
15009 MVT InterSubVT = ContainerVecVT;
15010 SDValue AlignedExtract = Vec;
15011 unsigned AlignedIdx = OrigIdx - RemIdx.getKnownMinValue();
15012 if (SubVecVT.isFixedLengthVector()) {
15013 assert(VLen);
15014 AlignedIdx /= *VLen / RISCV::RVVBitsPerBlock;
15015 }
15016 if (ContainerVecVT.bitsGT(RISCVTargetLowering::getM1VT(ContainerVecVT))) {
15017 InterSubVT = RISCVTargetLowering::getM1VT(ContainerVecVT);
15018 // Extract a subvector equal to the nearest full vector register type. This
15019 // should resolve to a EXTRACT_SUBREG instruction.
15020 AlignedExtract = DAG.getExtractSubvector(DL, InterSubVT, Vec, AlignedIdx);
15021 }
15022
15023 SubVec = DAG.getInsertSubvector(DL, DAG.getUNDEF(InterSubVT), SubVec, 0);
15024
15025 ElementCount EndIndex = RemIdx + SubVecVT.getVectorElementCount();
15026 SDValue VL =
15027 DAG.getElementCount(DL, XLenVT, SubVecVT.getVectorElementCount());
15028
15029 // Use tail agnostic policy if we're inserting over InterSubVT's tail.
15031 if (Subtarget.expandVScale(EndIndex) ==
15032 Subtarget.expandVScale(InterSubVT.getVectorElementCount()))
15034
15035 // If we're inserting into the lowest elements, use a tail undisturbed
15036 // vmv.v.v.
15037 if (RemIdx.isZero()) {
15038 SubVec = DAG.getNode(RISCVISD::VMV_V_V_VL, DL, InterSubVT, AlignedExtract,
15039 SubVec, VL);
15040 } else {
15041 SDValue SlideupAmt = DAG.getElementCount(DL, XLenVT, RemIdx);
15042
15043 // Construct the vector length corresponding to RemIdx + length(SubVecVT).
15044 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
15045
15046 SDValue Mask = getAllOnesMask(InterSubVT, VL, DL, DAG);
15047 SubVec = getVSlideup(DAG, Subtarget, DL, InterSubVT, AlignedExtract, SubVec,
15048 SlideupAmt, Mask, VL, Policy);
15049 }
15050
15051 // If required, insert this subvector back into the correct vector register.
15052 // This should resolve to an INSERT_SUBREG instruction.
15053 if (ContainerVecVT.bitsGT(InterSubVT))
15054 SubVec = DAG.getInsertSubvector(DL, Vec, SubVec, AlignedIdx);
15055
15056 if (VecVT.isFixedLengthVector())
15057 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
15058
15059 // We might have bitcast from a mask type: cast back to the original type if
15060 // required.
15061 return DAG.getBitcast(Op.getSimpleValueType(), SubVec);
15062}
15063
15064SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
15065 SelectionDAG &DAG) const {
15066 SDValue Vec = Op.getOperand(0);
15067 MVT SubVecVT = Op.getSimpleValueType();
15068 MVT VecVT = Vec.getSimpleValueType();
15069
15070 SDLoc DL(Op);
15071 MVT XLenVT = Subtarget.getXLenVT();
15072 unsigned OrigIdx = Op.getConstantOperandVal(1);
15073 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
15074
15075 // With an index of 0 this is a cast-like subvector, which can be performed
15076 // with subregister operations.
15077 if (OrigIdx == 0)
15078 return Op;
15079
15080 // We don't have the ability to slide mask vectors down indexed by their i1
15081 // elements; the smallest we can do is i8. Often we are able to bitcast to
15082 // equivalent i8 vectors. Note that when extracting a fixed-length vector
15083 // from a scalable one, we might not necessarily have enough scalable
15084 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
15085 if (SubVecVT.getVectorElementType() == MVT::i1) {
15086 if (VecVT.getVectorMinNumElements() >= 8 &&
15087 SubVecVT.getVectorMinNumElements() >= 8) {
15088 assert(OrigIdx % 8 == 0 && "Invalid index");
15089 assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
15090 SubVecVT.getVectorMinNumElements() % 8 == 0 &&
15091 "Unexpected mask vector lowering");
15092 OrigIdx /= 8;
15093 SubVecVT =
15094 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
15095 SubVecVT.isScalableVector());
15096 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
15097 VecVT.isScalableVector());
15098 Vec = DAG.getBitcast(VecVT, Vec);
15099 } else {
15100 // We can't slide this mask vector down, indexed by its i1 elements.
15101 // This poses a problem when we wish to extract a scalable vector which
15102 // can't be re-expressed as a larger type. Just choose the slow path and
15103 // extend to a larger type, then truncate back down.
15104 // TODO: We could probably improve this when extracting certain fixed
15105 // from fixed, where we can extract as i8 and shift the correct element
15106 // right to reach the desired subvector?
15107 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
15108 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
15109 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
15110 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
15111 Op.getOperand(1));
15112 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
15113 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
15114 }
15115 }
15116
15117 const auto VLen = Subtarget.getRealVLen();
15118
15119 // If the subvector vector is a fixed-length type and we don't know VLEN
15120 // exactly, we cannot use subregister manipulation to simplify the codegen; we
15121 // don't know which register of a LMUL group contains the specific subvector
15122 // as we only know the minimum register size. Therefore we must slide the
15123 // vector group down the full amount.
15124 if (SubVecVT.isFixedLengthVector() && !VLen) {
15125 MVT ContainerVT = VecVT;
15126 if (VecVT.isFixedLengthVector()) {
15128 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
15129 }
15130
15131 // Shrink down Vec so we're performing the slidedown on a smaller LMUL.
15132 unsigned LastIdx = OrigIdx + SubVecVT.getVectorNumElements() - 1;
15133 if (auto ShrunkVT =
15134 getSmallestVTForIndex(ContainerVT, LastIdx, DL, DAG, Subtarget)) {
15135 ContainerVT = *ShrunkVT;
15136 Vec = DAG.getExtractSubvector(DL, ContainerVT, Vec, 0);
15137 }
15138
15139 SDValue Mask =
15140 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
15141 // Set the vector length to only the number of elements we care about. This
15142 // avoids sliding down elements we're going to discard straight away.
15143 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
15144 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
15145 SDValue Slidedown =
15146 getVSlidedown(DAG, Subtarget, DL, ContainerVT,
15147 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
15148 // Now we can use a cast-like subvector extract to get the result.
15149 Slidedown = DAG.getExtractSubvector(DL, SubVecVT, Slidedown, 0);
15150 return DAG.getBitcast(Op.getValueType(), Slidedown);
15151 }
15152
15153 if (VecVT.isFixedLengthVector()) {
15154 VecVT = getContainerForFixedLengthVector(VecVT);
15155 Vec = convertToScalableVector(VecVT, Vec, DAG, Subtarget);
15156 }
15157
15158 MVT ContainerSubVecVT = SubVecVT;
15159 if (SubVecVT.isFixedLengthVector())
15160 ContainerSubVecVT = getContainerForFixedLengthVector(SubVecVT);
15161
15162 unsigned SubRegIdx;
15163 ElementCount RemIdx;
15164 // extract_subvector scales the index by vscale if the subvector is scalable,
15165 // and decomposeSubvectorInsertExtractToSubRegs takes this into account. So if
15166 // we have a fixed length subvector, we need to adjust the index by 1/vscale.
15167 if (SubVecVT.isFixedLengthVector()) {
15168 assert(VLen);
15169 unsigned Vscale = *VLen / RISCV::RVVBitsPerBlock;
15170 auto Decompose =
15172 VecVT, ContainerSubVecVT, OrigIdx / Vscale, TRI);
15173 SubRegIdx = Decompose.first;
15174 RemIdx = ElementCount::getFixed((Decompose.second * Vscale) +
15175 (OrigIdx % Vscale));
15176 } else {
15177 auto Decompose =
15179 VecVT, ContainerSubVecVT, OrigIdx, TRI);
15180 SubRegIdx = Decompose.first;
15181 RemIdx = ElementCount::getScalable(Decompose.second);
15182 }
15183
15184 // If the Idx has been completely eliminated then this is a subvector extract
15185 // which naturally aligns to a vector register. These can easily be handled
15186 // using subregister manipulation. We use an extract_subvector that will
15187 // resolve to an extract subreg.
15188 if (RemIdx.isZero()) {
15189 if (SubVecVT.isFixedLengthVector()) {
15190 assert(VLen);
15191 unsigned Vscale = *VLen / RISCV::RVVBitsPerBlock;
15192 Vec =
15193 DAG.getExtractSubvector(DL, ContainerSubVecVT, Vec, OrigIdx / Vscale);
15194 return convertFromScalableVector(SubVecVT, Vec, DAG, Subtarget);
15195 }
15196 return Op;
15197 }
15198
15199 // Else SubVecVT is M1 or smaller and may need to be slid down: if SubVecVT
15200 // was > M1 then the index would need to be a multiple of VLMAX, and so would
15201 // divide exactly.
15202 assert(RISCVVType::decodeVLMUL(getLMUL(ContainerSubVecVT)).second ||
15203 getLMUL(ContainerSubVecVT) == RISCVVType::LMUL_1);
15204
15205 // If the vector type is an LMUL-group type, extract a subvector equal to the
15206 // nearest full vector register type.
15207 MVT InterSubVT = VecVT;
15208 if (VecVT.bitsGT(RISCVTargetLowering::getM1VT(VecVT))) {
15209 // If VecVT has an LMUL > 1, then SubVecVT should have a smaller LMUL, and
15210 // we should have successfully decomposed the extract into a subregister.
15211 // We use an extract_subvector that will resolve to a subreg extract.
15212 assert(SubRegIdx != RISCV::NoSubRegister);
15213 (void)SubRegIdx;
15214 unsigned Idx = OrigIdx - RemIdx.getKnownMinValue();
15215 if (SubVecVT.isFixedLengthVector()) {
15216 assert(VLen);
15217 Idx /= *VLen / RISCV::RVVBitsPerBlock;
15218 }
15219 InterSubVT = RISCVTargetLowering::getM1VT(VecVT);
15220 Vec = DAG.getExtractSubvector(DL, InterSubVT, Vec, Idx);
15221 }
15222
15223 // Slide this vector register down by the desired number of elements in order
15224 // to place the desired subvector starting at element 0.
15225 SDValue SlidedownAmt = DAG.getElementCount(DL, XLenVT, RemIdx);
15226 auto [Mask, VL] = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
15227 if (SubVecVT.isFixedLengthVector())
15228 VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
15229 SDValue Slidedown =
15230 getVSlidedown(DAG, Subtarget, DL, InterSubVT, DAG.getUNDEF(InterSubVT),
15231 Vec, SlidedownAmt, Mask, VL);
15232
15233 // Now the vector is in the right position, extract our final subvector. This
15234 // should resolve to a COPY.
15235 Slidedown = DAG.getExtractSubvector(DL, SubVecVT, Slidedown, 0);
15236
15237 // We might have bitcast from a mask type: cast back to the original type if
15238 // required.
15239 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
15240}
15241
15242// Widen a vector's operands to i8, then truncate its results back to the
15243// original type, typically i1. All operand and result types must be the same.
15245 SelectionDAG &DAG) {
15246 MVT VT = N.getSimpleValueType();
15247 MVT WideVT = VT.changeVectorElementType(MVT::i8);
15249 for (SDValue Op : N->ops()) {
15250 assert(Op.getSimpleValueType() == VT &&
15251 "Operands and result must be same type");
15252 WideOps.push_back(DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Op));
15253 }
15254
15255 unsigned NumVals = N->getNumValues();
15256
15258 NumVals,
15259 N.getValueType().changeVectorElementType(*DAG.getContext(), MVT::i8)));
15260 SDValue WideN = DAG.getNode(N.getOpcode(), DL, VTs, WideOps);
15261 SmallVector<SDValue, 4> TruncVals;
15262 for (unsigned I = 0; I < NumVals; I++) {
15263 TruncVals.push_back(
15264 DAG.getSetCC(DL, N->getSimpleValueType(I), WideN.getValue(I),
15265 DAG.getConstant(0, DL, WideVT), ISD::SETNE));
15266 }
15267
15268 if (TruncVals.size() > 1)
15269 return DAG.getMergeValues(TruncVals, DL);
15270 return TruncVals.front();
15271}
15272
15273SDValue RISCVTargetLowering::lowerVECTOR_DEINTERLEAVE(SDValue Op,
15274 SelectionDAG &DAG) const {
15275 SDLoc DL(Op);
15276 MVT VecVT = Op.getSimpleValueType();
15277
15278 const unsigned Factor = Op->getNumValues();
15279 assert(Factor <= 8);
15280
15281 // 1 bit element vectors need to be widened to e8
15282 if (VecVT.getVectorElementType() == MVT::i1)
15283 return widenVectorOpsToi8(Op, DL, DAG);
15284
15285 bool IsFixedVector = VecVT.isFixedLengthVector();
15286
15287 MVT ContainerVecVT = VecVT;
15288 if (IsFixedVector)
15289 ContainerVecVT = getContainerForFixedLengthVector(VecVT);
15290
15291 // If concatenating would exceed LMUL=8, we need to split.
15292 if ((ContainerVecVT.getSizeInBits().getKnownMinValue() * Factor) >
15293 (8 * RISCV::RVVBitsPerBlock)) {
15294 SmallVector<SDValue, 8> Ops(Factor * 2);
15295 for (unsigned i = 0; i != Factor; ++i) {
15296 auto [OpLo, OpHi] = DAG.SplitVectorOperand(Op.getNode(), i);
15297 Ops[i * 2] = OpLo;
15298 Ops[i * 2 + 1] = OpHi;
15299 }
15300
15301 SmallVector<EVT, 8> VTs(Factor, Ops[0].getValueType());
15302
15304 ArrayRef(Ops).slice(0, Factor));
15306 ArrayRef(Ops).slice(Factor, Factor));
15307
15308 SmallVector<SDValue, 8> Res(Factor);
15309 for (unsigned i = 0; i != Factor; ++i)
15310 Res[i] = DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo.getValue(i),
15311 Hi.getValue(i));
15312
15313 return DAG.getMergeValues(Res, DL);
15314 }
15315
15316 if (Subtarget.hasStdExtZvzip() && Factor == 2 && !IsFixedVector) {
15317 MVT VT = Op->getSimpleValueType(0);
15318 MVT NewVT = VT.getDoubleNumVectorElementsVT();
15319 if (isTypeLegal(NewVT) &&
15321 SDValue V1 = Op->getOperand(0);
15322 SDValue V2 = Op->getOperand(1);
15323 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, NewVT, V1, V2);
15324 SDValue Even =
15325 lowerZvzipVUNZIP(RISCVISD::VUNZIPE_VL, V, DL, DAG, Subtarget);
15326 SDValue Odd =
15327 lowerZvzipVUNZIP(RISCVISD::VUNZIPO_VL, V, DL, DAG, Subtarget);
15328 return DAG.getMergeValues({Even, Odd}, DL);
15329 }
15330 }
15331
15332 if (Factor == 2 && IsFixedVector) {
15333 unsigned NumElts = VecVT.getVectorNumElements();
15334 SDValue Results[2];
15335 for (unsigned I = 0; I != Factor; ++I)
15336 Results[I] =
15337 DAG.getVectorShuffle(VecVT, DL, Op.getOperand(0), Op.getOperand(1),
15338 createStrideMask(I, Factor, NumElts));
15339 return DAG.getMergeValues(Results, DL);
15340 }
15341
15342 SmallVector<SDValue, 8> Ops(Op->op_values());
15343
15344 // Concatenate the vectors as one vector to deinterleave
15345 MVT ConcatVT =
15347 VecVT.getVectorElementCount() * PowerOf2Ceil(Factor));
15348 if (Ops.size() < PowerOf2Ceil(Factor))
15349 Ops.append(PowerOf2Ceil(Factor) - Factor, DAG.getUNDEF(VecVT));
15350 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, Ops);
15351
15352 if (Factor == 2 && !IsFixedVector) {
15353 // We can deinterleave through vnsrl.wi if the element type is smaller than
15354 // ELEN
15355 if (VecVT.getScalarSizeInBits() < Subtarget.getELen()) {
15356 SDValue Even = getDeinterleaveShiftAndTrunc(DL, VecVT, Concat, 2, 0, DAG);
15357 SDValue Odd = getDeinterleaveShiftAndTrunc(DL, VecVT, Concat, 2, 1, DAG);
15358 return DAG.getMergeValues({Even, Odd}, DL);
15359 }
15360
15361 // For the indices, use the vmv.v.x of an i8 constant to fill the largest
15362 // possibly mask vector, then extract the required subvector. Doing this
15363 // (instead of a vid, vmsne sequence) reduces LMUL, and allows the mask
15364 // creation to be rematerialized during register allocation to reduce
15365 // register pressure if needed.
15366
15367 MVT MaskVT = ConcatVT.changeVectorElementType(MVT::i1);
15368
15369 SDValue EvenSplat = DAG.getConstant(0b01010101, DL, MVT::nxv8i8);
15370 EvenSplat = DAG.getBitcast(MVT::nxv64i1, EvenSplat);
15371 SDValue EvenMask = DAG.getExtractSubvector(DL, MaskVT, EvenSplat, 0);
15372
15373 SDValue OddSplat = DAG.getConstant(0b10101010, DL, MVT::nxv8i8);
15374 OddSplat = DAG.getBitcast(MVT::nxv64i1, OddSplat);
15375 SDValue OddMask = DAG.getExtractSubvector(DL, MaskVT, OddSplat, 0);
15376
15377 // vcompress the even and odd elements into two separate vectors
15378 SDValue EvenWide = DAG.getNode(ISD::VECTOR_COMPRESS, DL, ConcatVT, Concat,
15379 EvenMask, DAG.getUNDEF(ConcatVT));
15380 SDValue OddWide = DAG.getNode(ISD::VECTOR_COMPRESS, DL, ConcatVT, Concat,
15381 OddMask, DAG.getUNDEF(ConcatVT));
15382
15383 // Extract the result half of the gather for even and odd
15384 SDValue Even = DAG.getExtractSubvector(DL, VecVT, EvenWide, 0);
15385 SDValue Odd = DAG.getExtractSubvector(DL, VecVT, OddWide, 0);
15386
15387 return DAG.getMergeValues({Even, Odd}, DL);
15388 }
15389
15390 // Store with unit-stride store and load it back with segmented load.
15391 SDValue Mask, VL;
15392 MVT XLenVT = Subtarget.getXLenVT();
15393 auto &MF = DAG.getMachineFunction();
15394 SDValue Chain = DAG.getEntryNode();
15395 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
15397 MachinePointerInfo PtrInfo;
15398 if (IsFixedVector) {
15399 // Calculating the stack size.
15400 ElementCount ActualConcatEC = VecVT.getVectorElementCount() * Factor;
15401 EVT ConcatEVT = EVT::getVectorVT(
15402 *DAG.getContext(), VecVT.getVectorElementType(), ActualConcatEC);
15403 StackPtr = DAG.CreateStackTemporary(ConcatEVT.getStoreSize(), Alignment);
15404 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
15405 PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
15406
15407 // If this is a fixed vector, instead of using the concat vector, we simply
15408 // store each fixed vector operand directly onto the stack, individually.
15409 // The reason being that if the fixed vector is (much) smaller than the
15410 // container vector, we will be wasting space on stack.
15411 TypeSize VecSize = VecVT.getStoreSize();
15413 MachinePointerInfo PI = PtrInfo;
15414 SmallVector<SDValue, 8> Tokens(Factor);
15415 for (auto [Idx, FieldOp] : enumerate(Op->op_values())) {
15416 if (Idx) {
15417 // Advance the pointer.
15418 BasePtr = DAG.getObjectPtrOffset(DL, BasePtr, VecSize);
15419 PI = PI.getWithOffset(VecSize);
15420 }
15421 Tokens[Idx] = DAG.getStore(Chain, DL, FieldOp, BasePtr, PI, Alignment);
15422 }
15423 Chain = DAG.getTokenFactor(DL, Tokens);
15424
15425 // Calculating Mask and VL for later usages.
15426 std::tie(Mask, VL) =
15427 getDefaultVLOps(VecVT, ContainerVecVT, DL, DAG, Subtarget);
15428 ConcatVT = getContainerForFixedLengthVector(ConcatVT);
15429 } else {
15430 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
15431 StackPtr = DAG.CreateStackTemporary(ConcatVT.getStoreSize(), Alignment);
15432 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
15433 PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
15434
15435 SDValue StoreOps[] = {
15436 Chain, DAG.getTargetConstant(Intrinsic::riscv_vse, DL, XLenVT), Concat,
15437 StackPtr, VL};
15438
15439 Chain = DAG.getMemIntrinsicNode(
15440 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), StoreOps,
15441 ConcatVT.getVectorElementType(), PtrInfo, Alignment,
15443 }
15444
15445 // Load it back with segmented load.
15446 SDValue Passthru = DAG.getUNDEF(ConcatVT);
15447 static const Intrinsic::ID VlsegIntrinsicsIds[] = {
15448 Intrinsic::riscv_vlseg2_mask, Intrinsic::riscv_vlseg3_mask,
15449 Intrinsic::riscv_vlseg4_mask, Intrinsic::riscv_vlseg5_mask,
15450 Intrinsic::riscv_vlseg6_mask, Intrinsic::riscv_vlseg7_mask,
15451 Intrinsic::riscv_vlseg8_mask};
15452
15453 SDValue LoadOps[] = {
15454 Chain,
15455 DAG.getTargetConstant(VlsegIntrinsicsIds[Factor - 2], DL, XLenVT),
15456 Passthru,
15457 StackPtr,
15458 Mask,
15459 VL,
15462 DAG.getTargetConstant(Log2_64(VecVT.getScalarSizeInBits()), DL, XLenVT)};
15463
15464 unsigned Sz = Factor * ContainerVecVT.getVectorMinNumElements() *
15465 ContainerVecVT.getScalarSizeInBits();
15466 EVT VecTupTy = MVT::getRISCVVectorTupleVT(Sz, Factor);
15467
15469 ISD::INTRINSIC_W_CHAIN, DL, DAG.getVTList({VecTupTy, MVT::Other}),
15470 LoadOps, ConcatVT.getVectorElementType(), PtrInfo, Alignment,
15472
15473 SmallVector<SDValue, 8> Res(Factor);
15474
15475 for (unsigned i = 0U; i < Factor; ++i) {
15476 SDValue FieldRes =
15477 DAG.getNode(RISCVISD::TUPLE_EXTRACT, DL, ContainerVecVT, Load,
15478 DAG.getTargetConstant(i, DL, MVT::i32));
15479 if (IsFixedVector)
15480 FieldRes = convertFromScalableVector(VecVT, FieldRes, DAG, Subtarget);
15481 Res[i] = FieldRes;
15482 }
15483
15484 return DAG.getMergeValues(Res, DL);
15485}
15486
15487SDValue RISCVTargetLowering::lowerVECTOR_INTERLEAVE(SDValue Op,
15488 SelectionDAG &DAG) const {
15489 SDLoc DL(Op);
15490 MVT VecVT = Op.getSimpleValueType();
15491
15492 const unsigned Factor = Op.getNumOperands();
15493 assert(Factor <= 8);
15494
15495 // Keep both halves of a fixed-length interleave together while widening an
15496 // i1 vector. Widening each result independently requires two comparisons to
15497 // recreate the mask and then has to concatenate those masks again.
15498 if (VecVT.getVectorElementType() == MVT::i1 && Factor == 2 &&
15499 VecVT.isFixedLengthVector()) {
15500 unsigned NumElts = VecVT.getVectorNumElements();
15501 MVT InterleavedVT = VecVT.getDoubleNumVectorElementsVT();
15502 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, InterleavedVT,
15503 Op.getOperand(0), Op.getOperand(1));
15504 SDValue Interleaved = DAG.getVectorShuffle(
15505 InterleavedVT, DL, Concat, DAG.getUNDEF(InterleavedVT),
15506 createInterleaveMask(NumElts, Factor));
15507 SDValue Lo = DAG.getExtractSubvector(DL, VecVT, Interleaved, 0);
15508 SDValue Hi = DAG.getExtractSubvector(DL, VecVT, Interleaved, NumElts);
15509 return DAG.getMergeValues({Lo, Hi}, DL);
15510 }
15511
15512 // i1 vectors need to be widened to i8
15513 if (VecVT.getVectorElementType() == MVT::i1)
15514 return widenVectorOpsToi8(Op, DL, DAG);
15515
15516 MVT ContainerVecVT = VecVT;
15517 if (VecVT.isFixedLengthVector())
15518 ContainerVecVT = getContainerForFixedLengthVector(VecVT);
15519
15520 // If the VT is larger than LMUL=8, we need to split and reassemble.
15521 if ((ContainerVecVT.getSizeInBits().getKnownMinValue() * Factor) >
15522 (8 * RISCV::RVVBitsPerBlock) ||
15523 // In an unlikely case, a vector type might be legal to RISC-V but
15524 // exceeds the MVT limit, in which we also want to split it.
15525 (Subtarget.hasStdExtZvzip() && Factor == 2 &&
15527 VecVT.getVectorElementCount() * Factor)))) {
15528 SmallVector<SDValue, 8> Ops(Factor * 2);
15529 for (unsigned i = 0; i != Factor; ++i) {
15530 auto [OpLo, OpHi] = DAG.SplitVectorOperand(Op.getNode(), i);
15531 Ops[i] = OpLo;
15532 Ops[i + Factor] = OpHi;
15533 }
15534
15535 SmallVector<EVT, 8> VTs(Factor, Ops[0].getValueType());
15536
15537 SDValue Res[] = {DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, VTs,
15538 ArrayRef(Ops).take_front(Factor)),
15540 ArrayRef(Ops).drop_front(Factor))};
15541
15542 SmallVector<SDValue, 8> Concats(Factor);
15543 for (unsigned i = 0; i != Factor; ++i) {
15544 unsigned IdxLo = 2 * i;
15545 unsigned IdxHi = 2 * i + 1;
15546 Concats[i] = DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT,
15547 Res[IdxLo / Factor].getValue(IdxLo % Factor),
15548 Res[IdxHi / Factor].getValue(IdxHi % Factor));
15549 }
15550
15551 return DAG.getMergeValues(Concats, DL);
15552 }
15553
15554 MVT XLenVT = Subtarget.getXLenVT();
15555 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVecVT, DL, DAG, Subtarget);
15556
15557 SDValue Interleaved;
15558
15559 // Spill to the stack using a segment store for simplicity.
15560 if (Factor != 2) {
15561 EVT MemVT =
15563 VecVT.getVectorElementCount() * Factor);
15564
15565 // Allocate a stack slot.
15566 // Note that in the case where VecVT is fixed vector, even we later
15567 // create a container for each (fixed vector) operand, we still allocate
15568 // the stack with fixed vector size, rather than container size, as
15569 // fixed vector size is already sufficient.
15570 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
15572 DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
15573 EVT PtrVT = StackPtr.getValueType();
15574 auto &MF = DAG.getMachineFunction();
15575 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
15576 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
15577
15578 static const Intrinsic::ID IntrIds[] = {
15579 Intrinsic::riscv_vsseg2_mask, Intrinsic::riscv_vsseg3_mask,
15580 Intrinsic::riscv_vsseg4_mask, Intrinsic::riscv_vsseg5_mask,
15581 Intrinsic::riscv_vsseg6_mask, Intrinsic::riscv_vsseg7_mask,
15582 Intrinsic::riscv_vsseg8_mask,
15583 };
15584
15585 unsigned Sz = Factor * ContainerVecVT.getVectorMinNumElements() *
15586 ContainerVecVT.getScalarSizeInBits();
15587 EVT VecTupTy = MVT::getRISCVVectorTupleVT(Sz, Factor);
15588
15589 SDValue StoredVal = DAG.getUNDEF(VecTupTy);
15590 for (unsigned i = 0; i < Factor; i++) {
15591 SDValue OpVal = Op.getOperand(i);
15592 if (VecVT.isFixedLengthVector())
15593 OpVal = convertToScalableVector(ContainerVecVT, OpVal, DAG, Subtarget);
15594 StoredVal = DAG.getNode(RISCVISD::TUPLE_INSERT, DL, VecTupTy, StoredVal,
15595 OpVal, DAG.getTargetConstant(i, DL, MVT::i32));
15596 }
15597
15598 SDValue Ops[] = {DAG.getEntryNode(),
15599 DAG.getTargetConstant(IntrIds[Factor - 2], DL, XLenVT),
15600 StoredVal,
15601 StackPtr,
15602 Mask,
15603 VL,
15605 DL, XLenVT)};
15606
15607 SDValue Chain = DAG.getMemIntrinsicNode(
15608 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Ops,
15609 VecVT.getVectorElementType(), PtrInfo, Alignment,
15611
15612 SmallVector<SDValue, 8> Loads(Factor);
15613
15614 SDValue Increment = DAG.getTypeSize(DL, PtrVT, VecVT.getStoreSize());
15615 for (unsigned i = 0; i != Factor; ++i) {
15616 if (i != 0)
15617 StackPtr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, Increment);
15618
15619 Loads[i] = DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo);
15620 }
15621
15622 return DAG.getMergeValues(Loads, DL);
15623 }
15624
15625 if (Subtarget.hasStdExtZvzip() && !Op.getOperand(0).isUndef() &&
15626 !Op.getOperand(1).isUndef()) {
15627 MVT VT = Op->getSimpleValueType(0);
15628 MVT NewVT = VT.getDoubleNumVectorElementsVT();
15629 if (isLegalVTForZvzipInterleavedOperand(NewVT, Subtarget)) {
15630 // Freeze the sources so we can increase their use count.
15631 SDValue V1 = DAG.getFreeze(Op->getOperand(0));
15632 SDValue V2 = DAG.getFreeze(Op->getOperand(1));
15633 SDValue Interleaved = lowerZvzipVZIP(V1, V2, DL, DAG, Subtarget);
15634 SDValue Lo = DAG.getExtractSubvector(DL, VT, Interleaved, 0);
15635 SDValue Hi = DAG.getExtractSubvector(DL, VT, Interleaved,
15637 return DAG.getMergeValues({Lo, Hi}, DL);
15638 }
15639 }
15640
15641 // If the element type is smaller than ELEN, then we can interleave with
15642 // vwaddu.vv and vwmaccu.vx
15643 if (VecVT.getScalarSizeInBits() < Subtarget.getELen()) {
15644 Interleaved = getWideningInterleave(Op.getOperand(0), Op.getOperand(1), DL,
15645 DAG, Subtarget);
15646 } else if (Factor == 2 && VecVT.isFixedLengthVector()) {
15647 unsigned NumElts = VecVT.getVectorNumElements();
15648 SmallVector<int, 8> ShuffleMask = createInterleaveMask(NumElts, Factor);
15649 SDValue Results[2];
15650 for (unsigned I = 0; I != Factor; ++I)
15651 Results[I] = DAG.getVectorShuffle(
15652 VecVT, DL, Op.getOperand(0), Op.getOperand(1),
15653 ArrayRef(ShuffleMask).slice(I * NumElts, NumElts));
15654 return DAG.getMergeValues(Results, DL);
15655 } else {
15656 // Otherwise, fallback to using vrgathere16.vv
15657 MVT ConcatVT = MVT::getVectorVT(VecVT.getVectorElementType(),
15658 VecVT.getVectorElementCount() * 2);
15659 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT,
15660 Op.getOperand(0), Op.getOperand(1));
15661
15662 MVT IdxVT = ConcatVT.changeVectorElementType(MVT::i16);
15663
15664 // 0 1 2 3 4 5 6 7 ...
15665 SDValue StepVec = DAG.getStepVector(DL, IdxVT);
15666
15667 // 1 1 1 1 1 1 1 1 ...
15668 SDValue Ones = DAG.getSplatVector(IdxVT, DL, DAG.getConstant(1, DL, XLenVT));
15669
15670 // 1 0 1 0 1 0 1 0 ...
15671 SDValue OddMask = DAG.getNode(ISD::AND, DL, IdxVT, StepVec, Ones);
15672 OddMask = DAG.getSetCC(
15673 DL, IdxVT.changeVectorElementType(MVT::i1), OddMask,
15674 DAG.getSplatVector(IdxVT, DL, DAG.getConstant(0, DL, XLenVT)),
15676
15677 SDValue VLMax = DAG.getSplatVector(IdxVT, DL, computeVLMax(VecVT, DL, DAG));
15678
15679 // Build up the index vector for interleaving the concatenated vector
15680 // 0 0 1 1 2 2 3 3 ...
15681 SDValue Idx = DAG.getNode(ISD::SRL, DL, IdxVT, StepVec, Ones);
15682 // 0 n 1 n+1 2 n+2 3 n+3 ...
15683 Idx =
15684 DAG.getNode(RISCVISD::ADD_VL, DL, IdxVT, Idx, VLMax, Idx, OddMask, VL);
15685
15686 // Then perform the interleave
15687 // v[0] v[n] v[1] v[n+1] v[2] v[n+2] v[3] v[n+3] ...
15688 SDValue TrueMask = getAllOnesMask(IdxVT, VL, DL, DAG);
15689 Interleaved = DAG.getNode(RISCVISD::VRGATHEREI16_VV_VL, DL, ConcatVT,
15690 Concat, Idx, DAG.getUNDEF(ConcatVT), TrueMask, VL);
15691 }
15692
15693 // Extract the two halves from the interleaved result
15694 SDValue Lo = DAG.getExtractSubvector(DL, VecVT, Interleaved, 0);
15695 SDValue Hi = DAG.getExtractSubvector(DL, VecVT, Interleaved,
15696 VecVT.getVectorMinNumElements());
15697
15698 return DAG.getMergeValues({Lo, Hi}, DL);
15699}
15700
15701// Lower step_vector to the vid instruction. Any non-identity step value must
15702// be accounted for my manual expansion.
15703SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
15704 SelectionDAG &DAG) const {
15705 SDLoc DL(Op);
15706 MVT VT = Op.getSimpleValueType();
15707 assert(VT.isScalableVector() && "Expected scalable vector");
15708 MVT XLenVT = Subtarget.getXLenVT();
15709 auto [Mask, VL] = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
15710 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
15711 uint64_t StepValImm = Op.getConstantOperandVal(0);
15712 if (StepValImm != 1) {
15713 if (isPowerOf2_64(StepValImm)) {
15714 SDValue StepVal =
15715 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
15716 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT), VL);
15717 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
15718 } else {
15719 SDValue StepVal = lowerScalarSplat(
15720 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
15721 VL, VT, DL, DAG, Subtarget);
15722 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
15723 }
15724 }
15725 return StepVec;
15726}
15727
15728// Implement vector_reverse using vrgather.vv with indices determined by
15729// subtracting the id of each element from (VLMAX-1). This will convert
15730// the indices like so:
15731// (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
15732// TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
15733SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
15734 SelectionDAG &DAG) const {
15735 SDLoc DL(Op);
15736 MVT VecVT = Op.getSimpleValueType();
15737
15738 // Reverse a 64-bit packed vector on RV32 by reversing each 32-bit half and
15739 // swapping them.
15740 if (Subtarget.hasStdExtP() && !Subtarget.hasVInstructions()) {
15741 assert(!Subtarget.is64Bit() && VecVT.getSizeInBits() == 64 &&
15742 "Unexpected packed VECTOR_REVERSE type");
15743 SDValue V = Op.getOperand(0);
15744 if (VecVT == MVT::v2i32) {
15745 // A 2-element reverse is just an element swap.
15746 SDValue Lo = DAG.getExtractVectorElt(DL, MVT::i32, V, 0);
15747 SDValue Hi = DAG.getExtractVectorElt(DL, MVT::i32, V, 1);
15748 return DAG.getBuildVector(VecVT, DL, {Hi, Lo});
15749 }
15750 auto [Lo, Hi] = DAG.SplitVector(V, DL);
15751 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, Lo.getSimpleValueType(), Lo);
15752 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, Hi.getSimpleValueType(), Hi);
15753 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Hi, Lo);
15754 }
15755
15756 if (VecVT.getVectorElementType() == MVT::i1) {
15757 MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
15758 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0));
15759 SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1);
15760 return DAG.getSetCC(DL, VecVT, Op2,
15761 DAG.getConstant(0, DL, Op2.getValueType()), ISD::SETNE);
15762 }
15763
15764 MVT ContainerVT = VecVT;
15765 SDValue Vec = Op.getOperand(0);
15766 if (VecVT.isFixedLengthVector()) {
15768 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
15769 }
15770
15771 MVT XLenVT = Subtarget.getXLenVT();
15772 auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
15773
15774 // On some uarchs vrgather.vv will read from every input register for each
15775 // output register, regardless of the indices. However to reverse a vector
15776 // each output register only needs to read from one register. So decompose it
15777 // into LMUL * M1 vrgather.vvs, so we get O(LMUL) performance instead of
15778 // O(LMUL^2).
15779 //
15780 // vsetvli a1, zero, e64, m4, ta, ma
15781 // vrgatherei16.vv v12, v8, v16
15782 // ->
15783 // vsetvli a1, zero, e64, m1, ta, ma
15784 // vrgather.vv v15, v8, v16
15785 // vrgather.vv v14, v9, v16
15786 // vrgather.vv v13, v10, v16
15787 // vrgather.vv v12, v11, v16
15790 auto [Lo, Hi] = DAG.SplitVector(Vec, DL);
15791 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, Lo.getValueType(), Lo);
15792 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, Hi.getValueType(), Hi);
15794
15795 // Fixed length vectors might not fit exactly into their container, and so
15796 // leave a gap in the front of the vector after being reversed. Slide this
15797 // away.
15798 //
15799 // x x x x 3 2 1 0 <- v4i16 @ vlen=128
15800 // 0 1 2 3 x x x x <- reverse
15801 // x x x x 0 1 2 3 <- vslidedown.vx
15802 if (VecVT.isFixedLengthVector()) {
15803 SDValue Offset = DAG.getNode(
15804 ISD::SUB, DL, XLenVT,
15806 DAG.getElementCount(DL, XLenVT, VecVT.getVectorElementCount()));
15807 Concat =
15808 getVSlidedown(DAG, Subtarget, DL, ContainerVT,
15809 DAG.getUNDEF(ContainerVT), Concat, Offset, Mask, VL);
15810 Concat = convertFromScalableVector(VecVT, Concat, DAG, Subtarget);
15811 }
15812 return Concat;
15813 }
15814
15815 unsigned EltSize = ContainerVT.getScalarSizeInBits();
15816 unsigned MinSize = ContainerVT.getSizeInBits().getKnownMinValue();
15817 unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
15818 unsigned MaxVLMAX =
15819 VecVT.isFixedLengthVector()
15820 ? VecVT.getVectorNumElements()
15821 : RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
15822
15823 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
15825
15826 // If this is SEW=8 and VLMAX is potentially more than 256, we need
15827 // to use vrgatherei16.vv.
15828 if (MaxVLMAX > 256 && EltSize == 8) {
15829 // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
15830 // Reverse each half, then reassemble them in reverse order.
15831 // NOTE: It's also possible that after splitting that VLMAX no longer
15832 // requires vrgatherei16.vv.
15833 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
15834 auto [Lo, Hi] = DAG.SplitVectorOperand(Op.getNode(), 0);
15835 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VecVT);
15836 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
15837 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
15838 // Reassemble the low and high pieces reversed.
15839 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Hi, Lo);
15840 }
15841
15842 // Just promote the int type to i16 which will double the LMUL.
15844 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
15845 }
15846
15847 // At LMUL > 1, do the index computation in 16 bits to reduce register
15848 // pressure.
15849 if (IntVT.getScalarType().bitsGT(MVT::i16) &&
15850 IntVT.bitsGT(RISCVTargetLowering::getM1VT(IntVT))) {
15851 assert(isUInt<16>(MaxVLMAX - 1)); // Largest VLMAX is 65536 @ zvl65536b
15852 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
15853 IntVT = IntVT.changeVectorElementType(MVT::i16);
15854 }
15855
15856 // Calculate VLMAX-1 for the desired SEW.
15857 SDValue VLMinus1 = DAG.getNode(
15858 ISD::SUB, DL, XLenVT,
15859 DAG.getElementCount(DL, XLenVT, VecVT.getVectorElementCount()),
15860 DAG.getConstant(1, DL, XLenVT));
15861
15862 // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
15863 bool IsRV32E64 =
15864 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
15865 SDValue SplatVL;
15866 if (!IsRV32E64)
15867 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
15868 else
15869 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
15870 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
15871
15872 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
15873 SDValue Indices = DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID,
15874 DAG.getUNDEF(IntVT), Mask, VL);
15875
15876 SDValue Gather = DAG.getNode(GatherOpc, DL, ContainerVT, Vec, Indices,
15877 DAG.getUNDEF(ContainerVT), Mask, VL);
15878 if (VecVT.isFixedLengthVector())
15879 Gather = convertFromScalableVector(VecVT, Gather, DAG, Subtarget);
15880 return Gather;
15881}
15882
15883SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
15884 SelectionDAG &DAG) const {
15885 SDLoc DL(Op);
15886 SDValue V1 = Op.getOperand(0);
15887 SDValue V2 = Op.getOperand(1);
15888 SDValue Offset = Op.getOperand(2);
15889 MVT XLenVT = Subtarget.getXLenVT();
15890 MVT VecVT = Op.getSimpleValueType();
15891
15892 SDValue VLMax = computeVLMax(VecVT, DL, DAG);
15893
15894 SDValue DownOffset, UpOffset;
15895 if (Op.getOpcode() == ISD::VECTOR_SPLICE_LEFT) {
15896 // The operand is a TargetConstant, we need to rebuild it as a regular
15897 // constant.
15898 DownOffset = Offset;
15899 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, Offset);
15900 } else {
15901 // The operand is a TargetConstant, we need to rebuild it as a regular
15902 // constant rather than negating the original operand.
15903 UpOffset = Offset;
15904 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, Offset);
15905 }
15906
15907 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
15908
15909 SDValue SlideDown = getVSlidedown(
15910 DAG, Subtarget, DL, VecVT, DAG.getUNDEF(VecVT), V1, DownOffset, TrueMask,
15911 Subtarget.hasVLDependentLatency() ? UpOffset
15912 : DAG.getRegister(RISCV::X0, XLenVT));
15913 return getVSlideup(DAG, Subtarget, DL, VecVT, SlideDown, V2, UpOffset,
15914 TrueMask, DAG.getRegister(RISCV::X0, XLenVT),
15916}
15917
15918SDValue
15919RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
15920 SelectionDAG &DAG) const {
15921 SDLoc DL(Op);
15922 auto *Load = cast<LoadSDNode>(Op);
15923
15925 Load->getMemoryVT(),
15926 *Load->getMemOperand()) &&
15927 "Expecting a correctly-aligned load");
15928
15929 MVT VT = Op.getSimpleValueType();
15930 MVT XLenVT = Subtarget.getXLenVT();
15932
15933 // If we know the exact VLEN and our fixed length vector completely fills
15934 // the container, use a whole register load instead.
15935 const auto [MinVLMAX, MaxVLMAX] =
15937 if (MinVLMAX == MaxVLMAX && MinVLMAX == VT.getVectorNumElements() &&
15939 MachineMemOperand *MMO = Load->getMemOperand();
15940 SDValue NewLoad =
15941 DAG.getLoad(ContainerVT, DL, Load->getChain(), Load->getBasePtr(),
15942 MMO->getPointerInfo(), MMO->getBaseAlign(), MMO->getFlags(),
15943 MMOMetadata(MMO->getAAInfo(), MMO->getRanges()));
15944 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
15945 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
15946 }
15947
15948 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
15949
15950 bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
15951 SDValue IntID = DAG.getTargetConstant(
15952 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
15953 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
15954 if (!IsMaskOp)
15955 Ops.push_back(DAG.getUNDEF(ContainerVT));
15956 Ops.push_back(Load->getBasePtr());
15957 Ops.push_back(VL);
15958 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
15959 SDValue NewLoad =
15961 Load->getMemoryVT(), Load->getMemOperand());
15962
15963 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
15964 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
15965}
15966
15967SDValue
15968RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
15969 SelectionDAG &DAG) const {
15970 SDLoc DL(Op);
15971 auto *Store = cast<StoreSDNode>(Op);
15972
15974 Store->getMemoryVT(),
15975 *Store->getMemOperand()) &&
15976 "Expecting a correctly-aligned store");
15977
15978 SDValue StoreVal = Store->getValue();
15979 MVT VT = StoreVal.getSimpleValueType();
15980 MVT XLenVT = Subtarget.getXLenVT();
15981
15982 // If the size less than a byte, we need to pad with zeros to make a byte.
15983 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
15984 VT = MVT::v8i1;
15985 StoreVal =
15986 DAG.getInsertSubvector(DL, DAG.getConstant(0, DL, VT), StoreVal, 0);
15987 }
15988
15990
15991 SDValue NewValue =
15992 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
15993
15994 // If we know the exact VLEN and our fixed length vector completely fills
15995 // the container, use a whole register store instead.
15996 const auto [MinVLMAX, MaxVLMAX] =
15998 if (MinVLMAX == MaxVLMAX && MinVLMAX == VT.getVectorNumElements() &&
16000 MachineMemOperand *MMO = Store->getMemOperand();
16001 return DAG.getStore(Store->getChain(), DL, NewValue, Store->getBasePtr(),
16002 MMO->getPointerInfo(), MMO->getBaseAlign(),
16003 MMO->getFlags(), MMO->getAAInfo());
16004 }
16005
16006 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
16007
16008 bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
16009 SDValue IntID = DAG.getTargetConstant(
16010 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
16011 return DAG.getMemIntrinsicNode(
16012 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
16013 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
16014 Store->getMemoryVT(), Store->getMemOperand());
16015}
16016
16017SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
16018 SelectionDAG &DAG) const {
16019 SDLoc DL(Op);
16020 MVT VT = Op.getSimpleValueType();
16021
16022 const auto *MemSD = cast<MemSDNode>(Op);
16023 EVT MemVT = MemSD->getMemoryVT();
16024 MachineMemOperand *MMO = MemSD->getMemOperand();
16025 SDValue Chain = MemSD->getChain();
16026 SDValue BasePtr = MemSD->getBasePtr();
16027
16028 SDValue Mask, PassThru, VL;
16029 bool IsExpandingLoad = false;
16030 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
16031 Mask = VPLoad->getMask();
16032 PassThru = DAG.getUNDEF(VT);
16033 VL = VPLoad->getVectorLength();
16034 } else {
16035 const auto *MLoad = cast<MaskedLoadSDNode>(Op);
16036 Mask = MLoad->getMask();
16037 PassThru = MLoad->getPassThru();
16038 IsExpandingLoad = MLoad->isExpandingLoad();
16039 }
16040
16041 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask);
16042
16043 MVT XLenVT = Subtarget.getXLenVT();
16044
16045 MVT ContainerVT = VT;
16046 if (VT.isFixedLengthVector()) {
16048 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
16049 if (!IsUnmasked) {
16050 MVT MaskVT = getMaskTypeFor(ContainerVT);
16051 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
16052 }
16053 }
16054
16055 if (!VL)
16056 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
16057
16058 SDValue ExpandingVL;
16059 if (!IsUnmasked && IsExpandingLoad) {
16060 ExpandingVL = VL;
16061 VL =
16062 DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Mask,
16063 getAllOnesMask(Mask.getSimpleValueType(), VL, DL, DAG), VL);
16064 }
16065
16066 unsigned IntID = IsUnmasked || IsExpandingLoad ? Intrinsic::riscv_vle
16067 : Intrinsic::riscv_vle_mask;
16068 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
16069 if (IntID == Intrinsic::riscv_vle)
16070 Ops.push_back(DAG.getUNDEF(ContainerVT));
16071 else
16072 Ops.push_back(PassThru);
16073 Ops.push_back(BasePtr);
16074 if (IntID == Intrinsic::riscv_vle_mask)
16075 Ops.push_back(Mask);
16076 Ops.push_back(VL);
16077 if (IntID == Intrinsic::riscv_vle_mask)
16078 Ops.push_back(DAG.getTargetConstant(RISCVVType::TAIL_AGNOSTIC, DL, XLenVT));
16079
16080 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
16081
16082 SDValue Result =
16083 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
16084 Chain = Result.getValue(1);
16085 if (ExpandingVL) {
16086 MVT IndexVT = ContainerVT;
16089
16090 MVT IndexEltVT = IndexVT.getVectorElementType();
16091 bool UseVRGATHEREI16 = false;
16092 // If index vector is an i8 vector and the element count exceeds 256, we
16093 // should change the element type of index vector to i16 to avoid
16094 // overflow.
16095 uint64_t MaxEltCount = VT.getVectorMinNumElements();
16096 if (VT.isScalableVector())
16097 MaxEltCount *= Subtarget.getRealMaxVLen() / RISCV::RVVBitsPerBlock;
16098 if (IndexEltVT == MVT::i8 && MaxEltCount > 256) {
16099 // FIXME: We need to do vector splitting manually for LMUL=8 cases.
16100 assert(getLMUL(IndexVT) != RISCVVType::LMUL_8);
16101 IndexVT = IndexVT.changeVectorElementType(MVT::i16);
16102 UseVRGATHEREI16 = true;
16103 }
16104
16105 SDValue Iota =
16106 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
16107 DAG.getTargetConstant(Intrinsic::riscv_viota, DL, XLenVT),
16108 DAG.getUNDEF(IndexVT), Mask, ExpandingVL);
16109 Result =
16110 DAG.getNode(UseVRGATHEREI16 ? RISCVISD::VRGATHEREI16_VV_VL
16111 : RISCVISD::VRGATHER_VV_VL,
16112 DL, ContainerVT, Result, Iota, PassThru, Mask, ExpandingVL);
16113 }
16114
16115 if (VT.isFixedLengthVector())
16116 Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
16117
16118 return DAG.getMergeValues({Result, Chain}, DL);
16119}
16120
16121SDValue RISCVTargetLowering::lowerLoadFF(SDValue Op, SelectionDAG &DAG) const {
16122 SDLoc DL(Op);
16123 MVT VT = Op->getSimpleValueType(0);
16124
16125 const auto *VPLoadFF = cast<VPLoadFFSDNode>(Op);
16126 EVT MemVT = VPLoadFF->getMemoryVT();
16127 MachineMemOperand *MMO = VPLoadFF->getMemOperand();
16128 SDValue Chain = VPLoadFF->getChain();
16129 SDValue BasePtr = VPLoadFF->getBasePtr();
16130
16131 SDValue Mask = VPLoadFF->getMask();
16132 SDValue VL = VPLoadFF->getVectorLength();
16133
16134 MVT XLenVT = Subtarget.getXLenVT();
16135
16136 MVT ContainerVT = VT;
16137 if (VT.isFixedLengthVector()) {
16139 MVT MaskVT = getMaskTypeFor(ContainerVT);
16140 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
16141 }
16142
16143 unsigned IntID = Intrinsic::riscv_vleff_mask;
16144 SDValue Ops[] = {
16145 Chain,
16146 DAG.getTargetConstant(IntID, DL, XLenVT),
16147 DAG.getUNDEF(ContainerVT),
16148 BasePtr,
16149 Mask,
16150 VL,
16152
16153 SDVTList VTs = DAG.getVTList({ContainerVT, Op->getValueType(1), MVT::Other});
16154
16155 SDValue Result =
16156 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
16157 SDValue OutVL = Result.getValue(1);
16158 Chain = Result.getValue(2);
16159
16160 if (VT.isFixedLengthVector())
16161 Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
16162
16163 return DAG.getMergeValues({Result, OutVL, Chain}, DL);
16164}
16165
16166SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
16167 SelectionDAG &DAG) const {
16168 SDLoc DL(Op);
16169
16170 const auto *MemSD = cast<MemSDNode>(Op);
16171 EVT MemVT = MemSD->getMemoryVT();
16172 MachineMemOperand *MMO = MemSD->getMemOperand();
16173 SDValue Chain = MemSD->getChain();
16174 SDValue BasePtr = MemSD->getBasePtr();
16175 SDValue Val, Mask, VL;
16176
16177 bool IsCompressingStore = false;
16178 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
16179 Val = VPStore->getValue();
16180 Mask = VPStore->getMask();
16181 VL = VPStore->getVectorLength();
16182 } else {
16183 const auto *MStore = cast<MaskedStoreSDNode>(Op);
16184 Val = MStore->getValue();
16185 Mask = MStore->getMask();
16186 IsCompressingStore = MStore->isCompressingStore();
16187 }
16188
16189 bool IsUnmasked =
16190 ISD::isConstantSplatVectorAllOnes(Mask) || IsCompressingStore;
16191
16192 MVT VT = Val.getSimpleValueType();
16193 MVT XLenVT = Subtarget.getXLenVT();
16194
16195 MVT ContainerVT = VT;
16196 if (VT.isFixedLengthVector()) {
16198
16199 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
16200 if (!IsUnmasked || IsCompressingStore) {
16201 MVT MaskVT = getMaskTypeFor(ContainerVT);
16202 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
16203 }
16204 }
16205
16206 if (!VL)
16207 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
16208
16209 if (IsCompressingStore) {
16210 Val = DAG.getNode(
16212 DAG.getTargetConstant(Intrinsic::riscv_vcompress, DL, XLenVT),
16213 DAG.getUNDEF(ContainerVT), Val, Mask, VL);
16214 VL =
16215 DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Mask,
16216 getAllOnesMask(Mask.getSimpleValueType(), VL, DL, DAG), VL);
16217 }
16218
16219 unsigned IntID =
16220 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
16221 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
16222 Ops.push_back(Val);
16223 Ops.push_back(BasePtr);
16224 if (!IsUnmasked)
16225 Ops.push_back(Mask);
16226 Ops.push_back(VL);
16227
16229 DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
16230}
16231
16232SDValue RISCVTargetLowering::lowerVectorCompress(SDValue Op,
16233 SelectionDAG &DAG) const {
16234 SDLoc DL(Op);
16235 SDValue Val = Op.getOperand(0);
16236 SDValue Mask = Op.getOperand(1);
16237 SDValue Passthru = Op.getOperand(2);
16238
16239 MVT VT = Val.getSimpleValueType();
16240 MVT XLenVT = Subtarget.getXLenVT();
16241 MVT ContainerVT = VT;
16242 if (VT.isFixedLengthVector()) {
16244 MVT MaskVT = getMaskTypeFor(ContainerVT);
16245 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
16246 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
16247 Passthru = convertToScalableVector(ContainerVT, Passthru, DAG, Subtarget);
16248 }
16249
16250 SDValue VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
16251 SDValue Res =
16253 DAG.getTargetConstant(Intrinsic::riscv_vcompress, DL, XLenVT),
16254 Passthru, Val, Mask, VL);
16255
16256 if (VT.isFixedLengthVector())
16257 Res = convertFromScalableVector(VT, Res, DAG, Subtarget);
16258
16259 return Res;
16260}
16261
16262SDValue RISCVTargetLowering::lowerVectorStrictFSetcc(SDValue Op,
16263 SelectionDAG &DAG) const {
16264 unsigned Opc = Op.getOpcode();
16265 SDLoc DL(Op);
16266 SDValue Chain = Op.getOperand(0);
16267 SDValue Op1 = Op.getOperand(1);
16268 SDValue Op2 = Op.getOperand(2);
16269 SDValue CC = Op.getOperand(3);
16270 ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get();
16271 MVT VT = Op.getSimpleValueType();
16272 MVT InVT = Op1.getSimpleValueType();
16273
16274 // RVV VMFEQ/VMFNE ignores qNan, so we expand strict_fsetccs with OEQ/UNE
16275 // condition code.
16276 if (Opc == ISD::STRICT_FSETCCS) {
16277 // Expand strict_fsetccs(x, oeq) to
16278 // (and strict_fsetccs(x, y, oge), strict_fsetccs(x, y, ole))
16279 SDVTList VTList = Op->getVTList();
16280 if (CCVal == ISD::SETEQ || CCVal == ISD::SETOEQ) {
16281 SDValue OLECCVal = DAG.getCondCode(ISD::SETOLE);
16282 SDValue Tmp1 = DAG.getNode(ISD::STRICT_FSETCCS, DL, VTList, Chain, Op1,
16283 Op2, OLECCVal);
16284 SDValue Tmp2 = DAG.getNode(ISD::STRICT_FSETCCS, DL, VTList, Chain, Op2,
16285 Op1, OLECCVal);
16286 SDValue OutChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
16287 Tmp1.getValue(1), Tmp2.getValue(1));
16288 // Tmp1 and Tmp2 might be the same node.
16289 if (Tmp1 != Tmp2)
16290 Tmp1 = DAG.getNode(ISD::AND, DL, VT, Tmp1, Tmp2);
16291 return DAG.getMergeValues({Tmp1, OutChain}, DL);
16292 }
16293
16294 // Expand (strict_fsetccs x, y, une) to (not (strict_fsetccs x, y, oeq))
16295 if (CCVal == ISD::SETNE || CCVal == ISD::SETUNE) {
16296 SDValue OEQCCVal = DAG.getCondCode(ISD::SETOEQ);
16297 SDValue OEQ = DAG.getNode(ISD::STRICT_FSETCCS, DL, VTList, Chain, Op1,
16298 Op2, OEQCCVal);
16299 SDValue Res = DAG.getNOT(DL, OEQ, VT);
16300 return DAG.getMergeValues({Res, OEQ.getValue(1)}, DL);
16301 }
16302 }
16303
16304 MVT ContainerInVT = InVT;
16305 if (InVT.isFixedLengthVector()) {
16306 ContainerInVT = getContainerForFixedLengthVector(InVT);
16307 Op1 = convertToScalableVector(ContainerInVT, Op1, DAG, Subtarget);
16308 Op2 = convertToScalableVector(ContainerInVT, Op2, DAG, Subtarget);
16309 }
16310 MVT MaskVT = getMaskTypeFor(ContainerInVT);
16311
16312 auto [Mask, VL] = getDefaultVLOps(InVT, ContainerInVT, DL, DAG, Subtarget);
16313
16314 SDValue Res;
16315 if (Opc == ISD::STRICT_FSETCC &&
16316 (CCVal == ISD::SETLT || CCVal == ISD::SETOLT || CCVal == ISD::SETLE ||
16317 CCVal == ISD::SETOLE)) {
16318 // VMFLT/VMFLE/VMFGT/VMFGE raise exception for qNan. Generate a mask to only
16319 // active when both input elements are ordered.
16320 SDValue True = getAllOnesMask(ContainerInVT, VL, DL, DAG);
16321 SDValue OrderMask1 = DAG.getNode(
16322 RISCVISD::STRICT_FSETCC_VL, DL, DAG.getVTList(MaskVT, MVT::Other),
16323 {Chain, Op1, Op1, DAG.getCondCode(ISD::SETOEQ), DAG.getUNDEF(MaskVT),
16324 True, VL});
16325 SDValue OrderMask2 = DAG.getNode(
16326 RISCVISD::STRICT_FSETCC_VL, DL, DAG.getVTList(MaskVT, MVT::Other),
16327 {Chain, Op2, Op2, DAG.getCondCode(ISD::SETOEQ), DAG.getUNDEF(MaskVT),
16328 True, VL});
16329 Mask =
16330 DAG.getNode(RISCVISD::VMAND_VL, DL, MaskVT, OrderMask1, OrderMask2, VL);
16331 // Use Mask as the passthru operand to let the result be 0 if either of the
16332 // inputs is unordered.
16333 Res = DAG.getNode(RISCVISD::STRICT_FSETCCS_VL, DL,
16334 DAG.getVTList(MaskVT, MVT::Other),
16335 {Chain, Op1, Op2, CC, Mask, Mask, VL});
16336 } else {
16337 unsigned RVVOpc = Opc == ISD::STRICT_FSETCC ? RISCVISD::STRICT_FSETCC_VL
16338 : RISCVISD::STRICT_FSETCCS_VL;
16339 Res = DAG.getNode(RVVOpc, DL, DAG.getVTList(MaskVT, MVT::Other),
16340 {Chain, Op1, Op2, CC, DAG.getUNDEF(MaskVT), Mask, VL});
16341 }
16342
16343 if (VT.isFixedLengthVector()) {
16344 SDValue SubVec = convertFromScalableVector(VT, Res, DAG, Subtarget);
16345 return DAG.getMergeValues({SubVec, Res.getValue(1)}, DL);
16346 }
16347 return Res;
16348}
16349
16350// Lower vector ABS to smax(X, sub(0, X)).
16351SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
16352 SDLoc DL(Op);
16353 MVT VT = Op.getSimpleValueType();
16354 SDValue X = Op.getOperand(0);
16355
16356 assert(VT.isFixedLengthVector() && "Unexpected type for ISD::ABS");
16357
16359 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
16360
16361 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
16362
16363 SDValue SplatZero = DAG.getNode(
16364 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
16365 DAG.getConstant(0, DL, Subtarget.getXLenVT()), VL);
16367 if (Subtarget.hasStdExtZvabd()) {
16368 Result = DAG.getNode(RISCVISD::ABDS_VL, DL, ContainerVT, X, SplatZero,
16369 DAG.getUNDEF(ContainerVT), Mask, VL);
16370 } else {
16371 SDValue NegX = DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X,
16372 DAG.getUNDEF(ContainerVT), Mask, VL);
16373 Result = DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX,
16374 DAG.getUNDEF(ContainerVT), Mask, VL);
16375 }
16376 return convertFromScalableVector(VT, Result, DAG, Subtarget);
16377}
16378
16379SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op,
16380 SelectionDAG &DAG) const {
16381 const auto &TSInfo =
16382 static_cast<const RISCVSelectionDAGInfo &>(DAG.getSelectionDAGInfo());
16383
16384 unsigned NewOpc = getRISCVVLOp(Op);
16385 bool HasPassthruOp = TSInfo.hasPassthruOp(NewOpc);
16386 bool HasMask = TSInfo.hasMaskOp(NewOpc);
16387
16388 MVT VT = Op.getSimpleValueType();
16390
16391 // Create list of operands by converting existing ones to scalable types.
16393 for (const SDValue &V : Op->op_values()) {
16394 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
16395
16396 // Pass through non-vector operands.
16397 if (!V.getValueType().isVector()) {
16398 Ops.push_back(V);
16399 continue;
16400 }
16401
16402 // "cast" fixed length vector to a scalable vector.
16403 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
16404 "Only fixed length vectors are supported!");
16405 MVT VContainerVT = ContainerVT.changeVectorElementType(
16406 V.getSimpleValueType().getVectorElementType());
16407 Ops.push_back(convertToScalableVector(VContainerVT, V, DAG, Subtarget));
16408 }
16409
16410 SDLoc DL(Op);
16411 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
16412 if (HasPassthruOp)
16413 Ops.push_back(DAG.getUNDEF(ContainerVT));
16414 if (HasMask)
16415 Ops.push_back(Mask);
16416 Ops.push_back(VL);
16417
16418 // StrictFP operations have two result values. Their lowered result should
16419 // have same result count.
16420 if (Op->isStrictFPOpcode()) {
16421 SDValue ScalableRes =
16422 DAG.getNode(NewOpc, DL, DAG.getVTList(ContainerVT, MVT::Other), Ops,
16423 Op->getFlags());
16424 SDValue SubVec = convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
16425 return DAG.getMergeValues({SubVec, ScalableRes.getValue(1)}, DL);
16426 }
16427
16428 SDValue ScalableRes =
16429 DAG.getNode(NewOpc, DL, ContainerVT, Ops, Op->getFlags());
16430 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
16431}
16432
16433// Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
16434// * Operands of each node are assumed to be in the same order.
16435// * The EVL operand is promoted from i32 to i64 on RV64.
16436// * Fixed-length vectors are converted to their scalable-vector container
16437// types.
16438SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG) const {
16439 const auto &TSInfo =
16440 static_cast<const RISCVSelectionDAGInfo &>(DAG.getSelectionDAGInfo());
16441
16442 unsigned RISCVISDOpc = getRISCVVLOp(Op);
16443 bool HasPassthruOp = TSInfo.hasPassthruOp(RISCVISDOpc);
16444
16445 SDLoc DL(Op);
16446 MVT VT = Op.getSimpleValueType();
16448
16449 MVT ContainerVT = VT;
16450 if (VT.isFixedLengthVector())
16452
16453 for (const auto &OpIdx : enumerate(Op->ops())) {
16454 SDValue V = OpIdx.value();
16455 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
16456 // Add dummy passthru value before the mask. Or if there isn't a mask,
16457 // before EVL.
16458 if (HasPassthruOp) {
16459 auto MaskIdx = ISD::getVPMaskIdx(Op.getOpcode());
16460 if (MaskIdx) {
16461 if (*MaskIdx == OpIdx.index())
16462 Ops.push_back(DAG.getUNDEF(ContainerVT));
16463 } else if (ISD::getVPExplicitVectorLengthIdx(Op.getOpcode()) ==
16464 OpIdx.index()) {
16465 assert(Op.getOpcode() == ISD::VP_MERGE);
16466 // For VP_MERGE, copy the false operand instead of an undef value.
16467 Ops.push_back(Ops.back());
16468 }
16469 }
16470 // VFCVT_RM_X_F_VL requires a rounding mode to be injected before the VL.
16471 if (RISCVISDOpc == RISCVISD::VFCVT_RM_X_F_VL &&
16472 ISD::getVPExplicitVectorLengthIdx(Op.getOpcode()) == OpIdx.index())
16474 Subtarget.getXLenVT()));
16475 // Pass through operands which aren't fixed-length vectors.
16476 if (!V.getValueType().isFixedLengthVector()) {
16477 Ops.push_back(V);
16478 continue;
16479 }
16480 // "cast" fixed length vector to a scalable vector.
16481 MVT OpVT = V.getSimpleValueType();
16483 assert(useRVVForFixedLengthVectorVT(OpVT) &&
16484 "Only fixed length vectors are supported!");
16485 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
16486 }
16487
16488 if (!VT.isFixedLengthVector())
16489 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
16490
16491 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
16492
16493 return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
16494}
16495
16496SDValue RISCVTargetLowering::lowerVPMergeMask(SDValue Op,
16497 SelectionDAG &DAG) const {
16498 SDLoc DL(Op);
16499 MVT VT = Op.getSimpleValueType();
16500 MVT XLenVT = Subtarget.getXLenVT();
16501
16502 SDValue Mask = Op.getOperand(0);
16503 SDValue TrueVal = Op.getOperand(1);
16504 SDValue FalseVal = Op.getOperand(2);
16505 SDValue VL = Op.getOperand(3);
16506
16507 // Use default legalization if a vector of EVL type would be legal.
16508 EVT EVLVecVT = EVT::getVectorVT(*DAG.getContext(), VL.getValueType(),
16510 if (isTypeLegal(EVLVecVT))
16511 return SDValue();
16512
16513 MVT ContainerVT = VT;
16514 if (VT.isFixedLengthVector()) {
16516 Mask = convertToScalableVector(ContainerVT, Mask, DAG, Subtarget);
16517 TrueVal = convertToScalableVector(ContainerVT, TrueVal, DAG, Subtarget);
16518 FalseVal = convertToScalableVector(ContainerVT, FalseVal, DAG, Subtarget);
16519 }
16520
16521 // Promote to a vector of i8.
16522 MVT PromotedVT = ContainerVT.changeVectorElementType(MVT::i8);
16523
16524 // Promote TrueVal and FalseVal using VLMax.
16525 // FIXME: Is there a better way to do this?
16526 SDValue VLMax = DAG.getRegister(RISCV::X0, XLenVT);
16527 SDValue SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, PromotedVT,
16528 DAG.getUNDEF(PromotedVT),
16529 DAG.getConstant(1, DL, XLenVT), VLMax);
16530 SDValue SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, PromotedVT,
16531 DAG.getUNDEF(PromotedVT),
16532 DAG.getConstant(0, DL, XLenVT), VLMax);
16533 TrueVal = DAG.getNode(RISCVISD::VMERGE_VL, DL, PromotedVT, TrueVal, SplatOne,
16534 SplatZero, DAG.getUNDEF(PromotedVT), VL);
16535 // Any element past VL uses FalseVal, so use VLMax
16536 FalseVal = DAG.getNode(RISCVISD::VMERGE_VL, DL, PromotedVT, FalseVal,
16537 SplatOne, SplatZero, DAG.getUNDEF(PromotedVT), VLMax);
16538
16539 // VP_MERGE the two promoted values.
16540 SDValue VPMerge = DAG.getNode(RISCVISD::VMERGE_VL, DL, PromotedVT, Mask,
16541 TrueVal, FalseVal, FalseVal, VL);
16542
16543 // Convert back to mask.
16544 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
16545 SDValue Result = DAG.getNode(
16546 RISCVISD::SETCC_VL, DL, ContainerVT,
16547 {VPMerge, DAG.getConstant(0, DL, PromotedVT), DAG.getCondCode(ISD::SETNE),
16548 DAG.getUNDEF(getMaskTypeFor(ContainerVT)), TrueMask, VLMax});
16549
16550 if (VT.isFixedLengthVector())
16551 Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
16552 return Result;
16553}
16554
16555SDValue
16556RISCVTargetLowering::lowerVPSpliceExperimental(SDValue Op,
16557 SelectionDAG &DAG) const {
16558 using namespace SDPatternMatch;
16559
16560 SDLoc DL(Op);
16561
16562 SDValue Op1 = Op.getOperand(0);
16563 SDValue Op2 = Op.getOperand(1);
16564 SDValue Offset = Op.getOperand(2);
16565 SDValue Mask = Op.getOperand(3);
16566 SDValue EVL1 = Op.getOperand(4);
16567 SDValue EVL2 = Op.getOperand(5);
16568
16569 const MVT XLenVT = Subtarget.getXLenVT();
16570 MVT VT = Op.getSimpleValueType();
16571 MVT ContainerVT = VT;
16572 if (VT.isFixedLengthVector()) {
16574 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
16575 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
16576 MVT MaskVT = getMaskTypeFor(ContainerVT);
16577 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
16578 }
16579
16580 bool IsMaskVector = VT.getVectorElementType() == MVT::i1;
16581 if (IsMaskVector) {
16583
16584 // Expand input operands
16585 SDValue SplatOneOp1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
16586 DAG.getUNDEF(ContainerVT),
16587 DAG.getConstant(1, DL, XLenVT), EVL1);
16588 SDValue SplatZeroOp1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
16589 DAG.getUNDEF(ContainerVT),
16590 DAG.getConstant(0, DL, XLenVT), EVL1);
16591 Op1 = DAG.getNode(RISCVISD::VMERGE_VL, DL, ContainerVT, Op1, SplatOneOp1,
16592 SplatZeroOp1, DAG.getUNDEF(ContainerVT), EVL1);
16593
16594 SDValue SplatOneOp2 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
16595 DAG.getUNDEF(ContainerVT),
16596 DAG.getConstant(1, DL, XLenVT), EVL2);
16597 SDValue SplatZeroOp2 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
16598 DAG.getUNDEF(ContainerVT),
16599 DAG.getConstant(0, DL, XLenVT), EVL2);
16600 Op2 = DAG.getNode(RISCVISD::VMERGE_VL, DL, ContainerVT, Op2, SplatOneOp2,
16601 SplatZeroOp2, DAG.getUNDEF(ContainerVT), EVL2);
16602 }
16603
16604 auto getVectorFirstEle = [](SDValue Vec) {
16605 SDValue FirstEle;
16606 if (sd_match(Vec, m_InsertElt(m_Value(), m_Value(FirstEle), m_Zero())))
16607 return FirstEle;
16608
16609 if (Vec.getOpcode() == ISD::SPLAT_VECTOR ||
16611 return Vec.getOperand(0);
16612
16613 return SDValue();
16614 };
16615
16616 if (!IsMaskVector && isNullConstant(Offset) && isOneConstant(EVL1))
16617 if (auto FirstEle = getVectorFirstEle(Op->getOperand(0))) {
16618 MVT EltVT = ContainerVT.getVectorElementType();
16620 if ((EltVT == MVT::f16 && !Subtarget.hasVInstructionsF16()) ||
16621 (EltVT == MVT::bf16 && !Subtarget.hasVInstructionsBF16())) {
16622 EltVT = EltVT.changeTypeToInteger();
16624 Op2 = DAG.getBitcast(ContainerVT, Op2);
16625 FirstEle =
16626 DAG.getAnyExtOrTrunc(DAG.getBitcast(EltVT, FirstEle), DL, XLenVT);
16627 }
16628 Result = DAG.getNode(EltVT.isFloatingPoint() ? RISCVISD::VFSLIDE1UP_VL
16629 : RISCVISD::VSLIDE1UP_VL,
16630 DL, ContainerVT, DAG.getUNDEF(ContainerVT), Op2,
16631 FirstEle, Mask, EVL2);
16632 Result = DAG.getBitcast(
16634 Result);
16635 return VT.isFixedLengthVector()
16636 ? convertFromScalableVector(VT, Result, DAG, Subtarget)
16637 : Result;
16638 }
16639
16640 int64_t ImmValue = cast<ConstantSDNode>(Offset)->getSExtValue();
16641 SDValue DownOffset, UpOffset;
16642 if (ImmValue >= 0) {
16643 // The operand is a TargetConstant, we need to rebuild it as a regular
16644 // constant.
16645 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
16646 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, EVL1, DownOffset);
16647 } else {
16648 // The operand is a TargetConstant, we need to rebuild it as a regular
16649 // constant rather than negating the original operand.
16650 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
16651 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, EVL1, UpOffset);
16652 }
16653
16654 if (ImmValue != 0)
16655 Op1 = getVSlidedown(DAG, Subtarget, DL, ContainerVT,
16656 DAG.getUNDEF(ContainerVT), Op1, DownOffset, Mask,
16657 Subtarget.hasVLDependentLatency() ? UpOffset : EVL2);
16658 SDValue Result = getVSlideup(DAG, Subtarget, DL, ContainerVT, Op1, Op2,
16659 UpOffset, Mask, EVL2, RISCVVType::TAIL_AGNOSTIC);
16660
16661 if (IsMaskVector) {
16662 // Truncate Result back to a mask vector (Result has same EVL as Op2)
16663 Result = DAG.getNode(
16664 RISCVISD::SETCC_VL, DL, ContainerVT.changeVectorElementType(MVT::i1),
16665 {Result, DAG.getConstant(0, DL, ContainerVT),
16666 DAG.getCondCode(ISD::SETNE), DAG.getUNDEF(getMaskTypeFor(ContainerVT)),
16667 Mask, EVL2});
16668 }
16669
16670 if (!VT.isFixedLengthVector())
16671 return Result;
16672 return convertFromScalableVector(VT, Result, DAG, Subtarget);
16673}
16674
16675SDValue
16676RISCVTargetLowering::lowerVPReverseExperimental(SDValue Op,
16677 SelectionDAG &DAG) const {
16678 SDLoc DL(Op);
16679 MVT VT = Op.getSimpleValueType();
16680 MVT XLenVT = Subtarget.getXLenVT();
16681
16682 SDValue Op1 = Op.getOperand(0);
16683 SDValue Mask = Op.getOperand(1);
16684 SDValue EVL = Op.getOperand(2);
16685
16686 MVT ContainerVT = VT;
16687 if (VT.isFixedLengthVector()) {
16689 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
16690 MVT MaskVT = getMaskTypeFor(ContainerVT);
16691 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
16692 }
16693
16694 MVT GatherVT = ContainerVT;
16696 // Check if we are working with mask vectors
16697 bool IsMaskVector = ContainerVT.getVectorElementType() == MVT::i1;
16698 if (IsMaskVector) {
16699 GatherVT = IndicesVT = ContainerVT.changeVectorElementType(MVT::i8);
16700
16701 // Expand input operand
16702 SDValue SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IndicesVT,
16703 DAG.getUNDEF(IndicesVT),
16704 DAG.getConstant(1, DL, XLenVT), EVL);
16705 SDValue SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IndicesVT,
16706 DAG.getUNDEF(IndicesVT),
16707 DAG.getConstant(0, DL, XLenVT), EVL);
16708 Op1 = DAG.getNode(RISCVISD::VMERGE_VL, DL, IndicesVT, Op1, SplatOne,
16709 SplatZero, DAG.getUNDEF(IndicesVT), EVL);
16710 }
16711
16712 unsigned EltSize = GatherVT.getScalarSizeInBits();
16713 unsigned MinSize = GatherVT.getSizeInBits().getKnownMinValue();
16714 unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
16715 unsigned MaxVLMAX =
16716 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
16717
16718 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
16719 // If this is SEW=8 and VLMAX is unknown or more than 256, we need
16720 // to use vrgatherei16.vv.
16721 // TODO: It's also possible to use vrgatherei16.vv for other types to
16722 // decrease register width for the index calculation.
16723 // NOTE: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
16724 if (MaxVLMAX > 256 && EltSize == 8) {
16725 // If this is LMUL=8, we have to split before using vrgatherei16.vv.
16726 // Split the vector in half and reverse each half using a full register
16727 // reverse.
16728 // Swap the halves and concatenate them.
16729 // Slide the concatenated result by (VLMax - VL).
16730 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
16731 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(GatherVT);
16732 auto [Lo, Hi] = DAG.SplitVector(Op1, DL);
16733
16734 SDValue LoRev = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
16735 SDValue HiRev = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
16736
16737 // Reassemble the low and high pieces reversed.
16738 // NOTE: this Result is unmasked (because we do not need masks for
16739 // shuffles). If in the future this has to change, we can use a SELECT_VL
16740 // between Result and UNDEF using the mask originally passed to VP_REVERSE
16741 SDValue Result =
16742 DAG.getNode(ISD::CONCAT_VECTORS, DL, GatherVT, HiRev, LoRev);
16743
16744 // Slide off any elements from past EVL that were reversed into the low
16745 // elements.
16746 SDValue VLMax =
16747 DAG.getElementCount(DL, XLenVT, GatherVT.getVectorElementCount());
16748 SDValue Diff = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, EVL);
16749
16750 Result = getVSlidedown(DAG, Subtarget, DL, GatherVT,
16751 DAG.getUNDEF(GatherVT), Result, Diff, Mask, EVL);
16752
16753 if (IsMaskVector) {
16754 // Truncate Result back to a mask vector
16755 Result =
16756 DAG.getNode(RISCVISD::SETCC_VL, DL, ContainerVT,
16757 {Result, DAG.getConstant(0, DL, GatherVT),
16760 }
16761
16762 if (!VT.isFixedLengthVector())
16763 return Result;
16764 return convertFromScalableVector(VT, Result, DAG, Subtarget);
16765 }
16766
16767 // Just promote the int type to i16 which will double the LMUL.
16768 IndicesVT = MVT::getVectorVT(MVT::i16, IndicesVT.getVectorElementCount());
16769 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
16770 }
16771
16772 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IndicesVT, Mask, EVL);
16773 SDValue VecLen =
16774 DAG.getNode(ISD::SUB, DL, XLenVT, EVL, DAG.getConstant(1, DL, XLenVT));
16775 SDValue VecLenSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IndicesVT,
16776 DAG.getUNDEF(IndicesVT), VecLen, EVL);
16777 SDValue VRSUB = DAG.getNode(RISCVISD::SUB_VL, DL, IndicesVT, VecLenSplat, VID,
16778 DAG.getUNDEF(IndicesVT), Mask, EVL);
16779 SDValue Result = DAG.getNode(GatherOpc, DL, GatherVT, Op1, VRSUB,
16780 DAG.getUNDEF(GatherVT), Mask, EVL);
16781
16782 if (IsMaskVector) {
16783 // Truncate Result back to a mask vector
16784 Result = DAG.getNode(
16785 RISCVISD::SETCC_VL, DL, ContainerVT,
16786 {Result, DAG.getConstant(0, DL, GatherVT), DAG.getCondCode(ISD::SETNE),
16788 }
16789
16790 if (!VT.isFixedLengthVector())
16791 return Result;
16792 return convertFromScalableVector(VT, Result, DAG, Subtarget);
16793}
16794
16795SDValue RISCVTargetLowering::lowerVPStridedLoad(SDValue Op,
16796 SelectionDAG &DAG) const {
16797 SDLoc DL(Op);
16798 MVT XLenVT = Subtarget.getXLenVT();
16799 MVT VT = Op.getSimpleValueType();
16800 MVT ContainerVT = VT;
16801 if (VT.isFixedLengthVector())
16803
16804 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
16805
16806 auto *VPNode = cast<VPStridedLoadSDNode>(Op);
16807 // Check if the mask is known to be all ones
16808 SDValue Mask = VPNode->getMask();
16809 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask);
16810
16811 SDValue IntID = DAG.getTargetConstant(IsUnmasked ? Intrinsic::riscv_vlse
16812 : Intrinsic::riscv_vlse_mask,
16813 DL, XLenVT);
16814 SmallVector<SDValue, 8> Ops{VPNode->getChain(), IntID,
16815 DAG.getUNDEF(ContainerVT), VPNode->getBasePtr(),
16816 VPNode->getStride()};
16817 if (!IsUnmasked) {
16818 if (VT.isFixedLengthVector()) {
16819 MVT MaskVT = ContainerVT.changeVectorElementType(MVT::i1);
16820 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
16821 }
16822 Ops.push_back(Mask);
16823 }
16824 Ops.push_back(VPNode->getVectorLength());
16825 if (!IsUnmasked) {
16826 SDValue Policy =
16828 Ops.push_back(Policy);
16829 }
16830
16831 SDValue Result =
16833 VPNode->getMemoryVT(), VPNode->getMemOperand());
16834 SDValue Chain = Result.getValue(1);
16835
16836 if (VT.isFixedLengthVector())
16837 Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
16838
16839 return DAG.getMergeValues({Result, Chain}, DL);
16840}
16841
16842SDValue RISCVTargetLowering::lowerVPStridedStore(SDValue Op,
16843 SelectionDAG &DAG) const {
16844 SDLoc DL(Op);
16845 MVT XLenVT = Subtarget.getXLenVT();
16846
16847 auto *VPNode = cast<VPStridedStoreSDNode>(Op);
16848 SDValue StoreVal = VPNode->getValue();
16849 MVT VT = StoreVal.getSimpleValueType();
16850 MVT ContainerVT = VT;
16851 if (VT.isFixedLengthVector()) {
16853 StoreVal = convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
16854 }
16855
16856 // Check if the mask is known to be all ones
16857 SDValue Mask = VPNode->getMask();
16858 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask);
16859
16860 SDValue IntID = DAG.getTargetConstant(IsUnmasked ? Intrinsic::riscv_vsse
16861 : Intrinsic::riscv_vsse_mask,
16862 DL, XLenVT);
16863 SmallVector<SDValue, 8> Ops{VPNode->getChain(), IntID, StoreVal,
16864 VPNode->getBasePtr(), VPNode->getStride()};
16865 if (!IsUnmasked) {
16866 if (VT.isFixedLengthVector()) {
16867 MVT MaskVT = ContainerVT.changeVectorElementType(MVT::i1);
16868 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
16869 }
16870 Ops.push_back(Mask);
16871 }
16872 Ops.push_back(VPNode->getVectorLength());
16873
16874 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, VPNode->getVTList(),
16875 Ops, VPNode->getMemoryVT(),
16876 VPNode->getMemOperand());
16877}
16878
16879// Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
16880// matched to a RVV indexed load. The RVV indexed load instructions only
16881// support the "unsigned unscaled" addressing mode; indices are implicitly
16882// zero-extended or truncated to XLEN and are treated as byte offsets. Any
16883// signed or scaled indexing is extended to the XLEN value type and scaled
16884// accordingly.
16885SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
16886 SelectionDAG &DAG) const {
16887 SDLoc DL(Op);
16888 MVT VT = Op.getSimpleValueType();
16889
16890 const auto *MemSD = cast<MemSDNode>(Op.getNode());
16891 EVT MemVT = MemSD->getMemoryVT();
16892 MachineMemOperand *MMO = MemSD->getMemOperand();
16893 SDValue Chain = MemSD->getChain();
16894 SDValue BasePtr = MemSD->getBasePtr();
16895
16896 [[maybe_unused]] ISD::LoadExtType LoadExtType;
16897 SDValue Index, Mask, PassThru, VL;
16898
16899 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
16900 Index = VPGN->getIndex();
16901 Mask = VPGN->getMask();
16902 PassThru = DAG.getUNDEF(VT);
16903 VL = VPGN->getVectorLength();
16904 // VP doesn't support extending loads.
16906 } else {
16907 // Else it must be a MGATHER.
16908 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
16909 Index = MGN->getIndex();
16910 Mask = MGN->getMask();
16911 PassThru = MGN->getPassThru();
16912 LoadExtType = MGN->getExtensionType();
16913 }
16914
16915 MVT IndexVT = Index.getSimpleValueType();
16916 MVT XLenVT = Subtarget.getXLenVT();
16917
16919 "Unexpected VTs!");
16920 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
16921 // Targets have to explicitly opt-in for extending vector loads.
16922 assert(LoadExtType == ISD::NON_EXTLOAD &&
16923 "Unexpected extending MGATHER/VP_GATHER");
16924
16925 // If the mask is known to be all ones, optimize to an unmasked intrinsic;
16926 // the selection of the masked intrinsics doesn't do this for us.
16927 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask);
16928
16929 MVT ContainerVT = VT;
16930 if (VT.isFixedLengthVector()) {
16932 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
16934
16935 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
16936
16937 if (!IsUnmasked) {
16938 MVT MaskVT = getMaskTypeFor(ContainerVT);
16939 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
16940 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
16941 }
16942 }
16943
16944 if (!VL)
16945 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
16946
16947 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
16948 IndexVT = IndexVT.changeVectorElementType(XLenVT);
16949 Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
16950 }
16951
16952 unsigned IntID =
16953 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
16954 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
16955 if (IsUnmasked)
16956 Ops.push_back(DAG.getUNDEF(ContainerVT));
16957 else
16958 Ops.push_back(PassThru);
16959 Ops.push_back(BasePtr);
16960 Ops.push_back(Index);
16961 if (!IsUnmasked)
16962 Ops.push_back(Mask);
16963 Ops.push_back(VL);
16964 if (!IsUnmasked)
16965 Ops.push_back(DAG.getTargetConstant(RISCVVType::TAIL_AGNOSTIC, DL, XLenVT));
16966
16967 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
16968 SDValue Result =
16969 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
16970 Chain = Result.getValue(1);
16971
16972 if (VT.isFixedLengthVector())
16973 Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
16974
16975 return DAG.getMergeValues({Result, Chain}, DL);
16976}
16977
16978// Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
16979// matched to a RVV indexed store. The RVV indexed store instructions only
16980// support the "unsigned unscaled" addressing mode; indices are implicitly
16981// zero-extended or truncated to XLEN and are treated as byte offsets. Any
16982// signed or scaled indexing is extended to the XLEN value type and scaled
16983// accordingly.
16984SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
16985 SelectionDAG &DAG) const {
16986 SDLoc DL(Op);
16987 const auto *MemSD = cast<MemSDNode>(Op.getNode());
16988 EVT MemVT = MemSD->getMemoryVT();
16989 MachineMemOperand *MMO = MemSD->getMemOperand();
16990 SDValue Chain = MemSD->getChain();
16991 SDValue BasePtr = MemSD->getBasePtr();
16992
16993 [[maybe_unused]] bool IsTruncatingStore = false;
16994 SDValue Index, Mask, Val, VL;
16995
16996 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
16997 Index = VPSN->getIndex();
16998 Mask = VPSN->getMask();
16999 Val = VPSN->getValue();
17000 VL = VPSN->getVectorLength();
17001 // VP doesn't support truncating stores.
17002 IsTruncatingStore = false;
17003 } else {
17004 // Else it must be a MSCATTER.
17005 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
17006 Index = MSN->getIndex();
17007 Mask = MSN->getMask();
17008 Val = MSN->getValue();
17009 IsTruncatingStore = MSN->isTruncatingStore();
17010 }
17011
17012 MVT VT = Val.getSimpleValueType();
17013 MVT IndexVT = Index.getSimpleValueType();
17014 MVT XLenVT = Subtarget.getXLenVT();
17015
17017 "Unexpected VTs!");
17018 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
17019 // Targets have to explicitly opt-in for extending vector loads and
17020 // truncating vector stores.
17021 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
17022
17023 // If the mask is known to be all ones, optimize to an unmasked intrinsic;
17024 // the selection of the masked intrinsics doesn't do this for us.
17025 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask);
17026
17027 MVT ContainerVT = VT;
17028 if (VT.isFixedLengthVector()) {
17030 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
17032
17033 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
17034 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
17035
17036 if (!IsUnmasked) {
17037 MVT MaskVT = getMaskTypeFor(ContainerVT);
17038 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
17039 }
17040 }
17041
17042 if (!VL)
17043 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
17044
17045 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
17046 IndexVT = IndexVT.changeVectorElementType(XLenVT);
17047 Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
17048 }
17049
17050 unsigned IntID =
17051 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
17052 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
17053 Ops.push_back(Val);
17054 Ops.push_back(BasePtr);
17055 Ops.push_back(Index);
17056 if (!IsUnmasked)
17057 Ops.push_back(Mask);
17058 Ops.push_back(VL);
17059
17061 DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
17062}
17063
17064SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
17065 SelectionDAG &DAG) const {
17066 const MVT XLenVT = Subtarget.getXLenVT();
17067 SDLoc DL(Op);
17068 SDValue Chain = Op->getOperand(0);
17069 SDValue SysRegNo = DAG.getTargetConstant(RISCVSysReg::frm, DL, XLenVT);
17070 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
17071 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
17072
17073 // Encoding used for rounding mode in RISC-V differs from that used in
17074 // FLT_ROUNDS. To convert it the RISC-V rounding mode is used as an index in a
17075 // table, which consists of a sequence of 4-bit fields, each representing
17076 // corresponding FLT_ROUNDS mode.
17077 static const int Table =
17083
17084 SDValue Shift =
17085 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
17086 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
17087 DAG.getConstant(Table, DL, XLenVT), Shift);
17088 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
17089 DAG.getConstant(7, DL, XLenVT));
17090
17091 return DAG.getMergeValues({Masked, Chain}, DL);
17092}
17093
17094SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
17095 SelectionDAG &DAG) const {
17096 const MVT XLenVT = Subtarget.getXLenVT();
17097 SDLoc DL(Op);
17098 SDValue Chain = Op->getOperand(0);
17099 SDValue RMValue = Op->getOperand(1);
17100 SDValue SysRegNo = DAG.getTargetConstant(RISCVSysReg::frm, DL, XLenVT);
17101
17102 // Encoding used for rounding mode in RISC-V differs from that used in
17103 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
17104 // a table, which consists of a sequence of 4-bit fields, each representing
17105 // corresponding RISC-V mode.
17106 static const unsigned Table =
17112
17113 RMValue = DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, RMValue);
17114
17115 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
17116 DAG.getConstant(2, DL, XLenVT));
17117 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
17118 DAG.getConstant(Table, DL, XLenVT), Shift);
17119 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
17120 DAG.getConstant(0x7, DL, XLenVT));
17121 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
17122 RMValue);
17123}
17124
17125SDValue RISCVTargetLowering::lowerGET_FPENV(SDValue Op,
17126 SelectionDAG &DAG) const {
17127 const MVT XLenVT = Subtarget.getXLenVT();
17128 SDLoc DL(Op);
17129 SDValue Chain = Op->getOperand(0);
17130 SDValue SysRegNo = DAG.getTargetConstant(RISCVSysReg::fcsr, DL, XLenVT);
17131 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
17132 return DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
17133}
17134
17135SDValue RISCVTargetLowering::lowerSET_FPENV(SDValue Op,
17136 SelectionDAG &DAG) const {
17137 const MVT XLenVT = Subtarget.getXLenVT();
17138 SDLoc DL(Op);
17139 SDValue Chain = Op->getOperand(0);
17140 SDValue EnvValue = Op->getOperand(1);
17141 SDValue SysRegNo = DAG.getTargetConstant(RISCVSysReg::fcsr, DL, XLenVT);
17142
17143 EnvValue = DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, EnvValue);
17144 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
17145 EnvValue);
17146}
17147
17148SDValue RISCVTargetLowering::lowerRESET_FPENV(SDValue Op,
17149 SelectionDAG &DAG) const {
17150 const MVT XLenVT = Subtarget.getXLenVT();
17151 SDLoc DL(Op);
17152 SDValue Chain = Op->getOperand(0);
17153 SDValue EnvValue = DAG.getRegister(RISCV::X0, XLenVT);
17154 SDValue SysRegNo = DAG.getTargetConstant(RISCVSysReg::fcsr, DL, XLenVT);
17155
17156 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
17157 EnvValue);
17158}
17159
17162
17163SDValue RISCVTargetLowering::lowerGET_FPMODE(SDValue Op,
17164 SelectionDAG &DAG) const {
17165 const MVT XLenVT = Subtarget.getXLenVT();
17166 SDLoc DL(Op);
17167 SDValue Chain = Op->getOperand(0);
17168 SDValue SysRegNo = DAG.getTargetConstant(RISCVSysReg::fcsr, DL, XLenVT);
17169 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
17170 SDValue Result = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
17171 Chain = Result.getValue(1);
17172 return DAG.getMergeValues({Result, Chain}, DL);
17173}
17174
17175SDValue RISCVTargetLowering::lowerSET_FPMODE(SDValue Op,
17176 SelectionDAG &DAG) const {
17177 const MVT XLenVT = Subtarget.getXLenVT();
17178 const uint64_t ModeMaskValue = Subtarget.is64Bit() ? ModeMask64 : ModeMask32;
17179 SDLoc DL(Op);
17180 SDValue Chain = Op->getOperand(0);
17181 SDValue EnvValue = Op->getOperand(1);
17182 SDValue SysRegNo = DAG.getTargetConstant(RISCVSysReg::fcsr, DL, XLenVT);
17183 SDValue ModeMask = DAG.getConstant(ModeMaskValue, DL, XLenVT);
17184
17185 EnvValue = DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, EnvValue);
17186 EnvValue = DAG.getNode(ISD::AND, DL, XLenVT, EnvValue, ModeMask);
17187 Chain = DAG.getNode(RISCVISD::CLEAR_CSR, DL, MVT::Other, Chain, SysRegNo,
17188 ModeMask);
17189 return DAG.getNode(RISCVISD::SET_CSR, DL, MVT::Other, Chain, SysRegNo,
17190 EnvValue);
17191}
17192
17193SDValue RISCVTargetLowering::lowerRESET_FPMODE(SDValue Op,
17194 SelectionDAG &DAG) const {
17195 const MVT XLenVT = Subtarget.getXLenVT();
17196 const uint64_t ModeMaskValue = Subtarget.is64Bit() ? ModeMask64 : ModeMask32;
17197 SDLoc DL(Op);
17198 SDValue Chain = Op->getOperand(0);
17199 SDValue SysRegNo = DAG.getTargetConstant(RISCVSysReg::fcsr, DL, XLenVT);
17200 SDValue ModeMask = DAG.getConstant(ModeMaskValue, DL, XLenVT);
17201
17202 return DAG.getNode(RISCVISD::CLEAR_CSR, DL, MVT::Other, Chain, SysRegNo,
17203 ModeMask);
17204}
17205
17206SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
17207 SelectionDAG &DAG) const {
17209
17210 bool isRISCV64 = Subtarget.is64Bit();
17211 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17212
17213 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false);
17214 return DAG.getFrameIndex(FI, PtrVT);
17215}
17216
17217// Returns the opcode of the target-specific SDNode that implements the 32-bit
17218// form of the given Opcode.
17219static unsigned getRISCVWOpcode(unsigned Opcode) {
17220 switch (Opcode) {
17221 default:
17222 llvm_unreachable("Unexpected opcode");
17223 case ISD::SHL:
17224 return RISCVISD::SLLW;
17225 case ISD::SRA:
17226 return RISCVISD::SRAW;
17227 case ISD::SRL:
17228 return RISCVISD::SRLW;
17229 case ISD::SDIV:
17230 return RISCVISD::DIVW;
17231 case ISD::UDIV:
17232 return RISCVISD::DIVUW;
17233 case ISD::UREM:
17234 return RISCVISD::REMUW;
17235 case ISD::ROTL:
17236 return RISCVISD::ROLW;
17237 case ISD::ROTR:
17238 return RISCVISD::RORW;
17239 }
17240}
17241
17242// Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
17243// node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
17244// otherwise be promoted to i64, making it difficult to select the
17245// SLLW/DIVUW/.../*W later one because the fact the operation was originally of
17246// type i8/i16/i32 is lost.
17248 unsigned ExtOpc = ISD::ANY_EXTEND) {
17249 SDLoc DL(N);
17250 unsigned WOpcode = getRISCVWOpcode(N->getOpcode());
17251 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
17252 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
17253 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
17254 // ReplaceNodeResults requires we maintain the same type for the return value.
17255 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
17256}
17257
17258// Converts the given 32-bit operation to a i64 operation with signed extension
17259// semantic to reduce the signed extension instructions.
17261 SDLoc DL(N);
17262 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
17263 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
17264 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
17265 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
17266 DAG.getValueType(MVT::i32));
17267 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
17268}
17269
17270// Widen a 32-bit packed vector to the 64-bit packed type WideVT by
17271// concatenating it with zeros, clearing the upper lanes.
17273 SDValue V, MVT WideVT) {
17274 SDValue Zero = DAG.getConstant(0, DL, V.getValueType());
17275 return DAG.getNode(ISD::CONCAT_VECTORS, DL, WideVT, V, Zero);
17276}
17277
17280 SelectionDAG &DAG) const {
17281 SDLoc DL(N);
17282 switch (N->getOpcode()) {
17283 default:
17284 llvm_unreachable("Don't know how to custom type legalize this operation!");
17287 case ISD::FP_TO_SINT:
17288 case ISD::FP_TO_UINT: {
17289 bool IsStrict = N->isStrictFPOpcode();
17290 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
17291 N->getOpcode() == ISD::STRICT_FP_TO_SINT;
17292 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
17293
17294 // On RV32 only f16 is handled here: it is the only FP type whose finite
17295 // values always fit in an i32 after truncation towards zero, so convert in
17296 // i32 and extend instead of calling __fix(un)hfdi, which compiler-rt does
17297 // not provide. Out of range values and NaN are poison, so the fcvt clamping
17298 // is acceptable. Without Zfh/Zhinx the i32 conversion promotes f16 to f32.
17299 if (!Subtarget.is64Bit()) {
17300 assert(N->getValueType(0) == MVT::i64 &&
17301 "Unexpected custom legalisation");
17302 if (Op0.getValueType() != MVT::f16)
17303 return;
17304 SDValue Cvt;
17305 if (IsStrict) {
17306 Cvt = DAG.getNode(IsSigned ? ISD::STRICT_FP_TO_SINT
17308 DL, {MVT::i32, MVT::Other}, {N->getOperand(0), Op0});
17309 } else {
17310 Cvt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, DL,
17311 MVT::i32, Op0);
17312 }
17313 Results.push_back(DAG.getNode(
17314 IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, MVT::i64, Cvt));
17315 if (IsStrict)
17316 Results.push_back(Cvt.getValue(1));
17317 return;
17318 }
17319
17320 assert(N->getValueType(0) == MVT::i32 && "Unexpected custom legalisation");
17321 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
17323 if (!isTypeLegal(Op0.getValueType()))
17324 return;
17325 if (IsStrict) {
17326 SDValue Chain = N->getOperand(0);
17327 // In absence of Zfh, promote f16 to f32, then convert.
17328 if (Op0.getValueType() == MVT::f16 &&
17329 !Subtarget.hasStdExtZfhOrZhinx()) {
17330 Op0 = DAG.getNode(ISD::STRICT_FP_EXTEND, DL, {MVT::f32, MVT::Other},
17331 {Chain, Op0});
17332 Chain = Op0.getValue(1);
17333 }
17334 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
17335 : RISCVISD::STRICT_FCVT_WU_RV64;
17336 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
17337 SDValue Res = DAG.getNode(
17338 Opc, DL, VTs, Chain, Op0,
17339 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
17340 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
17341 Results.push_back(Res.getValue(1));
17342 return;
17343 }
17344 // For bf16, or f16 in absence of Zfh, promote [b]f16 to f32 and then
17345 // convert.
17346 if ((Op0.getValueType() == MVT::f16 &&
17347 !Subtarget.hasStdExtZfhOrZhinx()) ||
17348 Op0.getValueType() == MVT::bf16)
17349 Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op0);
17350
17351 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
17352 SDValue Res =
17353 DAG.getNode(Opc, DL, MVT::i64, Op0,
17354 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
17355 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
17356 return;
17357 }
17358 // If the FP type needs to be softened, emit a library call using the 'si'
17359 // version. If we left it to default legalization we'd end up with 'di'. If
17360 // the FP type doesn't need to be softened just let generic type
17361 // legalization promote the result type.
17362 RTLIB::Libcall LC;
17363 if (IsSigned)
17364 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
17365 else
17366 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
17367 MakeLibCallOptions CallOptions;
17368 EVT OpVT = Op0.getValueType();
17369 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0));
17370 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
17371 SDValue Result;
17372 std::tie(Result, Chain) =
17373 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
17374 Results.push_back(Result);
17375 if (IsStrict)
17376 Results.push_back(Chain);
17377 break;
17378 }
17379 case ISD::LROUND: {
17380 SDValue Op0 = N->getOperand(0);
17381 EVT Op0VT = Op0.getValueType();
17382 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
17384 if (!isTypeLegal(Op0VT))
17385 return;
17386
17387 // In absence of Zfh, promote f16 to f32, then convert.
17388 if (Op0.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfhOrZhinx())
17389 Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op0);
17390
17391 SDValue Res =
17392 DAG.getNode(RISCVISD::FCVT_W_RV64, DL, MVT::i64, Op0,
17393 DAG.getTargetConstant(RISCVFPRndMode::RMM, DL, MVT::i64));
17394 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
17395 return;
17396 }
17397 // If the FP type needs to be softened, emit a library call to lround. We'll
17398 // need to truncate the result. We assume any value that doesn't fit in i32
17399 // is allowed to return an unspecified value.
17400 RTLIB::Libcall LC = RTLIB::getLROUND(Op0.getValueType());
17401 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected FP type for LROUND!");
17402 MakeLibCallOptions CallOptions;
17403 EVT OpVT = Op0.getValueType();
17404 CallOptions.setTypeListBeforeSoften(OpVT, MVT::i64);
17405 SDValue Result = makeLibCall(DAG, LC, MVT::i64, Op0, CallOptions, DL).first;
17406 Result = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Result);
17407 Results.push_back(Result);
17408 break;
17409 }
17412 assert(!Subtarget.is64Bit() && "READCYCLECOUNTER/READSTEADYCOUNTER only "
17413 "has custom type legalization on riscv32");
17414
17415 SDValue LoCounter, HiCounter;
17416 MVT XLenVT = Subtarget.getXLenVT();
17417 if (N->getOpcode() == ISD::READCYCLECOUNTER) {
17418 LoCounter = DAG.getTargetConstant(RISCVSysReg::cycle, DL, XLenVT);
17419 HiCounter = DAG.getTargetConstant(RISCVSysReg::cycleh, DL, XLenVT);
17420 } else {
17421 LoCounter = DAG.getTargetConstant(RISCVSysReg::time, DL, XLenVT);
17422 HiCounter = DAG.getTargetConstant(RISCVSysReg::timeh, DL, XLenVT);
17423 }
17424 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
17425 SDValue RCW = DAG.getNode(RISCVISD::READ_COUNTER_WIDE, DL, VTs,
17426 N->getOperand(0), LoCounter, HiCounter);
17427
17428 Results.push_back(
17429 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
17430 Results.push_back(RCW.getValue(2));
17431 break;
17432 }
17433 case ISD::LOAD: {
17434 if (!ISD::isNON_EXTLoad(N))
17435 return;
17436
17437 // Use a SEXTLOAD instead of the default EXTLOAD. Similar to the
17438 // sext_inreg we emit for ADD/SUB/MUL/SLLI.
17440
17441 if (N->getValueType(0) == MVT::i64) {
17442 assert(Subtarget.hasStdExtZilsd() && !Subtarget.is64Bit() &&
17443 "Unexpected custom legalisation");
17444
17445 if (Ld->getAlign() < Subtarget.getZilsdAlign())
17446 return;
17447
17448 SDLoc DL(N);
17449 SDValue Result = DAG.getMemIntrinsicNode(
17450 RISCVISD::LD_RV32, DL,
17451 DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
17452 {Ld->getChain(), Ld->getBasePtr()}, MVT::i64, Ld->getMemOperand());
17453 SDValue Lo = Result.getValue(0);
17454 SDValue Hi = Result.getValue(1);
17455 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
17456 Results.append({Pair, Result.getValue(2)});
17457 return;
17458 }
17459
17460 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
17461 "Unexpected custom legalisation");
17462
17463 SDLoc dl(N);
17464 SDValue Res = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Ld->getChain(),
17465 Ld->getBasePtr(), Ld->getMemoryVT(),
17466 Ld->getMemOperand());
17467 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Res));
17468 Results.push_back(Res.getValue(1));
17469 return;
17470 }
17471 case ISD::MUL: {
17472 unsigned Size = N->getSimpleValueType(0).getSizeInBits();
17473 unsigned XLen = Subtarget.getXLen();
17474 if (Size > XLen) {
17475 // This multiply needs to be expanded, try to use MULH+MUL or WMUL if
17476 // possible. We duplicate the default legalization to
17477 // MULHU/MULHS/UMUL_LOHI/SMUL_LOHI to minimize the number of calls to
17478 // MaskedValueIsZero and ComputeNumSignBits
17479 // FIXME: Should we have a target independent MULHSU/WMULSU node? Are
17480 // there are other targets that could use it?
17481 assert(Size == (XLen * 2) && "Unexpected custom legalisation");
17482
17483 auto MakeMULPair = [&](SDValue L, SDValue R, unsigned HighOpc,
17484 unsigned LoHiOpc) {
17485 MVT XLenVT = Subtarget.getXLenVT();
17486 L = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, L);
17487 R = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, R);
17488 SDValue Lo, Hi;
17489 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit()) {
17490 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
17491 Lo = DAG.getNode(LoHiOpc, DL, VTs, L, R);
17492 Hi = Lo.getValue(1);
17493 } else {
17494 Lo = DAG.getNode(ISD::MUL, DL, XLenVT, L, R);
17495 Hi = DAG.getNode(HighOpc, DL, XLenVT, L, R);
17496 }
17497 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
17498 };
17499
17500 SDValue LHS = N->getOperand(0);
17501 SDValue RHS = N->getOperand(1);
17502
17503 APInt HighMask = APInt::getHighBitsSet(Size, XLen);
17504 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
17505 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
17506 if (LHSIsU && RHSIsU) {
17507 Results.push_back(MakeMULPair(LHS, RHS, ISD::MULHU, ISD::UMUL_LOHI));
17508 return;
17509 }
17510
17511 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
17512 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
17513 if (LHSIsS && RHSIsS)
17514 Results.push_back(MakeMULPair(LHS, RHS, ISD::MULHS, ISD::SMUL_LOHI));
17515 else if (RHSIsU && LHSIsS)
17516 Results.push_back(
17517 MakeMULPair(LHS, RHS, RISCVISD::MULHSU, RISCVISD::WMULSU));
17518 else if (LHSIsU && RHSIsS)
17519 Results.push_back(
17520 MakeMULPair(RHS, LHS, RISCVISD::MULHSU, RISCVISD::WMULSU));
17521
17522 return;
17523 }
17524 [[fallthrough]];
17525 }
17526 case ISD::ADD:
17527 case ISD::SUB:
17528 if (N->getValueType(0) == MVT::i64) {
17529 assert(!Subtarget.is64Bit() && Subtarget.hasStdExtP() &&
17530 "Unexpected custom legalisation");
17531
17532 // Expand to ADDD/SUBD.
17533 auto [LHSLo, LHSHi] =
17534 DAG.SplitScalar(N->getOperand(0), DL, MVT::i32, MVT::i32);
17535 auto [RHSLo, RHSHi] =
17536 DAG.SplitScalar(N->getOperand(1), DL, MVT::i32, MVT::i32);
17537 unsigned Opc =
17538 N->getOpcode() == ISD::ADD ? RISCVISD::ADDD : RISCVISD::SUBD;
17539 SDValue Res = DAG.getNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::i32),
17540 LHSLo, LHSHi, RHSLo, RHSHi);
17541 Res = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Res, Res.getValue(1));
17542 Results.push_back(Res);
17543 return;
17544 }
17545
17546 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
17547 "Unexpected custom legalisation");
17548 Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
17549 break;
17550 case ISD::TRUNCATE: {
17551 MVT VT = N->getSimpleValueType(0);
17552 assert(VT.isFixedLengthVector() && Subtarget.hasStdExtP() &&
17553 Subtarget.is64Bit() && (VT == MVT::v2i16 || VT == MVT::v4i8) &&
17554 "Unexpected custom legalisation");
17555
17556 // v4i16->v4i8 and v2i32->v2i16 truncates aren't legal on their own, but
17557 // the widened result type is. Bitcast the operand to the widened result
17558 // type and use a shuffle to select the low half of each element, which
17559 // gets matched to a P-extension packed narrowing convert
17560 // (unzip8p/unzip16p).
17561
17562 SDValue Op0 = N->getOperand(0);
17563
17564 // Input should be a 64-bit vector.
17565 if (!Op0.getValueType().is64BitVector())
17566 break;
17567
17568 MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
17569
17570 unsigned NumElts = VT.getVectorNumElements();
17571 SmallVector<int, 8> ShuffleMask(WidenVT.getVectorNumElements(), -1);
17572 for (unsigned i = 0; i != NumElts; ++i)
17573 ShuffleMask[i] = i * 2;
17574
17575 SDValue Src = DAG.getBitcast(WidenVT, Op0);
17576 Results.push_back(DAG.getVectorShuffle(WidenVT, DL, Src,
17577 DAG.getUNDEF(WidenVT), ShuffleMask));
17578 return;
17579 }
17580 case ISD::SHL:
17581 case ISD::SRA:
17582 case ISD::SRL: {
17583 EVT VT = N->getValueType(0);
17584 if (VT.isFixedLengthVector() && Subtarget.hasStdExtP()) {
17585 assert(Subtarget.is64Bit() && (VT == MVT::v2i16 || VT == MVT::v4i8) &&
17586 "Unexpected vector type for P-extension shift");
17587
17588 // If shift amount is a splat, don't scalarize - let normal widening
17589 // and SIMD patterns handle it (pslli.h, psrli.h, etc.)
17590 SDValue ShiftAmt = N->getOperand(1);
17591 if (DAG.isSplatValue(ShiftAmt, /*AllowUndefs=*/true))
17592 break;
17593
17594 EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT);
17595 unsigned WidenNumElts = WidenVT.getVectorNumElements();
17596 // Unroll with OrigNumElts operations, padding result to WidenNumElts
17597 SDValue Res = DAG.UnrollVectorOp(N, WidenNumElts);
17598 Results.push_back(Res);
17599 break;
17600 }
17601
17602 if (VT == MVT::i64) {
17603 assert(!Subtarget.is64Bit() && Subtarget.hasStdExtP() &&
17604 "Unexpected custom legalisation");
17605
17606 SDValue LHS = N->getOperand(0);
17607 SDValue ShAmt = N->getOperand(1);
17608
17609 unsigned WideOpc = 0;
17610 if (N->getOpcode() == ISD::SHL) {
17611 APInt HighMask = APInt::getHighBitsSet(64, 32);
17612 if (DAG.MaskedValueIsZero(LHS, HighMask))
17613 WideOpc = RISCVISD::WSLL;
17614 else if (DAG.ComputeMaxSignificantBits(LHS) <= 32)
17615 WideOpc = RISCVISD::WSLA;
17616 }
17617
17618 if (WideOpc) {
17619 SDValue Res =
17620 DAG.getNode(WideOpc, DL, DAG.getVTList(MVT::i32, MVT::i32),
17621 DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LHS),
17622 DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ShAmt));
17623 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0),
17624 Res, Res.getValue(1)));
17625 return;
17626 }
17627
17628 // Only handle constant shifts < 32. Non-constant shifts are handled by
17629 // lowerShiftLeftParts/lowerShiftRightParts, and shifts >= 32 use default
17630 // legalization.
17631 auto *ShAmtC = dyn_cast<ConstantSDNode>(N->getOperand(1));
17632 if (!ShAmtC || ShAmtC->getZExtValue() >= 32)
17633 break;
17634
17635 auto [Lo, Hi] = DAG.SplitScalar(LHS, DL, MVT::i32, MVT::i32);
17636
17637 // If the shift amount operand is coming from a vector legalization it may
17638 // have an illegal type.
17639 if (ShAmt.getValueType() != MVT::i32)
17640 ShAmt = DAG.getZExtOrTrunc(ShAmt, DL, MVT::i32);
17641
17642 SDValue LoRes, HiRes;
17643 if (N->getOpcode() == ISD::SHL) {
17644 // Lo = slli Lo, shamt
17645 // Hi = nsrli {Hi, Lo}, (32 - shamt)
17646 uint64_t ShAmtVal = ShAmtC->getZExtValue();
17647 LoRes = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, ShAmt);
17648 HiRes = DAG.getNode(RISCVISD::NSRL, DL, MVT::i32, Lo, Hi,
17649 DAG.getConstant(32 - ShAmtVal, DL, MVT::i32));
17650 } else {
17651 bool IsSRA = N->getOpcode() == ISD::SRA;
17652 LoRes = DAG.getNode(IsSRA ? RISCVISD::NSRA : RISCVISD::NSRL, DL,
17653 MVT::i32, Lo, Hi, ShAmt);
17654 HiRes =
17655 DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32, Hi, ShAmt);
17656 }
17657 SDValue Res = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, LoRes, HiRes);
17658 Results.push_back(Res);
17659 return;
17660 }
17661
17662 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
17663 "Unexpected custom legalisation");
17664 if (N->getOperand(1).getOpcode() != ISD::Constant) {
17665 // If we can use a BSET instruction, allow default promotion to apply.
17666 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
17667 isOneConstant(N->getOperand(0)))
17668 break;
17669 Results.push_back(customLegalizeToWOp(N, DAG));
17670 break;
17671 }
17672
17673 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
17674 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
17675 // shift amount.
17676 if (N->getOpcode() == ISD::SHL) {
17677 SDLoc DL(N);
17678 SDValue NewOp0 =
17679 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
17680 SDValue NewOp1 =
17681 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
17682 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
17683 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
17684 DAG.getValueType(MVT::i32));
17685 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
17686 }
17687
17688 break;
17689 }
17690 case ISD::FSHL:
17691 case ISD::FSHR: {
17692 assert(!Subtarget.is64Bit() && Subtarget.hasStdExtP() &&
17693 N->getValueType(0) == MVT::i64 &&
17694 "Unexpected custom funnel shift legalization");
17695
17696 auto [XLo, XHi] = DAG.SplitScalar(N->getOperand(0), DL, MVT::i32, MVT::i32);
17697 auto [YLo, YHi] = DAG.SplitScalar(N->getOperand(1), DL, MVT::i32, MVT::i32);
17698
17699 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
17700 unsigned Amt = C->getZExtValue() % 64;
17701 // Use default expansion for 0 and 32.
17702 if (Amt == 0 || Amt == 32)
17703 return;
17704 // Normalize to a funnel shift right by Amt. One result word is a
17705 // narrowing shift of a single input pair (XLo/XHi or YLo/YHi), which
17706 // needs no copies to form the register pair. The other word straddles X
17707 // and Y and uses a 32-bit funnel shift. SLX ties its first funnel
17708 // operand and SRX ties its second, so the direction used for each branch
17709 // was chosen empirically to minimize the copies in the generated code.
17710 if (N->getOpcode() == ISD::FSHL)
17711 Amt = 64 - Amt;
17712
17713 auto Nsrl = [&](SDValue Lo, SDValue Hi, unsigned Imm) {
17714 return DAG.getNode(RISCVISD::NSRL, DL, MVT::i32, Lo, Hi,
17715 DAG.getConstant(Imm, DL, MVT::i32));
17716 };
17717
17718 SDValue Lo, Hi;
17719 if (Amt < 32) {
17720 Lo = Nsrl(YLo, YHi, Amt);
17721 Hi = DAG.getNode(ISD::FSHL, DL, MVT::i32, XLo, YHi,
17722 DAG.getConstant(32 - Amt, DL, MVT::i32));
17723 } else {
17724 assert(Amt > 32);
17725 Lo = DAG.getNode(ISD::FSHR, DL, MVT::i32, XLo, YHi,
17726 DAG.getConstant(Amt - 32, DL, MVT::i32));
17727 Hi = Nsrl(XLo, XHi, Amt - 32);
17728 }
17729 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi));
17730 return;
17731 }
17732
17733 SDValue Shamt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, N->getOperand(2));
17734 unsigned Opc = N->getOpcode();
17735 auto Funnel = [&](SDValue Lo, SDValue Hi) {
17736 return DAG.getNode(Opc, DL, MVT::i32, Lo, Hi, Shamt);
17737 };
17738
17739 // The i32 funnel shifts use the low 5 shift bits. Convert bit 5 into a
17740 // mask and use packed merge instructions to select the adjacent results.
17741 SDValue Mask = DAG.getNode(ISD::SRA, DL, MVT::i32,
17742 DAG.getNode(ISD::SHL, DL, MVT::i32, Shamt,
17743 DAG.getConstant(26, DL, MVT::i32)),
17744 DAG.getConstant(31, DL, MVT::i32));
17745 auto Merge = [&](SDValue Below32, SDValue AtLeast32) {
17746 return DAG.getNode(RISCVISD::MERGE, DL, MVT::i32, Mask, Below32,
17747 AtLeast32);
17748 };
17749
17750 // Form the three adjacent 32-bit funnel shifts. The mask then selects the
17751 // two parts corresponding to shifts below or above 32 bits.
17752 SDValue Cross = Funnel(XLo, YHi);
17753 SDValue LoBelow32, HiBelow32, LoAtLeast32, HiAtLeast32;
17754 if (Opc == ISD::FSHL) {
17755 LoBelow32 = Cross;
17756 HiBelow32 = Funnel(XHi, XLo);
17757 LoAtLeast32 = Funnel(YHi, YLo);
17758 HiAtLeast32 = Cross;
17759 } else {
17760 LoBelow32 = Funnel(YHi, YLo);
17761 HiBelow32 = Cross;
17762 LoAtLeast32 = Cross;
17763 HiAtLeast32 = Funnel(XHi, XLo);
17764 }
17765
17766 SDValue Lo = Merge(LoBelow32, LoAtLeast32);
17767 SDValue Hi = Merge(HiBelow32, HiAtLeast32);
17768 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi));
17769 return;
17770 }
17771 case ISD::ROTL:
17772 case ISD::ROTR:
17773 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
17774 "Unexpected custom legalisation");
17775 assert((Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb() ||
17776 Subtarget.hasVendorXTHeadBb()) &&
17777 "Unexpected custom legalization");
17778 if (!isa<ConstantSDNode>(N->getOperand(1)) &&
17779 !(Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()))
17780 return;
17781 Results.push_back(customLegalizeToWOp(N, DAG));
17782 break;
17783 case ISD::CTTZ:
17785 case ISD::CTLZ:
17787 case ISD::CTLS: {
17788 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
17789 "Unexpected custom legalisation");
17790
17791 SDValue NewOp0 =
17792 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
17793 unsigned Opc;
17794 switch (N->getOpcode()) {
17795 default: llvm_unreachable("Unexpected opcode");
17796 case ISD::CTTZ:
17798 Opc = RISCVISD::CTZW;
17799 break;
17800 case ISD::CTLZ:
17802 Opc = RISCVISD::CLZW;
17803 break;
17804 case ISD::CTLS:
17805 Opc = RISCVISD::CLSW;
17806 break;
17807 }
17808
17809 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
17810 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
17811 return;
17812 }
17813 case ISD::SDIV:
17814 case ISD::UDIV:
17815 case ISD::UREM: {
17816 MVT VT = N->getSimpleValueType(0);
17817 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
17818 Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
17819 "Unexpected custom legalisation");
17820 // Don't promote division/remainder by constant since we should expand those
17821 // to multiply by magic constant.
17823 if (N->getOperand(1).getOpcode() == ISD::Constant &&
17824 !isIntDivCheap(N->getValueType(0), Attr))
17825 return;
17826
17827 // If the input is i32, use ANY_EXTEND since the W instructions don't read
17828 // the upper 32 bits. For other types we need to sign or zero extend
17829 // based on the opcode.
17830 unsigned ExtOpc = ISD::ANY_EXTEND;
17831 if (VT != MVT::i32)
17832 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
17834
17835 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
17836 break;
17837 }
17838 case ISD::SADDO:
17839 case ISD::SSUBO: {
17840 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
17841 "Unexpected custom legalisation");
17842
17843 // This is similar to the default legalization, but we return the
17844 // sext_inreg instead of the add/sub.
17845 bool IsAdd = N->getOpcode() == ISD::SADDO;
17846 SDValue LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
17847 SDValue RHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
17848 SDValue Op =
17849 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
17850 SDValue Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Op,
17851 DAG.getValueType(MVT::i32));
17852
17853 SDValue Overflow;
17854
17855 // If the RHS is a constant, we can simplify ConditionRHS below. Otherwise
17856 // use the default legalization.
17857 if (IsAdd && isa<ConstantSDNode>(N->getOperand(1))) {
17858 SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
17859
17860 // For an addition, the result should be less than one of the operands
17861 // (LHS) if and only if the other operand (RHS) is negative, otherwise
17862 // there will be overflow.
17863 EVT OType = N->getValueType(1);
17864 SDValue ResultLowerThanLHS =
17865 DAG.getSetCC(DL, OType, Res, LHS, ISD::SETLT);
17866 SDValue ConditionRHS = DAG.getSetCC(DL, OType, RHS, Zero, ISD::SETLT);
17867
17868 Overflow =
17869 DAG.getNode(ISD::XOR, DL, OType, ConditionRHS, ResultLowerThanLHS);
17870 } else {
17871 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, Op, ISD::SETNE);
17872 }
17873
17874 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
17875 Results.push_back(Overflow);
17876 return;
17877 }
17878 case ISD::UADDO:
17879 case ISD::USUBO: {
17880 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
17881 "Unexpected custom legalisation");
17882 bool IsAdd = N->getOpcode() == ISD::UADDO;
17883 // Create an ADDW or SUBW.
17884 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
17885 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
17886 SDValue Res =
17887 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
17888 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
17889 DAG.getValueType(MVT::i32));
17890
17891 SDValue Overflow;
17892 if (IsAdd && isOneConstant(RHS)) {
17893 // Special case uaddo X, 1 overflowed if the addition result is 0.
17894 // The general case (X + C) < C is not necessarily beneficial. Although we
17895 // reduce the live range of X, we may introduce the materialization of
17896 // constant C, especially when the setcc result is used by branch. We have
17897 // no compare with constant and branch instructions.
17898 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
17899 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
17900 } else if (IsAdd && isAllOnesConstant(RHS)) {
17901 // Special case uaddo X, -1 overflowed if X != 0.
17902 Overflow = DAG.getSetCC(DL, N->getValueType(1), N->getOperand(0),
17903 DAG.getConstant(0, DL, MVT::i32), ISD::SETNE);
17904 } else {
17905 // Sign extend the LHS and perform an unsigned compare with the ADDW
17906 // result. Since the inputs are sign extended from i32, this is equivalent
17907 // to comparing the lower 32 bits.
17908 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
17909 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
17910 IsAdd ? ISD::SETULT : ISD::SETUGT);
17911 }
17912
17913 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
17914 Results.push_back(Overflow);
17915 return;
17916 }
17917 case ISD::UADDSAT:
17918 case ISD::USUBSAT:
17919 case ISD::SADDSAT:
17920 case ISD::SSUBSAT: {
17921 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
17922 "Unexpected custom legalisation");
17923
17924 if (Subtarget.hasStdExtP()) {
17925 // On RV64, map scalar i32 saturating add/sub through lane 0 of a packed
17926 // v2i32 operation so we can select ps*.w instructions.
17927 SDValue LHS = DAG.getNode(
17928 ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32,
17929 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)));
17930 SDValue RHS = DAG.getNode(
17931 ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32,
17932 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)));
17933 SDValue VecRes = DAG.getNode(N->getOpcode(), DL, MVT::v2i32, LHS, RHS);
17934 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
17935 Results.push_back(
17936 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, VecRes, Zero));
17937 return;
17938 }
17939
17940 assert(!Subtarget.hasStdExtZbb() && "Unexpected custom legalisation");
17941 Results.push_back(expandAddSubSat(N, DAG));
17942 return;
17943 }
17944 case ISD::ABS:
17945 case ISD::ABS_MIN_POISON: {
17946 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
17947 "Unexpected custom legalisation");
17948
17949 if (Subtarget.hasStdExtP()) {
17950 SDValue Src =
17951 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
17952 SDValue Abs = DAG.getNode(RISCVISD::ABSW, DL, MVT::i64, Src);
17953 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Abs));
17954 return;
17955 }
17956
17957 if (Subtarget.hasStdExtZbb()) {
17958 // Emit a special node that will be expanded to NEGW+MAX at isel.
17959 // This allows us to remember that the result is sign extended. Expanding
17960 // to NEGW+MAX here requires a Freeze which breaks ComputeNumSignBits.
17961 SDValue Src = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64,
17962 N->getOperand(0));
17963 SDValue Abs = DAG.getNode(RISCVISD::NEGW_MAX, DL, MVT::i64, Src);
17964 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Abs));
17965 return;
17966 }
17967
17968 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
17969 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
17970
17971 // Freeze the source so we can increase it's use count.
17972 Src = DAG.getFreeze(Src);
17973
17974 // Copy sign bit to all bits using the sraiw pattern.
17975 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
17976 DAG.getValueType(MVT::i32));
17977 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
17978 DAG.getConstant(31, DL, MVT::i64));
17979
17980 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
17981 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
17982
17983 // NOTE: The result is only required to be anyextended, but sext is
17984 // consistent with type legalization of sub.
17985 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
17986 DAG.getValueType(MVT::i32));
17987 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
17988 return;
17989 }
17990 case ISD::BITCAST: {
17991 EVT VT = N->getValueType(0);
17992 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
17993 SDValue Op0 = N->getOperand(0);
17994 EVT Op0VT = Op0.getValueType();
17995 MVT XLenVT = Subtarget.getXLenVT();
17996 if (VT == MVT::i16 &&
17997 ((Op0VT == MVT::f16 && Subtarget.hasStdExtZfhminOrZhinxmin()) ||
17998 (Op0VT == MVT::bf16 && Subtarget.hasStdExtZfbfmin()))) {
17999 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
18000 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
18001 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
18002 Subtarget.hasStdExtFOrZfinx()) {
18003 SDValue FPConv =
18004 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
18005 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
18006 } else if (VT == MVT::i64 && Op0VT == MVT::f64 && !Subtarget.is64Bit() &&
18007 Subtarget.hasStdExtDOrZdinx()) {
18008 SDValue NewReg = DAG.getNode(RISCVISD::SplitF64, DL,
18009 DAG.getVTList(MVT::i32, MVT::i32), Op0);
18010 SDValue Lo = NewReg.getValue(0);
18011 SDValue Hi = NewReg.getValue(1);
18012 // For big-endian, swap the order when building the i64 pair.
18013 if (!Subtarget.isLittleEndian())
18014 std::swap(Lo, Hi);
18015 SDValue RetReg = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
18016 Results.push_back(RetReg);
18017 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
18018 isTypeLegal(Op0VT)) {
18019 // Custom-legalize bitcasts from fixed-length vector types to illegal
18020 // scalar types in order to improve codegen. Bitcast the vector to a
18021 // one-element vector type whose element type is the same as the result
18022 // type, and extract the first element.
18023 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
18024 if (isTypeLegal(BVT)) {
18025 SDValue BVec = DAG.getBitcast(BVT, Op0);
18026 Results.push_back(DAG.getExtractVectorElt(DL, VT, BVec, 0));
18027 }
18028 }
18029 break;
18030 }
18031 case ISD::BITREVERSE: {
18032 assert(N->getValueType(0) == MVT::i8 && Subtarget.hasStdExtZbkb() &&
18033 "Unexpected custom legalisation");
18034 MVT XLenVT = Subtarget.getXLenVT();
18035 SDValue NewOp = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
18036 SDValue NewRes = DAG.getNode(RISCVISD::BREV8, DL, XLenVT, NewOp);
18037 // ReplaceNodeResults requires we maintain the same type for the return
18038 // value.
18039 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, NewRes));
18040 break;
18041 }
18042 case RISCVISD::BREV8:
18043 case RISCVISD::ORC_B: {
18044 MVT VT = N->getSimpleValueType(0);
18045 MVT XLenVT = Subtarget.getXLenVT();
18046 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
18047 "Unexpected custom legalisation");
18048 assert(((N->getOpcode() == RISCVISD::BREV8 && Subtarget.hasStdExtZbkb()) ||
18049 (N->getOpcode() == RISCVISD::ORC_B && Subtarget.hasStdExtZbb())) &&
18050 "Unexpected extension");
18051 SDValue NewOp = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
18052 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp);
18053 // ReplaceNodeResults requires we maintain the same type for the return
18054 // value.
18055 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
18056 break;
18057 }
18058 case RISCVISD::MULHSU:
18059 case RISCVISD::MULHR:
18060 case RISCVISD::MULHRU:
18061 case RISCVISD::MULHRSU: {
18062 MVT VT = N->getSimpleValueType(0);
18063 SDValue Op0 = N->getOperand(0);
18064 SDValue Op1 = N->getOperand(1);
18065 unsigned Opcode = N->getOpcode();
18066 assert(VT == MVT::v2i16);
18067 MVT NewVT = MVT::v4i16;
18068 SDValue Undef = DAG.getUNDEF(VT);
18069 Op0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, NewVT, Op0, Undef);
18070 Op1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, NewVT, Op1, Undef);
18071 Results.push_back(DAG.getNode(Opcode, DL, NewVT, Op0, Op1));
18072 return;
18073 }
18075 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
18076 // type is illegal (currently only vXi64 RV32).
18077 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
18078 // transferred to the destination register. We issue two of these from the
18079 // upper- and lower- halves of the SEW-bit vector element, slid down to the
18080 // first element.
18081 SDValue Vec = N->getOperand(0);
18082 SDValue Idx = N->getOperand(1);
18083
18084 // The vector type hasn't been legalized yet so we can't issue target
18085 // specific nodes if it needs legalization.
18086 // FIXME: We would manually legalize if it's important.
18087 if (!isTypeLegal(Vec.getValueType()))
18088 return;
18089
18090 MVT VecVT = Vec.getSimpleValueType();
18091
18092 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
18093 VecVT.getVectorElementType() == MVT::i64 &&
18094 "Unexpected EXTRACT_VECTOR_ELT legalization");
18095
18096 // If this is a fixed vector, we need to convert it to a scalable vector.
18097 MVT ContainerVT = VecVT;
18098 if (VecVT.isFixedLengthVector()) {
18100 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
18101 }
18102
18103 MVT XLenVT = Subtarget.getXLenVT();
18104
18105 // Use a VL of 1 to avoid processing more elements than we need.
18106 auto [Mask, VL] = getDefaultVLOps(1, ContainerVT, DL, DAG, Subtarget);
18107
18108 // Unless the index is known to be 0, we must slide the vector down to get
18109 // the desired element into index 0.
18110 if (!isNullConstant(Idx)) {
18111 Vec = getVSlidedown(DAG, Subtarget, DL, ContainerVT,
18112 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
18113 }
18114
18115 // Extract the lower XLEN bits of the correct vector element.
18116 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
18117
18118 // To extract the upper XLEN bits of the vector element, shift the first
18119 // element right by 32 bits and re-extract the lower XLEN bits.
18120 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
18121 DAG.getUNDEF(ContainerVT),
18122 DAG.getConstant(32, DL, XLenVT), VL);
18123 SDValue LShr32 =
18124 DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, ThirtyTwoV,
18125 DAG.getUNDEF(ContainerVT), Mask, VL);
18126
18127 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
18128
18129 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
18130 break;
18131 }
18133 unsigned IntNo = N->getConstantOperandVal(0);
18134 switch (IntNo) {
18135 default:
18137 "Don't know how to custom type legalize this intrinsic!");
18138 case Intrinsic::experimental_get_vector_length: {
18139 SDValue Res = lowerGetVectorLength(N, DAG, Subtarget);
18140 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
18141 return;
18142 }
18143 case Intrinsic::riscv_psext_h:
18144 reportFatalUsageError("unsupported llvm.riscv.psext intrinsic");
18145 case Intrinsic::riscv_pzext_h:
18146 reportFatalUsageError("unsupported llvm.riscv.pzext intrinsic");
18147 case Intrinsic::riscv_psext_b:
18148 case Intrinsic::riscv_pzext_b: {
18149 bool IsSExt = IntNo == Intrinsic::riscv_psext_b;
18150 const char *UnsupportedMsg =
18151 IsSExt ? "unsupported llvm.riscv.psext intrinsic"
18152 : "unsupported llvm.riscv.pzext intrinsic";
18153 EVT VT = N->getValueType(0);
18154 if (!Subtarget.is64Bit() || VT != MVT::v2i16)
18155 reportFatalUsageError(UnsupportedMsg);
18156
18157 SDValue Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16,
18158 N->getOperand(1), DAG.getUNDEF(VT));
18159 SDValue Res;
18160 if (IsSExt)
18161 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::v4i16, Src,
18162 DAG.getValueType(MVT::v4i8));
18163 else
18164 Res = lowerPZExt(Src, DL, DAG, Subtarget);
18165 Results.push_back(DAG.getExtractSubvector(DL, VT, Res, 0));
18166 return;
18167 }
18168 case Intrinsic::riscv_pmhacc:
18169 case Intrinsic::riscv_pmhracc:
18170 case Intrinsic::riscv_pmhaccu:
18171 case Intrinsic::riscv_pmhraccu:
18172 case Intrinsic::riscv_pmhaccsu:
18173 case Intrinsic::riscv_pmhraccsu: {
18174 EVT VT = N->getValueType(0);
18175 if (!Subtarget.is64Bit() || VT != MVT::v2i16)
18176 return;
18177
18178 EVT WideVT = MVT::v4i16;
18179 SDValue Undef = DAG.getUNDEF(VT);
18180 SDValue Rd =
18181 DAG.getNode(ISD::CONCAT_VECTORS, DL, WideVT, N->getOperand(1), Undef);
18182 SDValue Rs1 =
18183 DAG.getNode(ISD::CONCAT_VECTORS, DL, WideVT, N->getOperand(2), Undef);
18184 SDValue Rs2 =
18185 DAG.getNode(ISD::CONCAT_VECTORS, DL, WideVT, N->getOperand(3), Undef);
18187 WideVT, Rd, Rs1, Rs2);
18188 Results.push_back(DAG.getExtractSubvector(DL, VT, Res, 0));
18189 return;
18190 }
18191 case Intrinsic::riscv_pmhacc_half_0:
18192 case Intrinsic::riscv_pmhacc_half_1:
18193 case Intrinsic::riscv_pmhaccsu_half_0:
18194 case Intrinsic::riscv_pmhaccsu_half_1: {
18195 // pmhacc.h.bXX operates on the whole register: v2i16 on RV32 and
18196 // v4i16 on RV64. On RV64 a v2i16 result widens to the packed v4i16
18197 // form and extracts the low half.
18198 EVT VT = N->getValueType(0);
18199 if (!Subtarget.is64Bit() || VT != MVT::v2i16)
18200 return;
18201
18202 EVT WideVT = MVT::v4i16;
18203 SDValue Undef = DAG.getUNDEF(VT);
18204 SDValue Rd =
18205 DAG.getNode(ISD::CONCAT_VECTORS, DL, WideVT, N->getOperand(1), Undef);
18206 SDValue Rs1 =
18207 DAG.getNode(ISD::CONCAT_VECTORS, DL, WideVT, N->getOperand(2), Undef);
18208 // Third operand is v4i8 - expand to v8i8
18209 SDValue Rs2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8,
18210 N->getOperand(3), DAG.getUNDEF(MVT::v4i8));
18212 WideVT, Rd, Rs1, Rs2);
18213 Results.push_back(DAG.getExtractSubvector(DL, VT, Res, 0));
18214 return;
18215 }
18216 case Intrinsic::riscv_pm4add:
18217 case Intrinsic::riscv_pm2add:
18218 case Intrinsic::riscv_pm2add_x:
18219 case Intrinsic::riscv_pm4addu:
18220 case Intrinsic::riscv_pm2addu:
18221 case Intrinsic::riscv_pmq2add:
18222 case Intrinsic::riscv_pmqr2add:
18223 case Intrinsic::riscv_pm2sadd:
18224 case Intrinsic::riscv_pm2sadd_x:
18225 case Intrinsic::riscv_pm2sub:
18226 case Intrinsic::riscv_pm2sub_x:
18227 case Intrinsic::riscv_pm4addsu:
18228 case Intrinsic::riscv_pm2addsu: {
18229 MVT VT = N->getSimpleValueType(0);
18230 unsigned Opc = getRVPHorizontalMulOpcode(IntNo);
18231 SDValue Rs1 = N->getOperand(1);
18232 SDValue Rs2 = N->getOperand(2);
18233
18234 if (!Subtarget.is64Bit() && VT == MVT::i64) {
18235 SDValue Res = lowerRV32HorizontalMul64(IntNo, Rs1, Rs2, DL, DAG);
18236 Results.push_back(Res);
18237 return;
18238 }
18239
18240 assert(Subtarget.is64Bit() && VT == MVT::i32 &&
18241 "Unexpected horizontal multiply legalization");
18242 MVT SrcVT = Rs1.getSimpleValueType();
18243 MVT WideSrcVT = SrcVT == MVT::v4i8 ? MVT::v8i8 : MVT::v4i16;
18244 Rs1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, WideSrcVT, Rs1,
18245 DAG.getUNDEF(SrcVT));
18246 Rs2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, WideSrcVT, Rs2,
18247 DAG.getUNDEF(SrcVT));
18248 SDValue Wide = DAG.getNode(Opc, DL, MVT::v2i32, Rs1, Rs2);
18249 Results.push_back(DAG.getExtractVectorElt(DL, MVT::i32, Wide, 0));
18250 return;
18251 }
18252
18253 case Intrinsic::riscv_pm2wadd:
18254 case Intrinsic::riscv_pm2wadd_x:
18255 case Intrinsic::riscv_pm2waddu:
18256 case Intrinsic::riscv_pm2wsub:
18257 case Intrinsic::riscv_pm2wsub_x:
18258 case Intrinsic::riscv_pm2waddsu: {
18259 // i64 is only illegal here on RV32; the RV64 (legal i64) case is
18260 // handled directly in LowerOperation.
18261 assert(!Subtarget.is64Bit() && N->getSimpleValueType(0) == MVT::i64 &&
18262 "Unexpected widening horizontal multiply-add legalization");
18263 SDValue Rs1 = N->getOperand(1);
18264 SDValue Rs2 = N->getOperand(2);
18265 Results.push_back(lowerRV32HorizontalMul64(IntNo, Rs1, Rs2, DL, DAG));
18266 return;
18267 }
18268
18269 case Intrinsic::riscv_pm2wadda:
18270 case Intrinsic::riscv_pm2wadda_x:
18271 case Intrinsic::riscv_pm2waddau:
18272 case Intrinsic::riscv_pm2wsuba:
18273 case Intrinsic::riscv_pm2wsuba_x:
18274 case Intrinsic::riscv_pm2waddasu: {
18275
18276 assert(!Subtarget.is64Bit() && N->getSimpleValueType(0) == MVT::i64 &&
18277 "Unexpected widening horizontal multiply-accumulate legalization");
18278 SDValue Rs1 = N->getOperand(2);
18279 SDValue Rs2 = N->getOperand(3);
18280 auto [RdLo, RdHi] =
18281 DAG.SplitScalar(N->getOperand(1), DL, MVT::i32, MVT::i32);
18282 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
18283 SDValue Res = DAG.getNode(getRVPHorizontalMulAccOpcode(IntNo), DL, VTs,
18284 {RdLo, RdHi, Rs1, Rs2});
18285 Results.push_back(
18286 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Res, Res.getValue(1)));
18287 return;
18288 }
18289
18290 case Intrinsic::riscv_pm2adda:
18291 case Intrinsic::riscv_pm2adda_x:
18292 case Intrinsic::riscv_pm2addau:
18293 case Intrinsic::riscv_pmq2adda:
18294 case Intrinsic::riscv_pmqr2adda:
18295 case Intrinsic::riscv_pm2suba:
18296 case Intrinsic::riscv_pm2suba_x:
18297 case Intrinsic::riscv_pm2addasu: {
18298
18299 if (N->getSimpleValueType(0) == MVT::i32) {
18300 SDValue Rd = N->getOperand(1);
18301 SDValue Rs1 = N->getOperand(2);
18302 SDValue Rs2 = N->getOperand(3);
18303 SDValue WideRd = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32, Rd);
18304 SDValue Undef = DAG.getUNDEF(MVT::v2i16);
18305 SDValue WideRs1 =
18306 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16, Rs1, Undef);
18307 SDValue WideRs2 =
18308 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16, Rs2, Undef);
18309 SDValue Res = DAG.getNode(getRVPMulAddAccOpcode(IntNo), DL, MVT::v2i32,
18310 WideRd, WideRs1, WideRs2);
18311 Results.push_back(DAG.getExtractVectorElt(DL, MVT::i32, Res, 0));
18312 return;
18313 }
18314
18315 assert(!Subtarget.is64Bit() && N->getSimpleValueType(0) == MVT::i64 &&
18316 "Unexpected multiply-horizontal-add-accumulate legalization");
18317 SDValue Rs1 = N->getOperand(2);
18318 SDValue Rs2 = N->getOperand(3);
18319 auto [RdLo, RdHi] =
18320 DAG.SplitScalar(N->getOperand(1), DL, MVT::i32, MVT::i32);
18321 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
18322 auto Extract = [&](SDValue V, unsigned Idx) {
18323 return DAG.getExtractVectorElt(DL, MVT::i32, V, Idx);
18324 };
18325 SDValue Rs1Lo = Extract(Rs1, 0);
18326 SDValue Rs1Hi = Extract(Rs1, 1);
18327 SDValue Rs2Lo = Extract(Rs2, 0);
18328 SDValue Rs2Hi = Extract(Rs2, 1);
18329
18330 if (IntNo == Intrinsic::riscv_pmq2adda ||
18331 IntNo == Intrinsic::riscv_pmqr2adda) {
18332 unsigned AccOpc = IntNo == Intrinsic::riscv_pmq2adda
18333 ? RISCVISD::MQWACC
18334 : RISCVISD::MQRWACC;
18335 SDValue Acc = DAG.getNode(AccOpc, DL, VTs, {RdLo, RdHi, Rs1Lo, Rs2Lo});
18336 Acc =
18337 DAG.getNode(AccOpc, DL, VTs, {Acc, Acc.getValue(1), Rs1Hi, Rs2Hi});
18338 Results.push_back(
18339 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Acc, Acc.getValue(1)));
18340 return;
18341 }
18342
18343 if (IntNo == Intrinsic::riscv_pm2suba ||
18344 IntNo == Intrinsic::riscv_pm2suba_x) {
18345 if (IntNo == Intrinsic::riscv_pm2suba_x)
18346 std::swap(Rs2Lo, Rs2Hi);
18347 SDValue LoMul = DAG.getNode(ISD::SMUL_LOHI, DL, VTs, Rs1Lo, Rs2Lo);
18348 SDValue Acc = DAG.getNode(RISCVISD::ADDD, DL, VTs, RdLo, RdHi, LoMul,
18349 LoMul.getValue(1));
18350 SDValue HiMul = DAG.getNode(ISD::SMUL_LOHI, DL, VTs, Rs1Hi, Rs2Hi);
18351 SDValue Res = DAG.getNode(RISCVISD::SUBD, DL, VTs, Acc, Acc.getValue(1),
18352 HiMul, HiMul.getValue(1));
18353 Results.push_back(
18354 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Res, Res.getValue(1)));
18355 return;
18356 }
18357
18358 if (IntNo == Intrinsic::riscv_pm2adda_x)
18359 std::swap(Rs2Lo, Rs2Hi);
18360
18361 unsigned MulOpc = ISD::SMUL_LOHI;
18362 if (IntNo == Intrinsic::riscv_pm2addau)
18363 MulOpc = ISD::UMUL_LOHI;
18364 else if (IntNo == Intrinsic::riscv_pm2addasu)
18365 MulOpc = RISCVISD::WMULSU;
18366
18367 SDValue LoMul = DAG.getNode(MulOpc, DL, VTs, Rs1Lo, Rs2Lo);
18368 SDValue Acc = DAG.getNode(RISCVISD::ADDD, DL, VTs, RdLo, RdHi, LoMul,
18369 LoMul.getValue(1));
18370 SDValue HiMul = DAG.getNode(MulOpc, DL, VTs, Rs1Hi, Rs2Hi);
18371 SDValue Res = DAG.getNode(RISCVISD::ADDD, DL, VTs, Acc, Acc.getValue(1),
18372 HiMul, HiMul.getValue(1));
18373 Results.push_back(
18374 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Res, Res.getValue(1)));
18375 return;
18376 }
18377
18378 case Intrinsic::riscv_pm4adda:
18379 case Intrinsic::riscv_pm4addau:
18380 case Intrinsic::riscv_pm4addasu: {
18381
18382 if (N->getSimpleValueType(0) == MVT::i32) {
18383 SDValue Rd = N->getOperand(1);
18384 SDValue Rs1 = N->getOperand(2);
18385 SDValue Rs2 = N->getOperand(3);
18386 unsigned Opc = getRVPMulAddAccOpcode(IntNo);
18387 SDValue WideRd = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32, Rd);
18388 SDValue Undef = DAG.getUNDEF(MVT::v4i8);
18389 SDValue WideRs1 =
18390 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Rs1, Undef);
18391 SDValue WideRs2 =
18392 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Rs2, Undef);
18393 SDValue Res =
18394 DAG.getNode(Opc, DL, MVT::v2i32, WideRd, WideRs1, WideRs2);
18395 Results.push_back(DAG.getExtractVectorElt(DL, MVT::i32, Res, 0));
18396 return;
18397 }
18398
18399 assert(!Subtarget.is64Bit() && N->getSimpleValueType(0) == MVT::i64 &&
18400 "Unexpected widening horizontal multiply-accumulate legalization");
18401 SDValue Rs1 = N->getOperand(2);
18402 SDValue Rs2 = N->getOperand(3);
18403 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
18404 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
18405 auto [RdLo, RdHi] =
18406 DAG.SplitScalar(N->getOperand(1), DL, MVT::i32, MVT::i32);
18407 unsigned AccOpc = IntNo == Intrinsic::riscv_pm4addau ? RISCVISD::PM2WADDAU
18408 : IntNo == Intrinsic::riscv_pm4addasu
18409 ? RISCVISD::PM2WADDASU
18410 : RISCVISD::PM2WADDA;
18411 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
18412 SDValue Acc = DAG.getNode(AccOpc, DL, VTs, {RdLo, RdHi, Rs1Lo, Rs2Lo});
18413 Acc = DAG.getNode(AccOpc, DL, VTs, {Acc, Acc.getValue(1), Rs1Hi, Rs2Hi});
18414 Results.push_back(
18415 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Acc, Acc.getValue(1)));
18416 return;
18417 }
18418
18419 case Intrinsic::riscv_pmul_00:
18420 case Intrinsic::riscv_pmul_01:
18421 case Intrinsic::riscv_pmul_11:
18422 case Intrinsic::riscv_pmulu_00:
18423 case Intrinsic::riscv_pmulu_01:
18424 case Intrinsic::riscv_pmulu_11:
18425 case Intrinsic::riscv_pmulsu_00:
18426 case Intrinsic::riscv_pmulsu_11: {
18427 MVT VT = N->getSimpleValueType(0);
18428 if (!Subtarget.is64Bit() || VT != MVT::v2i16)
18429 return;
18430
18431 SDValue Undef = DAG.getUNDEF(MVT::v4i8);
18432 SDValue Rs1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8,
18433 N->getOperand(1), Undef);
18434 SDValue Rs2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8,
18435 N->getOperand(2), Undef);
18436 SDValue Res =
18437 DAG.getNode(getRVPMulHalvesOpcode(IntNo), DL, MVT::v4i16, Rs1, Rs2);
18438 Results.push_back(DAG.getExtractSubvector(DL, VT, Res, 0));
18439 return;
18440 }
18441 case Intrinsic::riscv_mul_00:
18442 case Intrinsic::riscv_mul_01:
18443 case Intrinsic::riscv_mul_11:
18444 case Intrinsic::riscv_mulu_00:
18445 case Intrinsic::riscv_mulu_01:
18446 case Intrinsic::riscv_mulu_11:
18447 case Intrinsic::riscv_mulsu_00:
18448 case Intrinsic::riscv_mulsu_11: {
18449 // mul.hXX exists only on RV32 and mul.wXX only on RV64; the other XLEN
18450 // has to build the product here.
18451 MVT VT = N->getSimpleValueType(0);
18452 MVT SrcVT = N->getOperand(1).getSimpleValueType();
18453 if (Subtarget.hasStdExtP() && Subtarget.is64Bit() && VT == MVT::i32 &&
18454 SrcVT == MVT::v2i16) {
18455 // The halfword product is the first element of the packed one.
18456 SDValue Undef = DAG.getUNDEF(SrcVT);
18457 SDValue Rs1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16,
18458 N->getOperand(1), Undef);
18459 SDValue Rs2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16,
18460 N->getOperand(2), Undef);
18461 SDValue Res =
18462 DAG.getNode(getRVPMulHalvesOpcode(IntNo), DL, MVT::v2i32, Rs1, Rs2);
18463 Results.push_back(DAG.getExtractVectorElt(DL, MVT::i32, Res, 0));
18464 return;
18465 }
18466 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() && VT == MVT::i64 &&
18467 SrcVT == MVT::v2i32) {
18468 auto [Opc, Rs1Lane, Rs2Lane] = getRVPWordMulPartsOpcodeAndLanes(IntNo);
18469 SDValue Rs1 =
18470 DAG.getExtractVectorElt(DL, MVT::i32, N->getOperand(1), Rs1Lane);
18471 SDValue Rs2 =
18472 DAG.getExtractVectorElt(DL, MVT::i32, N->getOperand(2), Rs2Lane);
18473 SDValue Res =
18474 DAG.getNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::i32), Rs1, Rs2);
18475 Results.push_back(
18476 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Res, Res.getValue(1)));
18477 return;
18478 }
18479 reportFatalUsageError("unsupported llvm.riscv multiply-parts intrinsic");
18480 }
18481 case Intrinsic::riscv_pmulh_half_0:
18482 case Intrinsic::riscv_pmulh_half_1:
18483 case Intrinsic::riscv_pmulhsu_half_0:
18484 case Intrinsic::riscv_pmulhsu_half_1: {
18485 // A 32-bit result has no legal container on RV64; widen the result and
18486 // both sources to the 64-bit packed form.
18487 EVT VT = N->getValueType(0);
18488 if (!Subtarget.is64Bit() || VT != MVT::v2i16)
18489 return;
18490
18491 SDValue Undef = DAG.getUNDEF(VT);
18492 SDValue Rs1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16,
18493 N->getOperand(1), Undef);
18494 SDValue Src2 = N->getOperand(2);
18495 SDValue Rs2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Src2,
18496 DAG.getUNDEF(Src2.getValueType()));
18497 SDValue Res =
18498 DAG.getNode(getRVPMulHighHalfOpcode(IntNo), DL, MVT::v4i16, Rs1, Rs2);
18499 Results.push_back(DAG.getExtractSubvector(DL, VT, Res, 0));
18500 return;
18501 }
18502 case Intrinsic::riscv_mulh_h0:
18503 case Intrinsic::riscv_mulh_h1:
18504 case Intrinsic::riscv_mulhsu_h0:
18505 case Intrinsic::riscv_mulhsu_h1: {
18506 // mulh.h0/h1 exist only on RV32 and pmulh.w.h0/h1 only on RV64; the
18507 // other XLEN has to build the product here.
18508 MVT VT = N->getSimpleValueType(0);
18509 MVT SrcVT = N->getOperand(2).getSimpleValueType();
18510 if (Subtarget.hasStdExtP() && Subtarget.is64Bit() && VT == MVT::i32 &&
18511 SrcVT == MVT::v2i16) {
18512 // The halfword product is the first element of the packed one.
18513 SDValue Rd = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32,
18514 N->getOperand(1));
18515 SDValue Undef = DAG.getUNDEF(SrcVT);
18516 SDValue Rs1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16,
18517 N->getOperand(2), Undef);
18518 SDValue Res = DAG.getNode(getRVPMulHighHalfOpcode(IntNo), DL,
18519 MVT::v2i32, Rd, Rs1);
18520 Results.push_back(DAG.getExtractVectorElt(DL, MVT::i32, Res, 0));
18521 return;
18522 }
18524 "unsupported llvm.riscv multiply-high-parts intrinsic");
18525 }
18526 case Intrinsic::riscv_macc_00:
18527 case Intrinsic::riscv_macc_01:
18528 case Intrinsic::riscv_macc_11:
18529 case Intrinsic::riscv_maccu_00:
18530 case Intrinsic::riscv_maccu_01:
18531 case Intrinsic::riscv_maccu_11:
18532 case Intrinsic::riscv_maccsu_00:
18533 case Intrinsic::riscv_maccsu_11: {
18534 // macc.hXX exists only on RV32 and macc.wXX only on RV64; the other XLEN
18535 // has to build the product here.
18536 MVT VT = N->getSimpleValueType(0);
18537 MVT SrcVT = N->getOperand(2).getSimpleValueType();
18538 if (Subtarget.hasStdExtP() && Subtarget.is64Bit() && VT == MVT::i32 &&
18539 SrcVT == MVT::v2i16) {
18540 // Accumulate into the first element of the packed product.
18541 SDValue Undef = DAG.getUNDEF(SrcVT);
18542 SDValue Rd = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32,
18543 N->getOperand(1));
18544 SDValue Rs1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16,
18545 N->getOperand(2), Undef);
18546 SDValue Rs2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16,
18547 N->getOperand(3), Undef);
18548 SDValue Res = DAG.getNode(getRVPMulAccHalvesOpcode(IntNo), DL,
18549 MVT::v2i32, Rd, Rs1, Rs2);
18550 Results.push_back(DAG.getExtractVectorElt(DL, MVT::i32, Res, 0));
18551 return;
18552 }
18553 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() && VT == MVT::i64 &&
18554 SrcVT == MVT::v2i32) {
18555 auto [Opc, Rs1Lane, Rs2Lane] =
18557 auto [RdLo, RdHi] =
18558 DAG.SplitScalar(N->getOperand(1), DL, MVT::i32, MVT::i32);
18559 SDValue Rs1 =
18560 DAG.getExtractVectorElt(DL, MVT::i32, N->getOperand(2), Rs1Lane);
18561 SDValue Rs2 =
18562 DAG.getExtractVectorElt(DL, MVT::i32, N->getOperand(3), Rs2Lane);
18563 SDValue Res = DAG.getNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::i32),
18564 RdLo, RdHi, Rs1, Rs2);
18565 Results.push_back(
18566 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Res, Res.getValue(1)));
18567 return;
18568 }
18569 reportFatalUsageError("unsupported llvm.riscv multiply-parts intrinsic");
18570 }
18571 case Intrinsic::riscv_paadd:
18572 case Intrinsic::riscv_paaddu:
18573 case Intrinsic::riscv_pasub:
18574 case Intrinsic::riscv_pasubu:
18575 case Intrinsic::riscv_pabd:
18576 case Intrinsic::riscv_pabdu:
18577 case Intrinsic::riscv_pas:
18578 case Intrinsic::riscv_psa:
18579 case Intrinsic::riscv_psas:
18580 case Intrinsic::riscv_pssa:
18581 case Intrinsic::riscv_paas:
18582 case Intrinsic::riscv_pasa:
18583 case Intrinsic::riscv_pmerge:
18584 case Intrinsic::riscv_pmulq:
18585 case Intrinsic::riscv_pmulqr:
18586 case Intrinsic::riscv_pmulhr:
18587 case Intrinsic::riscv_pmulhru:
18588 case Intrinsic::riscv_pmulhsu:
18589 case Intrinsic::riscv_pmulhrsu:
18590 case Intrinsic::riscv_psabs:
18591 case Intrinsic::riscv_psati:
18592 case Intrinsic::riscv_pusati: {
18593 EVT VT = N->getValueType(0);
18594 if (!Subtarget.is64Bit() || (VT != MVT::v4i8 && VT != MVT::v2i16))
18595 return;
18596
18597 unsigned Opc;
18598 switch (IntNo) {
18599 case Intrinsic::riscv_paadd:
18601 break;
18602 case Intrinsic::riscv_paaddu:
18604 break;
18605 case Intrinsic::riscv_pasub:
18607 break;
18608 case Intrinsic::riscv_pasubu:
18610 break;
18611 case Intrinsic::riscv_pabd:
18612 Opc = ISD::ABDS;
18613 break;
18614 case Intrinsic::riscv_pabdu:
18615 Opc = ISD::ABDU;
18616 break;
18617 case Intrinsic::riscv_psabs:
18618 Opc = RISCVISD::PSABS;
18619 break;
18620 case Intrinsic::riscv_pmulq:
18621 Opc = RISCVISD::MULQ;
18622 break;
18623 case Intrinsic::riscv_pmulqr:
18624 Opc = RISCVISD::MULQR;
18625 break;
18626 case Intrinsic::riscv_pmulhr:
18627 case Intrinsic::riscv_pmulhru:
18628 case Intrinsic::riscv_pmulhsu:
18629 case Intrinsic::riscv_pmulhrsu:
18630 Opc = getRVPMulHighOpcode(IntNo);
18631 break;
18632 case Intrinsic::riscv_psati:
18633 Opc = RISCVISD::SATI;
18634 break;
18635 case Intrinsic::riscv_pusati:
18636 Opc = RISCVISD::USATI;
18637 break;
18638 case Intrinsic::riscv_pmerge:
18639 Opc = RISCVISD::MERGE;
18640 break;
18641 default:
18642 // pas/psa/psas/pssa/paas/pasa and pmerge: re-emit at the widened type
18643 // rather than lowering to a generic node.
18645 break;
18646 }
18647
18648 EVT WideVT = VT == MVT::v4i8 ? MVT::v8i8 : MVT::v4i16;
18649 SDValue Undef = DAG.getUNDEF(VT);
18651 for (SDValue &Op : Ops) {
18652 if (Op.getValueType() == VT)
18653 Op = DAG.getNode(ISD::CONCAT_VECTORS, DL, WideVT, Op, Undef);
18654 }
18655 SDValue Res;
18657 Res = DAG.getNode(Opc, DL, WideVT, Ops);
18658 } else if (Opc == RISCVISD::SATI || Opc == RISCVISD::USATI) {
18659 SDValue Imm = DAG.getTargetConstant(N->getConstantOperandVal(2), DL,
18660 Subtarget.getXLenVT());
18661 Res = DAG.getNode(Opc, DL, WideVT, Ops[1], Imm);
18662 } else if (Opc == RISCVISD::MERGE) {
18663 // The intrinsic is (rs1, rs2, rd) but MERGE is (mask, false, true).
18664 Res = DAG.getNode(Opc, DL, WideVT, Ops[3], Ops[1], Ops[2]);
18665 } else {
18666 Res = DAG.getNode(Opc, DL, WideVT, ArrayRef(Ops).slice(1));
18667 }
18668 Results.push_back(DAG.getExtractSubvector(DL, VT, Res, 0));
18669 return;
18670 }
18671 case Intrinsic::riscv_mseq_u32:
18672 case Intrinsic::riscv_mslt_i32:
18673 case Intrinsic::riscv_msltu_u32: {
18674 if (!Subtarget.is64Bit() || N->getValueType(0) != MVT::i32)
18675 return;
18677 switch (IntNo) {
18678 case Intrinsic::riscv_mseq_u32:
18679 CC = ISD::SETEQ;
18680 break;
18681 case Intrinsic::riscv_mslt_i32:
18682 CC = ISD::SETLT;
18683 break;
18684 case Intrinsic::riscv_msltu_u32:
18685 CC = ISD::SETULT;
18686 break;
18687 default:
18688 llvm_unreachable("Unexpected comparison intrinsic");
18689 }
18690 SDValue LHS =
18691 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32, N->getOperand(1));
18692 SDValue RHS =
18693 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32, N->getOperand(2));
18694 SDValue Cmp = DAG.getSetCC(DL, MVT::v2i32, LHS, RHS, CC);
18695 Results.push_back(DAG.getExtractVectorElt(DL, MVT::i32, Cmp, 0));
18696 return;
18697 }
18698 case Intrinsic::riscv_aadd_i32:
18699 case Intrinsic::riscv_aaddu_u32:
18700 case Intrinsic::riscv_asub_i32:
18701 case Intrinsic::riscv_asubu_u32:
18702 case Intrinsic::riscv_ssh1sadd_i32:
18703 case Intrinsic::riscv_mulhr_i32:
18704 case Intrinsic::riscv_mulhru_u32:
18705 case Intrinsic::riscv_mulhsu_i32:
18706 case Intrinsic::riscv_mulhrsu_i32:
18707 case Intrinsic::riscv_mulq_i32:
18708 case Intrinsic::riscv_mulqr_i32:
18709 case Intrinsic::riscv_mhacc_i32:
18710 case Intrinsic::riscv_mhracc_i32:
18711 case Intrinsic::riscv_mhaccu_u32:
18712 case Intrinsic::riscv_mhraccu_u32:
18713 case Intrinsic::riscv_mhaccsu_i32:
18714 case Intrinsic::riscv_mhraccsu_i32: {
18715 // RV64 has no scalar averaging, shift-add, mulh, mulq or mhacc
18716 // instructions; reuse the packed .w family on the low words, whose
18717 // element 0 is the scalar result.
18718 assert(Subtarget.is64Bit() && N->getValueType(0) == MVT::i32 &&
18719 "Unexpected subtarget or result type");
18720 unsigned Opc = getRVPScalarOpcode(IntNo);
18722 for (SDValue Op : drop_begin(N->ops()))
18723 Ops.push_back(DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32, Op));
18724 SDValue Res = DAG.getNode(Opc, DL, MVT::v2i32, Ops);
18725 Results.push_back(DAG.getExtractVectorElt(DL, MVT::i32, Res, 0));
18726 return;
18727 }
18728 case Intrinsic::riscv_sati:
18729 case Intrinsic::riscv_usati: {
18730 // RV64 has no 32-bit sati; promote to i64.
18731 if (!Subtarget.is64Bit() || N->getValueType(0) != MVT::i32)
18732 return;
18733 unsigned Opc =
18734 IntNo == Intrinsic::riscv_sati ? RISCVISD::SATI : RISCVISD::USATI;
18735 SDValue Rs1 =
18736 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
18737 SDValue Res = DAG.getNode(
18738 Opc, DL, MVT::i64, Rs1,
18739 DAG.getTargetConstant(N->getConstantOperandVal(2), DL, MVT::i64));
18740 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
18741 return;
18742 }
18743 case Intrinsic::riscv_nclipu_u32:
18744 case Intrinsic::riscv_nclipru_u32:
18745 case Intrinsic::riscv_nsrar_i32:
18746 case Intrinsic::riscv_nclip_i32:
18747 case Intrinsic::riscv_nclipr_i32: {
18748 if (!Subtarget.is64Bit() || N->getValueType(0) != MVT::i32)
18749 return;
18750
18751 SDValue Src = N->getOperand(1);
18752 SDValue ShAmt =
18753 getRVPScalarNarrowingShiftAmount(N->getOperand(2), DL, MVT::i64, DAG);
18754 bool IsSigned = IntNo == Intrinsic::riscv_nsrar_i32 ||
18755 IntNo == Intrinsic::riscv_nclip_i32 ||
18756 IntNo == Intrinsic::riscv_nclipr_i32;
18757 bool IsRounding = IntNo == Intrinsic::riscv_nclipru_u32 ||
18758 IntNo == Intrinsic::riscv_nsrar_i32 ||
18759 IntNo == Intrinsic::riscv_nclipr_i32;
18760
18761 unsigned ShiftOpc;
18762 if (IsRounding) {
18763 ShAmt = DAG.getNegative(ShAmt, DL, MVT::i64);
18764 ShiftOpc = IsSigned ? RISCVISD::SHAR : RISCVISD::SHLR;
18765 } else {
18766 ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
18767 }
18768 SDValue Shifted = DAG.getNode(ShiftOpc, DL, MVT::i64, Src, ShAmt);
18769
18770 if (IntNo == Intrinsic::riscv_nsrar_i32) {
18771 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shifted));
18772 return;
18773 }
18774
18775 SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
18776 unsigned ClipOpc = IsSigned ? RISCVISD::PNCLIPP : RISCVISD::PNCLIPUP;
18777 SDValue Clipped = DAG.getNode(ClipOpc, DL, MVT::v2i32, Shifted, Zero);
18778 Results.push_back(DAG.getExtractVectorElt(DL, MVT::i32, Clipped, 0));
18779 return;
18780 }
18781 case Intrinsic::riscv_mqwacc_i64:
18782 case Intrinsic::riscv_mqrwacc_i64: {
18783 if (Subtarget.is64Bit())
18784 return;
18785 unsigned Opc = IntNo == Intrinsic::riscv_mqwacc_i64 ? RISCVISD::MQWACC
18786 : RISCVISD::MQRWACC;
18787 auto [RdLo, RdHi] =
18788 DAG.SplitScalar(N->getOperand(1), DL, MVT::i32, MVT::i32);
18789 SDValue Acc =
18790 DAG.getNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::i32),
18791 {RdLo, RdHi, N->getOperand(2), N->getOperand(3)});
18792 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
18793 Acc.getValue(0), Acc.getValue(1)));
18794 return;
18795 }
18796 case Intrinsic::riscv_pnclipp:
18797 case Intrinsic::riscv_pnclipup: {
18798 bool IsSigned = IntNo == Intrinsic::riscv_pnclipp;
18799 EVT VT = N->getValueType(0);
18800 if (!Subtarget.is64Bit() || (VT != MVT::v4i8 && VT != MVT::v2i16))
18801 return;
18802 unsigned Opc = IsSigned ? RISCVISD::PNCLIPP : RISCVISD::PNCLIPUP;
18803 SDValue Src1 = N->getOperand(1);
18804 SDValue Src2 = N->getOperand(2);
18805 if (VT == MVT::v4i8) {
18806 MVT WideSrcVT = MVT::v4i16;
18807 SDValue Packed =
18808 DAG.getNode(ISD::CONCAT_VECTORS, DL, WideSrcVT, {Src1, Src2});
18809 SDValue Res = DAG.getNode(Opc, DL, MVT::v8i8, {Packed, Packed});
18810 Results.push_back(DAG.getExtractSubvector(DL, VT, Res, 0));
18811 } else {
18812 MVT WideSrcVT = MVT::v2i32;
18813 SDValue Packed =
18814 DAG.getNode(ISD::BUILD_VECTOR, DL, WideSrcVT, {Src1, Src2});
18815 SDValue Res = DAG.getNode(Opc, DL, MVT::v4i16, {Packed, Packed});
18816 Results.push_back(DAG.getExtractSubvector(DL, VT, Res, 0));
18817 }
18818 return;
18819 }
18820 case Intrinsic::riscv_psll:
18821 case Intrinsic::riscv_psrl:
18822 case Intrinsic::riscv_psra:
18823 case Intrinsic::riscv_pssha:
18824 case Intrinsic::riscv_psshar:
18825 case Intrinsic::riscv_psshl:
18826 case Intrinsic::riscv_psshlr: {
18827 MVT VT = N->getSimpleValueType(0);
18828 if (!Subtarget.is64Bit() || (VT != MVT::v4i8 && VT != MVT::v2i16))
18829 return;
18830
18831 EVT WideVT = VT == MVT::v4i8 ? MVT::v8i8 : MVT::v4i16;
18832 SDValue Op0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, WideVT,
18833 N->getOperand(1), DAG.getUNDEF(VT));
18834 SDValue ShAmt = N->getOperand(2);
18835 ShAmt = DAG.getAnyExtOrTrunc(ShAmt, DL, Subtarget.getXLenVT());
18836 SDValue Res =
18837 DAG.getNode(getRVPShiftOpcode(IntNo), DL, WideVT, Op0, ShAmt);
18838 Results.push_back(DAG.getExtractSubvector(DL, VT, Res, 0));
18839 return;
18840 }
18841 case Intrinsic::riscv_pnsrl:
18842 case Intrinsic::riscv_pnsra:
18843 case Intrinsic::riscv_pnsrar: {
18844 MVT VT = N->getSimpleValueType(0);
18845 if (!Subtarget.is64Bit() || (VT != MVT::v4i8 && VT != MVT::v2i16))
18846 return;
18847
18848 SDValue Src = N->getOperand(1);
18849 MVT SrcVT = Src.getSimpleValueType();
18850 if (!((VT == MVT::v4i8 && SrcVT == MVT::v4i16) ||
18851 (VT == MVT::v2i16 && SrcVT == MVT::v2i32)))
18852 reportFatalUsageError("unsupported packed narrowing shift intrinsic");
18853
18854 MVT XLenVT = Subtarget.getXLenVT();
18855 SDValue ShAmt =
18856 DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(2));
18857 unsigned Opc;
18858 switch (IntNo) {
18859 default:
18860 llvm_unreachable("Unexpected packed narrowing shift intrinsic");
18861 case Intrinsic::riscv_pnsrl:
18862 Opc = RISCVISD::PSRL;
18863 break;
18864 case Intrinsic::riscv_pnsra:
18865 Opc = RISCVISD::PSRA;
18866 break;
18867 case Intrinsic::riscv_pnsrar:
18868 Opc = RISCVISD::PSSHAR;
18869 ShAmt = DAG.getNode(ISD::AND, DL, XLenVT, ShAmt,
18870 DAG.getConstant(31, DL, XLenVT));
18871 ShAmt = DAG.getNegative(ShAmt, DL, XLenVT);
18872 break;
18873 }
18874
18875 SDValue Shifted = DAG.getNode(Opc, DL, SrcVT, Src, ShAmt);
18876 MVT UnzipVT = VT == MVT::v4i8 ? MVT::v8i8 : MVT::v4i16;
18877 Shifted = DAG.getBitcast(UnzipVT, Shifted);
18878 SDValue Unzip = DAG.getNode(RISCVISD::PUNZIPE, DL, UnzipVT, Shifted,
18879 DAG.getUNDEF(UnzipVT));
18880 Results.push_back(DAG.getExtractSubvector(DL, VT, Unzip, 0));
18881 return;
18882 }
18883 case Intrinsic::riscv_pnclipu:
18884 case Intrinsic::riscv_pnclipru:
18885 case Intrinsic::riscv_pnclip:
18886 case Intrinsic::riscv_pnclipr: {
18887 MVT VT = N->getSimpleValueType(0);
18888 if (!Subtarget.is64Bit() || (VT != MVT::v4i8 && VT != MVT::v2i16))
18889 return;
18890
18891 SDValue Src = N->getOperand(1);
18892 MVT SrcVT = Src.getSimpleValueType();
18893 if (!((VT == MVT::v4i8 && SrcVT == MVT::v4i16) ||
18894 (VT == MVT::v2i16 && SrcVT == MVT::v2i32)))
18895 reportFatalUsageError("unsupported packed narrowing clip intrinsic");
18896
18897 MVT XLenVT = Subtarget.getXLenVT();
18898 SDValue ShAmt =
18899 DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(2));
18900 bool IsSigned =
18901 IntNo == Intrinsic::riscv_pnclip || IntNo == Intrinsic::riscv_pnclipr;
18902 bool IsRounding = IntNo == Intrinsic::riscv_pnclipru ||
18903 IntNo == Intrinsic::riscv_pnclipr;
18904 if (IsRounding) {
18905 ShAmt = DAG.getNode(ISD::AND, DL, XLenVT, ShAmt,
18906 DAG.getConstant(31, DL, XLenVT));
18907 ShAmt = DAG.getNegative(ShAmt, DL, XLenVT);
18908 }
18909
18910 unsigned ShiftOpc = IsRounding
18911 ? (IsSigned ? RISCVISD::PSSHAR : RISCVISD::PSSHLR)
18912 : (IsSigned ? RISCVISD::PSRA : RISCVISD::PSRL);
18913 SDValue Shifted = DAG.getNode(ShiftOpc, DL, SrcVT, Src, ShAmt);
18914 MVT WideVT = VT == MVT::v4i8 ? MVT::v8i8 : MVT::v4i16;
18915 SDValue Zero = DAG.getConstant(0, DL, SrcVT);
18916 unsigned ClipOpc = IsSigned ? RISCVISD::PNCLIPP : RISCVISD::PNCLIPUP;
18917 SDValue Clipped = DAG.getNode(ClipOpc, DL, WideVT, Shifted, Zero);
18918 Results.push_back(DAG.getExtractSubvector(DL, VT, Clipped, 0));
18919 return;
18920 }
18921 case Intrinsic::riscv_predsum:
18922 case Intrinsic::riscv_predsumu: {
18923 bool IsSigned = IntNo == Intrinsic::riscv_predsum;
18924 SDValue Vec = N->getOperand(1);
18925 MVT VecVT = Vec.getSimpleValueType();
18926 auto Ext = [&](SDValue V) {
18927 return DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
18928 MVT::i64, V);
18929 };
18930 auto RedSum = [&](MVT VT, SDValue V, SDValue Acc) {
18931 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, N->getOperand(0), V,
18932 Acc);
18933 };
18934
18935 // RV32: i64 accumulator. Reduce to a 32-bit partial sum, then
18936 // widening-accumulate into i64 via wadda/waddau (v2i32 uses wadda alone).
18937 if (!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64) {
18938 SDValue Acc = N->getOperand(2);
18939 SDValue Res;
18940 if (VecVT == MVT::v2i32) {
18941 Res = DAG.getNode(ISD::ADD, DL, MVT::i64, Acc,
18942 Ext(DAG.getExtractVectorElt(DL, MVT::i32, Vec, 0)));
18943 Res = DAG.getNode(ISD::ADD, DL, MVT::i64, Res,
18944 Ext(DAG.getExtractVectorElt(DL, MVT::i32, Vec, 1)));
18945 } else {
18946 // The paired predsum.dbs/dhs computes the 32-bit element sum.
18947 SDValue Partial =
18948 RedSum(MVT::i32, Vec, DAG.getConstant(0, DL, MVT::i32));
18949 Res = DAG.getNode(ISD::ADD, DL, MVT::i64, Acc, Ext(Partial));
18950 }
18951 Results.push_back(Res);
18952 return;
18953 }
18954
18955 // RV64: i32 accumulator. Reduce at i64 (XLEN), then truncate.
18956 if (!Subtarget.is64Bit() || N->getValueType(0) != MVT::i32)
18957 return;
18958
18959 // Zero the upper lanes (zext.w) so they don't contribute to the sum.
18960 if (VecVT == MVT::v4i8 || VecVT == MVT::v2i16)
18962 DAG, DL, Vec, VecVT == MVT::v4i8 ? MVT::v8i8 : MVT::v4i16);
18963
18964 // The result is truncated to i32, so the accumulator's upper bits are
18965 // unused and need no sign/zero extension.
18966 SDValue Acc =
18967 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
18968 SDValue Res = RedSum(MVT::i64, Vec, Acc);
18969 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
18970 return;
18971 }
18972 case Intrinsic::riscv_pabdsumu:
18973 case Intrinsic::riscv_pabdsumau: {
18974 bool IsAcc = IntNo == Intrinsic::riscv_pabdsumau;
18975 // The two packed sources (rs1, rs2) are the last two operands.
18976 SDValue Rs1 = N->getOperand(N->getNumOperands() - 2);
18977 SDValue Rs2 = N->getOperand(N->getNumOperands() - 1);
18978 MVT VecVT = Rs1.getSimpleValueType();
18979
18980 // RV32: i64 result, always from a v8i8 source. The accumulator, if any,
18981 // folds into the widening add below.
18982 if (!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64) {
18983 // Sum of absolute differences of two v4i8 halves.
18984 auto Sad = [&](SDValue A, SDValue B) {
18985 SDValue S = DAG.getNode(
18986 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
18987 DAG.getTargetConstant(Intrinsic::riscv_pabdsumu, DL, MVT::i32), A,
18988 B);
18989 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, S);
18990 };
18991 auto [Rs1Lo, Rs1Hi] = DAG.SplitVector(Rs1, DL);
18992 auto [Rs2Lo, Rs2Hi] = DAG.SplitVector(Rs2, DL);
18993 SDValue Lo = Sad(Rs1Lo, Rs2Lo);
18994 SDValue Hi = Sad(Rs1Hi, Rs2Hi);
18995 // (acc + lo) + hi keeps the accumulate chained so it folds into a
18996 // single waddau; without an accumulator lo + hi folds into waddu.
18997 SDValue Res =
18998 IsAcc ? DAG.getNode(ISD::ADD, DL, MVT::i64, N->getOperand(1), Lo)
18999 : Lo;
19000 Res = DAG.getNode(ISD::ADD, DL, MVT::i64, Res, Hi);
19001 Results.push_back(Res);
19002 return;
19003 }
19004
19005 // RV64: i32 result, so reduce at i64 and truncate. The source is v4i8 or
19006 // v8i8; widen a v4i8 to v8i8, zeroing the upper bytes (v8i8 is legal).
19007 if (!Subtarget.is64Bit() || N->getValueType(0) != MVT::i32)
19008 return;
19009 if (VecVT == MVT::v4i8) {
19010 Rs1 = widenPackedVectorWithZeros(DAG, DL, Rs1, MVT::v8i8);
19011 Rs2 = widenPackedVectorWithZeros(DAG, DL, Rs2, MVT::v8i8);
19012 }
19013 SmallVector<SDValue, 4> Ops = {N->getOperand(0)};
19014 if (IsAcc)
19015 Ops.push_back(
19016 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)));
19017 Ops.push_back(Rs1);
19018 Ops.push_back(Rs2);
19019 SDValue Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, Ops);
19020 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
19021 return;
19022 }
19023 case Intrinsic::riscv_mqacc_00:
19024 case Intrinsic::riscv_mqacc_01:
19025 case Intrinsic::riscv_mqacc_11:
19026 case Intrinsic::riscv_mqracc_00:
19027 case Intrinsic::riscv_mqracc_01:
19028 case Intrinsic::riscv_mqracc_11: {
19029 EVT VT = N->getValueType(0);
19030 if (Subtarget.is64Bit() && VT == MVT::i32) {
19031 SDValue Rd = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i32,
19032 N->getOperand(1));
19033 auto WidenSrc = [&](SDValue V) {
19034 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i16,
19035 {V, DAG.getUNDEF(MVT::v2i16)});
19036 };
19037 SDValue Rs1 = WidenSrc(N->getOperand(2));
19038 SDValue Rs2 = WidenSrc(N->getOperand(3));
19039 unsigned Opc = getRVPQFormatAccOpcode(IntNo);
19040 SDValue Res = DAG.getNode(Opc, DL, MVT::v2i32, Rd, Rs1, Rs2);
19041 Results.push_back(DAG.getExtractVectorElt(DL, MVT::i32, Res, 0));
19042 return;
19043 }
19044
19045 if (!Subtarget.is64Bit() && VT == MVT::i64) {
19046 bool IsRound = IntNo == Intrinsic::riscv_mqracc_00 ||
19047 IntNo == Intrinsic::riscv_mqracc_01 ||
19048 IntNo == Intrinsic::riscv_mqracc_11;
19049 bool Hi1 = IntNo == Intrinsic::riscv_mqacc_11 ||
19050 IntNo == Intrinsic::riscv_mqracc_11;
19051 bool Hi2 = IntNo == Intrinsic::riscv_mqacc_01 ||
19052 IntNo == Intrinsic::riscv_mqacc_11 ||
19053 IntNo == Intrinsic::riscv_mqracc_01 ||
19054 IntNo == Intrinsic::riscv_mqracc_11;
19055 MVT XLenVT = Subtarget.getXLenVT();
19056 SDValue Rs1 = N->getOperand(2);
19057 SDValue Rs2 = N->getOperand(3);
19058 SDValue A = DAG.getExtractVectorElt(DL, XLenVT, Rs1, Hi1 ? 1 : 0);
19059 SDValue B = DAG.getExtractVectorElt(DL, XLenVT, Rs2, Hi2 ? 1 : 0);
19060 auto [RdLo, RdHi] =
19061 DAG.SplitScalar(N->getOperand(1), DL, XLenVT, XLenVT);
19062 unsigned Opc = IsRound ? RISCVISD::MQRWACC : RISCVISD::MQWACC;
19063 SDVTList VTs = DAG.getVTList(XLenVT, XLenVT);
19064 SDValue Acc = DAG.getNode(Opc, DL, VTs, {RdLo, RdHi, A, B});
19065 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
19066 Acc.getValue(0), Acc.getValue(1)));
19067 return;
19068 }
19069 return;
19070 }
19071 case Intrinsic::riscv_orc_b:
19072 case Intrinsic::riscv_brev8:
19073 case Intrinsic::riscv_sha256sig0:
19074 case Intrinsic::riscv_sha256sig1:
19075 case Intrinsic::riscv_sha256sum0:
19076 case Intrinsic::riscv_sha256sum1:
19077 case Intrinsic::riscv_sm3p0:
19078 case Intrinsic::riscv_sm3p1: {
19079 if (!Subtarget.is64Bit() || N->getValueType(0) != MVT::i32)
19080 return;
19081 unsigned Opc;
19082 switch (IntNo) {
19083 case Intrinsic::riscv_orc_b: Opc = RISCVISD::ORC_B; break;
19084 case Intrinsic::riscv_brev8: Opc = RISCVISD::BREV8; break;
19085 case Intrinsic::riscv_sha256sig0: Opc = RISCVISD::SHA256SIG0; break;
19086 case Intrinsic::riscv_sha256sig1: Opc = RISCVISD::SHA256SIG1; break;
19087 case Intrinsic::riscv_sha256sum0: Opc = RISCVISD::SHA256SUM0; break;
19088 case Intrinsic::riscv_sha256sum1: Opc = RISCVISD::SHA256SUM1; break;
19089 case Intrinsic::riscv_sm3p0: Opc = RISCVISD::SM3P0; break;
19090 case Intrinsic::riscv_sm3p1: Opc = RISCVISD::SM3P1; break;
19091 }
19092
19093 SDValue NewOp =
19094 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
19095 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp);
19096 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
19097 return;
19098 }
19099 case Intrinsic::riscv_sm4ks:
19100 case Intrinsic::riscv_sm4ed: {
19101 unsigned Opc =
19102 IntNo == Intrinsic::riscv_sm4ks ? RISCVISD::SM4KS : RISCVISD::SM4ED;
19103 SDValue NewOp0 =
19104 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
19105 SDValue NewOp1 =
19106 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
19107 SDValue Res =
19108 DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, N->getOperand(3));
19109 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
19110 return;
19111 }
19112 case Intrinsic::riscv_mopr: {
19113 if (!Subtarget.is64Bit() || N->getValueType(0) != MVT::i32)
19114 return;
19115 SDValue NewOp =
19116 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
19117 SDValue Res = DAG.getNode(
19118 RISCVISD::MOP_R, DL, MVT::i64, NewOp,
19119 DAG.getTargetConstant(N->getConstantOperandVal(2), DL, MVT::i64));
19120 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
19121 return;
19122 }
19123 case Intrinsic::riscv_moprr: {
19124 if (!Subtarget.is64Bit() || N->getValueType(0) != MVT::i32)
19125 return;
19126 SDValue NewOp0 =
19127 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
19128 SDValue NewOp1 =
19129 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
19130 SDValue Res = DAG.getNode(
19131 RISCVISD::MOP_RR, DL, MVT::i64, NewOp0, NewOp1,
19132 DAG.getTargetConstant(N->getConstantOperandVal(3), DL, MVT::i64));
19133 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
19134 return;
19135 }
19136 case Intrinsic::riscv_clmulh:
19137 case Intrinsic::riscv_clmulr: {
19138 if (!Subtarget.is64Bit() || N->getValueType(0) != MVT::i32)
19139 return;
19140
19141 // Zero extend the inputs, use a clmul, then shift the result.
19142 SDValue NewOp0 =
19143 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
19144 SDValue NewOp1 =
19145 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(2));
19146 unsigned ShAmt = IntNo == Intrinsic::riscv_clmulh ? 32 : 31;
19147 SDValue Res = DAG.getNode(ISD::CLMUL, DL, MVT::i64, NewOp0, NewOp1);
19148 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, Res,
19149 DAG.getConstant(ShAmt, DL, MVT::i64));
19150 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
19151 return;
19152 }
19153 case Intrinsic::riscv_vmv_x_s: {
19154 EVT VT = N->getValueType(0);
19155 MVT XLenVT = Subtarget.getXLenVT();
19156 if (VT.bitsLT(XLenVT)) {
19157 // Simple case just extract using vmv.x.s and truncate.
19158 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
19159 Subtarget.getXLenVT(), N->getOperand(1));
19160 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
19161 return;
19162 }
19163
19164 assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
19165 "Unexpected custom legalization");
19166
19167 // We need to do the move in two steps.
19168 SDValue Vec = N->getOperand(1);
19169 MVT VecVT = Vec.getSimpleValueType();
19170
19171 // First extract the lower XLEN bits of the element.
19172 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
19173
19174 // To extract the upper XLEN bits of the vector element, shift the first
19175 // element right by 32 bits and re-extract the lower XLEN bits.
19176 auto [Mask, VL] = getDefaultVLOps(1, VecVT, DL, DAG, Subtarget);
19177
19178 SDValue ThirtyTwoV =
19179 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
19180 DAG.getConstant(32, DL, XLenVT), VL);
19181 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV,
19182 DAG.getUNDEF(VecVT), Mask, VL);
19183 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
19184
19185 Results.push_back(
19186 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
19187 break;
19188 }
19189 }
19190 break;
19191 }
19192 case ISD::VECREDUCE_ADD:
19193 case ISD::VECREDUCE_AND:
19194 case ISD::VECREDUCE_OR:
19195 case ISD::VECREDUCE_XOR:
19200 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
19201 Results.push_back(V);
19202 break;
19203 case ISD::VP_REDUCE_ADD:
19204 case ISD::VP_REDUCE_AND:
19205 case ISD::VP_REDUCE_OR:
19206 case ISD::VP_REDUCE_XOR:
19207 case ISD::VP_REDUCE_SMAX:
19208 case ISD::VP_REDUCE_UMAX:
19209 case ISD::VP_REDUCE_SMIN:
19210 case ISD::VP_REDUCE_UMIN:
19211 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
19212 Results.push_back(V);
19213 break;
19214 case ISD::GET_ROUNDING: {
19215 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
19216 SDValue Res = DAG.getNode(ISD::GET_ROUNDING, DL, VTs, N->getOperand(0));
19217 Results.push_back(Res.getValue(0));
19218 Results.push_back(Res.getValue(1));
19219 break;
19220 }
19221 }
19222}
19223
19224/// Given a binary operator, return the *associative* generic ISD::VECREDUCE_OP
19225/// which corresponds to it.
19226static unsigned getVecReduceOpcode(unsigned Opc) {
19227 switch (Opc) {
19228 default:
19229 llvm_unreachable("Unhandled binary to transform reduction");
19230 case ISD::ADD:
19231 return ISD::VECREDUCE_ADD;
19232 case ISD::UMAX:
19233 return ISD::VECREDUCE_UMAX;
19234 case ISD::SMAX:
19235 return ISD::VECREDUCE_SMAX;
19236 case ISD::UMIN:
19237 return ISD::VECREDUCE_UMIN;
19238 case ISD::SMIN:
19239 return ISD::VECREDUCE_SMIN;
19240 case ISD::AND:
19241 return ISD::VECREDUCE_AND;
19242 case ISD::OR:
19243 return ISD::VECREDUCE_OR;
19244 case ISD::XOR:
19245 return ISD::VECREDUCE_XOR;
19246 case ISD::FADD:
19247 // Note: This is the associative form of the generic reduction opcode.
19248 return ISD::VECREDUCE_FADD;
19249 case ISD::FMAXNUM:
19250 return ISD::VECREDUCE_FMAX;
19251 case ISD::FMINNUM:
19252 return ISD::VECREDUCE_FMIN;
19253 }
19254}
19255
19256/// Perform two related transforms whose purpose is to incrementally recognize
19257/// an explode_vector followed by scalar reduction as a vector reduction node.
19258/// This exists to recover from a deficiency in SLP which can't handle
19259/// forests with multiple roots sharing common nodes. In some cases, one
19260/// of the trees will be vectorized, and the other will remain (unprofitably)
19261/// scalarized.
19262static SDValue
19264 const RISCVSubtarget &Subtarget) {
19265
19266 // This transforms need to run before all integer types have been legalized
19267 // to i64 (so that the vector element type matches the add type), and while
19268 // it's safe to introduce odd sized vector types.
19270 return SDValue();
19271
19272 // Without V, this transform isn't useful. We could form the (illegal)
19273 // operations and let them be scalarized again, but there's really no point.
19274 if (!Subtarget.hasVInstructions())
19275 return SDValue();
19276
19277 const SDLoc DL(N);
19278 const EVT VT = N->getValueType(0);
19279 const unsigned Opc = N->getOpcode();
19280
19281 if (!VT.isInteger()) {
19282 switch (Opc) {
19283 default:
19284 return SDValue();
19285 case ISD::FADD:
19286 // For FADD, we only handle the case with reassociation allowed. We
19287 // could handle strict reduction order, but at the moment, there's no
19288 // known reason to, and the complexity isn't worth it.
19289 if (!N->getFlags().hasAllowReassociation())
19290 return SDValue();
19291 break;
19292 case ISD::FMAXNUM:
19293 case ISD::FMINNUM:
19294 break;
19295 }
19296 }
19297
19298 const unsigned ReduceOpc = getVecReduceOpcode(Opc);
19299 assert(Opc == ISD::getVecReduceBaseOpcode(ReduceOpc) &&
19300 "Inconsistent mappings");
19301 SDValue LHS = N->getOperand(0);
19302 SDValue RHS = N->getOperand(1);
19303
19304 if (!LHS.hasOneUse() || !RHS.hasOneUse())
19305 return SDValue();
19306
19307 if (RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19308 std::swap(LHS, RHS);
19309
19310 if (RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
19311 !isa<ConstantSDNode>(RHS.getOperand(1)))
19312 return SDValue();
19313
19314 uint64_t RHSIdx = cast<ConstantSDNode>(RHS.getOperand(1))->getLimitedValue();
19315 SDValue SrcVec = RHS.getOperand(0);
19316 EVT SrcVecVT = SrcVec.getValueType();
19317 if (SrcVecVT.getVectorElementType() != VT)
19318 return SDValue();
19319 if (SrcVecVT.isScalableVector())
19320 return SDValue();
19321
19322 if (SrcVecVT.getScalarSizeInBits() > Subtarget.getELen())
19323 return SDValue();
19324
19325 // match binop (extract_vector_elt V, 0), (extract_vector_elt V, 1) to
19326 // reduce_op (extract_subvector [2 x VT] from V). This will form the
19327 // root of our reduction tree. TODO: We could extend this to any two
19328 // adjacent aligned constant indices if desired.
19329 if (LHS.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
19330 LHS.getOperand(0) == SrcVec && isa<ConstantSDNode>(LHS.getOperand(1))) {
19331 uint64_t LHSIdx =
19332 cast<ConstantSDNode>(LHS.getOperand(1))->getLimitedValue();
19333 if (0 == std::min(LHSIdx, RHSIdx) && 1 == std::max(LHSIdx, RHSIdx)) {
19334 EVT ReduceVT = EVT::getVectorVT(*DAG.getContext(), VT, 2);
19335 SDValue Vec = DAG.getExtractSubvector(DL, ReduceVT, SrcVec, 0);
19336 return DAG.getNode(ReduceOpc, DL, VT, Vec, N->getFlags());
19337 }
19338 }
19339
19340 // Match (binop (reduce (extract_subvector V, 0),
19341 // (extract_vector_elt V, sizeof(SubVec))))
19342 // into a reduction of one more element from the original vector V.
19343 if (LHS.getOpcode() != ReduceOpc)
19344 return SDValue();
19345
19346 SDValue ReduceVec = LHS.getOperand(0);
19347 if (ReduceVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
19348 ReduceVec.hasOneUse() && ReduceVec.getOperand(0) == RHS.getOperand(0) &&
19349 isNullConstant(ReduceVec.getOperand(1)) &&
19350 ReduceVec.getValueType().getVectorNumElements() == RHSIdx) {
19351 // For illegal types (e.g. 3xi32), most will be combined again into a
19352 // wider (hopefully legal) type. If this is a terminal state, we are
19353 // relying on type legalization here to produce something reasonable
19354 // and this lowering quality could probably be improved. (TODO)
19355 EVT ReduceVT = EVT::getVectorVT(*DAG.getContext(), VT, RHSIdx + 1);
19356 SDValue Vec = DAG.getExtractSubvector(DL, ReduceVT, SrcVec, 0);
19357 return DAG.getNode(ReduceOpc, DL, VT, Vec,
19358 ReduceVec->getFlags() & N->getFlags());
19359 }
19360
19361 return SDValue();
19362}
19363
19364
19365// Try to fold (<bop> x, (reduction.<bop> vec, start))
19367 const RISCVSubtarget &Subtarget) {
19368 auto BinOpToRVVReduce = [](unsigned Opc) {
19369 switch (Opc) {
19370 default:
19371 llvm_unreachable("Unhandled binary to transform reduction");
19372 case ISD::ADD:
19373 return RISCVISD::VECREDUCE_ADD_VL;
19374 case ISD::UMAX:
19375 return RISCVISD::VECREDUCE_UMAX_VL;
19376 case ISD::SMAX:
19377 return RISCVISD::VECREDUCE_SMAX_VL;
19378 case ISD::UMIN:
19379 return RISCVISD::VECREDUCE_UMIN_VL;
19380 case ISD::SMIN:
19381 return RISCVISD::VECREDUCE_SMIN_VL;
19382 case ISD::AND:
19383 return RISCVISD::VECREDUCE_AND_VL;
19384 case ISD::OR:
19385 return RISCVISD::VECREDUCE_OR_VL;
19386 case ISD::XOR:
19387 return RISCVISD::VECREDUCE_XOR_VL;
19388 case ISD::FADD:
19389 return RISCVISD::VECREDUCE_FADD_VL;
19390 case ISD::FMAXNUM:
19391 return RISCVISD::VECREDUCE_FMAX_VL;
19392 case ISD::FMINNUM:
19393 return RISCVISD::VECREDUCE_FMIN_VL;
19394 }
19395 };
19396
19397 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
19398 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
19399 isNullConstant(V.getOperand(1)) &&
19400 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
19401 };
19402
19403 unsigned Opc = N->getOpcode();
19404 unsigned ReduceIdx;
19405 if (IsReduction(N->getOperand(0), Opc))
19406 ReduceIdx = 0;
19407 else if (IsReduction(N->getOperand(1), Opc))
19408 ReduceIdx = 1;
19409 else
19410 return SDValue();
19411
19412 // Skip if FADD disallows reassociation but the combiner needs.
19413 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
19414 return SDValue();
19415
19416 SDValue Extract = N->getOperand(ReduceIdx);
19417 SDValue Reduce = Extract.getOperand(0);
19418 if (!Extract.hasOneUse() || !Reduce.hasOneUse())
19419 return SDValue();
19420
19421 SDValue ScalarV = Reduce.getOperand(2);
19422 EVT ScalarVT = ScalarV.getValueType();
19423 if (ScalarV.getOpcode() == ISD::INSERT_SUBVECTOR &&
19424 ScalarV.getOperand(0)->isUndef() &&
19425 isNullConstant(ScalarV.getOperand(2)))
19426 ScalarV = ScalarV.getOperand(1);
19427
19428 // Make sure that ScalarV is a splat with VL=1.
19429 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
19430 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
19431 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
19432 return SDValue();
19433
19434 if (!isNonZeroAVL(ScalarV.getOperand(2)))
19435 return SDValue();
19436
19437 // Check the scalar of ScalarV is neutral element
19438 // TODO: Deal with value other than neutral element.
19439 if (!DAG.isIdentityElement(N->getOpcode(), N->getFlags(),
19440 ScalarV.getOperand(1), 0))
19441 return SDValue();
19442
19443 // If the AVL is zero, operand 0 will be returned. So it's not safe to fold.
19444 // FIXME: We might be able to improve this if operand 0 is undef.
19445 if (!isNonZeroAVL(Reduce.getOperand(5)))
19446 return SDValue();
19447
19448 SDValue NewStart = N->getOperand(1 - ReduceIdx);
19449
19450 SDLoc DL(N);
19451 SDValue NewScalarV =
19452 lowerScalarInsert(NewStart, ScalarV.getOperand(2),
19453 ScalarV.getSimpleValueType(), DL, DAG, Subtarget);
19454
19455 // If we looked through an INSERT_SUBVECTOR we need to restore it.
19456 if (ScalarVT != ScalarV.getValueType())
19457 NewScalarV =
19458 DAG.getInsertSubvector(DL, DAG.getUNDEF(ScalarVT), NewScalarV, 0);
19459
19460 SDValue Ops[] = {Reduce.getOperand(0), Reduce.getOperand(1),
19461 NewScalarV, Reduce.getOperand(3),
19462 Reduce.getOperand(4), Reduce.getOperand(5)};
19463 SDValue NewReduce =
19464 DAG.getNode(Reduce.getOpcode(), DL, Reduce.getValueType(), Ops);
19465 return DAG.getNode(Extract.getOpcode(), DL, Extract.getValueType(), NewReduce,
19466 Extract.getOperand(1));
19467}
19468
19469// Optimize (add (shl x, c0), (shl y, c1)) ->
19470// (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
19471// or
19472// (SLLI (QC.SHLADD x, y, c1 - c0), c0), if 4 <= (c1-c0) <=31.
19474 const RISCVSubtarget &Subtarget) {
19475 // Perform this optimization only in the zba/xandesperf/xqciac/xtheadba
19476 // extension.
19477 if (!Subtarget.hasShlAdd(3))
19478 return SDValue();
19479
19480 // Skip for vector types and larger types.
19481 EVT VT = N->getValueType(0);
19482 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
19483 return SDValue();
19484
19485 // The two operand nodes must be SHL and have no other use.
19486 SDValue N0 = N->getOperand(0);
19487 SDValue N1 = N->getOperand(1);
19488 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
19489 !N0->hasOneUse() || !N1->hasOneUse())
19490 return SDValue();
19491
19492 // Check c0 and c1.
19493 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
19494 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
19495 if (!N0C || !N1C)
19496 return SDValue();
19497 int64_t C0 = N0C->getSExtValue();
19498 int64_t C1 = N1C->getSExtValue();
19499 if (C0 <= 0 || C1 <= 0)
19500 return SDValue();
19501
19502 int64_t Diff = std::abs(C0 - C1);
19503 if (!Subtarget.hasShlAdd(Diff))
19504 return SDValue();
19505
19506 // Build nodes.
19507 SDLoc DL(N);
19508 int64_t Bits = std::min(C0, C1);
19509 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
19510 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
19511 SDValue SHADD = DAG.getNode(RISCVISD::SHL_ADD, DL, VT, NL,
19512 DAG.getTargetConstant(Diff, DL, VT), NS);
19513 return DAG.getNode(ISD::SHL, DL, VT, SHADD, DAG.getConstant(Bits, DL, VT));
19514}
19515
19516// Check if this SDValue is an add immediate that is fed by a shift of 1, 2,
19517// or 3.
19519 SelectionDAG &DAG) {
19520 using namespace llvm::SDPatternMatch;
19521
19522 // Looking for a reg-reg add and not an addi.
19523 if (isa<ConstantSDNode>(N->getOperand(1)))
19524 return SDValue();
19525
19526 // Based on testing it seems that performance degrades if the ADDI has
19527 // more than 2 uses.
19528 if (AddI->use_size() > 2)
19529 return SDValue();
19530
19531 APInt AddVal;
19532 SDValue SHLVal;
19533 if (!sd_match(AddI, m_Add(m_Value(SHLVal), m_ConstInt(AddVal))))
19534 return SDValue();
19535
19536 APInt VShift;
19537 if (!sd_match(SHLVal, m_OneUse(m_Shl(m_Value(), m_ConstInt(VShift)))))
19538 return SDValue();
19539
19540 if (VShift.slt(1) || VShift.sgt(3))
19541 return SDValue();
19542
19543 SDLoc DL(N);
19544 EVT VT = N->getValueType(0);
19545 // The shift must be positive but the add can be signed.
19546 uint64_t ShlConst = VShift.getZExtValue();
19547 int64_t AddConst = AddVal.getSExtValue();
19548
19549 SDValue SHADD = DAG.getNode(RISCVISD::SHL_ADD, DL, VT, SHLVal->getOperand(0),
19550 DAG.getTargetConstant(ShlConst, DL, VT), Other);
19551 return DAG.getNode(ISD::ADD, DL, VT, SHADD,
19552 DAG.getSignedConstant(AddConst, DL, VT));
19553}
19554
19555// Optimize (add (add (shl x, c0), c1), y) ->
19556// (ADDI (SH*ADD y, x), c1), if c0 equals to [1|2|3].
19558 const RISCVSubtarget &Subtarget) {
19559 // Perform this optimization only in the zba extension.
19560 if (!Subtarget.getCLOpts().reassoc_shl_addi_add || !Subtarget.hasShlAdd(3))
19561 return SDValue();
19562
19563 // Skip for vector types and larger types.
19564 EVT VT = N->getValueType(0);
19565 if (VT != Subtarget.getXLenVT())
19566 return SDValue();
19567
19568 SDValue AddI = N->getOperand(0);
19569 SDValue Other = N->getOperand(1);
19570 if (SDValue V = combineShlAddIAddImpl(N, AddI, Other, DAG))
19571 return V;
19572 if (SDValue V = combineShlAddIAddImpl(N, Other, AddI, DAG))
19573 return V;
19574 return SDValue();
19575}
19576
19577// Combine a constant select operand into its use:
19578//
19579// (and (select cond, -1, c), x)
19580// -> (select cond, x, (and x, c)) [AllOnes=1]
19581// (or (select cond, 0, c), x)
19582// -> (select cond, x, (or x, c)) [AllOnes=0]
19583// (xor (select cond, 0, c), x)
19584// -> (select cond, x, (xor x, c)) [AllOnes=0]
19585// (add (select cond, 0, c), x)
19586// -> (select cond, x, (add x, c)) [AllOnes=0]
19587// (sub x, (select cond, 0, c))
19588// -> (select cond, x, (sub x, c)) [AllOnes=0]
19590 SelectionDAG &DAG, bool AllOnes,
19591 const RISCVSubtarget &Subtarget) {
19592 EVT VT = N->getValueType(0);
19593
19594 // Skip vectors.
19595 if (VT.isVector())
19596 return SDValue();
19597
19598 if (!Subtarget.hasConditionalMoveFusion()) {
19599 // (select cond, x, (and x, c)) has custom lowering with Zicond.
19600 if (!Subtarget.hasStdExtZicond() || N->getOpcode() != ISD::AND)
19601 return SDValue();
19602
19603 // Maybe harmful when condition code has multiple use.
19604 if (Slct.getOpcode() == ISD::SELECT && !Slct.getOperand(0).hasOneUse())
19605 return SDValue();
19606
19607 // Maybe harmful when VT is wider than XLen.
19608 if (VT.getSizeInBits() > Subtarget.getXLen())
19609 return SDValue();
19610 }
19611
19612 if ((Slct.getOpcode() != ISD::SELECT &&
19613 Slct.getOpcode() != RISCVISD::SELECT_CC) ||
19614 !Slct.hasOneUse())
19615 return SDValue();
19616
19617 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
19619 };
19620
19621 bool SwapSelectOps;
19622 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
19623 SDValue TrueVal = Slct.getOperand(1 + OpOffset);
19624 SDValue FalseVal = Slct.getOperand(2 + OpOffset);
19625 SDValue NonConstantVal;
19626 if (isZeroOrAllOnes(TrueVal, AllOnes)) {
19627 SwapSelectOps = false;
19628 NonConstantVal = FalseVal;
19629 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
19630 SwapSelectOps = true;
19631 NonConstantVal = TrueVal;
19632 } else
19633 return SDValue();
19634
19635 // Slct is now know to be the desired identity constant when CC is true.
19636 TrueVal = OtherOp;
19637 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
19638 // Unless SwapSelectOps says the condition should be false.
19639 if (SwapSelectOps)
19640 std::swap(TrueVal, FalseVal);
19641
19642 if (Slct.getOpcode() == RISCVISD::SELECT_CC)
19643 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
19644 {Slct.getOperand(0), Slct.getOperand(1),
19645 Slct.getOperand(2), TrueVal, FalseVal});
19646
19647 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
19648 {Slct.getOperand(0), TrueVal, FalseVal});
19649}
19650
19651// Attempt combineSelectAndUse on each operand of a commutative operator N.
19653 bool AllOnes,
19654 const RISCVSubtarget &Subtarget) {
19655 SDValue N0 = N->getOperand(0);
19656 SDValue N1 = N->getOperand(1);
19657 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes, Subtarget))
19658 return Result;
19659 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes, Subtarget))
19660 return Result;
19661 return SDValue();
19662}
19663
19664// Transform (add (mul x, c0), c1) ->
19665// (add (mul (add x, c1/c0), c0), c1%c0).
19666// if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
19667// that should be excluded is when c0*(c1/c0) is simm12, which will lead
19668// to an infinite loop in DAGCombine if transformed.
19669// Or transform (add (mul x, c0), c1) ->
19670// (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
19671// if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
19672// case that should be excluded is when c0*(c1/c0+1) is simm12, which will
19673// lead to an infinite loop in DAGCombine if transformed.
19674// Or transform (add (mul x, c0), c1) ->
19675// (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
19676// if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
19677// case that should be excluded is when c0*(c1/c0-1) is simm12, which will
19678// lead to an infinite loop in DAGCombine if transformed.
19679// Or transform (add (mul x, c0), c1) ->
19680// (mul (add x, c1/c0), c0).
19681// if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
19683 const RISCVSubtarget &Subtarget) {
19684 // Skip for vector types and larger types.
19685 EVT VT = N->getValueType(0);
19686 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
19687 return SDValue();
19688 // The first operand node must be a MUL and has no other use.
19689 SDValue N0 = N->getOperand(0);
19690 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
19691 return SDValue();
19692 // Check if c0 and c1 match above conditions.
19693 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
19694 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19695 if (!N0C || !N1C)
19696 return SDValue();
19697 // If N0C has multiple uses it's possible one of the cases in
19698 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
19699 // in an infinite loop.
19700 if (!N0C->hasOneUse())
19701 return SDValue();
19702 int64_t C0 = N0C->getSExtValue();
19703 int64_t C1 = N1C->getSExtValue();
19704 int64_t CA, CB;
19705 // If C1 already fits in an add immediate, there is nothing to split out: the
19706 // (add (mul x, c0), c1) form is already canonical/cheap. Splitting it would
19707 // fight the generic DAGCombiner fold add(mul(add(A, CA), CM), CB) ->
19708 // add(mul(A, CM), CM*CA+CB) (which is gated on isLegalAddImmediate) and cause
19709 // an infinite loop.
19710 if (C0 == -1 || C0 == 0 || C0 == 1 ||
19711 Subtarget.getTargetLowering()->isLegalAddImmediate(C1))
19712 return SDValue();
19713 // Search for proper CA (non-zero) and CB that both are simm12.
19714 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
19715 !isInt<12>(C0 * (C1 / C0))) {
19716 CA = C1 / C0;
19717 CB = C1 % C0;
19718 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
19719 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
19720 CA = C1 / C0 + 1;
19721 CB = C1 % C0 - C0;
19722 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
19723 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
19724 CA = C1 / C0 - 1;
19725 CB = C1 % C0 + C0;
19726 } else
19727 return SDValue();
19728 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
19729 SDLoc DL(N);
19730 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
19731 DAG.getSignedConstant(CA, DL, VT));
19732 SDValue New1 =
19733 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getSignedConstant(C0, DL, VT));
19734 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getSignedConstant(CB, DL, VT));
19735}
19736
19737// add (ext X), (ext Y) -> ext (add X, Y)
19738// if the add can't overflow in the narrow type.
19739static SDValue
19741 const RISCVSubtarget &Subtarget) {
19742 EVT VT = N->getValueType(0);
19743 if (!VT.isVector() || !Subtarget.hasVInstructions())
19744 return SDValue();
19745
19746 // Ensure the user has a widening variant so the extend can be moved after
19747 // the add and still be combined. Do not interfere with existing fusion
19748 // opportunities, such as mul-add or .vx patterns.
19749 if (!N->hasOneUse())
19750 return SDValue();
19751
19752 const SDUse &Use = *N->use_begin();
19753 const SDNode *User = Use.getUser();
19754 if (User->getOpcode() == ISD::ADD) {
19755 const SDValue OtherOp = User->getOperand(1 - Use.getOperandNo());
19756 if (OtherOp->getOpcode() == ISD::MUL || DAG.isSplatValue(OtherOp))
19757 return SDValue();
19758 } else if (User->getOpcode() != ISD::VECREDUCE_ADD) {
19759 return SDValue();
19760 }
19761
19762 SDValue LHS = N->getOperand(0);
19763 SDValue RHS = N->getOperand(1);
19764 unsigned ExtOpc = LHS.getOpcode();
19765 if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
19766 RHS.getOpcode() != ExtOpc || !LHS.hasOneUse() || !RHS.hasOneUse())
19767 return SDValue();
19768
19769 SDValue LHSSrc = LHS.getOperand(0);
19770 SDValue RHSSrc = RHS.getOperand(0);
19771 if (LHSSrc.getValueType() != RHSSrc.getValueType() ||
19773 return SDValue();
19774
19775 if (!DAG.willNotOverflowAdd(ExtOpc == ISD::SIGN_EXTEND, LHSSrc, RHSSrc))
19776 return SDValue();
19777
19778 SDLoc DL(N);
19779 SDValue Add =
19780 DAG.getNode(ISD::ADD, DL, LHSSrc.getValueType(), LHSSrc, RHSSrc);
19781 return DAG.getNode(ExtOpc, DL, N->getValueType(0), Add);
19782}
19783
19784// add (zext, zext) -> zext (add (zext, zext))
19785// sub (zext, zext) -> sext (sub (zext, zext))
19786// mul (zext, zext) -> zext (mul (zext, zext))
19787// sdiv (zext, zext) -> zext (sdiv (zext, zext))
19788// udiv (zext, zext) -> zext (udiv (zext, zext))
19789// srem (zext, zext) -> zext (srem (zext, zext))
19790// urem (zext, zext) -> zext (urem (zext, zext))
19791//
19792// add/sub/mul/sdiv/srem (sext, ext) -> sext (binop (sext, ext))
19793// add/sub/mul/sdiv/srem (ext, sext) -> sext (binop (ext, sext))
19794//
19795// where the sum of the extend widths match, and the range of the bin op
19796// fits inside the width of the narrower bin op. (For profitability on rvv, we
19797// use a power of two for both inner and outer extend.)
19799
19800 EVT VT = N->getValueType(0);
19801 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
19802 return SDValue();
19803
19804 SDValue N0 = N->getOperand(0);
19805 SDValue N1 = N->getOperand(1);
19806 unsigned N0Opc = N0.getOpcode();
19807 unsigned N1Opc = N1.getOpcode();
19808 if ((N0Opc != ISD::ZERO_EXTEND && N0Opc != ISD::SIGN_EXTEND) ||
19809 (N1Opc != ISD::ZERO_EXTEND && N1Opc != ISD::SIGN_EXTEND))
19810 return SDValue();
19811 if (!N0.hasOneUse() || !N1.hasOneUse())
19812 return SDValue();
19813
19814 bool AnySExt = N0Opc == ISD::SIGN_EXTEND || N1Opc == ISD::SIGN_EXTEND;
19815 if ((N->getOpcode() == ISD::UDIV || N->getOpcode() == ISD::UREM) && AnySExt)
19816 return SDValue();
19817
19818 SDValue Src0 = N0.getOperand(0);
19819 SDValue Src1 = N1.getOperand(0);
19820 EVT SrcVT = Src0.getValueType();
19821 if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT) ||
19822 SrcVT != Src1.getValueType() || SrcVT.getScalarSizeInBits() < 8 ||
19823 SrcVT.getScalarSizeInBits() >= VT.getScalarSizeInBits() / 2)
19824 return SDValue();
19825
19826 LLVMContext &C = *DAG.getContext();
19828 EVT NarrowVT = EVT::getVectorVT(C, ElemVT, VT.getVectorElementCount());
19829
19830 Src0 = DAG.getNode(N0Opc, SDLoc(Src0), NarrowVT, Src0);
19831 Src1 = DAG.getNode(N1Opc, SDLoc(Src1), NarrowVT, Src1);
19832
19833 // If both operands are zero extended they're always positive, and every node
19834 // except sub produces a positive from two positive operands, so zero extend
19835 // instead.
19836 unsigned OuterExtend = AnySExt || N->getOpcode() == ISD::SUB
19839
19840 return DAG.getNode(
19841 OuterExtend, SDLoc(N), VT,
19842 DAG.getNode(N->getOpcode(), SDLoc(N), NarrowVT, Src0, Src1));
19843}
19844
19845// add (add X, (ext Y)), (ext Z) -> add (add (ext Y), (ext Z)), X
19846// This helps combineBinOpOfExt form more often.
19848 const RISCVSubtarget &Subtarget) {
19849 using namespace SDPatternMatch;
19850 EVT VT = N->getValueType(0);
19851 SDLoc DL(N);
19852 if (!Subtarget.hasVInstructions() || !VT.isVector())
19853 return SDValue();
19854
19855 SDValue Inner, ExtZ, Z;
19856 if (!sd_match(N, m_Add(m_OneUse(m_Value(Inner)),
19857 m_OneUse(m_Value(ExtZ, m_ZExtOrSExt(m_Value(Z)))))))
19858 return SDValue();
19859 auto SameExt =
19860 m_OneUse(m_UnaryOp(ExtZ.getOpcode(), m_SpecificVT(Z.getValueType())));
19861 SDValue X, ExtY;
19862 if (!sd_match(Inner, m_Add(m_Value(X), m_Value(ExtY, SameExt))))
19863 return SDValue();
19864
19865 // Don't break (add X, (zext mask)) -> masked vadd.vi patterns.
19866 if (Z.getValueType().getScalarType() == MVT::i1)
19867 return SDValue();
19868
19869 // Don't reassociate in a loop:
19870 // add (add (ext X), (ext Y)), (ext Z) -> add (add (ext Z), (ext Y)), (ext X)
19871 if (sd_match(X, SameExt))
19872 return SDValue();
19873
19874 return DAG.getNode(ISD::ADD, DL, VT,
19875 DAG.getNode(ISD::ADD, DL, VT, ExtY, ExtZ), X);
19876}
19877
19878// Try to turn (add (xor bool, 1) -1) into (neg bool).
19880 SDValue N0 = N->getOperand(0);
19881 SDValue N1 = N->getOperand(1);
19882 EVT VT = N->getValueType(0);
19883 SDLoc DL(N);
19884
19885 // RHS should be -1.
19886 if (!isAllOnesConstant(N1))
19887 return SDValue();
19888
19889 // Look for (xor X, 1).
19890 if (N0.getOpcode() != ISD::XOR || !isOneConstant(N0.getOperand(1)))
19891 return SDValue();
19892
19893 // First xor input should be 0 or 1.
19895 if (!DAG.MaskedValueIsZero(N0.getOperand(0), Mask))
19896 return SDValue();
19897
19898 // Emit a negate of the setcc.
19899 return DAG.getNegative(N0.getOperand(0), DL, VT);
19900}
19901
19902// Fold (add X, (mulhs X, C)) -> (mulhsu X, C) if C is negative. This occurs
19903// in the expansion of sdiv i32 X, 7 using magic multiply.
19904//
19905// mulhs returns the hi from X * C = hi * 2^32 + lo.
19906//
19907// Since C<0, u(C) as an unsigned constant is 2^32 + C = u(C).
19908// mulhsu computes
19909// X * u(C0) = X * (C + 2^32)
19910// = X * 2^32 + C * X // C * X is the same as mulhs
19911// = X * 2^32 + hi * 2^32 + lo
19912// = (X + hi) * 2^32 + lo
19913// So mulhsu computes (X + hi).
19915 const RISCVSubtarget &Subtarget) {
19916 EVT VT = N->getValueType(0);
19918 bool IsPExtPackedDoubleType =
19919 VT.isSimple() && Subtarget.isPExtPackedDoubleType(VT.getSimpleVT());
19920 if (!TLI.isOperationLegal(ISD::MULHS, VT) && !IsPExtPackedDoubleType &&
19921 !(Subtarget.hasStdExtP() && !Subtarget.is64Bit() && VT == MVT::v4i8) &&
19922 !(Subtarget.hasStdExtP() && Subtarget.is64Bit() && VT == MVT::v8i8))
19923 return SDValue();
19924
19925 using namespace SDPatternMatch;
19926 SDValue X, Mulh;
19927 APInt C;
19928 if (!sd_match(N,
19929 m_Add(m_Value(X),
19931 m_ConstInt(C)))))) ||
19932 !C.isNegative())
19933 return SDValue();
19934
19935 SDLoc DL(N);
19936
19937 // We don't have a v4i8 MULHSU instruction, use a WMULSU+SRL+TRUNC.
19938 auto MakePWMulSU = [&](SDValue A, SDValue B) -> SDValue {
19939 SDValue WMul = DAG.getNode(RISCVISD::PWMULSU, DL, MVT::v4i16, A, B);
19940 SDValue Shifted = DAG.getNode(ISD::SRL, DL, MVT::v4i16, WMul,
19941 DAG.getConstant(8, DL, MVT::v4i16));
19942 return DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i8, Shifted);
19943 };
19944
19945 // We need to split double wide vectors ourselves, op legalization won't
19946 // run for custom nodes.
19947 if (IsPExtPackedDoubleType) {
19949 auto [XLo, XHi] = DAG.SplitVector(X, DL, HalfVT, HalfVT);
19950 auto [CLo, CHi] = DAG.SplitVector(Mulh.getOperand(1), DL, HalfVT, HalfVT);
19951 SDValue ResLo, ResHi;
19952 if (HalfVT == MVT::v4i8) {
19953 ResLo = MakePWMulSU(XLo, CLo);
19954 ResHi = MakePWMulSU(XHi, CHi);
19955 } else {
19956 ResLo = DAG.getNode(RISCVISD::MULHSU, DL, HalfVT, XLo, CLo);
19957 ResHi = DAG.getNode(RISCVISD::MULHSU, DL, HalfVT, XHi, CHi);
19958 }
19959 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
19960 }
19961
19962 if (Subtarget.hasStdExtP() && !Subtarget.is64Bit() && VT == MVT::v4i8)
19963 return MakePWMulSU(X, Mulh.getOperand(1));
19964
19965 // We don't have a v8i8 MULHSU instruction on RV64 either; build it from a
19966 // pair of widening byte multiplies recombined with PPAIRO.
19967 if (Subtarget.hasStdExtP() && Subtarget.is64Bit() && VT == MVT::v8i8) {
19968 SDValue C = Mulh.getOperand(1);
19969 SDValue Lo = DAG.getNode(RISCVISD::PMULSU_HALVES_00, DL, MVT::v4i16, X, C);
19970 SDValue Hi = DAG.getNode(RISCVISD::PMULSU_HALVES_11, DL, MVT::v4i16, X, C);
19971 return DAG.getNode(RISCVISD::PPAIRO, DL, VT, DAG.getBitcast(VT, Lo),
19972 DAG.getBitcast(VT, Hi));
19973 }
19974
19975 return DAG.getNode(RISCVISD::MULHSU, DL, VT, X, Mulh.getOperand(1));
19976}
19977
19978// Fold an add of a multiply-parts product into the accumulating form.
19980 const RISCVSubtarget &Subtarget) {
19981 if (!Subtarget.hasStdExtP())
19982 return SDValue();
19983
19984 for (unsigned I = 0; I != 2; ++I) {
19985 SDValue Mul = N->getOperand(I);
19986 if (Mul.getOpcode() != ISD::INTRINSIC_WO_CHAIN || !Mul.hasOneUse())
19987 continue;
19988 Intrinsic::ID AccId =
19989 getRVPMulPartsAccIntrinsic(Mul.getConstantOperandVal(0));
19990 if (AccId == Intrinsic::not_intrinsic)
19991 continue;
19992
19993 SDLoc DL(N);
19994 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
19995 DAG.getTargetConstant(AccId, DL, Subtarget.getXLenVT()),
19996 N->getOperand(1 - I), Mul.getOperand(1),
19997 Mul.getOperand(2));
19998 }
19999 return SDValue();
20000}
20001
20002// Expose the two scalar accumulates instead of a dot-product pair and PADD.DW.
20004 const RISCVSubtarget &Subtarget) {
20005 if (!Subtarget.hasStdExtP() || Subtarget.is64Bit() ||
20006 N->getValueType(0) != MVT::v2i32)
20007 return SDValue();
20008
20009 using namespace SDPatternMatch;
20010 for (unsigned I = 0; I != 2; ++I) {
20011 SDValue Lo, Hi;
20012 if (!sd_match(N->getOperand(I), m_OneUse(m_Node(ISD::BUILD_VECTOR,
20013 m_Value(Lo), m_Value(Hi)))))
20014 continue;
20015 unsigned Opc = Lo.getOpcode();
20016 if (Opc != Hi.getOpcode() ||
20017 (Opc != RISCVISD::PM4ADD && Opc != RISCVISD::PM4ADDU &&
20018 Opc != RISCVISD::PM4ADDSU))
20019 continue;
20020 // Splitting is profitable if at least one dot can fold into its add.
20021 if (!Lo.hasOneUse() && !Hi.hasOneUse())
20022 continue;
20023
20024 SDLoc DL(N);
20025 SDValue Acc = N->getOperand(1 - I);
20026 SDValue AccLo = DAG.getExtractVectorElt(DL, MVT::i32, Acc, 0);
20027 SDValue AccHi = DAG.getExtractVectorElt(DL, MVT::i32, Acc, 1);
20028 SDValue SumLo = DAG.getNode(ISD::ADD, DL, MVT::i32, AccLo, Lo);
20029 SDValue SumHi = DAG.getNode(ISD::ADD, DL, MVT::i32, AccHi, Hi);
20030 return DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, SumLo, SumHi);
20031 }
20032 return SDValue();
20033}
20034
20036 const RISCVSubtarget &Subtarget) {
20037 // Recognize the RV64 decompositions listed for the 32-bit packed widening
20038 // add/sub operations. Mixed signed/unsigned PM2 forms are outside that group.
20039 if (!Subtarget.hasStdExtP() || !Subtarget.is64Bit())
20040 return SDValue();
20041
20042 unsigned Opcode = N->getOpcode();
20043 if (Opcode != ISD::ADD && Opcode != ISD::SUB)
20044 return SDValue();
20045
20046 EVT VT = N->getValueType(0);
20047 if (VT != MVT::v4i16 && VT != MVT::v2i32)
20048 return SDValue();
20049
20050 SDValue N0 = N->getOperand(0);
20051 SDValue N1 = N->getOperand(1);
20052 unsigned ExtendOpcode = N0.getOpcode();
20053 if ((ExtendOpcode != ISD::SIGN_EXTEND && ExtendOpcode != ISD::ZERO_EXTEND) ||
20054 N1.getOpcode() != ExtendOpcode || !N0.hasOneUse() || !N1.hasOneUse())
20055 return SDValue();
20056 bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND;
20057
20058 SDValue A = N0.getOperand(0);
20059 SDValue B = N1.getOperand(0);
20060 MVT SrcVT = VT == MVT::v4i16 ? MVT::v4i8 : MVT::v2i16;
20061 MVT LegalSrcVT = VT == MVT::v4i16 ? MVT::v8i8 : MVT::v4i16;
20062 if (A.getValueType() != SrcVT || B.getValueType() != SrcVT)
20063 return SDValue();
20064
20065 if (VT == MVT::v4i16 && !IsSExt)
20066 return SDValue();
20067
20068 bool IsPM2Halfword = VT == MVT::v2i32 && (IsSExt || Opcode == ISD::ADD);
20069 if (VT == MVT::v2i32 && !IsPM2Halfword)
20070 return SDValue();
20071
20072 SDLoc DL(N);
20073 A = DAG.getNode(ISD::CONCAT_VECTORS, DL, LegalSrcVT, A, DAG.getUNDEF(SrcVT));
20074 B = DAG.getNode(ISD::CONCAT_VECTORS, DL, LegalSrcVT, B, DAG.getUNDEF(SrcVT));
20075
20076 SDValue Zip = DAG.getNode(RISCVISD::PZIP, DL, LegalSrcVT, A, B);
20077 if (VT == MVT::v4i16) {
20078 SDValue ZipAsVT = DAG.getBitcast(VT, Zip);
20079 SDValue Low = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, ZipAsVT,
20080 DAG.getValueType(MVT::v4i8));
20081 SDValue High = DAG.getNode(RISCVISD::PSRA, DL, VT, ZipAsVT,
20082 DAG.getConstant(8, DL, MVT::i64));
20083 return DAG.getNode(Opcode, DL, VT, Low, High);
20084 }
20085
20086 SDValue Ones = DAG.getConstant(1, DL, LegalSrcVT);
20087 if (IsSExt) {
20088 unsigned Opc = Opcode == ISD::ADD ? RISCVISD::PM2ADD_H : RISCVISD::PM2SUB_H;
20089 return DAG.getNode(Opc, DL, VT, Zip, Ones);
20090 }
20091
20092 if (Opcode == ISD::ADD)
20093 return DAG.getNode(RISCVISD::PM2ADDU_H, DL, VT, Zip, Ones);
20094
20095 return SDValue();
20096}
20097
20099 const RISCVSubtarget &Subtarget) {
20100 using namespace SDPatternMatch;
20101
20102 if (!Subtarget.hasStdExtP() || !Subtarget.is64Bit())
20103 return SDValue();
20104
20105 if (N->getOpcode() != ISD::ADD)
20106 return SDValue();
20107
20108 EVT VT = N->getValueType(0);
20109 if (VT != MVT::v4i16 && VT != MVT::v2i32)
20110 return SDValue();
20111
20112 auto MatchExtend = [](SDValue V, unsigned ExtendOpcode, MVT SrcVT,
20113 SDValue &Src) {
20114 return sd_match(
20115 V, m_OneUse(m_Node(ExtendOpcode, m_Value(Src, m_SpecificVT(SrcVT)))));
20116 };
20117
20118 auto Match = [&](SDValue Ext, SDValue Add, SDValue &Acc, SDValue &A,
20119 SDValue &B, bool &IsSExt) {
20120 MVT SrcVT = VT == MVT::v4i16 ? MVT::v4i8 : MVT::v2i16;
20121 unsigned ExtendOpcode = Ext.getOpcode();
20122 if (ExtendOpcode != ISD::SIGN_EXTEND && ExtendOpcode != ISD::ZERO_EXTEND)
20123 return false;
20124
20125 if (!MatchExtend(Ext, ExtendOpcode, SrcVT, B))
20126 return false;
20127
20128 if (!sd_match(Add, m_OneUse(m_Add(m_Value(), m_Value()))))
20129 return false;
20130
20131 if (MatchExtend(Add.getOperand(0), ExtendOpcode, SrcVT, A))
20132 Acc = Add.getOperand(1);
20133 else if (MatchExtend(Add.getOperand(1), ExtendOpcode, SrcVT, A))
20134 Acc = Add.getOperand(0);
20135 else
20136 return false;
20137
20138 if (Acc.getValueType() != VT)
20139 return false;
20140
20141 IsSExt = ExtendOpcode == ISD::SIGN_EXTEND;
20142 return true;
20143 };
20144
20145 SDValue Acc, A, B;
20146 bool IsSExt;
20147 if (!Match(N->getOperand(0), N->getOperand(1), Acc, A, B, IsSExt) &&
20148 !Match(N->getOperand(1), N->getOperand(0), Acc, A, B, IsSExt))
20149 return SDValue();
20150
20151 if (VT == MVT::v4i16 && !IsSExt)
20152 return SDValue();
20153
20154 SDLoc DL(N);
20155 MVT LegalSrcVT = VT == MVT::v4i16 ? MVT::v8i8 : MVT::v4i16;
20156 MVT SrcVT = VT == MVT::v4i16 ? MVT::v4i8 : MVT::v2i16;
20157 A = DAG.getNode(ISD::CONCAT_VECTORS, DL, LegalSrcVT, A, DAG.getUNDEF(SrcVT));
20158 B = DAG.getNode(ISD::CONCAT_VECTORS, DL, LegalSrcVT, B, DAG.getUNDEF(SrcVT));
20159
20160 SDValue Zip = DAG.getNode(RISCVISD::PZIP, DL, LegalSrcVT, A, B);
20161 if (VT == MVT::v4i16) {
20162 SDValue ZipAsVT = DAG.getBitcast(VT, Zip);
20163 SDValue Low = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, ZipAsVT,
20164 DAG.getValueType(MVT::v4i8));
20165 SDValue High = DAG.getNode(RISCVISD::PSRA, DL, VT, ZipAsVT,
20166 DAG.getConstant(8, DL, MVT::i64));
20167 return DAG.getNode(ISD::ADD, DL, VT,
20168 DAG.getNode(ISD::ADD, DL, VT, Acc, Low), High);
20169 }
20170
20171 SDValue Ones = DAG.getConstant(1, DL, LegalSrcVT);
20172 unsigned Opc = IsSExt ? RISCVISD::PM2ADDA_H : RISCVISD::PM2ADDAU_H;
20173 return DAG.getNode(Opc, DL, VT, Acc, Zip, Ones);
20174}
20175
20176// Fold sub(add(Acc, ext A), ext B) to Acc + (A - B), where ext is sext/zext.
20178 const RISCVSubtarget &Subtarget) {
20179 using namespace SDPatternMatch;
20180
20181 if (!Subtarget.hasStdExtP() || !Subtarget.is64Bit())
20182 return SDValue();
20183
20184 if (N->getOpcode() != ISD::SUB)
20185 return SDValue();
20186
20187 EVT VT = N->getValueType(0);
20188 if (VT != MVT::v4i16 && VT != MVT::v2i32)
20189 return SDValue();
20190
20191 MVT SrcVT = VT == MVT::v4i16 ? MVT::v4i8 : MVT::v2i16;
20192 auto Extend = [&](SDValue &Ext, SDValue &Src) {
20193 return m_Value(
20194 Ext, m_OneUse(m_AnyOf(m_SExt(m_Value(Src, m_SpecificVT(SrcVT))),
20195 m_ZExt(m_Value(Src, m_SpecificVT(SrcVT))))));
20196 };
20197
20198 SDValue Acc, ExtA, A, ExtB, B;
20199 if (!sd_match(N, m_Sub(m_OneUse(m_Add(m_Value(Acc), Extend(ExtA, A))),
20200 Extend(ExtB, B))) ||
20201 ExtA.getOpcode() != ExtB.getOpcode())
20202 return SDValue();
20203
20204 SDLoc DL(N);
20205 if (ExtA.getOpcode() == ISD::ZERO_EXTEND) {
20206 // No unsigned PM2 accumulate-subtract; keep the binary widening subtract
20207 // off the accumulator's dependency chain.
20208 return DAG.getNode(ISD::ADD, DL, VT, Acc,
20209 DAG.getNode(ISD::SUB, DL, VT, ExtA, ExtB));
20210 }
20211
20212 MVT LegalSrcVT = VT == MVT::v4i16 ? MVT::v8i8 : MVT::v4i16;
20213 A = DAG.getNode(ISD::CONCAT_VECTORS, DL, LegalSrcVT, A, DAG.getUNDEF(SrcVT));
20214 B = DAG.getNode(ISD::CONCAT_VECTORS, DL, LegalSrcVT, B, DAG.getUNDEF(SrcVT));
20215
20216 SDValue Zip = DAG.getNode(RISCVISD::PZIP, DL, LegalSrcVT, A, B);
20217 if (VT == MVT::v4i16) {
20218 SDValue ZipAsVT = DAG.getBitcast(VT, Zip);
20219 SDValue Low = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, ZipAsVT,
20220 DAG.getValueType(MVT::v4i8));
20221 SDValue High = DAG.getNode(RISCVISD::PSRA, DL, VT, ZipAsVT,
20222 DAG.getConstant(8, DL, MVT::i64));
20223 return DAG.getNode(ISD::ADD, DL, VT, Acc,
20224 DAG.getNode(ISD::SUB, DL, VT, Low, High));
20225 }
20226
20227 SDValue Ones = DAG.getConstant(1, DL, LegalSrcVT);
20228 return DAG.getNode(RISCVISD::PM2SUBA_H, DL, VT, Acc, Zip, Ones);
20229}
20230
20233 const RISCVSubtarget &Subtarget) {
20234 SelectionDAG &DAG = DCI.DAG;
20235 if (SDValue V = combineAddOfBooleanXor(N, DAG))
20236 return V;
20238 return V;
20239 if (!DCI.isBeforeLegalize() && !DCI.isCalledByLegalizer()) {
20240 if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
20241 return V;
20242 if (SDValue V = combineShlAddIAdd(N, DAG, Subtarget))
20243 return V;
20244 }
20246 return V;
20248 return V;
20249 if (SDValue