LLVM 24.0.0git
NVPTXISelLowering.cpp
Go to the documentation of this file.
1//===-- NVPTXISelLowering.cpp - NVPTX 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 NVPTX uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "NVPTXISelLowering.h"
16#include "NVPTX.h"
19#include "NVPTXSubtarget.h"
20#include "NVPTXTargetMachine.h"
22#include "NVPTXUtilities.h"
23#include "NVVMProperties.h"
24#include "llvm/ADT/APFloat.h"
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/StringRef.h"
42#include "llvm/IR/Argument.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/FPEnv.h"
49#include "llvm/IR/Function.h"
50#include "llvm/IR/GlobalValue.h"
51#include "llvm/IR/IRBuilder.h"
52#include "llvm/IR/Instruction.h"
54#include "llvm/IR/IntrinsicsNVPTX.h"
55#include "llvm/IR/Module.h"
57#include "llvm/IR/Type.h"
58#include "llvm/IR/Value.h"
59#include "llvm/MC/MCContext.h"
60#include "llvm/MC/MCSymbol.h"
71#include <algorithm>
72#include <cassert>
73#include <cmath>
74#include <cstdint>
75#include <iterator>
76#include <optional>
77#include <tuple>
78#include <utility>
79#include <vector>
80
81#define DEBUG_TYPE "nvptx-lower"
82
83using namespace llvm;
84
86 "nvptx-sched4reg",
87 cl::desc("NVPTX Specific: schedule for register pressue"), cl::init(false));
88
90 "nvptx-fma-level", cl::Hidden,
91 cl::desc("NVPTX Specific: FMA contraction (0: don't do it"
92 " 1: do it 2: do it aggressively"),
93 cl::init(2));
94
96 "nvptx-prec-divf32", cl::Hidden,
98 "NVPTX Specific: Override the precision of the lowering for f32 fdiv"),
100 clEnumValN(NVPTX::DivPrecisionLevel::Approx, "0", "Use div.approx"),
101 clEnumValN(NVPTX::DivPrecisionLevel::Full, "1", "Use div.full"),
103 "Use IEEE Compliant F32 div.rnd if available (default)"),
105 "Use IEEE Compliant F32 div.rnd if available, no FTZ")),
107
109 "nvptx-prec-sqrtf32", cl::Hidden,
110 cl::desc("NVPTX Specific: 0 use sqrt.approx, 1 use sqrt.rn."),
111 cl::init(true));
112
113// PTX atom.add.f32 has fixed FTZ behavior that may not match the function's
114// (see shouldExpandAtomicRMWInIR), so we'd normally fall back to a CAS loop
115// when they disagree. This option (enabled by default) allows using atom.add
116// anyway, trading correct denormal handling for the speed of the native
117// instruction.
119 "nvptx-allow-ftz-atomics", cl::Hidden,
120 cl::desc("NVPTX Specific: Lower atomicrmw fadd to atom.add even when its "
121 "FTZ behavior does not match the function's denormal mode."),
122 cl::init(true));
123
124/// Whereas CUDA's implementation (see libdevice) uses ex2.approx for exp2(), it
125/// does NOT use lg2.approx for log2, so this is disabled by default.
127 "nvptx-approx-log2f32",
128 cl::desc("NVPTX Specific: whether to use lg2.approx for log2"),
129 cl::init(false));
130
133 const SDNode &N) const {
134 // If nvptx-prec-div32=N is used on the command-line, always honor it
135 if (UsePrecDivF32.getNumOccurrences() > 0)
136 return UsePrecDivF32;
137
138 const SDNodeFlags Flags = N.getFlags();
139 if (Flags.hasApproximateFuncs())
141
143}
144
146 // If nvptx-prec-sqrtf32 is used on the command-line, always honor it
147 if (UsePrecSqrtF32.getNumOccurrences() > 0)
148 return UsePrecSqrtF32;
149
150 if (N) {
151 const SDNodeFlags Flags = N->getFlags();
152 if (Flags.hasApproximateFuncs())
153 return false;
154 }
155
156 return true;
157}
158
163
164static bool IsPTXVectorType(MVT VT) {
165 switch (VT.SimpleTy) {
166 default:
167 return false;
168 case MVT::v2i1:
169 case MVT::v4i1:
170 case MVT::v2i8:
171 case MVT::v4i8:
172 case MVT::v8i8: // <2 x i8x4>
173 case MVT::v16i8: // <4 x i8x4>
174 case MVT::v2i16:
175 case MVT::v4i16:
176 case MVT::v8i16: // <4 x i16x2>
177 case MVT::v2i32:
178 case MVT::v4i32:
179 case MVT::v2i64:
180 case MVT::v2f16:
181 case MVT::v4f16:
182 case MVT::v8f16: // <4 x f16x2>
183 case MVT::v2bf16:
184 case MVT::v4bf16:
185 case MVT::v8bf16: // <4 x bf16x2>
186 case MVT::v2f32:
187 case MVT::v4f32:
188 case MVT::v2f64:
189 case MVT::v4i64:
190 case MVT::v4f64:
191 case MVT::v8i32:
192 case MVT::v8f32:
193 case MVT::v16f16: // <8 x f16x2>
194 case MVT::v16bf16: // <8 x bf16x2>
195 case MVT::v16i16: // <8 x i16x2>
196 case MVT::v32i8: // <8 x i8x4>
197 return true;
198 }
199}
200
201// When legalizing vector loads/stores, this function is called, which does two
202// things:
203// 1. Determines Whether the vector is something we want to custom lower,
204// std::nullopt is returned if we do not want to custom lower it.
205// 2. If we do want to handle it, returns two parameters:
206// - unsigned int NumElts - The number of elements in the final vector
207// - EVT EltVT - The type of the elements in the final vector
208static std::optional<std::pair<unsigned int, MVT>>
210 unsigned AddressSpace) {
211 const bool CanLowerTo256Bit = STI.has256BitVectorLoadStore(AddressSpace);
212
213 if (CanLowerTo256Bit && VectorEVT.isScalarInteger() &&
214 VectorEVT.getSizeInBits() == 256)
215 return {{4, MVT::i64}};
216
217 if (!VectorEVT.isSimple())
218 return std::nullopt;
219 const MVT VectorVT = VectorEVT.getSimpleVT();
220
221 if (!VectorVT.isVector()) {
222 if (VectorVT == MVT::i128 || VectorVT == MVT::f128)
223 return {{2, MVT::i64}};
224 return std::nullopt;
225 }
226
227 const MVT EltVT = VectorVT.getVectorElementType();
228 const unsigned NumElts = VectorVT.getVectorNumElements();
229
230 // The size of the PTX virtual register that holds a packed type.
231 unsigned PackRegSize;
232
233 // We only handle "native" vector sizes for now, e.g. <4 x double> is not
234 // legal. We can (and should) split that into 2 stores of <2 x double> here
235 // but I'm leaving that as a TODO for now.
236 switch (VectorVT.SimpleTy) {
237 default:
238 return std::nullopt;
239
240 case MVT::v4i64:
241 case MVT::v4f64:
242 // This is a "native" vector type iff the address space is global and the
243 // target supports 256-bit loads/stores
244 if (!CanLowerTo256Bit)
245 return std::nullopt;
246 [[fallthrough]];
247 case MVT::v2i8:
248 case MVT::v2i64:
249 case MVT::v2f64:
250 // This is a "native" vector type
251 return std::pair(NumElts, EltVT);
252
253 case MVT::v16f16: // <8 x f16x2>
254 case MVT::v16bf16: // <8 x bf16x2>
255 case MVT::v16i16: // <8 x i16x2>
256 case MVT::v32i8: // <8 x i8x4>
257 // This can be upsized into a "native" vector type iff the address space is
258 // global and the target supports 256-bit loads/stores.
259 if (!CanLowerTo256Bit)
260 return std::nullopt;
261 [[fallthrough]];
262 case MVT::v2i16: // <1 x i16x2>
263 case MVT::v2f16: // <1 x f16x2>
264 case MVT::v2bf16: // <1 x bf16x2>
265 case MVT::v4i8: // <1 x i8x4>
266 case MVT::v4i16: // <2 x i16x2>
267 case MVT::v4f16: // <2 x f16x2>
268 case MVT::v4bf16: // <2 x bf16x2>
269 case MVT::v8i8: // <2 x i8x4>
270 case MVT::v8f16: // <4 x f16x2>
271 case MVT::v8bf16: // <4 x bf16x2>
272 case MVT::v8i16: // <4 x i16x2>
273 case MVT::v16i8: // <4 x i8x4>
274 PackRegSize = 32;
275 break;
276
277 case MVT::v8f32: // <4 x f32x2>
278 case MVT::v8i32: // <4 x i32x2>
279 // This is a "native" vector type iff the address space is global and the
280 // target supports 256-bit loads/stores
281 if (!CanLowerTo256Bit)
282 return std::nullopt;
283 [[fallthrough]];
284 case MVT::v2f32: // <1 x f32x2>
285 case MVT::v4f32: // <2 x f32x2>
286 case MVT::v2i32: // <1 x i32x2>
287 case MVT::v4i32: // <2 x i32x2>
288 if (!STI.hasF32x2Instructions())
289 return std::pair(NumElts, EltVT);
290 PackRegSize = 64;
291 break;
292 }
293
294 // If we reach here, then we can pack 2 or more elements into a single 32-bit
295 // or 64-bit PTX register and treat the vector as a new vector containing
296 // packed elements.
297
298 // Number of elements to pack in one word.
299 const unsigned NPerReg = PackRegSize / EltVT.getSizeInBits();
300
301 return std::pair(NumElts / NPerReg, MVT::getVectorVT(EltVT, NPerReg));
302}
303
304/// ComputePTXValueVTs - For the given Type \p Ty, returns the set of primitive
305/// legal-ish MVTs that compose it. Unlike ComputeValueVTs, this will legalize
306/// the types as required by the calling convention (with special handling for
307/// i8s).
308/// NOTE: This is a band-aid for code that expects ComputeValueVTs to return the
309/// same number of types as the Ins/Outs arrays in LowerFormalArguments,
310/// LowerCall, and LowerReturn.
311static void ComputePTXValueVTs(const TargetLowering &TLI, const DataLayout &DL,
312 LLVMContext &Ctx, CallingConv::ID CallConv,
313 Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
315 uint64_t StartingOffset = 0) {
316 SmallVector<EVT, 16> TempVTs;
317 SmallVector<uint64_t, 16> TempOffsets;
318 ComputeValueVTs(TLI, DL, Ty, TempVTs, /*MemVTs=*/nullptr, &TempOffsets,
319 StartingOffset);
320
321 for (const auto [VT, Off] : zip(TempVTs, TempOffsets)) {
322 MVT RegisterVT = TLI.getRegisterTypeForCallingConv(Ctx, CallConv, VT);
323 unsigned NumRegs = TLI.getNumRegistersForCallingConv(Ctx, CallConv, VT);
324
325 // Since we actually can load/store b8, we need to ensure that we'll use
326 // the original sized type for any i8s or i8 vectors.
327 if (VT.getScalarType() == MVT::i8) {
328 if (RegisterVT == MVT::i16)
329 RegisterVT = MVT::i8;
330 else if (RegisterVT == MVT::v2i16)
331 RegisterVT = MVT::v2i8;
332 else
333 assert(RegisterVT == MVT::v4i8 &&
334 "Expected v4i8, v2i16, or i16 for i8 RegisterVT");
335 }
336
337 // TODO: This is horribly incorrect for cases where the vector elements are
338 // not a multiple of bytes (ex i1) and legal or i8. However, this problem
339 // has existed for as long as NVPTX has and no one has complained, so we'll
340 // leave it for now.
341 for (unsigned I : seq(NumRegs)) {
342 ValueVTs.push_back(RegisterVT);
343 Offsets.push_back(Off + I * RegisterVT.getStoreSize());
344 }
345 }
346}
347
348// We return an EVT that can hold N VTs
349// If the VT is a vector, the resulting EVT is a flat vector with the same
350// element type as VT's element type.
351static EVT getVectorizedVT(EVT VT, unsigned N, LLVMContext &C) {
352 if (N == 1)
353 return VT;
354
355 return VT.isVector() ? EVT::getVectorVT(C, VT.getScalarType(),
356 VT.getVectorNumElements() * N)
357 : EVT::getVectorVT(C, VT, N);
358}
359
361 const SDLoc &dl, SelectionDAG &DAG) {
362 if (V.getValueType() == VT) {
363 assert(I == 0 && "Index must be 0 for scalar value");
364 return V;
365 }
366
367 if (!VT.isVector())
368 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, V,
369 DAG.getVectorIdxConstant(I, dl));
370
371 return DAG.getNode(
372 ISD::EXTRACT_SUBVECTOR, dl, VT, V,
374}
375
376template <typename T>
377static inline SDValue getBuildVectorizedValue(unsigned N, const SDLoc &dl,
378 SelectionDAG &DAG, T GetElement) {
379 if (N == 1)
380 return GetElement(0);
381
383 for (const unsigned I : llvm::seq(N)) {
384 SDValue Val = GetElement(I);
385 if (Val.getValueType().isVector())
387 else
388 Values.push_back(Val);
389 }
390
391 EVT VT = EVT::getVectorVT(*DAG.getContext(), Values[0].getValueType(),
392 Values.size());
393 return DAG.getBuildVector(VT, dl, Values);
394}
395
396/// PromoteScalarIntegerPTX
397/// Used to make sure the arguments/returns are suitable for passing
398/// and promote them to a larger size if they're not.
399///
400/// The promoted type is placed in \p PromoteVT if the function returns true.
402 if (VT.isScalarInteger()) {
403 switch (PowerOf2Ceil(VT.getFixedSizeInBits())) {
404 default:
406 "Promotion is not suitable for scalars of size larger than 64-bits");
407 case 1:
408 return MVT::i1;
409 case 2:
410 case 4:
411 case 8:
412 return MVT::i8;
413 case 16:
414 return MVT::i16;
415 case 32:
416 return MVT::i32;
417 case 64:
418 return MVT::i64;
419 }
420 }
421 return VT;
422}
423
424// Check whether we can merge loads/stores of some of the pieces of a
425// flattened function parameter or return value into a single vector
426// load/store.
427//
428// The flattened parameter is represented as a list of EVTs and
429// offsets, and the whole structure is aligned to ParamAlignment. This
430// function determines whether we can load/store pieces of the
431// parameter starting at index Idx using a single vectorized op of
432// size AccessSize. If so, it returns the number of param pieces
433// covered by the vector op. Otherwise, it returns 1.
434template <typename T>
436 unsigned Idx, uint32_t AccessSize, const SmallVectorImpl<EVT> &ValueVTs,
437 const SmallVectorImpl<T> &Offsets, Align ParamAlignment) {
438
439 // Can't vectorize if param alignment is not sufficient.
440 if (ParamAlignment < AccessSize)
441 return 1;
442 // Can't vectorize if offset is not aligned.
443 if (Offsets[Idx] & (AccessSize - 1))
444 return 1;
445
446 EVT EltVT = ValueVTs[Idx];
447 unsigned EltSize = EltVT.getStoreSize();
448
449 // Element is too large to vectorize.
450 if (EltSize >= AccessSize)
451 return 1;
452
453 unsigned NumElts = AccessSize / EltSize;
454 // Can't vectorize if AccessBytes if not a multiple of EltSize.
455 if (AccessSize != EltSize * NumElts)
456 return 1;
457
458 // We don't have enough elements to vectorize.
459 if (Idx + NumElts > ValueVTs.size())
460 return 1;
461
462 // PTX ISA can only deal with 2- and 4-element vector ops.
463 if (NumElts != 4 && NumElts != 2)
464 return 1;
465
466 for (unsigned j = Idx + 1; j < Idx + NumElts; ++j) {
467 // Types do not match.
468 if (ValueVTs[j] != EltVT)
469 return 1;
470
471 // Elements are not contiguous.
472 if (Offsets[j] - Offsets[j - 1] != EltSize)
473 return 1;
474 }
475 // OK. We can vectorize ValueVTs[i..i+NumElts)
476 return NumElts;
477}
478
479// Computes whether and how we can vectorize the loads/stores of a
480// flattened function parameter or return value.
481//
482// The flattened parameter is represented as the list of ValueVTs and
483// Offsets, and is aligned to ParamAlignment bytes. We return a vector
484// of the same size as ValueVTs indicating how each piece should be
485// loaded/stored (i.e. as a scalar, or as part of a vector
486// load/store).
487template <typename T>
490 const SmallVectorImpl<T> &Offsets, Align ParamAlignment,
491 bool IsVAArg = false) {
492 // Set vector size to match ValueVTs and mark all elements as
493 // scalars by default.
494
495 if (IsVAArg)
496 return SmallVector<unsigned>(ValueVTs.size(), 1);
497
498 SmallVector<unsigned, 16> VectorInfo;
499
500 const auto GetNumElts = [&](unsigned I) -> unsigned {
501 for (const unsigned AccessSize : {16, 8, 4, 2}) {
502 const unsigned NumElts = canMergeParamLoadStoresStartingAt(
503 I, AccessSize, ValueVTs, Offsets, ParamAlignment);
504 assert((NumElts == 1 || NumElts == 2 || NumElts == 4) &&
505 "Unexpected vectorization size");
506 if (NumElts != 1)
507 return NumElts;
508 }
509 return 1;
510 };
511
512 // Check what we can vectorize using 128/64/32-bit accesses.
513 for (unsigned I = 0, E = ValueVTs.size(); I != E;) {
514 const unsigned NumElts = GetNumElts(I);
515 VectorInfo.push_back(NumElts);
516 I += NumElts;
517 }
518 assert(std::accumulate(VectorInfo.begin(), VectorInfo.end(), 0u) ==
519 ValueVTs.size());
520 return VectorInfo;
521}
522
523// NVPTXTargetLowering Constructor.
525 const NVPTXSubtarget &STI)
526 : TargetLowering(TM, STI), STI(STI), GlobalUniqueCallSite(0) {
527 // always lower memset, memcpy, and memmove intrinsics to load/store
528 // instructions, rather
529 // then generating calls to memset, mempcy or memmove.
533
536
537 // Jump is Expensive. Don't create extra control flow for 'and', 'or'
538 // condition branches.
539 setJumpIsExpensive(true);
540
541 // Wide divides are _very_ slow. Try to reduce the width of the divide if
542 // possible.
543 addBypassSlowDiv(64, 32);
544
545 // By default, use the Source scheduling
546 if (sched4reg)
548 else
550
551 auto setFP16OperationAction = [&](unsigned Op, MVT VT, LegalizeAction Action,
552 LegalizeAction NoF16Action) {
553 bool IsOpSupported = STI.allowFP16Math();
554 switch (Op) {
555 // Several FP16 instructions are available on sm_80 only.
556 case ISD::FMINNUM:
557 case ISD::FMAXNUM:
560 case ISD::FMAXIMUM:
561 case ISD::FMINIMUM:
562 case ISD::FMAXIMUMNUM:
563 case ISD::FMINIMUMNUM:
564 IsOpSupported &= STI.hasFeature(NVPTX::SM80);
565 break;
566 case ISD::FEXP2:
567 case ISD::FTANH:
568 IsOpSupported &=
569 STI.hasFeature(NVPTX::SM75) && STI.hasFeature(NVPTX::PTX70);
570 break;
571 }
572 setOperationAction(Op, VT, IsOpSupported ? Action : NoF16Action);
573 };
574
575 auto setBF16OperationAction = [&](unsigned Op, MVT VT, LegalizeAction Action,
576 LegalizeAction NoBF16Action) {
577 bool IsOpSupported = STI.hasNativeBF16Support(Op);
579 Op, VT, IsOpSupported ? Action : NoBF16Action);
580 };
581
582 auto setI16x2OperationAction = [&](unsigned Op, MVT VT, LegalizeAction Action,
583 LegalizeAction NoI16x2Action) {
584 bool IsOpSupported = false;
585 // instructions are available on sm_90 only
586 switch (Op) {
587 case ISD::ADD:
588 case ISD::SMAX:
589 case ISD::SMIN:
590 case ISD::UMIN:
591 case ISD::UMAX:
592 IsOpSupported =
593 STI.hasFeature(NVPTX::SM90) && STI.hasFeature(NVPTX::PTX80);
594 break;
595 }
596 setOperationAction(Op, VT, IsOpSupported ? Action : NoI16x2Action);
597 };
598
599 addRegisterClass(MVT::i1, &NVPTX::B1RegClass);
600 addRegisterClass(MVT::i16, &NVPTX::B16RegClass);
601 addRegisterClass(MVT::v2i16, &NVPTX::B32RegClass);
602 addRegisterClass(MVT::v4i8, &NVPTX::B32RegClass);
603 addRegisterClass(MVT::i32, &NVPTX::B32RegClass);
604 addRegisterClass(MVT::i64, &NVPTX::B64RegClass);
605 addRegisterClass(MVT::f32, &NVPTX::B32RegClass);
606 addRegisterClass(MVT::f64, &NVPTX::B64RegClass);
607 addRegisterClass(MVT::f16, &NVPTX::B16RegClass);
608 addRegisterClass(MVT::v2f16, &NVPTX::B32RegClass);
609 addRegisterClass(MVT::bf16, &NVPTX::B16RegClass);
610 addRegisterClass(MVT::v2bf16, &NVPTX::B32RegClass);
611
612 if (STI.hasF32x2Instructions()) {
613 addRegisterClass(MVT::v2f32, &NVPTX::B64RegClass);
614 addRegisterClass(MVT::v2i32, &NVPTX::B64RegClass);
615 }
616
617 // Conversion to/from FP16/FP16x2 is always legal.
622
624 if (STI.hasFeature(NVPTX::SM30))
626
627 setFP16OperationAction(ISD::SETCC, MVT::f16, Legal, Promote);
628 setFP16OperationAction(ISD::SETCC, MVT::v2f16, Legal, Expand);
629
630 // Conversion to/from BFP16/BFP16x2 is always legal.
635
636 setBF16OperationAction(ISD::SETCC, MVT::v2bf16, Legal, Expand);
637 setBF16OperationAction(ISD::SETCC, MVT::bf16, Legal, Promote);
638 if (getOperationAction(ISD::SETCC, MVT::bf16) == Promote)
639 AddPromotedToType(ISD::SETCC, MVT::bf16, MVT::f32);
640
641 // Conversion to/from i16/i16x2 is always legal.
646
651
652 // No support for these operations with v2f32/v2i32
653 setOperationAction(ISD::INSERT_VECTOR_ELT, {MVT::v2f32, MVT::v2i32}, Expand);
654 setOperationAction(ISD::VECTOR_SHUFFLE, {MVT::v2f32, MVT::v2i32}, Expand);
655
658 MVT::v2i32, Expand);
659
660 // Need custom lowering in case the index is dynamic.
661 if (STI.hasF32x2Instructions())
662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, {MVT::v2f32, MVT::v2i32},
663 Custom);
664
665 // Custom conversions to/from v2i8.
667
668 // Only logical ops can be done on v4i8/v2i32 directly, others must be done
669 // elementwise.
686 {MVT::v4i8, MVT::v2i32}, Expand);
687
688 // Operations not directly supported by NVPTX.
689 for (MVT VT : {MVT::bf16, MVT::f16, MVT::v2bf16, MVT::v2f16, MVT::f32,
690 MVT::v2f32, MVT::f64, MVT::i1, MVT::i8, MVT::i16, MVT::v2i16,
691 MVT::v4i8, MVT::i32, MVT::v2i32, MVT::i64}) {
694 }
695
696 // We don't want ops like FMINIMUM or UMAX to be lowered to SETCC+VSELECT.
697 setOperationAction(ISD::VSELECT, {MVT::v2f32, MVT::v2i32}, Expand);
698
699 // Some SIGN_EXTEND_INREG can be done using cvt instruction.
700 // For others we will expand to a SHL/SRA pair.
706 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::v2i16, MVT::v2i32}, Expand);
707
714
717
719 {MVT::i8, MVT::i16, MVT::v2i16, MVT::i32, MVT::i64},
720 Expand);
721
722 if (STI.hasHWROT32()) {
725 Custom);
726 }
727
728 setOperationAction(ISD::BR_JT, MVT::Other, STI.hasBrx() ? Legal : Expand);
730
731 // We want to legalize constant related memmove and memcopy
732 // intrinsics.
734
735 // FP extload/truncstore is not legal in PTX. We need to expand all these.
736 for (auto FloatVTs :
738 for (MVT ValVT : FloatVTs) {
739 for (MVT MemVT : FloatVTs) {
740 setLoadExtAction(ISD::EXTLOAD, ValVT, MemVT, Expand);
741 setTruncStoreAction(ValVT, MemVT, Expand);
742 }
743 }
744 }
745
746 // To improve CodeGen we'll legalize any-extend loads to zext loads. This is
747 // how they'll be lowered in ISel anyway, and by doing this a little earlier
748 // we allow for more DAG combine opportunities.
749 for (auto IntVTs :
751 for (MVT ValVT : IntVTs)
752 for (MVT MemVT : IntVTs)
753 if (isTypeLegal(ValVT))
754 setLoadExtAction(ISD::EXTLOAD, ValVT, MemVT, Custom);
755
756 // PTX does not support load / store predicate registers
758 for (MVT VT : MVT::integer_valuetypes()) {
760 Promote);
761 setTruncStoreAction(VT, MVT::i1, Expand);
762 }
763
764 // Disable generations of extload/truncstore for v2i32/v2i16/v2i8. The generic
765 // expansion for these nodes when they are unaligned is incorrect if the
766 // type is a vector.
767 //
768 // TODO: Fix the generic expansion for these nodes found in
769 // TargetLowering::expandUnalignedLoad/Store.
771 MVT::v2i8, Expand);
773 {MVT::v2i8, MVT::v2i16}, Expand);
774 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
775 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
776 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
777
778 // Register custom handling for illegal type loads/stores. We'll try to custom
779 // lower almost all illegal types and logic in the lowering will discard cases
780 // we can't handle.
781 setOperationAction({ISD::LOAD, ISD::STORE}, {MVT::i128, MVT::i256, MVT::f128},
782 Custom);
784 if (!isTypeLegal(VT) && VT.getStoreSizeInBits() <= 256)
786 Custom);
787
788 // Custom legalization for LDU intrinsics.
789 // TODO: The logic to lower these is not very robust and we should rewrite it.
790 // Perhaps LDU should not be represented as an intrinsic at all.
793 if (IsPTXVectorType(VT))
795
799 MVT::i1, Expand);
800
801 // This is legal in NVPTX
806
807 setOperationAction(ISD::DYNAMIC_STACKALLOC, {MVT::i32, MVT::i64}, Custom);
809
810 // TRAP can be lowered to PTX trap
811 setOperationAction(ISD::TRAP, MVT::Other, Legal);
812 // DEBUGTRAP can be lowered to PTX brkpt
814
815 // Support varargs.
820
822 {MVT::i16, MVT::i32, MVT::i64}, Legal);
823 // PTX abs.s is undefined for INT_MIN, so ISD::ABS (which requires
824 // abs(INT_MIN) == INT_MIN) must be expanded. ABS_MIN_POISON matches
825 // PTX abs semantics since INT_MIN input is poison/undefined.
826 setOperationAction(ISD::ABS, {MVT::i16, MVT::i32, MVT::i64}, Expand);
827 setOperationAction(ISD::ABS_MIN_POISON, {MVT::i16, MVT::i32, MVT::i64},
828 Legal);
829
831 Promote);
834
835 setI16x2OperationAction(ISD::ABS_MIN_POISON, MVT::v2i16, Legal, Custom);
836 setI16x2OperationAction(ISD::SMIN, MVT::v2i16, Legal, Custom);
837 setI16x2OperationAction(ISD::SMAX, MVT::v2i16, Legal, Custom);
838 setI16x2OperationAction(ISD::UMIN, MVT::v2i16, Legal, Custom);
839 setI16x2OperationAction(ISD::UMAX, MVT::v2i16, Legal, Custom);
840 setI16x2OperationAction(ISD::CTPOP, MVT::v2i16, Legal, Expand);
841 setI16x2OperationAction(ISD::CTLZ, MVT::v2i16, Legal, Expand);
842
843 setI16x2OperationAction(ISD::ADD, MVT::v2i16, Legal, Custom);
844 setI16x2OperationAction(ISD::SUB, MVT::v2i16, Legal, Custom);
845 setI16x2OperationAction(ISD::MUL, MVT::v2i16, Legal, Custom);
846 setI16x2OperationAction(ISD::SHL, MVT::v2i16, Legal, Custom);
847 setI16x2OperationAction(ISD::SREM, MVT::v2i16, Legal, Custom);
848 setI16x2OperationAction(ISD::UREM, MVT::v2i16, Legal, Custom);
849
850 // Other arithmetic and logic ops are unsupported.
854 {MVT::v2i16, MVT::v2i32}, Expand);
855
856 // v2i32 is not supported for any arithmetic operations
861 MVT::v2i32, Expand);
862
867 if (STI.hasFeature(NVPTX::PTX43)) {
872 }
873
875 setOperationAction(ISD::CTTZ, {MVT::v2i16, MVT::v2i32}, Expand);
878
879 // PTX does not directly support SELP of i1, so promote to i32 first
881
882 // PTX cannot multiply two i64s in a single instruction.
885
886 // We have some custom DAG combine patterns for these nodes
888 ISD::AND,
890 ISD::FADD,
897 ISD::MUL,
899 ISD::SHL,
900 ISD::SREM,
901 ISD::UREM,
905 ISD::LOAD,
910
911 // If the vector operands require register coalescing, scalarize instead
912 if (STI.hasF32x2Instructions())
914
915 // setcc for f16x2 and bf16x2 needs special handling to prevent
916 // legalizer's attempt to scalarize it due to v2i1 not being legal.
917 if (STI.allowFP16Math() || STI.hasBF16Math())
919
920 // Vector reduction operations. These may be turned into shuffle or tree
921 // reductions depending on what instructions are available for each type.
923 MVT EltVT = VT.getVectorElementType();
924 if (EltVT == MVT::f32 || EltVT == MVT::f64) {
927 VT, Custom);
928 }
929 }
930
931 // Promote fp16 arithmetic if fp16 hardware isn't available or the
932 // user passed --nvptx-no-fp16-math. The flag is useful because,
933 // although sm_53+ GPUs have some sort of FP16 support in
934 // hardware, only sm_53 and sm_60 have full implementation. Others
935 // only have token amount of hardware and are likely to run faster
936 // by using fp32 units instead.
937 for (const auto &Op : {ISD::FADD, ISD::FMUL, ISD::FSUB, ISD::FMA}) {
938 setFP16OperationAction(Op, MVT::f16, Legal, Promote);
939 setFP16OperationAction(Op, MVT::v2f16, Legal, Expand);
940 setBF16OperationAction(Op, MVT::v2bf16, Legal, Expand);
941 // bf16 must be promoted to f32.
942 setBF16OperationAction(Op, MVT::bf16, Legal, Promote);
943 if (getOperationAction(Op, MVT::bf16) == Promote)
944 AddPromotedToType(Op, MVT::bf16, MVT::f32);
945 setOperationAction(Op, MVT::v2f32,
946 STI.hasF32x2Instructions() ? Legal : Expand);
947 }
948
949 // On SM80, we select add/mul/sub as fma to avoid promotion to float
950 for (const auto &Op : {ISD::FADD, ISD::FMUL, ISD::FSUB}) {
951 for (const auto &VT : {MVT::bf16, MVT::v2bf16}) {
952 if (!STI.hasNativeBF16Support(Op) && STI.hasNativeBF16Support(ISD::FMA)) {
954 }
955 }
956 }
957
958 // f16/f16x2 neg was introduced in PTX 60, SM_53.
959 const bool IsFP16FP16x2NegAvailable = STI.hasFeature(NVPTX::SM53) &&
960 STI.hasFeature(NVPTX::PTX60) &&
961 STI.allowFP16Math();
962 for (const auto &VT : {MVT::f16, MVT::v2f16})
964 IsFP16FP16x2NegAvailable ? Legal : Expand);
965
966 setBF16OperationAction(ISD::FNEG, MVT::bf16, Legal, Expand);
967 setBF16OperationAction(ISD::FNEG, MVT::v2bf16, Legal, Expand);
968 setOperationAction(ISD::FNEG, MVT::v2f32, Expand);
969 // (would be) Library functions.
970
971 // These map to conversion instructions for scalar FP types.
972 for (const auto &Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, ISD::FRINT,
974 setOperationAction(Op, MVT::f16, Legal);
975 setOperationAction(Op, MVT::f32, Legal);
976 setOperationAction(Op, MVT::f64, Legal);
977 setOperationAction(Op, MVT::v2f16, Expand);
978 setOperationAction(Op, MVT::v2bf16, Expand);
979 setOperationAction(Op, MVT::v2f32, Expand);
980 setBF16OperationAction(Op, MVT::bf16, Legal, Promote);
981 if (getOperationAction(Op, MVT::bf16) == Promote)
982 AddPromotedToType(Op, MVT::bf16, MVT::f32);
983 }
984
985 if (!STI.hasFeature(NVPTX::SM80) || !STI.hasFeature(NVPTX::PTX71)) {
987 }
988 if (!STI.hasFeature(NVPTX::SM90)) {
989 for (MVT VT : {MVT::bf16, MVT::f32, MVT::f64}) {
992 }
993 }
994
995 // Expand v2f32 = fp_extend
997 // Expand v2[b]f16 = fp_round v2f32
998 setOperationAction(ISD::FP_ROUND, {MVT::v2bf16, MVT::v2f16}, Expand);
999
1000 // sm_80 only has conversions between f32 and bf16. Custom lower all other
1001 // bf16 conversions.
1002 if (!STI.hasFeature(NVPTX::SM90)) {
1003 for (MVT VT : {MVT::i1, MVT::i16, MVT::i32, MVT::i64}) {
1006 VT, Custom);
1007 }
1010 MVT::bf16, Custom);
1011 }
1012
1016 setOperationAction(ISD::FROUND, MVT::v2bf16, Expand);
1020 AddPromotedToType(ISD::FROUND, MVT::bf16, MVT::f32);
1021
1022 setOperationAction({ISD::LROUND, ISD::LLROUND}, {MVT::f32, MVT::f64}, Expand);
1023
1024 // 'Expand' implements FCOPYSIGN without calling an external library.
1031
1032 // These map to corresponding instructions for f32/f64. f16 must be
1033 // promoted to f32. v2f16 is expanded to f16, which is then promoted
1034 // to f32.
1035 for (const auto &Op :
1037 setOperationAction(Op, MVT::f16, Promote);
1038 setOperationAction(Op, MVT::f32, Legal);
1039 // only div/rem/sqrt are legal for f64
1040 if (Op == ISD::FDIV || Op == ISD::FREM || Op == ISD::FSQRT) {
1041 setOperationAction(Op, MVT::f64, Legal);
1042 }
1043 setOperationAction(Op, {MVT::v2f16, MVT::v2bf16, MVT::v2f32}, Expand);
1044 setOperationAction(Op, MVT::bf16, Promote);
1045 AddPromotedToType(Op, MVT::bf16, MVT::f32);
1046 }
1047 setOperationAction(ISD::FREM, {MVT::f32, MVT::f64}, Custom);
1048
1049 // FTANH support:
1050 // - f32 (sm_75+, PTX 7.0+)
1051 // - f16/f16x2 (sm_75+, PTX 7.0+)
1052 // - bf16/bf16x2 (sm_90+, PTX 7.8+)
1053 // When f16/bf16 types aren't supported, they are promoted/expanded to f32.
1054 if (STI.hasFeature(NVPTX::SM75) && STI.hasFeature(NVPTX::PTX70))
1056 setOperationAction(ISD::FTANH, MVT::v2f32, Expand);
1057
1058 // Scalar f16/bf16: promote to f32 when not natively supported.
1059 setFP16OperationAction(ISD::FTANH, MVT::f16, Legal, Promote);
1060 setBF16OperationAction(ISD::FTANH, MVT::bf16, Legal, Promote);
1061 if (getOperationAction(ISD::FTANH, MVT::bf16) == Promote)
1062 AddPromotedToType(ISD::FTANH, MVT::bf16, MVT::f32);
1063
1064 // Vector v2f16/v2bf16: expand when not natively supported.
1065 setFP16OperationAction(ISD::FTANH, MVT::v2f16, Legal, Expand);
1066 setBF16OperationAction(ISD::FTANH, MVT::v2bf16, Legal, Expand);
1067
1068 setOperationAction(ISD::FABS, {MVT::f32, MVT::f64}, Legal);
1069 setOperationAction(ISD::FABS, MVT::v2f32, Expand);
1070 if (STI.hasFeature(NVPTX::PTX65)) {
1071 setFP16OperationAction(ISD::FABS, MVT::f16, Legal, Promote);
1072 setFP16OperationAction(ISD::FABS, MVT::v2f16, Legal, Expand);
1073 } else {
1075 setOperationAction(ISD::FABS, MVT::v2f16, Expand);
1076 }
1077 setBF16OperationAction(ISD::FABS, MVT::v2bf16, Legal, Expand);
1078 setBF16OperationAction(ISD::FABS, MVT::bf16, Legal, Promote);
1079 if (getOperationAction(ISD::FABS, MVT::bf16) == Promote)
1080 AddPromotedToType(ISD::FABS, MVT::bf16, MVT::f32);
1081
1082 for (const auto &Op :
1084 setOperationAction(Op, MVT::f32, Legal);
1085 setOperationAction(Op, MVT::f64, Legal);
1086 setFP16OperationAction(Op, MVT::f16, Legal, Promote);
1087 setFP16OperationAction(Op, MVT::v2f16, Legal, Expand);
1088 setBF16OperationAction(Op, MVT::v2bf16, Legal, Expand);
1089 setBF16OperationAction(Op, MVT::bf16, Legal, Promote);
1090 if (getOperationAction(Op, MVT::bf16) == Promote)
1091 AddPromotedToType(Op, MVT::bf16, MVT::f32);
1092 setOperationAction(Op, MVT::v2f32, Expand);
1093 }
1094 bool SupportsF32MinMaxNaN = STI.hasFeature(NVPTX::SM80);
1095 for (const auto &Op : {ISD::FMINIMUM, ISD::FMAXIMUM}) {
1096 setOperationAction(Op, MVT::f32, SupportsF32MinMaxNaN ? Legal : Expand);
1097 setFP16OperationAction(Op, MVT::f16, Legal, Expand);
1098 setFP16OperationAction(Op, MVT::v2f16, Legal, Expand);
1099 setBF16OperationAction(Op, MVT::bf16, Legal, Expand);
1100 setBF16OperationAction(Op, MVT::v2bf16, Legal, Expand);
1101 setOperationAction(Op, MVT::v2f32, Expand);
1102 }
1103
1104 // Custom lowering for inline asm with 128-bit operands
1107
1108 // FEXP2 support:
1109 // - f32
1110 // - f16/f16x2 (sm_70+, PTX 7.0+)
1111 // - bf16/bf16x2 (sm_90+, PTX 7.8+)
1112 // When f16/bf16 types aren't supported, they are promoted/expanded to f32.
1114 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
1115 setFP16OperationAction(ISD::FEXP2, MVT::f16, Legal, Promote);
1116 setFP16OperationAction(ISD::FEXP2, MVT::v2f16, Legal, Expand);
1117 setBF16OperationAction(ISD::FEXP2, MVT::bf16, Legal, Promote);
1118 setBF16OperationAction(ISD::FEXP2, MVT::v2bf16, Legal, Expand);
1119
1120 // FLOG2 supports f32 only
1121 // f16/bf16 types aren't supported, but they are promoted/expanded to f32.
1122 if (UseApproxLog2F32) {
1124 setOperationPromotedToType(ISD::FLOG2, MVT::f16, MVT::f32);
1125 setOperationPromotedToType(ISD::FLOG2, MVT::bf16, MVT::f32);
1126 setOperationAction(ISD::FLOG2, {MVT::v2f16, MVT::v2bf16, MVT::v2f32},
1127 Expand);
1128 }
1129
1130 setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
1131
1132 setOperationAction(ISD::ATOMIC_LOAD_SUB, {MVT::i32, MVT::i64}, Expand);
1133
1134 // atom.b128 is legal in PTX but since we don't represent i128 as a legal
1135 // type, we need to custom lower it.
1137 Custom);
1138
1139 // Now deduce the information based on the above mentioned
1140 // actions
1141 computeRegisterProperties(STI.getRegisterInfo());
1142
1143 // PTX support for 16-bit CAS is emulated. Only use 32+
1144 setMinCmpXchgSizeInBits(STI.getMinCmpXchgSizeInBits());
1145 setMaxAtomicSizeInBitsSupported(STI.hasAtomSwap128() ? 128 : 64);
1148
1149 // Custom lowering for tcgen05.ld vector operands
1151 {MVT::v1i32, MVT::v2i32, MVT::v4i32, MVT::v8i32,
1152 MVT::v16i32, MVT::v32i32, MVT::v64i32, MVT::v128i32,
1153 MVT::v2f32, MVT::v4f32, MVT::v8f32, MVT::v16f32,
1154 MVT::v32f32, MVT::v64f32, MVT::v128f32},
1155 Custom);
1156
1157 // Custom lowering for tcgen05.st vector operands and the st.async
1158 // i128 (.b128) operand. MVT::i8 is needed for the st.async.{sys,gpu} b8
1159 // variant.
1161 {MVT::i8, MVT::v1i32, MVT::v2i32, MVT::v4i32, MVT::v8i32,
1162 MVT::v16i32, MVT::v32i32, MVT::v64i32, MVT::v128i32,
1163 MVT::i128, MVT::Other},
1164 Custom);
1165
1166 // Enable custom lowering for the following:
1167 // * MVT::i128 - clusterlaunchcontrol
1168 // * MVT::i32 - prmt
1169 // * MVT::v4f32 - cvt_rs fp{4/6/8}x4 intrinsics
1170 // * MVT::Other - internal.addrspace.wrap
1172 {MVT::i32, MVT::i128, MVT::v4f32, MVT::Other}, Custom);
1173
1174 // Custom lowering for bswap
1175 setOperationAction(ISD::BSWAP, {MVT::i16, MVT::i32, MVT::i64, MVT::v2i16},
1176 Custom);
1177}
1178
1181 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1182 VT.getScalarType() == MVT::i1)
1183 return TypeSplitVector;
1185}
1186
1188 int Enabled, int &ExtraSteps,
1189 bool &UseOneConst,
1190 bool Reciprocal) const {
1193 return SDValue();
1194
1195 if (ExtraSteps == ReciprocalEstimate::Unspecified)
1196 ExtraSteps = 0;
1197
1198 SDLoc DL(Operand);
1199 EVT VT = Operand.getValueType();
1200 bool Ftz = useF32FTZ(DAG.getMachineFunction());
1201
1202 auto MakeIntrinsicCall = [&](Intrinsic::ID IID) {
1203 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
1204 DAG.getConstant(IID, DL, MVT::i32), Operand);
1205 };
1206
1207 // The sqrt and rsqrt refinement processes assume we always start out with an
1208 // approximation of the rsqrt. Therefore, if we're going to do any refinement
1209 // (i.e. ExtraSteps > 0), we must return an rsqrt. But if we're *not* doing
1210 // any refinement, we must return a regular sqrt.
1211 if (Reciprocal || ExtraSteps > 0) {
1212 if (VT == MVT::f32)
1213 return MakeIntrinsicCall(Ftz ? Intrinsic::nvvm_rsqrt_approx_ftz_f
1214 : Intrinsic::nvvm_rsqrt_approx_f);
1215 else if (VT == MVT::f64)
1216 return MakeIntrinsicCall(Intrinsic::nvvm_rsqrt_approx_d);
1217 else
1218 return SDValue();
1219 } else {
1220 if (VT == MVT::f32)
1221 return MakeIntrinsicCall(Ftz ? Intrinsic::nvvm_sqrt_approx_ftz_f
1222 : Intrinsic::nvvm_sqrt_approx_f);
1223 else {
1224 // There's no sqrt.approx.f64 instruction, so we emit
1225 // reciprocal(rsqrt(x)). This is faster than
1226 // select(x == 0, 0, x * rsqrt(x)). (In fact, it's faster than plain
1227 // x * rsqrt(x).)
1228 return DAG.getNode(
1230 DAG.getConstant(Intrinsic::nvvm_rcp_approx_ftz_d, DL, MVT::i32),
1231 MakeIntrinsicCall(Intrinsic::nvvm_rsqrt_approx_d));
1232 }
1233 }
1234}
1235
1237 // Load directly from the source address space of a cast to generic.
1238 unsigned SrcAS = ADDRESS_SPACE_GENERIC;
1239 if (Ptr->getOpcode() == ISD::ADDRSPACECAST) {
1240 const auto *ASC = cast<AddrSpaceCastSDNode>(Ptr);
1241 if (ASC->getDestAddressSpace() == ADDRESS_SPACE_GENERIC) {
1242 Ptr = ASC->getOperand(0);
1243 SrcAS = ASC->getSrcAddressSpace();
1244 }
1245 }
1246
1247 // Preserve the alloca's address space through frame-index inference.
1248 if (const auto *FIN = dyn_cast<FrameIndexSDNode>(Ptr))
1249 if (const AllocaInst *AI =
1251 FIN->getIndex()))
1252 return MachinePointerInfo(AI);
1253
1254 return MachinePointerInfo(SrcAS);
1255}
1256
1258 if (Flags.isSExt())
1259 return ISD::SIGN_EXTEND;
1260 if (Flags.isZExt())
1261 return ISD::ZERO_EXTEND;
1262 return ISD::ANY_EXTEND;
1263}
1264
1266 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1267 SDLoc dl) {
1268 const EVT ActualVT = V.getValueType();
1269 assert((ActualVT == ExpectedVT ||
1270 (ExpectedVT.isInteger() && ActualVT.isInteger())) &&
1271 "Non-integer argument type size mismatch");
1272 if (ExpectedVT.bitsGT(ActualVT))
1273 return DAG.getNode(getExtOpcode(Flags), dl, ExpectedVT, V);
1274 if (ExpectedVT.bitsLT(ActualVT))
1275 return DAG.getNode(ISD::TRUNCATE, dl, ExpectedVT, V);
1276
1277 return V;
1278}
1279
1281 return DAG.getNode(NVPTXISD::Symbol, SDLoc(), T, DAG.getMCSymbol(Sym, T));
1282}
1283
1284static SDValue getSymbolNode(SelectionDAG &DAG, const Twine &Name, EVT T) {
1286 return getSymbolNode(DAG, Ctx.getOrCreateSymbol(Name), T);
1287}
1288
1290 SmallVectorImpl<SDValue> &InVals) const {
1291
1292 if (CLI.IsVarArg &&
1293 (!STI.hasFeature(NVPTX::PTX60) || !STI.hasFeature(NVPTX::SM30)))
1295 "Support for variadic functions (unsized array parameter) introduced "
1296 "in PTX ISA version 6.0 and requires target sm_30.");
1297
1298 SelectionDAG &DAG = CLI.DAG;
1299 SDLoc dl = CLI.DL;
1300 const SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1301 SDValue Callee = CLI.Callee;
1302 ArgListTy &Args = CLI.getArgs();
1303 Type *RetTy = CLI.RetTy;
1304 const CallBase *CB = CLI.CB;
1305 const DataLayout &DL = DAG.getDataLayout();
1306 LLVMContext &Ctx = *DAG.getContext();
1307
1308 const auto GetI32 = [&](const unsigned I) {
1309 return DAG.getConstant(I, dl, MVT::i32);
1310 };
1311
1312 const unsigned UniqueCallSite = GlobalUniqueCallSite++;
1313 const SDValue CallChain = CLI.Chain;
1314 const SDValue StartChain =
1315 DAG.getCALLSEQ_START(CallChain, UniqueCallSite, 0, dl);
1316 SDValue DeclareGlue = StartChain.getValue(1);
1317
1318 SmallVector<SDValue, 16> CallPrereqs{StartChain};
1319
1320 const auto MakeDeclareScalarParam = [&](SDValue Symbol, unsigned Size) {
1321 // PTX ABI requires integral types to be at least 32 bits in size. FP16 is
1322 // loaded/stored using i16, so it's handled here as well.
1323 const unsigned SizeBits = promoteScalarArgumentSize(Size * 8);
1324 SDValue Declare =
1325 DAG.getNode(NVPTXISD::DeclareScalarParam, dl, {MVT::Other, MVT::Glue},
1326 {StartChain, Symbol, GetI32(SizeBits), DeclareGlue});
1327 CallPrereqs.push_back(Declare);
1328 DeclareGlue = Declare.getValue(1);
1329 return Declare;
1330 };
1331
1332 const auto MakeDeclareArrayParam = [&](SDValue Symbol, Align Align,
1333 unsigned Size) {
1334 SDValue Declare = DAG.getNode(
1335 NVPTXISD::DeclareArrayParam, dl, {MVT::Other, MVT::Glue},
1336 {StartChain, Symbol, GetI32(Align.value()), GetI32(Size), DeclareGlue});
1337 CallPrereqs.push_back(Declare);
1338 DeclareGlue = Declare.getValue(1);
1339 return Declare;
1340 };
1341
1342 // Variadic arguments.
1343 //
1344 // Normally, for each argument, we declare a param scalar or a param
1345 // byte array in the .param space, and store the argument value to that
1346 // param scalar or array starting at offset 0.
1347 //
1348 // In the case of the first variadic argument, we declare a vararg byte array
1349 // with size 0. The exact size of this array isn't known at this point, so
1350 // it'll be patched later. All the variadic arguments will be stored to this
1351 // array at a certain offset (which gets tracked by 'VAOffset'). The offset is
1352 // initially set to 0, so it can be used for non-variadic arguments (which use
1353 // 0 offset) to simplify the code.
1354 //
1355 // After all vararg is processed, 'VAOffset' holds the size of the
1356 // vararg byte array.
1357 assert((CLI.IsVarArg || CLI.Args.size() <= CLI.NumFixedArgs) &&
1358 "Non-VarArg function with extra arguments");
1359
1360 const unsigned FirstVAArg = CLI.NumFixedArgs; // position of first variadic
1361 unsigned VAOffset = 0; // current offset in the param array
1362
1363 const SDValue VADeclareParam =
1364 CLI.Args.size() > FirstVAArg
1365 ? MakeDeclareArrayParam(
1366 getCallParamSymbolNode(DAG, FirstVAArg, MVT::i32),
1367 Align(STI.getMaxRequiredAlignment()), 0)
1368 : SDValue();
1369
1370 // Args.size() and Outs.size() need not match.
1371 // Outs.size() will be larger
1372 // * if there is an aggregate argument with multiple fields (each field
1373 // showing up separately in Outs)
1374 // * if there is a vector argument with more than typical vector-length
1375 // elements (generally if more than 4) where each vector element is
1376 // individually present in Outs.
1377 // So a different index should be used for indexing into Outs/OutVals.
1378 // See similar issue in LowerFormalArguments.
1379 auto AllOuts = ArrayRef(CLI.Outs);
1380 auto AllOutVals = ArrayRef(CLI.OutVals);
1381 assert(AllOuts.size() == AllOutVals.size() &&
1382 "Outs and OutVals must be the same size");
1383 // Declare the .params or .reg need to pass values
1384 // to the function
1385 for (const auto E : llvm::enumerate(Args)) {
1386 const auto ArgI = E.index();
1387 const auto Arg = E.value();
1388 const auto ArgOuts =
1389 AllOuts.take_while([&](auto O) { return O.OrigArgIndex == ArgI; });
1390 const auto ArgOutVals = AllOutVals.take_front(ArgOuts.size());
1391 AllOuts = AllOuts.drop_front(ArgOuts.size());
1392 AllOutVals = AllOutVals.drop_front(ArgOuts.size());
1393
1394 const bool IsVAArg = (ArgI >= FirstVAArg);
1395 const bool IsByVal = Arg.IsByVal;
1396
1397 const SDValue ParamSymbol =
1398 getCallParamSymbolNode(DAG, IsVAArg ? FirstVAArg : ArgI, MVT::i32);
1399
1400 assert((!IsByVal || Arg.IndirectType) &&
1401 "byval arg must have indirect type");
1402 Type *ETy = (IsByVal ? Arg.IndirectType : Arg.Ty);
1403
1404 const Align ArgAlign = [&]() {
1405 const unsigned ParamIdx = ArgI + AttributeList::FirstArgIndex;
1406 if (IsByVal)
1407 return getDeviceByValParamAlign(CB, ETy, ParamIdx, DL);
1408 return getPTXParamAlign(CB, Arg.Ty, ParamIdx, DL);
1409 }();
1410
1411 const unsigned TySize = DL.getTypeAllocSize(ETy);
1412 assert((!IsByVal || TySize == ArgOuts[0].Flags.getByValSize()) &&
1413 "type size mismatch");
1414
1415 const SDValue ArgDeclare = [&]() {
1416 if (IsVAArg)
1417 return VADeclareParam;
1418
1419 if (IsByVal || shouldPassAsArray(Arg.Ty))
1420 return MakeDeclareArrayParam(ParamSymbol, ArgAlign, TySize);
1421
1422 assert(ArgOuts.size() == 1 && "We must pass only one value as non-array");
1423 assert((ArgOuts[0].VT.isInteger() || ArgOuts[0].VT.isFloatingPoint()) &&
1424 "Only int and float types are supported as non-array arguments");
1425
1426 return MakeDeclareScalarParam(ParamSymbol, TySize);
1427 }();
1428
1429 if (IsByVal) {
1430 assert(ArgOutVals.size() == 1 && "We must pass only one value as byval");
1431 SDValue SrcPtr = ArgOutVals[0];
1432 const MachinePointerInfo SrcPtrInfo = refinePtrAS(SrcPtr, DAG);
1433 // Don't use Flags.getNonZeroByValAlign as this includes the stackalign,
1434 // which does not apply to the source pointer.
1435 const Align BaseSrcAlign = [&]() {
1436 // The align attribute on a byval argument indicates the known alignment
1437 // of the pointer passed to the function.
1438 if (CB)
1439 if (const MaybeAlign A = CB->getParamAlign(ArgI))
1440 return *A;
1441 // Fall back to the default alignment for the type.
1442 // TODO: This might be too aggressive but we haven't had a problem with
1443 // it yet.
1444 return getPTXParamTypeAlign(ETy, DL);
1445 }();
1446
1447 if (IsVAArg)
1448 VAOffset = alignTo(VAOffset, ArgAlign);
1449
1450 SmallVector<EVT, 4> ValueVTs, MemVTs;
1452 ComputeValueVTs(*this, DL, ETy, ValueVTs, &MemVTs, &Offsets);
1453
1454 unsigned J = 0;
1455 const auto VI = VectorizePTXValueVTs(MemVTs, Offsets, ArgAlign, IsVAArg);
1456 for (const unsigned NumElts : VI) {
1457 EVT LoadVT = getVectorizedVT(MemVTs[J], NumElts, Ctx);
1458 Align SrcAlign = commonAlignment(BaseSrcAlign, Offsets[J]);
1459 SDValue SrcAddr = DAG.getObjectPtrOffset(dl, SrcPtr, Offsets[J]);
1460 SDValue SrcLoad =
1461 DAG.getLoad(LoadVT, dl, CallChain, SrcAddr,
1462 SrcPtrInfo.getWithOffset(Offsets[J]), SrcAlign);
1463
1464 TypeSize ParamOffset = Offsets[J].getWithIncrement(VAOffset);
1465 Align ParamAlign = commonAlignment(ArgAlign, ParamOffset);
1466 SDValue ParamAddr =
1467 DAG.getObjectPtrOffset(dl, ParamSymbol, ParamOffset);
1468 SDValue StoreParam = DAG.getStore(
1469 ArgDeclare, dl, SrcLoad, ParamAddr,
1471 CallPrereqs.push_back(StoreParam);
1472
1473 J += NumElts;
1474 }
1475 if (IsVAArg)
1476 VAOffset += TySize;
1477 } else {
1480 ComputePTXValueVTs(*this, DL, Ctx, CLI.CallConv, Arg.Ty, VTs, Offsets,
1481 VAOffset);
1482 assert(VTs.size() == Offsets.size() && "Size mismatch");
1483 assert(VTs.size() == ArgOuts.size() && "Size mismatch");
1484
1485 // PTX Interoperability Guide 3.3(A): [Integer] Values shorter
1486 // than 32-bits are sign extended or zero extended, depending on
1487 // whether they are signed or unsigned types. This case applies
1488 // only to scalar parameters and not to aggregate values.
1489 const bool ExtendIntegerParam =
1490 Arg.Ty->isIntegerTy() && DL.getTypeAllocSizeInBits(Arg.Ty) < 32;
1491
1492 const auto GetStoredValue = [&](const unsigned I) {
1493 SDValue StVal = ArgOutVals[I];
1495 StVal.getValueType() &&
1496 "OutVal type should always be legal");
1497
1498 const EVT VTI = promoteScalarIntegerPTX(VTs[I]);
1499 const EVT StoreVT =
1500 ExtendIntegerParam ? MVT::i32 : (VTI == MVT::i1 ? MVT::i8 : VTI);
1501
1502 return correctParamType(StVal, StoreVT, ArgOuts[I].Flags, DAG, dl);
1503 };
1504
1505 unsigned J = 0;
1506 const auto VI = VectorizePTXValueVTs(VTs, Offsets, ArgAlign, IsVAArg);
1507 for (const unsigned NumElts : VI) {
1508 const EVT EltVT = promoteScalarIntegerPTX(VTs[J]);
1509
1510 unsigned Offset;
1511 if (IsVAArg) {
1512 // TODO: We may need to support vector types that can be passed
1513 // as scalars in variadic arguments.
1514 assert(NumElts == 1 &&
1515 "Vectorization should be disabled for vaargs.");
1516
1517 // Align each part of the variadic argument to their type.
1518 VAOffset = alignTo(VAOffset, DAG.getEVTAlign(EltVT));
1519 Offset = VAOffset;
1520
1521 const EVT TheStoreType = ExtendIntegerParam ? MVT::i32 : EltVT;
1522 VAOffset += DL.getTypeAllocSize(TheStoreType.getTypeForEVT(Ctx));
1523 } else {
1524 assert(VAOffset == 0 && "VAOffset must be 0 for non-VA args");
1525 Offset = Offsets[J];
1526 }
1527
1528 SDValue Ptr =
1529 DAG.getObjectPtrOffset(dl, ParamSymbol, TypeSize::getFixed(Offset));
1530
1531 const MaybeAlign CurrentAlign = ExtendIntegerParam
1532 ? MaybeAlign(std::nullopt)
1533 : commonAlignment(ArgAlign, Offset);
1534
1535 SDValue Val =
1536 getBuildVectorizedValue(NumElts, dl, DAG, [&](unsigned K) {
1537 return GetStoredValue(J + K);
1538 });
1539
1540 SDValue StoreParam = DAG.getStore(
1541 ArgDeclare, dl, Val, Ptr,
1543 CallPrereqs.push_back(StoreParam);
1544
1545 J += NumElts;
1546 }
1547 }
1548 }
1549
1550 // Handle Result
1551 if (!Ins.empty()) {
1552 const SDValue RetSymbol = getSymbolNode(DAG, "retval0", MVT::i32);
1553 const unsigned ResultSize = DL.getTypeAllocSize(RetTy);
1554 if (shouldPassAsArray(RetTy)) {
1555 const Align RetAlign =
1556 getPTXParamAlign(CB, RetTy, AttributeList::ReturnIndex, DL);
1557 MakeDeclareArrayParam(RetSymbol, RetAlign, ResultSize);
1558 } else {
1559 MakeDeclareScalarParam(RetSymbol, ResultSize);
1560 }
1561 }
1562
1563 // Set the size of the vararg param byte array if the callee is a variadic
1564 // function and the variadic part is not empty.
1565 if (VADeclareParam) {
1566 SDValue DeclareParamOps[] = {VADeclareParam.getOperand(0),
1567 VADeclareParam.getOperand(1),
1568 VADeclareParam.getOperand(2), GetI32(VAOffset),
1569 VADeclareParam.getOperand(4)};
1570 DAG.MorphNodeTo(VADeclareParam.getNode(), VADeclareParam.getOpcode(),
1571 VADeclareParam->getVTList(), DeclareParamOps);
1572 }
1573
1574 const auto *Func = dyn_cast<GlobalAddressSDNode>(Callee.getNode());
1575 const auto *CalleeF = Func ? dyn_cast<Function>(Func->getGlobal()) : nullptr;
1576
1577 // If the type of the callsite does not match that of the function, convert
1578 // the callsite to an indirect call.
1579 const bool ConvertToIndirectCall =
1580 CalleeF && CB->getFunctionType() != CalleeF->getFunctionType();
1581
1582 // Both indirect calls and libcalls have nullptr Func. In order to distinguish
1583 // between them we must rely on the call site value which is valid for
1584 // indirect calls but is always null for libcalls.
1585 const bool IsIndirectCall = (!Func && CB) || ConvertToIndirectCall;
1586
1587 if (isa<ExternalSymbolSDNode>(Callee)) {
1588 Function* CalleeFunc = nullptr;
1589
1590 // Try to find the callee in the current module.
1591 Callee = DAG.getSymbolFunctionGlobalAddress(Callee, &CalleeFunc);
1592 assert(CalleeFunc != nullptr && "Libcall callee must be set.");
1593
1594 // Set the "libcall callee" attribute to indicate that the function
1595 // must always have a declaration.
1596 CalleeFunc->addFnAttr("nvptx-libcall-callee", "true");
1597 }
1598
1599 // In the indirect function call case, PTX requires a prototype of the form:
1600 // proto_0 : .callprototype(.param .b32 _) _ (.param .b32 _);
1601 // Where the label is to be used as the last arg of the call instruction.
1602 // We record the call site here and emit all prototypes at the
1603 // start of the function in the AsmPrinter.
1604 if (IsIndirectCall)
1605 DAG.getMachineFunction()
1607 ->addCallPrototype(UniqueCallSite, CB);
1608
1609 const bool IsUnknownIntrinsic =
1610 CalleeF && CalleeF->isIntrinsic() &&
1611 CalleeF->getIntrinsicID() == Intrinsic::not_intrinsic;
1612 if (IsUnknownIntrinsic) {
1615 "call to unknown intrinsic '" + CalleeF->getName() +
1616 "' cannot be lowered by the NVPTX backend",
1617 dl.getDebugLoc()));
1618 }
1619
1620 const unsigned Proto = IsIndirectCall ? UniqueCallSite : 0;
1621 const unsigned NumArgs =
1622 std::min<unsigned>(CLI.NumFixedArgs + 1, Args.size());
1623 /// CALL(Chain, IsConvergent, IsIndirectCall/IsUniform, NumReturns,
1624 /// NumParams, Callee, Proto)
1625 const SDValue CallToken = DAG.getTokenFactor(dl, CallPrereqs);
1626 const SDValue Call = DAG.getNode(
1627 NVPTXISD::CALL, dl, MVT::Other,
1628 {CallToken, GetI32(CLI.IsConvergent), GetI32(IsIndirectCall),
1629 GetI32(Ins.empty() ? 0 : 1), GetI32(NumArgs), Callee, GetI32(Proto)});
1630
1631 SmallVector<SDValue, 16> LoadChains{Call};
1632 SmallVector<SDValue, 16> ProxyRegOps;
1633 if (!Ins.empty()) {
1636 ComputePTXValueVTs(*this, DL, Ctx, CLI.CallConv, RetTy, VTs, Offsets);
1637 assert(VTs.size() == Ins.size() && "Bad value decomposition");
1638
1639 const Align RetAlign =
1640 getPTXParamAlign(CB, RetTy, AttributeList::ReturnIndex, DL);
1641 const SDValue RetSymbol = getSymbolNode(DAG, "retval0", MVT::i32);
1642
1643 // PTX Interoperability Guide 3.3(A): [Integer] Values shorter than
1644 // 32-bits are sign extended or zero extended, depending on whether
1645 // they are signed or unsigned types.
1646 const bool ExtendIntegerRetVal =
1647 RetTy->isIntegerTy() && DL.getTypeAllocSizeInBits(RetTy) < 32;
1648
1649 unsigned I = 0;
1650 const auto VI = VectorizePTXValueVTs(VTs, Offsets, RetAlign);
1651 for (const unsigned NumElts : VI) {
1652 const MaybeAlign CurrentAlign =
1653 ExtendIntegerRetVal ? MaybeAlign(std::nullopt)
1654 : commonAlignment(RetAlign, Offsets[I]);
1655
1656 const EVT VTI = promoteScalarIntegerPTX(VTs[I]);
1657 const EVT LoadVT =
1658 ExtendIntegerRetVal ? MVT::i32 : (VTI == MVT::i1 ? MVT::i8 : VTI);
1659 const EVT VecVT = getVectorizedVT(LoadVT, NumElts, Ctx);
1660 SDValue Ptr =
1661 DAG.getObjectPtrOffset(dl, RetSymbol, TypeSize::getFixed(Offsets[I]));
1662
1663 SDValue R = DAG.getLoad(
1664 VecVT, dl, Call, Ptr,
1666
1667 LoadChains.push_back(R.getValue(1));
1668 for (const unsigned J : llvm::seq(NumElts))
1669 ProxyRegOps.push_back(getExtractVectorizedValue(R, J, LoadVT, dl, DAG));
1670 I += NumElts;
1671 }
1672 }
1673
1674 const SDValue EndToken = DAG.getTokenFactor(dl, LoadChains);
1675 const SDValue CallEnd = DAG.getCALLSEQ_END(EndToken, UniqueCallSite,
1676 UniqueCallSite + 1, SDValue(), dl);
1677
1678 // Append ProxyReg instructions to the chain to make sure that `callseq_end`
1679 // will not get lost. Otherwise, during libcalls expansion, the nodes can become
1680 // dangling.
1681 for (const auto [I, Reg] : llvm::enumerate(ProxyRegOps)) {
1682 SDValue Proxy =
1683 DAG.getNode(NVPTXISD::ProxyReg, dl, Reg.getValueType(), {CallEnd, Reg});
1684 SDValue Ret = correctParamType(Proxy, Ins[I].VT, Ins[I].Flags, DAG, dl);
1685 InVals.push_back(Ret);
1686 }
1687
1688 // set IsTailCall to false for now, until we figure out how to express
1689 // tail call optimization in PTX
1690 CLI.IsTailCall = false;
1691 return CallEnd;
1692}
1693
1695 SelectionDAG &DAG) const {
1696
1697 if (!STI.hasFeature(NVPTX::PTX73) || !STI.hasFeature(NVPTX::SM52)) {
1698 const Function &Fn = DAG.getMachineFunction().getFunction();
1699
1701 Fn,
1702 "Support for dynamic alloca introduced in PTX ISA version 7.3 and "
1703 "requires target sm_52.",
1704 SDLoc(Op).getDebugLoc()));
1705 auto Ops = {DAG.getConstant(0, SDLoc(), Op.getValueType()),
1706 Op.getOperand(0)};
1707 return DAG.getMergeValues(Ops, SDLoc());
1708 }
1709
1710 SDLoc DL(Op.getNode());
1711 SDValue Chain = Op.getOperand(0);
1712 SDValue Size = Op.getOperand(1);
1713 uint64_t Align = Op.getConstantOperandVal(2);
1714
1715 // The alignment on a ISD::DYNAMIC_STACKALLOC node may be 0 to indicate that
1716 // the default stack alignment should be used.
1717 if (Align == 0)
1719
1720 // The size for ptx alloca instruction is 64-bit for m64 and 32-bit for m32.
1721 const MVT LocalVT = getPointerTy(DAG.getDataLayout(), ADDRESS_SPACE_LOCAL);
1722
1723 SDValue Alloc =
1724 DAG.getNode(NVPTXISD::DYNAMIC_STACKALLOC, DL, {LocalVT, MVT::Other},
1725 {Chain, DAG.getZExtOrTrunc(Size, DL, LocalVT),
1726 DAG.getTargetConstant(Align, DL, MVT::i32)});
1727
1728 // NVPTXLowerAlloca puts allocas in the local address space, so a local
1729 // pointer is requested here; escapes are explicit addrspacecasts in the IR.
1730 assert(Op.getValueType() == LocalVT && "Unexpected alloca pointer size");
1731
1732 return DAG.getMergeValues({Alloc, SDValue(Alloc.getNode(), 1)}, DL);
1733}
1734
1736 SelectionDAG &DAG) const {
1737 SDLoc DL(Op.getNode());
1738 if (!STI.hasFeature(NVPTX::PTX73) || !STI.hasFeature(NVPTX::SM52)) {
1739 const Function &Fn = DAG.getMachineFunction().getFunction();
1740
1742 Fn,
1743 "Support for stackrestore requires PTX ISA version >= 7.3 and target "
1744 ">= sm_52.",
1745 DL.getDebugLoc()));
1746 return Op.getOperand(0);
1747 }
1748
1749 const MVT LocalVT = getPointerTy(DAG.getDataLayout(), ADDRESS_SPACE_LOCAL);
1750 SDValue Chain = Op.getOperand(0);
1751 SDValue Ptr = Op.getOperand(1);
1752 SDValue ASC = DAG.getAddrSpaceCast(DL, LocalVT, Ptr, ADDRESS_SPACE_GENERIC,
1754 return DAG.getNode(NVPTXISD::STACKRESTORE, DL, MVT::Other, {Chain, ASC});
1755}
1756
1758 SelectionDAG &DAG) const {
1759 SDLoc DL(Op.getNode());
1760 if (!STI.hasFeature(NVPTX::PTX73) || !STI.hasFeature(NVPTX::SM52)) {
1761 const Function &Fn = DAG.getMachineFunction().getFunction();
1762
1764 Fn,
1765 "Support for stacksave requires PTX ISA version >= 7.3 and target >= "
1766 "sm_52.",
1767 DL.getDebugLoc()));
1768 auto Ops = {DAG.getConstant(0, DL, Op.getValueType()), Op.getOperand(0)};
1769 return DAG.getMergeValues(Ops, DL);
1770 }
1771
1772 const MVT LocalVT = getPointerTy(DAG.getDataLayout(), ADDRESS_SPACE_LOCAL);
1773 SDValue Chain = Op.getOperand(0);
1774 SDValue SS =
1775 DAG.getNode(NVPTXISD::STACKSAVE, DL, {LocalVT, MVT::Other}, Chain);
1776 SDValue ASC = DAG.getAddrSpaceCast(
1777 DL, Op.getValueType(), SS, ADDRESS_SPACE_LOCAL, ADDRESS_SPACE_GENERIC);
1778 return DAG.getMergeValues({ASC, SDValue(SS.getNode(), 1)}, DL);
1779}
1780
1781// By default CONCAT_VECTORS is lowered by ExpandVectorBuildThroughStack()
1782// (see LegalizeDAG.cpp). This is slow and uses local memory.
1783// We use extract/insert/build vector just as what LegalizeOp() does in llvm 2.5
1784SDValue
1785NVPTXTargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
1786 SDNode *Node = Op.getNode();
1787 SDLoc dl(Node);
1789 unsigned NumOperands = Node->getNumOperands();
1790 for (unsigned i = 0; i < NumOperands; ++i) {
1791 SDValue SubOp = Node->getOperand(i);
1792 EVT VVT = SubOp.getNode()->getValueType(0);
1793 EVT EltVT = VVT.getVectorElementType();
1794 unsigned NumSubElem = VVT.getVectorNumElements();
1795 for (unsigned j = 0; j < NumSubElem; ++j) {
1796 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, SubOp,
1797 DAG.getIntPtrConstant(j, dl)));
1798 }
1799 }
1800 return DAG.getBuildVector(Node->getValueType(0), dl, Ops);
1801}
1802
1804 SelectionDAG &DAG,
1805 unsigned Mode = NVPTX::PTXPrmtMode::NONE) {
1806 assert(A.getValueType() == MVT::i32 && B.getValueType() == MVT::i32 &&
1807 Selector.getValueType() == MVT::i32 && "PRMT must have i32 operands");
1808 return DAG.getNode(NVPTXISD::PRMT, DL, MVT::i32,
1809 {A, B, Selector, DAG.getConstant(Mode, DL, MVT::i32)});
1810}
1811
1813 SelectionDAG &DAG,
1814 unsigned Mode = NVPTX::PTXPrmtMode::NONE) {
1815 return getPRMT(A, B, DAG.getConstant(Selector, DL, MVT::i32), DL, DAG, Mode);
1816}
1817
1818/// Reduces the elements using the scalar operations provided. The operations
1819/// are sorted descending in number of inputs they take. The flags on the
1820/// original reduction operation will be propagated to each scalar operation.
1821/// Nearby elements are grouped in tree reduction, unlike the shuffle reduction
1822/// used in ExpandReductions and SelectionDAG.
1824 const SmallVector<SDValue> &Elements, EVT EltTy,
1825 ArrayRef<std::pair<unsigned /*NodeType*/, unsigned /*NumInputs*/>> Ops,
1826 const SDLoc &DL, const SDNodeFlags Flags, SelectionDAG &DAG) {
1827 // Build the reduction tree at each level, starting with all the elements.
1828 SmallVector<SDValue> Level = Elements;
1829
1830 unsigned OpIdx = 0;
1831 while (Level.size() > 1) {
1832 // Try to reduce this level using the current operator.
1833 const auto [Op, NumInputs] = Ops[OpIdx];
1834
1835 // Build the next level by partially reducing all elements.
1836 SmallVector<SDValue> ReducedLevel;
1837 unsigned I = 0, E = Level.size();
1838 for (; I + NumInputs <= E; I += NumInputs) {
1839 // Reduce elements in groups of [NumInputs], as much as possible.
1840 ReducedLevel.push_back(DAG.getNode(
1841 Op, DL, EltTy, ArrayRef<SDValue>(Level).slice(I, NumInputs), Flags));
1842 }
1843
1844 if (I < E) {
1845 // Handle leftover elements.
1846
1847 if (ReducedLevel.empty()) {
1848 // We didn't reduce anything at this level. We need to pick a smaller
1849 // operator.
1850 ++OpIdx;
1851 assert(OpIdx < Ops.size() && "no smaller operators for reduction");
1852 continue;
1853 }
1854
1855 // We reduced some things but there's still more left, meaning the
1856 // operator's number of inputs doesn't evenly divide this level size. Move
1857 // these elements to the next level.
1858 for (; I < E; ++I)
1859 ReducedLevel.push_back(Level[I]);
1860 }
1861
1862 // Process the next level.
1863 Level = ReducedLevel;
1864 }
1865
1866 return *Level.begin();
1867}
1868
1869// Get scalar reduction opcode
1870static ISD::NodeType getScalarOpcodeForReduction(unsigned ReductionOpcode) {
1871 switch (ReductionOpcode) {
1873 return ISD::FMAXNUM;
1875 return ISD::FMINNUM;
1877 return ISD::FMAXIMUM;
1879 return ISD::FMINIMUM;
1880 default:
1881 llvm_unreachable("unhandled reduction opcode");
1882 }
1883}
1884
1885/// Get 3-input scalar reduction opcode
1886static std::optional<unsigned>
1887getScalar3OpcodeForReduction(unsigned ReductionOpcode) {
1888 switch (ReductionOpcode) {
1890 return NVPTXISD::FMAXNUM3;
1892 return NVPTXISD::FMINNUM3;
1894 return NVPTXISD::FMAXIMUM3;
1896 return NVPTXISD::FMINIMUM3;
1897 default:
1898 return std::nullopt;
1899 }
1900}
1901
1902/// Lower reductions to either a sequence of operations or a tree if
1903/// reassociations are allowed. This method will use larger operations like
1904/// max3/min3 when the target supports them.
1905SDValue NVPTXTargetLowering::LowerVECREDUCE(SDValue Op,
1906 SelectionDAG &DAG) const {
1907 SDLoc DL(Op);
1908 const SDNodeFlags Flags = Op->getFlags();
1909 SDValue Vector = Op.getOperand(0);
1910
1911 const unsigned Opcode = Op->getOpcode();
1912 const EVT EltTy = Vector.getValueType().getVectorElementType();
1913
1914 // Whether we can use 3-input min/max when expanding the reduction.
1915 const bool CanUseMinMax3 =
1916 EltTy == MVT::f32 && STI.hasFeature(NVPTX::SM100) &&
1917 STI.hasFeature(NVPTX::PTX88) &&
1918 (Opcode == ISD::VECREDUCE_FMAX || Opcode == ISD::VECREDUCE_FMIN ||
1919 Opcode == ISD::VECREDUCE_FMAXIMUM || Opcode == ISD::VECREDUCE_FMINIMUM);
1920
1921 // A list of SDNode opcodes with equivalent semantics, sorted descending by
1922 // number of inputs they take.
1923 SmallVector<std::pair<unsigned /*Op*/, unsigned /*NumIn*/>, 2> ScalarOps;
1924
1925 if (auto Opcode3Elem = getScalar3OpcodeForReduction(Opcode);
1926 CanUseMinMax3 && Opcode3Elem)
1927 ScalarOps.push_back({*Opcode3Elem, 3});
1928 ScalarOps.push_back({getScalarOpcodeForReduction(Opcode), 2});
1929
1931 DAG.ExtractVectorElements(Vector, Elements);
1932
1933 return buildTreeReduction(Elements, EltTy, ScalarOps, DL, Flags, DAG);
1934}
1935
1936SDValue NVPTXTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
1937 // Handle bitcasting from v2i8 without hitting the default promotion
1938 // strategy which goes through stack memory.
1939 EVT FromVT = Op->getOperand(0)->getValueType(0);
1940 if (FromVT != MVT::v2i8) {
1941 return Op;
1942 }
1943
1944 // Pack vector elements into i16 and bitcast to final type
1945 SDLoc DL(Op);
1946 SDValue Vec0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i8,
1947 Op->getOperand(0), DAG.getIntPtrConstant(0, DL));
1948 SDValue Vec1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i8,
1949 Op->getOperand(0), DAG.getIntPtrConstant(1, DL));
1950 SDValue Extend0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i16, Vec0);
1951 SDValue Extend1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i16, Vec1);
1952 SDValue Const8 = DAG.getConstant(8, DL, MVT::i16);
1953 SDValue AsInt = DAG.getNode(
1954 ISD::OR, DL, MVT::i16,
1955 {Extend0, DAG.getNode(ISD::SHL, DL, MVT::i16, {Extend1, Const8})});
1956 EVT ToVT = Op->getValueType(0);
1957 return DAG.getBitcast(ToVT, AsInt);
1958}
1959
1960// We can init constant f16x2/v2i16/v4i8 with a single .b32 move. Normally it
1961// would get lowered as two constant loads and vector-packing move.
1962// Instead we want just a constant move:
1963// mov.b32 %r2, 0x40003C00
1964SDValue NVPTXTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1965 SelectionDAG &DAG) const {
1966 EVT VT = Op->getValueType(0);
1967 if (!(NVPTX::isPackedVectorTy(VT) && VT.is32BitVector()))
1968 return Op;
1969 SDLoc DL(Op);
1970
1971 if (!llvm::all_of(Op->ops(), [](SDValue Operand) {
1972 return Operand->isUndef() || isa<ConstantSDNode>(Operand) ||
1973 isa<ConstantFPSDNode>(Operand);
1974 })) {
1975 if (VT != MVT::v4i8)
1976 return Op;
1977 // Lower non-const v4i8 vector as byte-wise constructed i32, which allows us
1978 // to optimize calculation of constant parts.
1979 auto GetPRMT = [&](const SDValue Left, const SDValue Right, bool Cast,
1980 uint64_t SelectionValue) -> SDValue {
1981 SDValue L = Left;
1982 SDValue R = Right;
1983 if (Cast) {
1984 L = DAG.getAnyExtOrTrunc(L, DL, MVT::i32);
1985 R = DAG.getAnyExtOrTrunc(R, DL, MVT::i32);
1986 }
1987 return getPRMT(L, R, SelectionValue, DL, DAG);
1988 };
1989 auto PRMT__10 = GetPRMT(Op->getOperand(0), Op->getOperand(1), true, 0x3340);
1990 auto PRMT__32 = GetPRMT(Op->getOperand(2), Op->getOperand(3), true, 0x3340);
1991 auto PRMT3210 = GetPRMT(PRMT__10, PRMT__32, false, 0x5410);
1992 return DAG.getBitcast(VT, PRMT3210);
1993 }
1994
1995 // Get value or the Nth operand as an APInt(32). Undef values treated as 0.
1996 auto GetOperand = [](SDValue Op, int N) -> APInt {
1997 const SDValue &Operand = Op->getOperand(N);
1998 EVT VT = Op->getValueType(0);
1999 if (Operand->isUndef())
2000 return APInt(32, 0);
2001 APInt Value;
2002 if (VT == MVT::v2f16 || VT == MVT::v2bf16)
2003 Value = cast<ConstantFPSDNode>(Operand)->getValueAPF().bitcastToAPInt();
2004 else if (VT == MVT::v2i16 || VT == MVT::v4i8)
2005 Value = Operand->getAsAPIntVal();
2006 else
2007 llvm_unreachable("Unsupported type");
2008 // i8 values are carried around as i16, so we need to zero out upper bits,
2009 // so they do not get in the way of combining individual byte values
2010 if (VT == MVT::v4i8)
2011 Value = Value.trunc(8);
2012 return Value.zext(32);
2013 };
2014
2015 // Construct a 32-bit constant by shifting into place smaller values
2016 // (elements of the vector type VT).
2017 // For example, if VT has 2 elements, then N == 2:
2018 // ShiftAmount = 32 / N = 16
2019 // Value |= Op0 (b16) << 0
2020 // Value |= Op1 (b16) << 16
2021 // If N == 4:
2022 // ShiftAmount = 32 / N = 8
2023 // Value |= Op0 (b8) << 0
2024 // Value |= Op1 (b8) << 8
2025 // Value |= Op2 (b8) << 16
2026 // Value |= Op3 (b8) << 24
2027 // ...etc
2028 APInt Value(32, 0);
2029 const unsigned NumElements = VT.getVectorNumElements();
2030 assert(32 % NumElements == 0 && "must evenly divide bit length");
2031 const unsigned ShiftAmount = 32 / NumElements;
2032 for (unsigned ElementNo : seq(NumElements))
2033 Value |= GetOperand(Op, ElementNo).shl(ElementNo * ShiftAmount);
2034 SDValue Const = DAG.getConstant(Value, DL, MVT::i32);
2035 return DAG.getNode(ISD::BITCAST, DL, Op->getValueType(0), Const);
2036}
2037
2038SDValue NVPTXTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
2039 SelectionDAG &DAG) const {
2040 SDValue Index = Op->getOperand(1);
2041 SDValue Vector = Op->getOperand(0);
2042 SDLoc DL(Op);
2043 EVT VectorVT = Vector.getValueType();
2044
2045 if (VectorVT == MVT::v4i8) {
2046 SDValue Selector = DAG.getNode(ISD::OR, DL, MVT::i32,
2047 DAG.getZExtOrTrunc(Index, DL, MVT::i32),
2048 DAG.getConstant(0x7770, DL, MVT::i32));
2049 SDValue PRMT = getPRMT(DAG.getBitcast(MVT::i32, Vector),
2050 DAG.getConstant(0, DL, MVT::i32), Selector, DL, DAG);
2051 SDValue Ext = DAG.getAnyExtOrTrunc(PRMT, DL, Op->getValueType(0));
2052 SDNodeFlags Flags;
2053 Flags.setNoSignedWrap(Ext.getScalarValueSizeInBits() > 8);
2054 Flags.setNoUnsignedWrap(Ext.getScalarValueSizeInBits() >= 8);
2055 Ext->setFlags(Flags);
2056 return Ext;
2057 }
2058
2059 // Constant index will be matched by tablegen.
2060 if (isa<ConstantSDNode>(Index.getNode()))
2061 return Op;
2062
2063 // Extract individual elements and select one of them.
2064 assert(NVPTX::isPackedVectorTy(VectorVT) &&
2065 VectorVT.getVectorNumElements() == 2 && "Unexpected vector type.");
2066 EVT EltVT = VectorVT.getVectorElementType();
2067
2068 SDLoc dl(Op.getNode());
2070 DAG.getIntPtrConstant(0, dl));
2071 SDValue E1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Vector,
2072 DAG.getIntPtrConstant(1, dl));
2073 return DAG.getSelectCC(dl, Index, DAG.getIntPtrConstant(0, dl), E0, E1,
2075}
2076
2077SDValue NVPTXTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
2078 SelectionDAG &DAG) const {
2079 SDValue Vector = Op->getOperand(0);
2080 EVT VectorVT = Vector.getValueType();
2081
2082 if (VectorVT != MVT::v4i8)
2083 return Op;
2084 SDLoc DL(Op);
2085 SDValue Value = Op->getOperand(1);
2086 if (Value->isUndef())
2087 return Vector;
2088
2089 SDValue Index = Op->getOperand(2);
2090
2091 SDValue BFI =
2092 DAG.getNode(NVPTXISD::BFI, DL, MVT::i32,
2093 {DAG.getZExtOrTrunc(Value, DL, MVT::i32), Vector,
2094 DAG.getNode(ISD::MUL, DL, MVT::i32,
2095 DAG.getZExtOrTrunc(Index, DL, MVT::i32),
2096 DAG.getConstant(8, DL, MVT::i32)),
2097 DAG.getConstant(8, DL, MVT::i32)});
2098 return DAG.getNode(ISD::BITCAST, DL, Op->getValueType(0), BFI);
2099}
2100
2101SDValue NVPTXTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
2102 SelectionDAG &DAG) const {
2103 SDValue V1 = Op.getOperand(0);
2104 EVT VectorVT = V1.getValueType();
2105 if (VectorVT != MVT::v4i8 || Op.getValueType() != MVT::v4i8)
2106 return Op;
2107
2108 // Lower shuffle to PRMT instruction.
2109 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2110 SDValue V2 = Op.getOperand(1);
2111 uint32_t Selector = 0;
2112 for (auto I : llvm::enumerate(SVN->getMask())) {
2113 if (I.value() != -1) // -1 is a placeholder for undef.
2114 Selector |= (I.value() << (I.index() * 4));
2115 }
2116
2117 SDLoc DL(Op);
2118 SDValue PRMT = getPRMT(DAG.getBitcast(MVT::i32, V1),
2119 DAG.getBitcast(MVT::i32, V2), Selector, DL, DAG);
2120 return DAG.getBitcast(Op.getValueType(), PRMT);
2121}
2122/// LowerShiftRightParts - Lower SRL_PARTS, SRA_PARTS, which
2123/// 1) returns two i32 values and take a 2 x i32 value to shift plus a shift
2124/// amount, or
2125/// 2) returns two i64 values and take a 2 x i64 value to shift plus a shift
2126/// amount.
2127SDValue NVPTXTargetLowering::LowerShiftRightParts(SDValue Op,
2128 SelectionDAG &DAG) const {
2129 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
2130 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
2131
2132 EVT VT = Op.getValueType();
2133 unsigned VTBits = VT.getSizeInBits();
2134 SDLoc dl(Op);
2135 SDValue ShOpLo = Op.getOperand(0);
2136 SDValue ShOpHi = Op.getOperand(1);
2137 SDValue ShAmt = Op.getOperand(2);
2138 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
2139
2140 if (VTBits == 32 && STI.hasFeature(NVPTX::SM35)) {
2141 // For 32bit and sm35, we can use the funnel shift 'shf' instruction.
2142 // {dHi, dLo} = {aHi, aLo} >> Amt
2143 // dHi = aHi >> Amt
2144 // dLo = shf.r.clamp aLo, aHi, Amt
2145
2146 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
2147 SDValue Lo =
2148 DAG.getNode(NVPTXISD::FSHR_CLAMP, dl, VT, ShOpHi, ShOpLo, ShAmt);
2149
2150 SDValue Ops[2] = { Lo, Hi };
2151 return DAG.getMergeValues(Ops, dl);
2152 } else {
2153 // {dHi, dLo} = {aHi, aLo} >> Amt
2154 // - if (Amt>=size) then
2155 // dLo = aHi >> (Amt-size)
2156 // dHi = aHi >> Amt (this is either all 0 or all 1)
2157 // else
2158 // dLo = (aLo >>logic Amt) | (aHi << (size-Amt))
2159 // dHi = aHi >> Amt
2160
2161 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
2162 DAG.getConstant(VTBits, dl, MVT::i32),
2163 ShAmt);
2164 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
2165 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
2166 DAG.getConstant(VTBits, dl, MVT::i32));
2167 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
2168 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2169 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
2170
2171 SDValue Cmp = DAG.getSetCC(dl, MVT::i1, ShAmt,
2172 DAG.getConstant(VTBits, dl, MVT::i32),
2173 ISD::SETGE);
2174 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
2175 SDValue Lo = DAG.getNode(ISD::SELECT, dl, VT, Cmp, TrueVal, FalseVal);
2176
2177 SDValue Ops[2] = { Lo, Hi };
2178 return DAG.getMergeValues(Ops, dl);
2179 }
2180}
2181
2182/// LowerShiftLeftParts - Lower SHL_PARTS, which
2183/// 1) returns two i32 values and take a 2 x i32 value to shift plus a shift
2184/// amount, or
2185/// 2) returns two i64 values and take a 2 x i64 value to shift plus a shift
2186/// amount.
2187SDValue NVPTXTargetLowering::LowerShiftLeftParts(SDValue Op,
2188 SelectionDAG &DAG) const {
2189 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
2190 assert(Op.getOpcode() == ISD::SHL_PARTS);
2191
2192 EVT VT = Op.getValueType();
2193 unsigned VTBits = VT.getSizeInBits();
2194 SDLoc dl(Op);
2195 SDValue ShOpLo = Op.getOperand(0);
2196 SDValue ShOpHi = Op.getOperand(1);
2197 SDValue ShAmt = Op.getOperand(2);
2198
2199 if (VTBits == 32 && STI.hasFeature(NVPTX::SM35)) {
2200 // For 32bit and sm35, we can use the funnel shift 'shf' instruction.
2201 // {dHi, dLo} = {aHi, aLo} << Amt
2202 // dHi = shf.l.clamp aLo, aHi, Amt
2203 // dLo = aLo << Amt
2204
2205 SDValue Hi =
2206 DAG.getNode(NVPTXISD::FSHL_CLAMP, dl, VT, ShOpHi, ShOpLo, ShAmt);
2207 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
2208
2209 SDValue Ops[2] = { Lo, Hi };
2210 return DAG.getMergeValues(Ops, dl);
2211 } else {
2212 // {dHi, dLo} = {aHi, aLo} << Amt
2213 // - if (Amt>=size) then
2214 // dLo = aLo << Amt (all 0)
2215 // dLo = aLo << (Amt-size)
2216 // else
2217 // dLo = aLo << Amt
2218 // dHi = (aHi << Amt) | (aLo >> (size-Amt))
2219
2220 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
2221 DAG.getConstant(VTBits, dl, MVT::i32),
2222 ShAmt);
2223 SDValue Tmp1 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
2224 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
2225 DAG.getConstant(VTBits, dl, MVT::i32));
2226 SDValue Tmp2 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
2227 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2228 SDValue TrueVal = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
2229
2230 SDValue Cmp = DAG.getSetCC(dl, MVT::i1, ShAmt,
2231 DAG.getConstant(VTBits, dl, MVT::i32),
2232 ISD::SETGE);
2233 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
2234 SDValue Hi = DAG.getNode(ISD::SELECT, dl, VT, Cmp, TrueVal, FalseVal);
2235
2236 SDValue Ops[2] = { Lo, Hi };
2237 return DAG.getMergeValues(Ops, dl);
2238 }
2239}
2240
2241/// If the types match, convert the generic copysign to the NVPTXISD version,
2242/// otherwise bail ensuring that mismatched cases are properly expaned.
2243SDValue NVPTXTargetLowering::LowerFCOPYSIGN(SDValue Op,
2244 SelectionDAG &DAG) const {
2245 EVT VT = Op.getValueType();
2246 SDLoc DL(Op);
2247
2248 SDValue In1 = Op.getOperand(0);
2249 SDValue In2 = Op.getOperand(1);
2250 EVT SrcVT = In2.getValueType();
2251
2252 if (!SrcVT.bitsEq(VT))
2253 return SDValue();
2254
2255 return DAG.getNode(NVPTXISD::FCOPYSIGN, DL, VT, In1, In2);
2256}
2257
2258SDValue NVPTXTargetLowering::LowerFROUND(SDValue Op, SelectionDAG &DAG) const {
2259 EVT VT = Op.getValueType();
2260
2261 if (VT == MVT::f32)
2262 return LowerFROUND32(Op, DAG);
2263
2264 if (VT == MVT::f64)
2265 return LowerFROUND64(Op, DAG);
2266
2267 llvm_unreachable("unhandled type");
2268}
2269
2270// This is the the rounding method used in CUDA libdevice in C like code:
2271// float roundf(float A)
2272// {
2273// float RoundedA = (float) (int) ( A > 0 ? (A + 0.5f) : (A - 0.5f));
2274// RoundedA = abs(A) > 0x1.0p23 ? A : RoundedA;
2275// return abs(A) < 0.5 ? (float)(int)A : RoundedA;
2276// }
2277SDValue NVPTXTargetLowering::LowerFROUND32(SDValue Op,
2278 SelectionDAG &DAG) const {
2279 SDLoc SL(Op);
2280 SDValue A = Op.getOperand(0);
2281 EVT VT = Op.getValueType();
2282
2283 SDValue AbsA = DAG.getNode(ISD::FABS, SL, VT, A);
2284
2285 // RoundedA = (float) (int) ( A > 0 ? (A + 0.5f) : (A - 0.5f))
2286 SDValue Bitcast = DAG.getNode(ISD::BITCAST, SL, MVT::i32, A);
2287 const unsigned SignBitMask = 0x80000000;
2288 SDValue Sign = DAG.getNode(ISD::AND, SL, MVT::i32, Bitcast,
2289 DAG.getConstant(SignBitMask, SL, MVT::i32));
2290 const unsigned PointFiveInBits = 0x3F000000;
2291 SDValue PointFiveWithSignRaw =
2292 DAG.getNode(ISD::OR, SL, MVT::i32, Sign,
2293 DAG.getConstant(PointFiveInBits, SL, MVT::i32));
2294 SDValue PointFiveWithSign =
2295 DAG.getNode(ISD::BITCAST, SL, VT, PointFiveWithSignRaw);
2296 SDValue AdjustedA = DAG.getNode(ISD::FADD, SL, VT, A, PointFiveWithSign);
2297 SDValue RoundedA = DAG.getNode(ISD::FTRUNC, SL, VT, AdjustedA);
2298
2299 // RoundedA = abs(A) > 0x1.0p23 ? A : RoundedA;
2300 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2301 SDValue IsLarge =
2302 DAG.getSetCC(SL, SetCCVT, AbsA, DAG.getConstantFP(pow(2.0, 23.0), SL, VT),
2303 ISD::SETOGT);
2304 RoundedA = DAG.getNode(ISD::SELECT, SL, VT, IsLarge, A, RoundedA);
2305
2306 // return abs(A) < 0.5 ? (float)(int)A : RoundedA;
2307 SDValue IsSmall =DAG.getSetCC(SL, SetCCVT, AbsA,
2308 DAG.getConstantFP(0.5, SL, VT), ISD::SETOLT);
2309 SDValue RoundedAForSmallA = DAG.getNode(ISD::FTRUNC, SL, VT, A);
2310 return DAG.getNode(ISD::SELECT, SL, VT, IsSmall, RoundedAForSmallA, RoundedA);
2311}
2312
2313// The implementation of round(double) is similar to that of round(float) in
2314// that they both separate the value range into three regions and use a method
2315// specific to the region to round the values. However, round(double) first
2316// calculates the round of the absolute value and then adds the sign back while
2317// round(float) directly rounds the value with sign.
2318SDValue NVPTXTargetLowering::LowerFROUND64(SDValue Op,
2319 SelectionDAG &DAG) const {
2320 SDLoc SL(Op);
2321 SDValue A = Op.getOperand(0);
2322 EVT VT = Op.getValueType();
2323
2324 SDValue AbsA = DAG.getNode(ISD::FABS, SL, VT, A);
2325
2326 // double RoundedA = (double) (int) (abs(A) + 0.5f);
2327 SDValue AdjustedA = DAG.getNode(ISD::FADD, SL, VT, AbsA,
2328 DAG.getConstantFP(0.5, SL, VT));
2329 SDValue RoundedA = DAG.getNode(ISD::FTRUNC, SL, VT, AdjustedA);
2330
2331 // RoundedA = abs(A) < 0.5 ? (double)0 : RoundedA;
2332 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2333 SDValue IsSmall =DAG.getSetCC(SL, SetCCVT, AbsA,
2334 DAG.getConstantFP(0.5, SL, VT), ISD::SETOLT);
2335 RoundedA = DAG.getNode(ISD::SELECT, SL, VT, IsSmall,
2336 DAG.getConstantFP(0, SL, VT),
2337 RoundedA);
2338
2339 // Add sign to rounded_A
2340 RoundedA = DAG.getNode(ISD::FCOPYSIGN, SL, VT, RoundedA, A);
2341 DAG.getNode(ISD::FTRUNC, SL, VT, A);
2342
2343 // RoundedA = abs(A) > 0x1.0p52 ? A : RoundedA;
2344 SDValue IsLarge =
2345 DAG.getSetCC(SL, SetCCVT, AbsA, DAG.getConstantFP(pow(2.0, 52.0), SL, VT),
2346 ISD::SETOGT);
2347 return DAG.getNode(ISD::SELECT, SL, VT, IsLarge, A, RoundedA);
2348}
2349
2351 EVT VT = N->getValueType(0);
2352 EVT NVT = MVT::f32;
2353 if (VT.isVector()) {
2354 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
2355 }
2356 SDLoc DL(N);
2357 SDValue Tmp0 = DAG.getFPExtendOrRound(N->getOperand(0), DL, NVT);
2358 SDValue Tmp1 = DAG.getFPExtendOrRound(N->getOperand(1), DL, NVT);
2359 SDValue Res = DAG.getNode(N->getOpcode(), DL, NVT, Tmp0, Tmp1, N->getFlags());
2360 return DAG.getFPExtendOrRound(Res, DL, VT);
2361}
2362
2363SDValue NVPTXTargetLowering::PromoteBinOpIfF32FTZ(SDValue Op,
2364 SelectionDAG &DAG) const {
2365 if (useF32FTZ(DAG.getMachineFunction())) {
2366 return PromoteBinOpToF32(Op.getNode(), DAG);
2367 }
2368 return Op;
2369}
2370
2371SDValue NVPTXTargetLowering::LowerINT_TO_FP(SDValue Op,
2372 SelectionDAG &DAG) const {
2373 assert(!STI.hasFeature(NVPTX::SM90));
2374
2375 if (Op.getValueType() == MVT::bf16) {
2376 SDLoc Loc(Op);
2377 return DAG.getNode(
2378 ISD::FP_ROUND, Loc, MVT::bf16,
2379 DAG.getNode(Op.getOpcode(), Loc, MVT::f32, Op.getOperand(0)),
2380 DAG.getIntPtrConstant(0, Loc, /*isTarget=*/true));
2381 }
2382
2383 // Everything else is considered legal.
2384 return Op;
2385}
2386
2387SDValue NVPTXTargetLowering::LowerFP_TO_INT(SDValue Op,
2388 SelectionDAG &DAG) const {
2389 assert(!STI.hasFeature(NVPTX::SM90));
2390
2391 if (Op.getOperand(0).getValueType() == MVT::bf16) {
2392 SDLoc Loc(Op);
2393 return DAG.getNode(
2394 Op.getOpcode(), Loc, Op.getValueType(),
2395 DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, Op.getOperand(0)));
2396 }
2397
2398 // Everything else is considered legal.
2399 return Op;
2400}
2401
2402SDValue NVPTXTargetLowering::LowerFP_ROUND(SDValue Op,
2403 SelectionDAG &DAG) const {
2404 EVT NarrowVT = Op.getValueType();
2405 SDValue Wide = Op.getOperand(0);
2406 EVT WideVT = Wide.getValueType();
2407 if (NarrowVT.getScalarType() == MVT::bf16) {
2408 const TargetLowering *TLI = STI.getTargetLowering();
2409 if (!STI.hasFeature(NVPTX::SM80)) {
2410 return TLI->expandFP_ROUND(Op.getNode(), DAG);
2411 }
2412 if (!STI.hasFeature(NVPTX::SM90)) {
2413 // sm_80 was the first architecture to support f32 -> bf16.
2414 if (WideVT.getScalarType() == MVT::f32) {
2415 return Op;
2416 }
2417 if (WideVT.getScalarType() == MVT::f64) {
2418 SDLoc Loc(Op);
2419 // Round-inexact-to-odd f64 to f32, then do the final rounding using
2420 // the hardware f32 -> bf16 instruction.
2422 WideVT.changeElementType(*DAG.getContext(), MVT::f32), Wide, Loc,
2423 DAG);
2424 return DAG.getFPExtendOrRound(rod, Loc, NarrowVT);
2425 }
2426 return TLI->expandFP_ROUND(Op.getNode(), DAG);
2427 }
2428 }
2429
2430 // Everything else is considered legal.
2431 return Op;
2432}
2433
2434SDValue NVPTXTargetLowering::LowerFP_EXTEND(SDValue Op,
2435 SelectionDAG &DAG) const {
2436 SDValue Narrow = Op.getOperand(0);
2437 EVT NarrowVT = Narrow.getValueType();
2438 EVT WideVT = Op.getValueType();
2439 if (NarrowVT.getScalarType() == MVT::bf16) {
2440 if (WideVT.getScalarType() == MVT::f32 &&
2441 (!STI.hasFeature(NVPTX::SM80) || !STI.hasFeature(NVPTX::PTX71))) {
2442 SDLoc Loc(Op);
2443 return DAG.getNode(ISD::BF16_TO_FP, Loc, WideVT, Narrow);
2444 }
2445 if (WideVT.getScalarType() == MVT::f64 && !STI.hasFeature(NVPTX::SM90)) {
2446 EVT F32 = NarrowVT.changeElementType(*DAG.getContext(), MVT::f32);
2447 SDLoc Loc(Op);
2448 if (STI.hasFeature(NVPTX::SM80) && STI.hasFeature(NVPTX::PTX71)) {
2449 Op = DAG.getNode(ISD::FP_EXTEND, Loc, F32, Narrow);
2450 } else {
2451 Op = DAG.getNode(ISD::BF16_TO_FP, Loc, F32, Narrow);
2452 }
2453 return DAG.getNode(ISD::FP_EXTEND, Loc, WideVT, Op);
2454 }
2455 }
2456
2457 // Everything else is considered legal.
2458 return Op;
2459}
2460
2462 SDLoc DL(Op);
2463 if (Op.getValueType() != MVT::v2i16)
2464 return Op;
2465 EVT EltVT = Op.getValueType().getVectorElementType();
2466 SmallVector<SDValue> VecElements;
2467 for (int I = 0, E = Op.getValueType().getVectorNumElements(); I < E; I++) {
2468 SmallVector<SDValue> ScalarArgs;
2469 llvm::transform(Op->ops(), std::back_inserter(ScalarArgs),
2470 [&](const SDUse &O) {
2471 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
2472 O.get(), DAG.getIntPtrConstant(I, DL));
2473 });
2474 VecElements.push_back(DAG.getNode(Op.getOpcode(), DL, EltVT, ScalarArgs));
2475 }
2476 SDValue V =
2477 DAG.getNode(ISD::BUILD_VECTOR, DL, Op.getValueType(), VecElements);
2478 return V;
2479}
2480
2482 bool hasOffset = false) {
2483 // skip lowering if the vector operand is already legalized
2484 if (!Op->getOperand(hasOffset ? 4 : 3).getValueType().isVector())
2485 return Op;
2486
2487 SDNode *N = Op.getNode();
2488 SDLoc DL(N);
2490
2491 // split the vector argument
2492 for (size_t I = 0; I < N->getNumOperands(); I++) {
2493 SDValue Val = N->getOperand(I);
2494 EVT ValVT = Val.getValueType();
2495 if (ValVT.isVector()) {
2496 EVT EltVT = ValVT.getVectorElementType();
2497 for (unsigned J = 0, NElts = ValVT.getVectorNumElements(); J < NElts; J++)
2498 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Val,
2499 DAG.getIntPtrConstant(J, DL)));
2500 } else
2501 Ops.push_back(Val);
2502 }
2503
2505 SDValue Tcgen05StNode =
2506 DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, N->getVTList(), Ops,
2507 MemSD->getMemoryVT(), MemSD->getMemOperand());
2508
2509 return Tcgen05StNode;
2510}
2511
2513 SDLoc DL(Op);
2514 SDValue Src = Op.getOperand(0);
2515 EVT VT = Op.getValueType();
2516
2517 switch (VT.getSimpleVT().SimpleTy) {
2518 case MVT::i16: {
2519 SDValue Extended = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
2520 SDValue Swapped =
2521 getPRMT(Extended, DAG.getConstant(0, DL, MVT::i32), 0x7701, DL, DAG);
2522 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Swapped);
2523 }
2524 case MVT::i32: {
2525 return getPRMT(Src, DAG.getConstant(0, DL, MVT::i32), 0x0123, DL, DAG);
2526 }
2527 case MVT::v2i16: {
2528 SDValue Converted = DAG.getBitcast(MVT::i32, Src);
2529 SDValue Swapped =
2530 getPRMT(Converted, DAG.getConstant(0, DL, MVT::i32), 0x2301, DL, DAG);
2531 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i16, Swapped);
2532 }
2533 case MVT::i64: {
2534 SDValue UnpackSrc =
2535 DAG.getNode(NVPTXISD::UNPACK_VECTOR, DL, {MVT::i32, MVT::i32}, Src);
2536 SDValue SwappedLow =
2537 getPRMT(UnpackSrc.getValue(0), DAG.getConstant(0, DL, MVT::i32), 0x0123,
2538 DL, DAG);
2539 SDValue SwappedHigh =
2540 getPRMT(UnpackSrc.getValue(1), DAG.getConstant(0, DL, MVT::i32), 0x0123,
2541 DL, DAG);
2542 return DAG.getNode(NVPTXISD::BUILD_VECTOR, DL, MVT::i64,
2543 {SwappedHigh, SwappedLow});
2544 }
2545 default:
2546 llvm_unreachable("unsupported type for bswap");
2547 }
2548}
2549
2551 const Function &Fn = DAG.getMachineFunction().getFunction();
2552 SDNode *N = Op.getNode();
2553 SDLoc DL(N);
2554 Intrinsic::ID IntrinsicID = N->getConstantOperandVal(1);
2555 SDValue DestAddr = N->getOperand(2);
2556 SDValue Value = N->getOperand(3);
2557 SDValue MbarAddr = N->getOperand(4);
2558
2559 MVT ValueVT = Value.getSimpleValueType();
2560
2561 if (ValueVT == MVT::i32 || ValueVT == MVT::i64)
2562 return Op;
2563
2564 if (ValueVT == MVT::i128) {
2565 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
2566 SDValue ValueLo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, Cast,
2567 DAG.getIntPtrConstant(0, DL));
2568 SDValue ValueHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, Cast,
2569 DAG.getIntPtrConstant(1, DL));
2570 SDValue Ops[] = {N->getOperand(0), DestAddr, ValueLo, ValueHi, MbarAddr};
2571 return DAG.getNode(NVPTXISD::ST_ASYNC_MBARRIER_B128, DL, MVT::Other, Ops);
2572 }
2573
2575 Fn,
2576 Twine("unsupported argument type ") + llvm::EVT(ValueVT).getEVTString() +
2577 " for " + llvm::Intrinsic::getName(IntrinsicID) + " intrinsic",
2578 DiagnosticLocation(DL.getDebugLoc())));
2579 return Op.getOperand(0); // Return only the chain
2580}
2581
2583 const Function &Fn = DAG.getMachineFunction().getFunction();
2584 SDNode *N = Op.getNode();
2585 SDLoc DL(N);
2586 Intrinsic::ID IntrinsicID = N->getConstantOperandVal(1);
2587 SDValue DestAddr = N->getOperand(2);
2588 SDValue Value = N->getOperand(3);
2589
2590 MVT ValueVT = Value.getSimpleValueType();
2591
2592 if (ValueVT == MVT::i16 || ValueVT == MVT::i32 || ValueVT == MVT::i64)
2593 return Op;
2594
2595 if (ValueVT == MVT::i8) {
2596 unsigned OpCode;
2597 switch (IntrinsicID) {
2598 case Intrinsic::nvvm_st_async_sys:
2599 OpCode = NVPTXISD::ST_ASYNC_SYS_B8;
2600 break;
2601 case Intrinsic::nvvm_st_async_gpu:
2602 OpCode = NVPTXISD::ST_ASYNC_GPU_B8;
2603 break;
2604 case Intrinsic::nvvm_st_async_mmio_sys:
2605 OpCode = NVPTXISD::ST_ASYNC_MMIO_SYS_B8;
2606 break;
2607 default:
2608 llvm_unreachable("unexpected intrinsic ID for st.async.release");
2609 }
2610
2611 Value = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i16, Value);
2612
2613 // The `.mmio` variant has no multimem form and therefore no `isMultimem`
2614 // operand.
2615 if (IntrinsicID == Intrinsic::nvvm_st_async_mmio_sys) {
2616 SDValue Ops[] = {N->getOperand(0), DestAddr, Value};
2617 return DAG.getNode(OpCode, DL, MVT::Other, Ops);
2618 }
2619
2620 SDValue IsMultimem =
2621 DAG.getTargetConstant(N->getConstantOperandVal(4), DL, MVT::i1);
2622 SDValue Ops[] = {N->getOperand(0), DestAddr, Value, IsMultimem};
2623 return DAG.getNode(OpCode, DL, MVT::Other, Ops);
2624 }
2625
2627 Fn,
2628 Twine("unsupported argument type ") + llvm::EVT(ValueVT).getEVTString() +
2629 " for " + llvm::Intrinsic::getName(IntrinsicID) + " intrinsic",
2630 DiagnosticLocation(DL.getDebugLoc())));
2631 return Op.getOperand(0); // Return only the chain
2632}
2633
2634static unsigned getTcgen05MMADisableOutputLane(unsigned IID) {
2635 switch (IID) {
2636 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg1:
2637 return NVPTXISD::TCGEN05_MMA_SHARED_DISABLE_OUTPUT_LANE_CG1;
2638 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg2:
2639 return NVPTXISD::TCGEN05_MMA_SHARED_DISABLE_OUTPUT_LANE_CG2;
2640 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg1:
2641 return NVPTXISD::TCGEN05_MMA_SHARED_SCALE_D_DISABLE_OUTPUT_LANE_CG1;
2642 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg2:
2643 return NVPTXISD::TCGEN05_MMA_SHARED_SCALE_D_DISABLE_OUTPUT_LANE_CG2;
2644 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1:
2645 return NVPTXISD::TCGEN05_MMA_TENSOR_DISABLE_OUTPUT_LANE_CG1;
2646 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2:
2647 return NVPTXISD::TCGEN05_MMA_TENSOR_DISABLE_OUTPUT_LANE_CG2;
2648 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1:
2649 return NVPTXISD::TCGEN05_MMA_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG1;
2650 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2:
2651 return NVPTXISD::TCGEN05_MMA_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG2;
2652 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1_ashift:
2653 return NVPTXISD::TCGEN05_MMA_TENSOR_DISABLE_OUTPUT_LANE_CG1_ASHIFT;
2654 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2_ashift:
2655 return NVPTXISD::TCGEN05_MMA_TENSOR_DISABLE_OUTPUT_LANE_CG2_ASHIFT;
2656 case Intrinsic::
2657 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1_ashift:
2658 return NVPTXISD::TCGEN05_MMA_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG1_ASHIFT;
2659 case Intrinsic::
2660 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2_ashift:
2661 return NVPTXISD::TCGEN05_MMA_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG2_ASHIFT;
2662 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg1:
2663 return NVPTXISD::TCGEN05_MMA_SP_SHARED_DISABLE_OUTPUT_LANE_CG1;
2664 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg2:
2665 return NVPTXISD::TCGEN05_MMA_SP_SHARED_DISABLE_OUTPUT_LANE_CG2;
2666 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg1:
2667 return NVPTXISD::TCGEN05_MMA_SP_SHARED_SCALE_D_DISABLE_OUTPUT_LANE_CG1;
2668 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg2:
2669 return NVPTXISD::TCGEN05_MMA_SP_SHARED_SCALE_D_DISABLE_OUTPUT_LANE_CG2;
2670 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1:
2671 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_DISABLE_OUTPUT_LANE_CG1;
2672 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2:
2673 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_DISABLE_OUTPUT_LANE_CG2;
2674 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1_ashift:
2675 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_DISABLE_OUTPUT_LANE_CG1_ASHIFT;
2676 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2_ashift:
2677 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_DISABLE_OUTPUT_LANE_CG2_ASHIFT;
2678 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1:
2679 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG1;
2680 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2:
2681 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG2;
2682 case Intrinsic::
2683 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1_ashift:
2684 return NVPTXISD::
2685 TCGEN05_MMA_SP_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG1_ASHIFT;
2686 case Intrinsic::
2687 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2_ashift:
2688 return NVPTXISD::
2689 TCGEN05_MMA_SP_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG2_ASHIFT;
2690 case Intrinsic::
2691 nvvm_tcgen05_mma_shared_f8f6f4_disable_output_lane_cg1_decompress_b:
2692 return NVPTXISD::TCGEN05_MMA_SHARED_DISABLE_OUTPUT_LANE_CG1_DECOMPRESS_B;
2693 case Intrinsic::
2694 nvvm_tcgen05_mma_shared_f8f6f4_disable_output_lane_cg2_decompress_b:
2695 return NVPTXISD::TCGEN05_MMA_SHARED_DISABLE_OUTPUT_LANE_CG2_DECOMPRESS_B;
2696 case Intrinsic::
2697 nvvm_tcgen05_mma_tensor_f8f6f4_disable_output_lane_cg1_decompress_b:
2698 return NVPTXISD::TCGEN05_MMA_TENSOR_DISABLE_OUTPUT_LANE_CG1_DECOMPRESS_B;
2699 case Intrinsic::
2700 nvvm_tcgen05_mma_tensor_f8f6f4_disable_output_lane_cg2_decompress_b:
2701 return NVPTXISD::TCGEN05_MMA_TENSOR_DISABLE_OUTPUT_LANE_CG2_DECOMPRESS_B;
2702 };
2703 llvm_unreachable("unhandled tcgen05.mma.disable_output_lane intrinsic");
2704}
2705
2707 SDNode *N = Op.getNode();
2708 SDLoc DL(N);
2709 unsigned IID = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2710
2712 // split the vector argument
2713 for (size_t I = 0; I < N->getNumOperands(); I++) {
2714 if (I == 1)
2715 continue; // skip IID
2716 SDValue Val = N->getOperand(I);
2717 EVT ValVT = Val.getValueType();
2718 if (ValVT.isVector()) {
2719 EVT EltVT = ValVT.getVectorElementType();
2720 for (unsigned J = 0, NElts = ValVT.getVectorNumElements(); J < NElts; J++)
2721 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Val,
2722 DAG.getIntPtrConstant(J, DL)));
2723 } else
2724 Ops.push_back(Val);
2725 }
2726
2728 SDValue Tcgen05MMANode = DAG.getMemIntrinsicNode(
2729 getTcgen05MMADisableOutputLane(IID), DL, N->getVTList(), Ops,
2730 MemSD->getMemoryVT(), MemSD->getMemOperand());
2731
2732 return Tcgen05MMANode;
2733}
2734
2735// Lower vector return type of tcgen05.ld intrinsics
2736static std::optional<std::pair<SDValue, SDValue>>
2737lowerTcgen05Ld(SDNode *N, SelectionDAG &DAG, bool HasOffset = false) {
2738 SDLoc DL(N);
2739 EVT ResVT = N->getValueType(0);
2740 if (!ResVT.isVector())
2741 return {}; // already legalized.
2742
2743 const unsigned NumElts = ResVT.getVectorNumElements();
2744
2745 // Create the return type of the instructions
2746 SmallVector<EVT, 5> ListVTs;
2747 for (unsigned i = 0; i < NumElts; ++i)
2748 ListVTs.push_back(MVT::i32);
2749
2750 ListVTs.push_back(N->getValueType(1)); // Chain
2751
2752 SDVTList ResVTs = DAG.getVTList(ListVTs);
2753
2754 SmallVector<SDValue, 8> Ops{N->getOperand(0), N->getOperand(1),
2755 N->getOperand(2)};
2756
2757 if (HasOffset) {
2758 Ops.push_back(N->getOperand(3)); // offset
2759 Ops.push_back(N->getOperand(4)); // Pack flag
2760 } else
2761 Ops.push_back(N->getOperand(3)); // Pack flag
2762
2764 SDValue NewNode =
2766 MemSD->getMemoryVT(), MemSD->getMemOperand());
2767
2768 // split the vector result
2769 SmallVector<SDValue, 4> ScalarRes;
2770 for (unsigned i = 0; i < NumElts; ++i) {
2771 SDValue Res = NewNode.getValue(i);
2772 ScalarRes.push_back(Res);
2773 }
2774
2775 SDValue Chain = NewNode.getValue(NumElts);
2776 SDValue BuildVector = DAG.getNode(ISD::BUILD_VECTOR, DL, ResVT, ScalarRes);
2777 return {{BuildVector, Chain}};
2778}
2779
2781 unsigned Val) {
2782 SDNode *N = Op.getNode();
2783 SDLoc DL(N);
2784
2785 const Function &Fn = DAG.getMachineFunction().getFunction();
2786
2787 unsigned AS = 0;
2788 if (auto *MemN = dyn_cast<MemIntrinsicSDNode>(N))
2789 AS = MemN->getAddressSpace();
2790 Type *PtrTy = PointerType::get(*DAG.getContext(), AS);
2792
2794 Fn,
2795 "Intrinsic " +
2796 Intrinsic::getName(N->getConstantOperandVal(1), {PtrTy}, M) +
2797 " with value " + Twine(Val) +
2798 " is not supported on the given target.",
2799 DL.getDebugLoc()));
2800 return Op.getOperand(0);
2801}
2802
2804 SDNode *N = Op.getNode();
2805 SDLoc DL(N);
2806
2807 // immediate argument representing elemtype
2808 unsigned Val = N->getConstantOperandVal(3);
2809
2811 Val))
2812 return reportInvalidTensormapReplaceUsage(Op, DAG, Val);
2813
2814 return Op;
2815}
2816
2818 SDNode *N = Op.getNode();
2819 SDLoc DL(N);
2820
2821 // immediate argument representing swizzle mode
2822 unsigned Val = N->getConstantOperandVal(3);
2823
2825 Val))
2826 return reportInvalidTensormapReplaceUsage(Op, DAG, Val);
2827
2828 return Op;
2829}
2830
2832 SDNode *N = Op.getNode();
2833 SDValue Intrin = N->getOperand(1);
2834
2835 // Get the intrinsic ID
2836 unsigned IntrinNo = cast<ConstantSDNode>(Intrin.getNode())->getZExtValue();
2837 switch (IntrinNo) {
2838 default:
2839 break;
2840 case Intrinsic::nvvm_st_async:
2841 return lowerStAsyncWithMbarrier(Op, DAG);
2842 case Intrinsic::nvvm_st_async_sys:
2843 case Intrinsic::nvvm_st_async_gpu:
2844 case Intrinsic::nvvm_st_async_mmio_sys:
2845 return lowerStAsyncRelease(Op, DAG);
2846
2847 case Intrinsic::nvvm_tcgen05_st_16x64b_x1:
2848 case Intrinsic::nvvm_tcgen05_st_16x64b_x2:
2849 case Intrinsic::nvvm_tcgen05_st_16x64b_x4:
2850 case Intrinsic::nvvm_tcgen05_st_16x64b_x8:
2851 case Intrinsic::nvvm_tcgen05_st_16x64b_x16:
2852 case Intrinsic::nvvm_tcgen05_st_16x64b_x32:
2853 case Intrinsic::nvvm_tcgen05_st_16x64b_x128:
2854 case Intrinsic::nvvm_tcgen05_st_16x128b_x1:
2855 case Intrinsic::nvvm_tcgen05_st_16x128b_x2:
2856 case Intrinsic::nvvm_tcgen05_st_16x128b_x4:
2857 case Intrinsic::nvvm_tcgen05_st_16x128b_x8:
2858 case Intrinsic::nvvm_tcgen05_st_16x128b_x16:
2859 case Intrinsic::nvvm_tcgen05_st_16x128b_x32:
2860 case Intrinsic::nvvm_tcgen05_st_16x128b_x64:
2861 case Intrinsic::nvvm_tcgen05_st_16x256b_x1:
2862 case Intrinsic::nvvm_tcgen05_st_16x256b_x2:
2863 case Intrinsic::nvvm_tcgen05_st_16x256b_x4:
2864 case Intrinsic::nvvm_tcgen05_st_16x256b_x8:
2865 case Intrinsic::nvvm_tcgen05_st_16x256b_x16:
2866 case Intrinsic::nvvm_tcgen05_st_16x256b_x32:
2867 case Intrinsic::nvvm_tcgen05_st_32x32b_x1:
2868 case Intrinsic::nvvm_tcgen05_st_32x32b_x2:
2869 case Intrinsic::nvvm_tcgen05_st_32x32b_x4:
2870 case Intrinsic::nvvm_tcgen05_st_32x32b_x8:
2871 case Intrinsic::nvvm_tcgen05_st_32x32b_x16:
2872 case Intrinsic::nvvm_tcgen05_st_32x32b_x32:
2873 case Intrinsic::nvvm_tcgen05_st_16x64b_x64:
2874 case Intrinsic::nvvm_tcgen05_st_32x32b_x64:
2875 case Intrinsic::nvvm_tcgen05_st_32x32b_x128:
2876 return lowerTcgen05St(Op, DAG);
2877 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x1:
2878 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x2:
2879 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x4:
2880 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x8:
2881 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x16:
2882 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x32:
2883 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x64:
2884 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x128:
2885 return lowerTcgen05St(Op, DAG, /* hasOffset */ true);
2886 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg1:
2887 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg2:
2888 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg1:
2889 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg2:
2890 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg1:
2891 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg2:
2892 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg1:
2893 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg2:
2894 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1:
2895 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2:
2896 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1:
2897 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2:
2898 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1:
2899 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2:
2900 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1:
2901 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2:
2902 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1_ashift:
2903 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2_ashift:
2904 case Intrinsic::
2905 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1_ashift:
2906 case Intrinsic::
2907 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2_ashift:
2908 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1_ashift:
2909 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2_ashift:
2910 case Intrinsic::
2911 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1_ashift:
2912 case Intrinsic::
2913 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2_ashift:
2914 case Intrinsic::
2915 nvvm_tcgen05_mma_shared_f8f6f4_disable_output_lane_cg1_decompress_b:
2916 case Intrinsic::
2917 nvvm_tcgen05_mma_shared_f8f6f4_disable_output_lane_cg2_decompress_b:
2918 case Intrinsic::
2919 nvvm_tcgen05_mma_tensor_f8f6f4_disable_output_lane_cg1_decompress_b:
2920 case Intrinsic::
2921 nvvm_tcgen05_mma_tensor_f8f6f4_disable_output_lane_cg2_decompress_b:
2923 case Intrinsic::nvvm_tensormap_replace_elemtype:
2924 return lowerTensormapReplaceElemtype(Op, DAG);
2925 case Intrinsic::nvvm_tensormap_replace_swizzle_mode:
2927 }
2928 return Op;
2929}
2930
2932 SelectionDAG &DAG) {
2933
2934 SDNode *N = Op.getNode();
2935 if (N->getOperand(1).getValueType() != MVT::i128) {
2936 // return, if the operand is already lowered
2937 return SDValue();
2938 }
2939
2940 unsigned IID =
2941 cast<ConstantSDNode>(N->getOperand(0).getNode())->getZExtValue();
2942 auto Opcode = [&]() {
2943 switch (IID) {
2944 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_is_canceled:
2945 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_IS_CANCELED;
2946 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_x:
2947 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_X;
2948 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_y:
2949 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_Y;
2950 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_z:
2951 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_Z;
2952 default:
2953 llvm_unreachable("unsupported/unhandled intrinsic");
2954 }
2955 }();
2956
2957 SDLoc DL(N);
2958 SDValue TryCancelResponse = N->getOperand(1);
2959 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TryCancelResponse);
2960 SDValue TryCancelResponse0 =
2961 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, Cast,
2962 DAG.getIntPtrConstant(0, DL));
2963 SDValue TryCancelResponse1 =
2964 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, Cast,
2965 DAG.getIntPtrConstant(1, DL));
2966
2967 return DAG.getNode(Opcode, DL, N->getVTList(),
2968 {TryCancelResponse0, TryCancelResponse1});
2969}
2970
2972 SDNode *N = Op.getNode();
2973 SDLoc DL(N);
2974 SDValue F32Vec = N->getOperand(1);
2975 SDValue RBits = N->getOperand(2);
2976
2977 unsigned IntrinsicID = N->getConstantOperandVal(0);
2978
2979 // Extract the 4 float elements from the vector
2981 for (unsigned i = 0; i < 4; ++i)
2982 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, F32Vec,
2983 DAG.getIntPtrConstant(i, DL)));
2984
2986
2987 auto [OpCode, RetTy, CvtModeFlag] =
2988 [&]() -> std::tuple<unsigned, MVT::SimpleValueType, uint32_t> {
2989 switch (IntrinsicID) {
2990 case Intrinsic::nvvm_f32x4_to_e4m3x4_rs_relu_satfinite:
2991 return {NVPTXISD::CVT_E4M3X4_F32X4_RS_SF, MVT::v4i8,
2992 CvtMode::RS | CvtMode::RELU_FLAG};
2993 case Intrinsic::nvvm_f32x4_to_e4m3x4_rs_satfinite:
2994 return {NVPTXISD::CVT_E4M3X4_F32X4_RS_SF, MVT::v4i8, CvtMode::RS};
2995 case Intrinsic::nvvm_f32x4_to_e5m2x4_rs_relu_satfinite:
2996 return {NVPTXISD::CVT_E5M2X4_F32X4_RS_SF, MVT::v4i8,
2997 CvtMode::RS | CvtMode::RELU_FLAG};
2998 case Intrinsic::nvvm_f32x4_to_e5m2x4_rs_satfinite:
2999 return {NVPTXISD::CVT_E5M2X4_F32X4_RS_SF, MVT::v4i8, CvtMode::RS};
3000 case Intrinsic::nvvm_f32x4_to_e2m3x4_rs_relu_satfinite:
3001 return {NVPTXISD::CVT_E2M3X4_F32X4_RS_SF, MVT::v4i8,
3002 CvtMode::RS | CvtMode::RELU_FLAG};
3003 case Intrinsic::nvvm_f32x4_to_e2m3x4_rs_satfinite:
3004 return {NVPTXISD::CVT_E2M3X4_F32X4_RS_SF, MVT::v4i8, CvtMode::RS};
3005 case Intrinsic::nvvm_f32x4_to_e3m2x4_rs_relu_satfinite:
3006 return {NVPTXISD::CVT_E3M2X4_F32X4_RS_SF, MVT::v4i8,
3007 CvtMode::RS | CvtMode::RELU_FLAG};
3008 case Intrinsic::nvvm_f32x4_to_e3m2x4_rs_satfinite:
3009 return {NVPTXISD::CVT_E3M2X4_F32X4_RS_SF, MVT::v4i8, CvtMode::RS};
3010 case Intrinsic::nvvm_f32x4_to_e2m1x4_rs_relu_satfinite:
3011 return {NVPTXISD::CVT_E2M1X4_F32X4_RS_SF, MVT::i16,
3012 CvtMode::RS | CvtMode::RELU_FLAG};
3013 case Intrinsic::nvvm_f32x4_to_e2m1x4_rs_satfinite:
3014 return {NVPTXISD::CVT_E2M1X4_F32X4_RS_SF, MVT::i16, CvtMode::RS};
3015 default:
3016 llvm_unreachable("unsupported/unhandled intrinsic");
3017 }
3018 }();
3019
3020 Ops.push_back(RBits);
3021 Ops.push_back(DAG.getConstant(CvtModeFlag, DL, MVT::i32));
3022
3023 return DAG.getNode(OpCode, DL, RetTy, Ops);
3024}
3025
3027 const unsigned Mode = [&]() {
3028 switch (Op->getConstantOperandVal(0)) {
3029 case Intrinsic::nvvm_prmt:
3031 case Intrinsic::nvvm_prmt_b4e:
3033 case Intrinsic::nvvm_prmt_ecl:
3035 case Intrinsic::nvvm_prmt_ecr:
3037 case Intrinsic::nvvm_prmt_f4e:
3039 case Intrinsic::nvvm_prmt_rc16:
3041 case Intrinsic::nvvm_prmt_rc8:
3043 default:
3044 llvm_unreachable("unsupported/unhandled intrinsic");
3045 }
3046 }();
3047 SDLoc DL(Op);
3048 SDValue A = Op->getOperand(1);
3049 SDValue B = Op.getNumOperands() == 4 ? Op.getOperand(2)
3050 : DAG.getConstant(0, DL, MVT::i32);
3051 SDValue Selector = (Op->op_end() - 1)->get();
3052 return getPRMT(A, B, Selector, DL, DAG, Mode);
3053}
3054
3055#define TCGEN05_LD_RED_INTR(SHAPE, NUM, TYPE) \
3056 Intrinsic::nvvm_tcgen05_ld_red_##SHAPE##_x##NUM##_##TYPE
3057
3058#define TCGEN05_LD_RED_INST(SHAPE, NUM, TYPE) \
3059 NVPTXISD::TCGEN05_LD_RED_##SHAPE##_X##NUM##_##TYPE
3060
3061static unsigned getTcgen05LdRedID(Intrinsic::ID IID) {
3062 switch (IID) {
3063 case TCGEN05_LD_RED_INTR(32x32b, 2, f32):
3064 return TCGEN05_LD_RED_INST(32x32b, 2, F32);
3065 case TCGEN05_LD_RED_INTR(32x32b, 4, f32):
3066 return TCGEN05_LD_RED_INST(32x32b, 4, F32);
3067 case TCGEN05_LD_RED_INTR(32x32b, 8, f32):
3068 return TCGEN05_LD_RED_INST(32x32b, 8, F32);
3069 case TCGEN05_LD_RED_INTR(32x32b, 16, f32):
3070 return TCGEN05_LD_RED_INST(32x32b, 16, F32);
3071 case TCGEN05_LD_RED_INTR(32x32b, 32, f32):
3072 return TCGEN05_LD_RED_INST(32x32b, 32, F32);
3073 case TCGEN05_LD_RED_INTR(32x32b, 64, f32):
3074 return TCGEN05_LD_RED_INST(32x32b, 64, F32);
3075 case TCGEN05_LD_RED_INTR(32x32b, 128, f32):
3076 return TCGEN05_LD_RED_INST(32x32b, 128, F32);
3077 case TCGEN05_LD_RED_INTR(16x32bx2, 2, f32):
3078 return TCGEN05_LD_RED_INST(16x32bx2, 2, F32);
3079 case TCGEN05_LD_RED_INTR(16x32bx2, 4, f32):
3080 return TCGEN05_LD_RED_INST(16x32bx2, 4, F32);
3081 case TCGEN05_LD_RED_INTR(16x32bx2, 8, f32):
3082 return TCGEN05_LD_RED_INST(16x32bx2, 8, F32);
3083 case TCGEN05_LD_RED_INTR(16x32bx2, 16, f32):
3084 return TCGEN05_LD_RED_INST(16x32bx2, 16, F32);
3085 case TCGEN05_LD_RED_INTR(16x32bx2, 32, f32):
3086 return TCGEN05_LD_RED_INST(16x32bx2, 32, F32);
3087 case TCGEN05_LD_RED_INTR(16x32bx2, 64, f32):
3088 return TCGEN05_LD_RED_INST(16x32bx2, 64, F32);
3089 case TCGEN05_LD_RED_INTR(16x32bx2, 128, f32):
3090 return TCGEN05_LD_RED_INST(16x32bx2, 128, F32);
3091 case TCGEN05_LD_RED_INTR(32x32b, 2, i32):
3092 return TCGEN05_LD_RED_INST(32x32b, 2, I32);
3093 case TCGEN05_LD_RED_INTR(32x32b, 4, i32):
3094 return TCGEN05_LD_RED_INST(32x32b, 4, I32);
3095 case TCGEN05_LD_RED_INTR(32x32b, 8, i32):
3096 return TCGEN05_LD_RED_INST(32x32b, 8, I32);
3097 case TCGEN05_LD_RED_INTR(32x32b, 16, i32):
3098 return TCGEN05_LD_RED_INST(32x32b, 16, I32);
3099 case TCGEN05_LD_RED_INTR(32x32b, 32, i32):
3100 return TCGEN05_LD_RED_INST(32x32b, 32, I32);
3101 case TCGEN05_LD_RED_INTR(32x32b, 64, i32):
3102 return TCGEN05_LD_RED_INST(32x32b, 64, I32);
3103 case TCGEN05_LD_RED_INTR(32x32b, 128, i32):
3104 return TCGEN05_LD_RED_INST(32x32b, 128, I32);
3105 case TCGEN05_LD_RED_INTR(16x32bx2, 2, i32):
3106 return TCGEN05_LD_RED_INST(16x32bx2, 2, I32);
3107 case TCGEN05_LD_RED_INTR(16x32bx2, 4, i32):
3108 return TCGEN05_LD_RED_INST(16x32bx2, 4, I32);
3109 case TCGEN05_LD_RED_INTR(16x32bx2, 8, i32):
3110 return TCGEN05_LD_RED_INST(16x32bx2, 8, I32);
3111 case TCGEN05_LD_RED_INTR(16x32bx2, 16, i32):
3112 return TCGEN05_LD_RED_INST(16x32bx2, 16, I32);
3113 case TCGEN05_LD_RED_INTR(16x32bx2, 32, i32):
3114 return TCGEN05_LD_RED_INST(16x32bx2, 32, I32);
3115 case TCGEN05_LD_RED_INTR(16x32bx2, 64, i32):
3116 return TCGEN05_LD_RED_INST(16x32bx2, 64, I32);
3117 case TCGEN05_LD_RED_INTR(16x32bx2, 128, i32):
3118 return TCGEN05_LD_RED_INST(16x32bx2, 128, I32);
3119 default:
3120 llvm_unreachable("Invalid tcgen05.ld.red intrinsic ID");
3121 }
3122}
3123
3124// Lower vector return type of tcgen05.ld intrinsics
3125static std::optional<std::tuple<SDValue, SDValue, SDValue>>
3127 SDLoc DL(N);
3128 EVT ResVT = N->getValueType(0);
3129 if (!ResVT.isVector())
3130 return {}; // already legalized.
3131
3132 const unsigned NumElts = ResVT.getVectorNumElements();
3133
3134 // Create the return type of the instructions
3135 // +1 represents the reduction value
3136 SmallVector<EVT, 132> ListVTs{
3137 NumElts + 1,
3138 ResVT.getVectorElementType().isFloatingPoint() ? MVT::f32 : MVT::i32};
3139
3140 ListVTs.push_back(MVT::Other); // Chain
3141
3142 SDVTList ResVTs = DAG.getVTList(ListVTs);
3143
3144 // Prepare the Operands
3145 SmallVector<SDValue, 8> Ops{N->getOperand(0)}; // Chain
3146
3147 // skip IID at index 1
3148 for (unsigned i = 2; i < N->getNumOperands(); i++)
3149 Ops.push_back(N->getOperand(i));
3150
3151 unsigned IID = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
3153 SDValue NewNode =
3154 DAG.getMemIntrinsicNode(getTcgen05LdRedID(IID), DL, ResVTs, Ops,
3155 MemSD->getMemoryVT(), MemSD->getMemOperand());
3156
3157 // Split vector result
3158 SmallVector<SDValue, 132> ScalarRes;
3159 for (unsigned i = 0; i < NumElts; ++i) {
3160 SDValue Res = NewNode.getValue(i);
3161 ScalarRes.push_back(Res);
3162 }
3163
3164 SDValue BuildVector = DAG.getNode(ISD::BUILD_VECTOR, DL, ResVT, ScalarRes);
3165 SDValue RedResult = NewNode.getValue(NumElts);
3166 SDValue Chain = NewNode.getValue(NumElts + 1);
3167 return {{BuildVector, RedResult, Chain}};
3168}
3169
3171 switch (Op->getConstantOperandVal(1)) {
3172 default:
3173 return Op;
3174
3175 // These tcgen05 intrinsics return a v2i32, which is legal, so we have to
3176 // lower them through LowerOperation() instead of ReplaceNodeResults().
3177 case Intrinsic::nvvm_tcgen05_ld_16x64b_x2:
3178 case Intrinsic::nvvm_tcgen05_ld_16x128b_x1:
3179 case Intrinsic::nvvm_tcgen05_ld_32x32b_x2:
3180 if (auto Res = lowerTcgen05Ld(Op.getNode(), DAG))
3181 return DAG.getMergeValues({Res->first, Res->second}, SDLoc(Op));
3182 return SDValue();
3183
3184 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x2:
3185 if (auto Res = lowerTcgen05Ld(Op.getNode(), DAG, /*HasOffset=*/true))
3186 return DAG.getMergeValues({Res->first, Res->second}, SDLoc(Op));
3187 return SDValue();
3188
3189 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x2_f32:
3190 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x2_i32:
3191 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x2_f32:
3192 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x2_i32:
3193 if (auto Res = lowerTcgen05LdRed(Op.getNode(), DAG))
3194 return DAG.getMergeValues(
3195 {std::get<0>(*Res), std::get<1>(*Res), std::get<2>(*Res)}, SDLoc(Op));
3196 return SDValue();
3197 }
3198}
3199
3201 switch (Op->getConstantOperandVal(0)) {
3202 default:
3203 return Op;
3204 case Intrinsic::nvvm_prmt:
3205 case Intrinsic::nvvm_prmt_b4e:
3206 case Intrinsic::nvvm_prmt_ecl:
3207 case Intrinsic::nvvm_prmt_ecr:
3208 case Intrinsic::nvvm_prmt_f4e:
3209 case Intrinsic::nvvm_prmt_rc16:
3210 case Intrinsic::nvvm_prmt_rc8:
3211 return lowerPrmtIntrinsic(Op, DAG);
3212 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_is_canceled:
3213 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_x:
3214 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_y:
3215 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_z:
3217 case Intrinsic::nvvm_f32x4_to_e4m3x4_rs_satfinite:
3218 case Intrinsic::nvvm_f32x4_to_e4m3x4_rs_relu_satfinite:
3219 case Intrinsic::nvvm_f32x4_to_e5m2x4_rs_satfinite:
3220 case Intrinsic::nvvm_f32x4_to_e5m2x4_rs_relu_satfinite:
3221 case Intrinsic::nvvm_f32x4_to_e2m3x4_rs_satfinite:
3222 case Intrinsic::nvvm_f32x4_to_e2m3x4_rs_relu_satfinite:
3223 case Intrinsic::nvvm_f32x4_to_e3m2x4_rs_satfinite:
3224 case Intrinsic::nvvm_f32x4_to_e3m2x4_rs_relu_satfinite:
3225 case Intrinsic::nvvm_f32x4_to_e2m1x4_rs_satfinite:
3226 case Intrinsic::nvvm_f32x4_to_e2m1x4_rs_relu_satfinite:
3227 return lowerCvtRSIntrinsics(Op, DAG);
3228 }
3229}
3230
3231// In PTX 64-bit CTLZ and CTPOP are supported, but they return a 32-bit value.
3232// Lower these into a node returning the correct type which is zero-extended
3233// back to the correct size.
3235 SDValue V = Op->getOperand(0);
3236 assert(V.getValueType() == MVT::i64 &&
3237 "Unexpected CTLZ/CTPOP type to legalize");
3238
3239 SDLoc DL(Op);
3240 SDValue CT = DAG.getNode(Op->getOpcode(), DL, MVT::i32, V);
3241 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, CT, SDNodeFlags::NonNeg);
3242}
3243
3245 unsigned Opcode, SelectionDAG &DAG) {
3246 assert(A.getValueType() == MVT::i64 && B.getValueType() == MVT::i64);
3247
3248 const auto *AmtConst = dyn_cast<ConstantSDNode>(ShiftAmount);
3249 if (!AmtConst)
3250 return SDValue();
3251 const auto Amt = AmtConst->getZExtValue() & 63;
3252
3253 SDValue UnpackA =
3254 DAG.getNode(NVPTXISD::UNPACK_VECTOR, DL, {MVT::i32, MVT::i32}, A);
3255 SDValue UnpackB =
3256 DAG.getNode(NVPTXISD::UNPACK_VECTOR, DL, {MVT::i32, MVT::i32}, B);
3257
3258 // Arch is Little endiain: 0 = low bits, 1 = high bits
3259 SDValue ALo = UnpackA.getValue(0);
3260 SDValue AHi = UnpackA.getValue(1);
3261 SDValue BLo = UnpackB.getValue(0);
3262 SDValue BHi = UnpackB.getValue(1);
3263
3264 // The bitfeild consists of { AHi : ALo : BHi : BLo }
3265 //
3266 // * FSHL, Amt < 32 - The window will contain { AHi : ALo : BHi }
3267 // * FSHL, Amt >= 32 - The window will contain { ALo : BHi : BLo }
3268 // * FSHR, Amt < 32 - The window will contain { ALo : BHi : BLo }
3269 // * FSHR, Amt >= 32 - The window will contain { AHi : ALo : BHi }
3270 //
3271 // Note that Amt = 0 and Amt = 32 are special cases where 32-bit funnel shifts
3272 // are not needed at all. Amt = 0 is a no-op producing either A or B depending
3273 // on the direction. Amt = 32 can be implemented by a packing and unpacking
3274 // move to select and arrange the 32bit values. For simplicity, these cases
3275 // are not handled here explicitly and instead we rely on DAGCombiner to
3276 // remove the no-op funnel shifts we insert.
3277 auto [High, Mid, Low] = ((Opcode == ISD::FSHL) == (Amt < 32))
3278 ? std::make_tuple(AHi, ALo, BHi)
3279 : std::make_tuple(ALo, BHi, BLo);
3280
3281 SDValue NewAmt = DAG.getConstant(Amt & 31, DL, MVT::i32);
3282 SDValue RHi = DAG.getNode(Opcode, DL, MVT::i32, {High, Mid, NewAmt});
3283 SDValue RLo = DAG.getNode(Opcode, DL, MVT::i32, {Mid, Low, NewAmt});
3284
3285 return DAG.getNode(NVPTXISD::BUILD_VECTOR, DL, MVT::i64, {RLo, RHi});
3286}
3287
3289 return expandFSH64(Op->getOperand(0), Op->getOperand(1), Op->getOperand(2),
3290 SDLoc(Op), Op->getOpcode(), DAG);
3291}
3292
3294 unsigned Opcode = Op->getOpcode() == ISD::ROTL ? ISD::FSHL : ISD::FSHR;
3295 return expandFSH64(Op->getOperand(0), Op->getOperand(0), Op->getOperand(1),
3296 SDLoc(Op), Opcode, DAG);
3297}
3298
3300 // Lower (frem x, y) into (sub x, (mul (ftrunc (div x, y)) y)),
3301 // i.e. "poor man's fmod()". When y is infinite, x is returned. This matches
3302 // the semantics of LLVM's frem.
3303 SDLoc DL(Op);
3304 SDValue X = Op->getOperand(0);
3305 SDValue Y = Op->getOperand(1);
3306 EVT Ty = Op.getValueType();
3307 SDNodeFlags Flags = Op->getFlags();
3308
3309 SDValue Div = DAG.getNode(ISD::FDIV, DL, Ty, X, Y, Flags);
3310 SDValue Trunc = DAG.getNode(ISD::FTRUNC, DL, Ty, Div, Flags);
3311 SDValue Mul = DAG.getNode(ISD::FMUL, DL, Ty, Trunc, Y,
3313 SDValue Sub = DAG.getNode(ISD::FSUB, DL, Ty, X, Mul,
3315
3316 if (Flags.hasNoInfs())
3317 return Sub;
3318
3319 // If Y is infinite, return X
3320 SDValue AbsY = DAG.getNode(ISD::FABS, DL, Ty, Y);
3321 SDValue Inf =
3322 DAG.getConstantFP(APFloat::getInf(Ty.getFltSemantics()), DL, Ty);
3323 SDValue IsInf = DAG.getSetCC(DL, MVT::i1, AbsY, Inf, ISD::SETEQ);
3324 return DAG.getSelect(DL, Ty, IsInf, X, Sub);
3325}
3326
3328 assert(Op.getValueType() == MVT::i1 && "Custom lowering enabled only for i1");
3329
3330 SDValue Cond = Op->getOperand(0);
3331 SDValue TrueVal = Op->getOperand(1);
3332 SDValue FalseVal = Op->getOperand(2);
3333 SDLoc DL(Op);
3334
3335 // If both operands are truncated, we push the select through the truncates.
3336 if (TrueVal.getOpcode() == ISD::TRUNCATE &&
3337 FalseVal.getOpcode() == ISD::TRUNCATE) {
3338 TrueVal = TrueVal.getOperand(0);
3339 FalseVal = FalseVal.getOperand(0);
3340
3341 EVT VT = TrueVal.getSimpleValueType().bitsLE(FalseVal.getSimpleValueType())
3342 ? TrueVal.getValueType()
3343 : FalseVal.getValueType();
3344 TrueVal = DAG.getAnyExtOrTrunc(TrueVal, DL, VT);
3345 FalseVal = DAG.getAnyExtOrTrunc(FalseVal, DL, VT);
3346 SDValue Select = DAG.getSelect(DL, VT, Cond, TrueVal, FalseVal);
3347 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Select);
3348 }
3349
3350 // Otherwise, expand the select into a series of logical operations. These
3351 // often can be folded into other operations either by us or ptxas.
3352 TrueVal = DAG.getFreeze(TrueVal);
3353 FalseVal = DAG.getFreeze(FalseVal);
3354 SDValue And1 = DAG.getNode(ISD::AND, DL, MVT::i1, Cond, TrueVal);
3355 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
3356 SDValue And2 = DAG.getNode(ISD::AND, DL, MVT::i1, NotCond, FalseVal);
3357 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i1, And1, And2);
3358 return Or;
3359}
3360
3362 SDNode *N = Op.getNode();
3363
3364 SDValue Chain = N->getOperand(0);
3365 SDValue Val = N->getOperand(1);
3366 SDValue BasePtr = N->getOperand(2);
3367 SDValue Offset = N->getOperand(3);
3368 SDValue Mask = N->getOperand(4);
3369
3370 SDLoc DL(N);
3371 EVT ValVT = Val.getValueType();
3372 MemSDNode *MemSD = cast<MemSDNode>(N);
3373 assert(ValVT.isVector() && "Masked vector store must have vector type");
3374 assert(MemSD->getAlign() >= DAG.getEVTAlign(ValVT) &&
3375 "Unexpected alignment for masked store");
3376
3377 unsigned Opcode = 0;
3378 switch (ValVT.getSimpleVT().SimpleTy) {
3379 default:
3380 llvm_unreachable("Unexpected masked vector store type");
3381 case MVT::v4i64:
3382 case MVT::v4f64: {
3383 Opcode = NVPTXISD::StoreV4;
3384 break;
3385 }
3386 case MVT::v8i32:
3387 case MVT::v8f32: {
3388 Opcode = NVPTXISD::StoreV8;
3389 break;
3390 }
3391 }
3392
3394
3395 // Construct the new SDNode. First operand is the chain.
3396 Ops.push_back(Chain);
3397
3398 // The next N operands are the values to store. Encode the mask into the
3399 // values using the sentinel register 0 to represent a masked-off element.
3400 assert(Mask.getValueType().isVector() &&
3401 Mask.getValueType().getVectorElementType() == MVT::i1 &&
3402 "Mask must be a vector of i1");
3403 assert(Mask.getOpcode() == ISD::BUILD_VECTOR &&
3404 "Mask expected to be a BUILD_VECTOR");
3405 assert(Mask.getValueType().getVectorNumElements() ==
3406 ValVT.getVectorNumElements() &&
3407 "Mask size must be the same as the vector size");
3408 for (auto [I, Op] : enumerate(Mask->ops())) {
3409 // Mask elements must be constants.
3410 if (Op.getNode()->getAsZExtVal() == 0) {
3411 // Append a sentinel register 0 to the Ops vector to represent a masked
3412 // off element, this will be handled in tablegen
3414 ValVT.getVectorElementType()));
3415 } else {
3416 // Extract the element from the vector to store
3417 SDValue ExtVal =
3419 Val, DAG.getIntPtrConstant(I, DL));
3420 Ops.push_back(ExtVal);
3421 }
3422 }
3423
3424 // Next, the pointer operand.
3425 Ops.push_back(BasePtr);
3426
3427 // Finally, the offset operand. We expect this to always be undef, and it will
3428 // be ignored in lowering, but to mirror the handling of the other vector
3429 // store instructions we include it in the new SDNode.
3430 assert(Offset.isUndef() && "Offset operand expected to be undef or poison");
3431 Ops.push_back(Offset);
3432
3433 SDValue NewSt =
3434 DAG.getMemIntrinsicNode(Opcode, DL, DAG.getVTList(MVT::Other), Ops,
3435 MemSD->getMemoryVT(), MemSD->getMemOperand());
3436
3437 return NewSt;
3438}
3439
3440SDValue
3442 switch (Op.getOpcode()) {
3443 case ISD::RETURNADDR:
3444 return SDValue();
3445 case ISD::FRAMEADDR:
3446 return SDValue();
3447 case ISD::ADDRSPACECAST:
3448 return LowerADDRSPACECAST(Op, DAG);
3450 return lowerIntrinsicWChain(Op, DAG);
3452 return lowerIntrinsicWOChain(Op, DAG);
3454 return lowerIntrinsicVoid(Op, DAG);
3455 case ISD::BUILD_VECTOR:
3456 return LowerBUILD_VECTOR(Op, DAG);
3457 case ISD::BITCAST:
3458 return LowerBITCAST(Op, DAG);
3460 return Op;
3462 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3464 return LowerINSERT_VECTOR_ELT(Op, DAG);
3466 return LowerVECTOR_SHUFFLE(Op, DAG);
3468 return LowerCONCAT_VECTORS(Op, DAG);
3473 return LowerVECREDUCE(Op, DAG);
3474 case ISD::STORE:
3475 return LowerSTORE(Op, DAG);
3476 case ISD::MSTORE: {
3477 assert(STI.has256BitVectorLoadStore(
3478 cast<MemSDNode>(Op.getNode())->getAddressSpace()) &&
3479 "Masked store vector not supported on subtarget.");
3480 return lowerMSTORE(Op, DAG);
3481 }
3482 case ISD::LOAD:
3483 return LowerLOAD(Op, DAG);
3484 case ISD::MLOAD:
3485 return LowerMLOAD(Op, DAG);
3486 case ISD::SHL_PARTS:
3487 return LowerShiftLeftParts(Op, DAG);
3488 case ISD::SRA_PARTS:
3489 case ISD::SRL_PARTS:
3490 return LowerShiftRightParts(Op, DAG);
3491 case ISD::SELECT:
3492 return lowerSELECT(Op, DAG);
3493 case ISD::FROUND:
3494 return LowerFROUND(Op, DAG);
3495 case ISD::FCOPYSIGN:
3496 return LowerFCOPYSIGN(Op, DAG);
3497 case ISD::SINT_TO_FP:
3498 case ISD::UINT_TO_FP:
3499 return LowerINT_TO_FP(Op, DAG);
3500 case ISD::FP_TO_SINT:
3501 case ISD::FP_TO_UINT:
3502 // fptosi/fptoui to i1 truncate toward zero, so the only defined results
3503 // are {0,-1} (signed) and {0,1} (unsigned); every other input results in
3504 // poison. Thus we can simply lower to `x <= -1.0` or `x >= 1.0`.
3505 if (Op.getValueType() == MVT::i1) {
3506 SDLoc DL(Op);
3507 SDValue X = Op.getOperand(0);
3508 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
3509 return DAG.getSetCC(
3510 DL, MVT::i1, X,
3511 DAG.getConstantFP(IsSigned ? -1.0 : 1.0, DL, X.getValueType()),
3512 IsSigned ? ISD::SETOLE : ISD::SETOGE);
3513 }
3514 return LowerFP_TO_INT(Op, DAG);
3515 case ISD::FP_ROUND:
3516 return LowerFP_ROUND(Op, DAG);
3517 case ISD::FP_EXTEND:
3518 return LowerFP_EXTEND(Op, DAG);
3519 case ISD::VAARG:
3520 return LowerVAARG(Op, DAG);
3521 case ISD::VASTART:
3522 return LowerVASTART(Op, DAG);
3523 case ISD::FSHL:
3524 case ISD::FSHR:
3525 return lowerFSH(Op, DAG);
3526 case ISD::ROTL:
3527 case ISD::ROTR:
3528 return lowerROT(Op, DAG);
3529 case ISD::ABS:
3531 case ISD::SMIN:
3532 case ISD::SMAX:
3533 case ISD::UMIN:
3534 case ISD::UMAX:
3535 case ISD::ADD:
3536 case ISD::SUB:
3537 case ISD::MUL:
3538 case ISD::SHL:
3539 case ISD::SREM:
3540 case ISD::UREM:
3541 return LowerVectorArith(Op, DAG);
3543 return LowerDYNAMIC_STACKALLOC(Op, DAG);
3544 case ISD::STACKRESTORE:
3545 return LowerSTACKRESTORE(Op, DAG);
3546 case ISD::STACKSAVE:
3547 return LowerSTACKSAVE(Op, DAG);
3548 case ISD::CopyToReg:
3549 return LowerCopyToReg_128(Op, DAG);
3550 case ISD::FADD:
3551 case ISD::FSUB:
3552 case ISD::FMUL:
3553 // Used only for bf16 on SM80, where we select fma for non-ftz operation
3554 return PromoteBinOpIfF32FTZ(Op, DAG);
3555 case ISD::CTPOP:
3556 case ISD::CTLZ:
3557 return lowerCTLZCTPOP(Op, DAG);
3558 case ISD::FREM:
3559 return lowerFREM(Op, DAG);
3560 case ISD::BSWAP:
3561 return lowerBSWAP(Op, DAG);
3562 default:
3563 llvm_unreachable("Custom lowering not defined for operation");
3564 }
3565}
3566
3567// This will prevent AsmPrinter from trying to print the jump tables itself.
3571
3572SDValue NVPTXTargetLowering::LowerADDRSPACECAST(SDValue Op,
3573 SelectionDAG &DAG) const {
3575 unsigned SrcAS = N->getSrcAddressSpace();
3576 unsigned DestAS = N->getDestAddressSpace();
3577 if (SrcAS != llvm::ADDRESS_SPACE_GENERIC &&
3578 DestAS != llvm::ADDRESS_SPACE_GENERIC) {
3579 // Shared and SharedCluster can be converted to each other through generic
3580 // space
3581 if ((SrcAS == llvm::ADDRESS_SPACE_SHARED &&
3584 DestAS == llvm::ADDRESS_SPACE_SHARED)) {
3585 SDLoc DL(Op.getNode());
3586 const MVT GenerictVT =
3588 SDValue GenericConversion = DAG.getAddrSpaceCast(
3589 DL, GenerictVT, Op.getOperand(0), SrcAS, ADDRESS_SPACE_GENERIC);
3590 SDValue SharedClusterConversion =
3591 DAG.getAddrSpaceCast(DL, Op.getValueType(), GenericConversion,
3592 ADDRESS_SPACE_GENERIC, DestAS);
3593 return SharedClusterConversion;
3594 }
3595
3596 return DAG.getUNDEF(Op.getValueType());
3597 }
3598
3599 return Op;
3600}
3601
3602// This function is almost a copy of SelectionDAG::expandVAArg().
3603// The only diff is that this one produces loads from local address space.
3604SDValue NVPTXTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3605 const TargetLowering *TLI = STI.getTargetLowering();
3606 SDLoc DL(Op);
3607
3608 SDNode *Node = Op.getNode();
3609 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3610 EVT VT = Node->getValueType(0);
3611 auto *Ty = VT.getTypeForEVT(*DAG.getContext());
3612 SDValue Tmp1 = Node->getOperand(0);
3613 SDValue Tmp2 = Node->getOperand(1);
3614 const MaybeAlign MA(Node->getConstantOperandVal(3));
3615
3616 SDValue VAListLoad = DAG.getLoad(TLI->getPointerTy(DAG.getDataLayout()), DL,
3617 Tmp1, Tmp2, MachinePointerInfo(V));
3618 SDValue VAList = VAListLoad;
3619
3620 if (MA && *MA > TLI->getMinStackArgumentAlignment()) {
3621 VAList = DAG.getNode(
3622 ISD::ADD, DL, VAList.getValueType(), VAList,
3623 DAG.getConstant(MA->value() - 1, DL, VAList.getValueType()));
3624
3625 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
3626 DAG.getSignedConstant(-(int64_t)MA->value(), DL,
3627 VAList.getValueType()));
3628 }
3629
3630 // Increment the pointer, VAList, to the next vaarg
3631 Tmp1 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
3633 DL, VAList.getValueType()));
3634
3635 // Store the incremented VAList to the legalized pointer
3636 Tmp1 = DAG.getStore(VAListLoad.getValue(1), DL, Tmp1, Tmp2,
3637 MachinePointerInfo(V));
3638
3639 const Value *SrcV = Constant::getNullValue(
3641
3642 // Load the actual argument out of the pointer VAList
3643 return DAG.getLoad(VT, DL, Tmp1, VAList, MachinePointerInfo(SrcV));
3644}
3645
3646SDValue NVPTXTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3647 const TargetLowering *TLI = STI.getTargetLowering();
3648 SDLoc DL(Op);
3649 EVT PtrVT = TLI->getPointerTy(DAG.getDataLayout());
3650
3651 // Store the address of unsized array <function>_vararg[] in the ap object.
3652 SDValue VAReg = getParamSymbolNode(DAG, /* vararg */ -1, PtrVT);
3653
3654 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3655 return DAG.getStore(Op.getOperand(0), DL, VAReg, Op.getOperand(1),
3656 MachinePointerInfo(SV));
3657}
3658
3659static std::pair<MemSDNode *, uint32_t>
3661 const NVPTXSubtarget &STI) {
3662 SDValue Chain = N->getOperand(0);
3663 SDValue BasePtr = N->getOperand(1);
3664 SDValue Mask = N->getOperand(3);
3665 [[maybe_unused]] SDValue Passthru = N->getOperand(4);
3666
3667 SDLoc DL(N);
3668 EVT ResVT = N->getValueType(0);
3669 assert(ResVT.isVector() && "Masked vector load must have vector type");
3670 // While we only expect poison passthru vectors as an input to the backend,
3671 // when the legalization framework splits a poison vector in half, it creates
3672 // two undef vectors, so we can technically expect those too.
3673 assert((Passthru.getOpcode() == ISD::POISON ||
3674 Passthru.getOpcode() == ISD::UNDEF) &&
3675 "Passthru operand expected to be poison or undef");
3676
3677 // Extract the mask and convert it to a uint32_t representing the used bytes
3678 // of the entire vector load
3679 uint32_t UsedBytesMask = 0;
3680 uint32_t ElementSizeInBits = ResVT.getVectorElementType().getSizeInBits();
3681 assert(ElementSizeInBits % 8 == 0 && "Unexpected element size");
3682 uint32_t ElementSizeInBytes = ElementSizeInBits / 8;
3683 uint32_t ElementMask = (1u << ElementSizeInBytes) - 1u;
3684
3685 for (SDValue Op : reverse(Mask->ops())) {
3686 // We technically only want to do this shift for every
3687 // iteration *but* the first, but in the first iteration UsedBytesMask is 0,
3688 // so this shift is a no-op.
3689 UsedBytesMask <<= ElementSizeInBytes;
3690
3691 // Mask elements must be constants.
3692 if (Op->getAsZExtVal() != 0)
3693 UsedBytesMask |= ElementMask;
3694 }
3695
3696 assert(UsedBytesMask != 0 && UsedBytesMask != UINT32_MAX &&
3697 "Unexpected masked load with elements masked all on or all off");
3698
3699 // Create a new load sd node to be handled normally by ReplaceLoadVector.
3700 MemSDNode *NewLD = cast<MemSDNode>(
3701 DAG.getLoad(ResVT, DL, Chain, BasePtr, N->getMemOperand()).getNode());
3702
3703 // If our subtarget does not support the used bytes mask pragma, "drop" the
3704 // mask by setting it to UINT32_MAX
3705 if (!STI.hasUsedBytesMaskPragma())
3706 UsedBytesMask = UINT32_MAX;
3707
3708 return {NewLD, UsedBytesMask};
3709}
3710
3711/// replaceLoadVector - Convert vector loads into multi-output scalar loads.
3712static std::optional<std::pair<SDValue, SDValue>>
3715 const EVT ResVT = LD->getValueType(0);
3716 const EVT MemVT = LD->getMemoryVT();
3717
3718 // If we're doing sign/zero extension as part of the load, avoid lowering to
3719 // a LoadV node. TODO: consider relaxing this restriction.
3720 if (ResVT != MemVT)
3721 return std::nullopt;
3722
3723 const auto NumEltsAndEltVT =
3724 getVectorLoweringShape(ResVT, STI, LD->getAddressSpace());
3725 if (!NumEltsAndEltVT)
3726 return std::nullopt;
3727 const auto [NumElts, EltVT] = NumEltsAndEltVT.value();
3728
3729 Align Alignment = LD->getAlign();
3730 const auto &TD = DAG.getDataLayout();
3731 Align PrefAlign = TD.getPrefTypeAlign(MemVT.getTypeForEVT(*DAG.getContext()));
3732 if (Alignment < PrefAlign) {
3733 // This load is not sufficiently aligned, so bail out and let this vector
3734 // load be scalarized. Note that we may still be able to emit smaller
3735 // vector loads. For example, if we are loading a <4 x float> with an
3736 // alignment of 8, this check will fail but the legalizer will try again
3737 // with 2 x <2 x float>, which will succeed with an alignment of 8.
3738 return std::nullopt;
3739 }
3740
3741 // If we have a masked load, convert it to a normal load now
3742 std::optional<uint32_t> UsedBytesMask = std::nullopt;
3743 if (LD->getOpcode() == ISD::MLOAD)
3744 std::tie(LD, UsedBytesMask) =
3746
3747 // Since LoadV2 is a target node, we cannot rely on DAG type legalization.
3748 // Therefore, we must ensure the type is legal. For i1 and i8, we set the
3749 // loaded type to i16 and propagate the "real" type as the memory type.
3750 const MVT LoadEltVT = (EltVT.getSizeInBits() < 16) ? MVT::i16 : EltVT;
3751
3752 unsigned Opcode;
3753 switch (NumElts) {
3754 default:
3755 return std::nullopt;
3756 case 2:
3757 Opcode = NVPTXISD::LoadV2;
3758 break;
3759 case 4:
3760 Opcode = NVPTXISD::LoadV4;
3761 break;
3762 case 8:
3763 Opcode = NVPTXISD::LoadV8;
3764 break;
3765 }
3766 auto ListVTs = SmallVector<EVT, 9>(NumElts, LoadEltVT);
3767 ListVTs.push_back(MVT::Other);
3768 SDVTList LdResVTs = DAG.getVTList(ListVTs);
3769
3770 SDLoc DL(LD);
3771
3772 // Copy regular operands
3773 SmallVector<SDValue, 8> OtherOps(LD->ops());
3774
3775 OtherOps.push_back(
3776 DAG.getConstant(UsedBytesMask.value_or(UINT32_MAX), DL, MVT::i32));
3777
3778 // The select routine does not have access to the LoadSDNode instance, so
3779 // pass along the extension information
3780 OtherOps.push_back(
3781 DAG.getIntPtrConstant(cast<LoadSDNode>(LD)->getExtensionType(), DL));
3782
3783 SDValue NewLD = DAG.getMemIntrinsicNode(Opcode, DL, LdResVTs, OtherOps, MemVT,
3784 LD->getMemOperand());
3785
3786 SmallVector<SDValue> ScalarRes;
3787 if (EltVT.isVector()) {
3789 assert(NumElts * EltVT.getVectorNumElements() ==
3790 ResVT.getVectorNumElements());
3791 // Generate EXTRACT_VECTOR_ELTs to split v2[i,f,bf]16/v4i8 subvectors back
3792 // into individual elements.
3793 for (const unsigned I : llvm::seq(NumElts)) {
3794 SDValue SubVector = NewLD.getValue(I);
3795 DAG.ExtractVectorElements(SubVector, ScalarRes);
3796 }
3797 } else {
3798 for (const unsigned I : llvm::seq(NumElts)) {
3799 SDValue Res = NewLD.getValue(I);
3800 if (LoadEltVT != EltVT)
3801 Res = DAG.getNode(ISD::TRUNCATE, DL, EltVT, Res);
3802 ScalarRes.push_back(Res);
3803 }
3804 }
3805
3806 SDValue LoadChain = NewLD.getValue(NumElts);
3807
3808 const MVT BuildVecVT =
3809 MVT::getVectorVT(EltVT.getScalarType(), ScalarRes.size());
3810 SDValue BuildVec = DAG.getBuildVector(BuildVecVT, DL, ScalarRes);
3811 SDValue LoadValue = DAG.getBitcast(ResVT, BuildVec);
3812
3813 return {{LoadValue, LoadChain}};
3814}
3815
3818 const NVPTXSubtarget &STI) {
3819 if (auto Res = replaceLoadVector(N, DAG, STI))
3820 Results.append({Res->first, Res->second});
3821}
3822
3824 const NVPTXSubtarget &STI) {
3825 if (auto Res = replaceLoadVector(N, DAG, STI))
3826 return DAG.getMergeValues({Res->first, Res->second}, SDLoc(N));
3827 return SDValue();
3828}
3829
3830// v = ld i1* addr
3831// =>
3832// v1 = ld i8* addr (-> i16)
3833// v = trunc i16 to i1
3835 SDLoc dl(LD);
3836 assert(LD->getExtensionType() == ISD::NON_EXTLOAD);
3837 assert(LD->getValueType(0) == MVT::i1 && "Custom lowering for i1 load only");
3838 SDValue newLD = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i16, LD->getChain(),
3839 LD->getBasePtr(), LD->getPointerInfo(),
3840 MVT::i8, LD->getAlign(),
3841 LD->getMemOperand()->getFlags());
3842 SDValue result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, newLD);
3843 // The legalizer (the caller) is expecting two values from the legalized
3844 // load, so we build a MergeValues node for it. See ExpandUnalignedLoad()
3845 // in LegalizeDAG.cpp which also uses MergeValues.
3846 return DAG.getMergeValues({result, LD->getChain()}, dl);
3847}
3848
3849SDValue NVPTXTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3850 LoadSDNode *LD = cast<LoadSDNode>(Op);
3851
3852 if (Op.getValueType() == MVT::i1)
3853 return lowerLOADi1(LD, DAG);
3854
3855 // To improve CodeGen we'll legalize any-extend loads to zext loads. This is
3856 // how they'll be lowered in ISel anyway, and by doing this a little earlier
3857 // we allow for more DAG combine opportunities.
3858 if (LD->getExtensionType() == ISD::EXTLOAD) {
3859 assert(LD->getValueType(0).isInteger() && LD->getMemoryVT().isInteger() &&
3860 "Unexpected fpext-load");
3861 return DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Op), Op.getValueType(),
3862 LD->getChain(), LD->getBasePtr(), LD->getMemoryVT(),
3863 LD->getMemOperand());
3864 }
3865
3866 llvm_unreachable("Unexpected custom lowering for load");
3867}
3868
3869SDValue NVPTXTargetLowering::LowerMLOAD(SDValue Op, SelectionDAG &DAG) const {
3870 // v2f16/v2bf16/v2i16/v4i8 are legal, so we can't rely on legalizer to handle
3871 // masked loads of these types and have to handle them here.
3872 // v2f32 also needs to be handled here if the subtarget has f32x2
3873 // instructions, making it legal.
3874 //
3875 // Note: misaligned masked loads should never reach this point
3876 // because the override of isLegalMaskedLoad in NVPTXTargetTransformInfo.cpp
3877 // will validate alignment. Therefore, we do not need to special case handle
3878 // them here.
3879 EVT VT = Op.getValueType();
3880 if (NVPTX::isPackedVectorTy(VT)) {
3882 cast<MemSDNode>(Op.getNode()), DAG, STI);
3883 MemSDNode *LD = std::get<0>(Result);
3884 uint32_t UsedBytesMask = std::get<1>(Result);
3885
3886 SDLoc DL(LD);
3887
3888 // Copy regular operands
3889 SmallVector<SDValue, 8> OtherOps(LD->ops());
3890
3891 OtherOps.push_back(DAG.getConstant(UsedBytesMask, DL, MVT::i32));
3892
3893 // We currently are not lowering extending loads, but pass the extension
3894 // type anyway as later handling expects it.
3895 OtherOps.push_back(
3896 DAG.getIntPtrConstant(cast<LoadSDNode>(LD)->getExtensionType(), DL));
3897 SDValue NewLD =
3898 DAG.getMemIntrinsicNode(NVPTXISD::MLoad, DL, LD->getVTList(), OtherOps,
3899 LD->getMemoryVT(), LD->getMemOperand());
3900 return NewLD;
3901 }
3902 return SDValue();
3903}
3904
3906 const NVPTXSubtarget &STI) {
3907 MemSDNode *N = cast<MemSDNode>(Op.getNode());
3908 SDValue Val = N->getOperand(1);
3909 SDLoc DL(N);
3910 const EVT ValVT = Val.getValueType();
3911 const EVT MemVT = N->getMemoryVT();
3912
3913 // If we're truncating as part of the store, avoid lowering to a StoreV node.
3914 // TODO: consider relaxing this restriction.
3915 if (ValVT != MemVT)
3916 return SDValue();
3917
3918 const auto NumEltsAndEltVT =
3919 getVectorLoweringShape(ValVT, STI, N->getAddressSpace());
3920 if (!NumEltsAndEltVT)
3921 return SDValue();
3922 const auto [NumElts, EltVT] = NumEltsAndEltVT.value();
3923
3924 const DataLayout &TD = DAG.getDataLayout();
3925
3926 Align Alignment = N->getAlign();
3927 Align PrefAlign = TD.getPrefTypeAlign(ValVT.getTypeForEVT(*DAG.getContext()));
3928 if (Alignment < PrefAlign) {
3929 // This store is not sufficiently aligned, so bail out and let this vector
3930 // store be scalarized. Note that we may still be able to emit smaller
3931 // vector stores. For example, if we are storing a <4 x float> with an
3932 // alignment of 8, this check will fail but the legalizer will try again
3933 // with 2 x <2 x float>, which will succeed with an alignment of 8.
3934 return SDValue();
3935 }
3936
3937 unsigned Opcode;
3938 switch (NumElts) {
3939 default:
3940 return SDValue();
3941 case 2:
3942 Opcode = NVPTXISD::StoreV2;
3943 break;
3944 case 4:
3945 Opcode = NVPTXISD::StoreV4;
3946 break;
3947 case 8:
3948 Opcode = NVPTXISD::StoreV8;
3949 break;
3950 }
3951
3953
3954 // First is the chain
3955 Ops.push_back(N->getOperand(0));
3956
3957 // Then the split values
3958 if (EltVT.isVector()) {
3960 assert(NumElts * EltVT.getVectorNumElements() ==
3961 ValVT.getVectorNumElements());
3962 // Combine individual elements into v2[i,f,bf]16/v4i8 subvectors to be
3963 // stored as b32s
3964 const unsigned NumEltsPerSubVector = EltVT.getVectorNumElements();
3965 for (const unsigned I : llvm::seq(NumElts)) {
3966 SmallVector<SDValue, 4> SubVectorElts;
3967 DAG.ExtractVectorElements(Val, SubVectorElts, I * NumEltsPerSubVector,
3968 NumEltsPerSubVector);
3969 Ops.push_back(DAG.getBuildVector(EltVT, DL, SubVectorElts));
3970 }
3971 } else {
3972 SDValue V = DAG.getBitcast(MVT::getVectorVT(EltVT, NumElts), Val);
3973 for (const unsigned I : llvm::seq(NumElts)) {
3974 SDValue ExtVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, V,
3975 DAG.getIntPtrConstant(I, DL));
3976
3977 // Since StoreV2 is a target node, we cannot rely on DAG type
3978 // legalization. Therefore, we must ensure the type is legal. For i1 and
3979 // i8, we set the stored type to i16 and propagate the "real" type as the
3980 // memory type.
3981 if (EltVT.getSizeInBits() < 16)
3982 ExtVal = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i16, ExtVal);
3983 Ops.push_back(ExtVal);
3984 }
3985 }
3986
3987 // Then any remaining arguments
3988 Ops.append(N->op_begin() + 2, N->op_end());
3989
3990 SDValue NewSt =
3991 DAG.getMemIntrinsicNode(Opcode, DL, DAG.getVTList(MVT::Other), Ops,
3992 N->getMemoryVT(), N->getMemOperand());
3993
3994 // return DCI.CombineTo(N, NewSt, true);
3995 return NewSt;
3996}
3997
3998SDValue NVPTXTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3999 StoreSDNode *Store = cast<StoreSDNode>(Op);
4000 EVT VT = Store->getMemoryVT();
4001
4002 if (VT == MVT::i1)
4003 return LowerSTOREi1(Op, DAG);
4004
4005 // Lower store of any other vector type, including v2f32 as we want to break
4006 // it apart since this is not a widely-supported type.
4007 return lowerSTOREVector(Op, DAG, STI);
4008}
4009
4010// st i1 v, addr
4011// =>
4012// v1 = zxt v to i16
4013// st.u8 i16, addr
4014SDValue NVPTXTargetLowering::LowerSTOREi1(SDValue Op, SelectionDAG &DAG) const {
4015 SDNode *Node = Op.getNode();
4016 SDLoc dl(Node);
4017 StoreSDNode *ST = cast<StoreSDNode>(Node);
4018 SDValue Tmp1 = ST->getChain();
4019 SDValue Tmp2 = ST->getBasePtr();
4020 SDValue Tmp3 = ST->getValue();
4021 assert(Tmp3.getValueType() == MVT::i1 && "Custom lowering for i1 store only");
4022 Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Tmp3);
4023 SDValue Result =
4024 DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(), MVT::i8,
4025 ST->getAlign(), ST->getMemOperand()->getFlags());
4026 return Result;
4027}
4028
4029SDValue NVPTXTargetLowering::LowerCopyToReg_128(SDValue Op,
4030 SelectionDAG &DAG) const {
4031 // Change the CopyToReg to take in two 64-bit operands instead of a 128-bit
4032 // operand so that it can pass the legalization.
4033
4034 assert(Op.getOperand(1).getValueType() == MVT::i128 &&
4035 "Custom lowering for 128-bit CopyToReg only");
4036
4037 SDNode *Node = Op.getNode();
4038 SDLoc DL(Node);
4039
4040 SDValue Cast = DAG.getBitcast(MVT::v2i64, Op->getOperand(2));
4041 SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, Cast,
4042 DAG.getIntPtrConstant(0, DL));
4043 SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, Cast,
4044 DAG.getIntPtrConstant(1, DL));
4045
4047 SmallVector<EVT, 3> ResultsType(Node->values());
4048
4049 NewOps[0] = Op->getOperand(0); // Chain
4050 NewOps[1] = Op->getOperand(1); // Dst Reg
4051 NewOps[2] = Lo; // Lower 64-bit
4052 NewOps[3] = Hi; // Higher 64-bit
4053 if (Op.getNumOperands() == 4)
4054 NewOps[4] = Op->getOperand(3); // Glue if exists
4055
4056 return DAG.getNode(ISD::CopyToReg, DL, ResultsType, NewOps);
4057}
4058
4059unsigned NVPTXTargetLowering::getNumRegisters(
4060 LLVMContext &Context, EVT VT,
4061 std::optional<MVT> RegisterVT = std::nullopt) const {
4062 if (VT == MVT::i128 && RegisterVT == MVT::i128)
4063 return 1;
4064 return TargetLoweringBase::getNumRegisters(Context, VT, RegisterVT);
4065}
4066
4067bool NVPTXTargetLowering::splitValueIntoRegisterParts(
4068 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4069 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4070 if (Val.getValueType() == MVT::i128 && NumParts == 1) {
4071 Parts[0] = Val;
4072 return true;
4073 }
4074 return false;
4075}
4076
4077SDValue NVPTXTargetLowering::getParamSymbolNode(SelectionDAG &DAG, int I,
4078 EVT T) const {
4079 const MachineFunction &MF = DAG.getMachineFunction();
4080 return getSymbolNode(
4081 DAG, getParamSymbol(MF.getContext(), &MF.getFunction(), I), T);
4082}
4083
4084SDValue NVPTXTargetLowering::getCallParamSymbolNode(SelectionDAG &DAG, int I,
4085 EVT T) const {
4086 return getSymbolNode(DAG, "param" + Twine(I), T);
4087}
4088
4090 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4091 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4092 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4093 const DataLayout &DL = DAG.getDataLayout();
4094 LLVMContext &Ctx = *DAG.getContext();
4095
4096 const Function &F = DAG.getMachineFunction().getFunction();
4097 const bool IsKernel = isKernelFunction(F);
4098
4099 const MVT PtrVT = getPointerTy(DL, IsKernel ? ADDRESS_SPACE_ENTRY_PARAM
4101
4102 SDValue Root = DAG.getRoot();
4103 SmallVector<SDValue, 16> OutChains;
4104
4105 // argTypes.size() (or theArgs.size()) and Ins.size() need not match.
4106 // Ins.size() will be larger
4107 // * if there is an aggregate argument with multiple fields (each field
4108 // showing up separately in Ins)
4109 // * if there is a vector argument with more than typical vector-length
4110 // elements (generally if more than 4) where each vector element is
4111 // individually present in Ins.
4112 // So a different index should be used for indexing into Ins.
4113 // See similar issue in LowerCall.
4114
4115 auto AllIns = ArrayRef(Ins);
4116 const auto NonEmptyArgs = make_filter_range(
4117 F.args(), [](const Argument &A) { return !A.getType()->isEmptyTy(); });
4118 for (const auto &[ParamI, Arg] : enumerate(NonEmptyArgs)) {
4119 const unsigned ArgNo = Arg.getArgNo();
4120 const auto ArgIns =
4121 AllIns.take_while([&](auto I) { return I.OrigArgIndex == ArgNo; });
4122 AllIns = AllIns.drop_front(ArgIns.size());
4123
4124 Type *Ty = Arg.getType();
4125 assert(!ArgIns.empty() &&
4126 "Non-empty argument produced no parameter values");
4127
4128 if (Arg.use_empty()) {
4129 // argument is dead
4130 for (const auto &In : ArgIns) {
4131 assert(!In.Used && "Arg.use_empty() is true but Arg is used?");
4132 InVals.push_back(DAG.getUNDEF(In.VT));
4133 }
4134 continue;
4135 }
4136
4137 SDValue ArgSymbol = getParamSymbolNode(DAG, ParamI, PtrVT);
4138
4139 // In the following cases, assign a node order of "i+1"
4140 // to newly created nodes. The SDNodes for params have to
4141 // appear in the same order as their order of appearance
4142 // in the original function. "i+1" holds that order.
4143 if (Arg.hasByValAttr()) {
4144 // Param has ByVal attribute
4145 // Return MoveParam(param symbol).
4146 // Ideally, the param symbol can be returned directly,
4147 // but when SDNode builder decides to use it in a CopyToReg(),
4148 // machine instruction fails because TargetExternalSymbol
4149 // (not lowered) is target dependent, and CopyToReg assumes
4150 // the source is lowered.
4151 assert(ArgIns.size() == 1 && "ByVal argument must be a pointer");
4152 const auto &ByvalIn = ArgIns[0];
4153 assert(getValueType(DL, Ty) == ByvalIn.VT &&
4154 "Ins type did not match function type");
4155
4156 SDValue P;
4157 if (IsKernel) {
4158 assert(Ty->getPointerAddressSpace() == ADDRESS_SPACE_ENTRY_PARAM &&
4159 "Kernel ByVal argument must be lowered to the param address "
4160 "space by NVPTXLowerArgs");
4161 P = ArgSymbol;
4162 P.getNode()->setIROrder(Arg.getArgNo() + 1);
4163 } else {
4164 P = DAG.getNode(NVPTXISD::MoveParam, dl, ArgSymbol.getValueType(),
4165 ArgSymbol);
4166 P.getNode()->setIROrder(Arg.getArgNo() + 1);
4167 P = DAG.getAddrSpaceCast(dl, ByvalIn.VT, P, ADDRESS_SPACE_LOCAL,
4169 }
4170 InVals.push_back(P);
4171 } else {
4174 ComputePTXValueVTs(*this, DL, Ctx, CallConv, Ty, VTs, Offsets);
4175 assert(VTs.size() == ArgIns.size() && "Size mismatch");
4176 assert(VTs.size() == Offsets.size() && "Size mismatch");
4177
4178 const Align ArgAlign = getPTXParamAlign(
4179 &F, Ty, Arg.getArgNo() + AttributeList::FirstArgIndex, DL);
4180
4181 unsigned I = 0;
4182 const auto VI = VectorizePTXValueVTs(VTs, Offsets, ArgAlign);
4183 for (const unsigned NumElts : VI) {
4184 // i1 is loaded/stored as i8
4185 const EVT LoadVT = VTs[I] == MVT::i1 ? MVT::i8 : VTs[I];
4186 const EVT VecVT = getVectorizedVT(LoadVT, NumElts, Ctx);
4187
4188 SDValue VecAddr = DAG.getObjectPtrOffset(
4189 dl, ArgSymbol, TypeSize::getFixed(Offsets[I]));
4190
4191 const Align PartAlign = commonAlignment(ArgAlign, Offsets[I]);
4192 const unsigned AS = IsKernel ? NVPTX::AddressSpace::EntryParam
4194 SDValue P = DAG.getLoad(VecVT, dl, Root, VecAddr,
4195 MachinePointerInfo(AS), PartAlign,
4198 P.getNode()->setIROrder(Arg.getArgNo() + 1);
4199 for (const unsigned J : llvm::seq(NumElts)) {
4200 SDValue Elt = getExtractVectorizedValue(P, J, LoadVT, dl, DAG);
4201
4202 Elt = correctParamType(Elt, ArgIns[I + J].VT, ArgIns[I + J].Flags,
4203 DAG, dl);
4204 InVals.push_back(Elt);
4205 }
4206 I += NumElts;
4207 }
4208 }
4209 }
4210
4211 if (!OutChains.empty())
4212 DAG.setRoot(DAG.getTokenFactor(dl, OutChains));
4213
4214 return Chain;
4215}
4216
4217SDValue
4219 bool isVarArg,
4221 const SmallVectorImpl<SDValue> &OutVals,
4222 const SDLoc &dl, SelectionDAG &DAG) const {
4223 const Function &F = DAG.getMachineFunction().getFunction();
4224 Type *RetTy = F.getReturnType();
4225
4226 if (RetTy->isVoidTy()) {
4227 assert(OutVals.empty() && Outs.empty() && "Return value expected for void");
4228 return DAG.getNode(NVPTXISD::RET_GLUE, dl, MVT::Other, Chain);
4229 }
4230
4231 const DataLayout &DL = DAG.getDataLayout();
4232 LLVMContext &Ctx = *DAG.getContext();
4233
4234 const SDValue RetSymbol = getSymbolNode(DAG, "func_retval0", MVT::i32);
4235 const auto RetAlign =
4236 getPTXParamAlign(&F, RetTy, AttributeList::ReturnIndex, DL);
4237
4238 // PTX Interoperability Guide 3.3(A): [Integer] Values shorter than
4239 // 32-bits are sign extended or zero extended, depending on whether
4240 // they are signed or unsigned types.
4241 const bool ExtendIntegerRetVal =
4242 RetTy->isIntegerTy() && DL.getTypeAllocSizeInBits(RetTy) < 32;
4243
4246 ComputePTXValueVTs(*this, DL, Ctx, CallConv, RetTy, VTs, Offsets);
4247 assert(VTs.size() == OutVals.size() && "Bad return value decomposition");
4248
4249 const auto GetRetVal = [&](unsigned I) -> SDValue {
4250 SDValue RetVal = OutVals[I];
4252 RetVal.getValueType() &&
4253 "OutVal type should always be legal");
4254
4255 const EVT VTI = promoteScalarIntegerPTX(VTs[I]);
4256 const EVT StoreVT =
4257 ExtendIntegerRetVal ? MVT::i32 : (VTI == MVT::i1 ? MVT::i8 : VTI);
4258 return correctParamType(RetVal, StoreVT, Outs[I].Flags, DAG, dl);
4259 };
4260
4261 unsigned I = 0;
4262 const auto VI = VectorizePTXValueVTs(VTs, Offsets, RetAlign);
4263 for (const unsigned NumElts : VI) {
4264 const MaybeAlign CurrentAlign = ExtendIntegerRetVal
4265 ? MaybeAlign(std::nullopt)
4266 : commonAlignment(RetAlign, Offsets[I]);
4267
4269 NumElts, dl, DAG, [&](unsigned K) { return GetRetVal(I + K); });
4270
4271 SDValue Ptr =
4272 DAG.getObjectPtrOffset(dl, RetSymbol, TypeSize::getFixed(Offsets[I]));
4273
4274 Chain = DAG.getStore(Chain, dl, Val, Ptr,
4276 CurrentAlign);
4277
4278 I += NumElts;
4279 }
4280
4281 return DAG.getNode(NVPTXISD::RET_GLUE, dl, MVT::Other, Chain);
4282}
4283
4285 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
4286 SelectionDAG &DAG) const {
4287 if (Constraint.size() > 1)
4288 return;
4290}
4291
4292// llvm.ptx.memcpy.const and llvm.ptx.memmove.const need to be modeled as
4293// TgtMemIntrinsic
4294// because we need the information that is only available in the "Value" type
4295// of destination
4296// pointer. In particular, the address space information.
4299 MachineFunction &MF, unsigned Intrinsic) const {
4300 IntrinsicInfo Info;
4301 switch (Intrinsic) {
4302 default:
4303 return;
4304 case Intrinsic::nvvm_match_all_sync_i32p:
4305 case Intrinsic::nvvm_match_all_sync_i64p:
4306 Info.opc = ISD::INTRINSIC_W_CHAIN;
4307 // memVT is bogus. These intrinsics have IntrInaccessibleMemOnly attribute
4308 // in order to model data exchange with other threads, but perform no real
4309 // memory accesses.
4310 Info.memVT = MVT::i1;
4311
4312 // Our result depends on both our and other thread's arguments.
4314 Infos.push_back(Info);
4315 return;
4316 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_col:
4317 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_row:
4318 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_col_stride:
4319 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_row_stride:
4320 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_col:
4321 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_row:
4322 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_col_stride:
4323 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_row_stride:
4324 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_col:
4325 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_row:
4326 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_col_stride:
4327 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_row_stride:
4328 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_col:
4329 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_row:
4330 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_col_stride:
4331 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_row_stride:
4332 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_col:
4333 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_row:
4334 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_col_stride:
4335 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_row_stride:
4336 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_col:
4337 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_row:
4338 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_col_stride:
4339 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_row_stride: {
4340 Info.opc = ISD::INTRINSIC_W_CHAIN;
4341 Info.memVT = MVT::v8f16;
4342 Info.ptrVal = I.getArgOperand(0);
4343 Info.offset = 0;
4344 Info.flags = MachineMemOperand::MOLoad;
4345 Info.align = Align(16);
4346 Infos.push_back(Info);
4347 return;
4348 }
4349 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_col:
4350 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_col_stride:
4351 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_col_stride:
4352 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_col:
4353 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_row:
4354 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_row_stride:
4355 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_row_stride:
4356 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_row:
4357 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_col:
4358 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_col_stride:
4359 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_row:
4360 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_row_stride:
4361 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_col:
4362 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_col_stride:
4363 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_col_stride:
4364 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_col:
4365 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_row:
4366 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_row_stride:
4367 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_row_stride:
4368 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_row:
4369 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_col:
4370 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_col_stride:
4371 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_row:
4372 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_row_stride: {
4373 Info.opc = ISD::INTRINSIC_W_CHAIN;
4374 Info.memVT = MVT::v2i32;
4375 Info.ptrVal = I.getArgOperand(0);
4376 Info.offset = 0;
4377 Info.flags = MachineMemOperand::MOLoad;
4378 Info.align = Align(8);
4379 Infos.push_back(Info);
4380 return;
4381 }
4382
4383 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_col:
4384 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_col_stride:
4385 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_col_stride:
4386 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_col:
4387 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_row:
4388 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_row_stride:
4389 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_row_stride:
4390 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_row:
4391 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_col:
4392 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_col_stride:
4393 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_row:
4394 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_row_stride:
4395 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_col:
4396 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_col_stride:
4397 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_row:
4398 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_row_stride:
4399
4400 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_col:
4401 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_col_stride:
4402 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_col_stride:
4403 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_col:
4404 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_row:
4405 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_row_stride:
4406 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_row_stride:
4407 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_row:
4408 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_col:
4409 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_col_stride:
4410 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_row:
4411 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_row_stride:
4412 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_col:
4413 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_col_stride:
4414 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_row:
4415 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_row_stride:
4416 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x4_b16:
4417 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x4_trans_b16:
4418 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x2_trans_b8:
4419 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x2_trans_b8x16_b4x16_p64:
4420 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x2_trans_b8x16_b6x16_p32:
4421 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x4_b8x16_b4x16_p64:
4422 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x4_b8x16_b6x16_p32: {
4423 Info.opc = ISD::INTRINSIC_W_CHAIN;
4424 Info.memVT = MVT::v4i32;
4425 Info.ptrVal = I.getArgOperand(0);
4426 Info.offset = 0;
4427 Info.flags = MachineMemOperand::MOLoad;
4428 Info.align = Align(16);
4429 Infos.push_back(Info);
4430 return;
4431 }
4432
4433 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_col:
4434 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_col_stride:
4435 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_col_stride:
4436 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_col:
4437 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_row:
4438 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_row_stride:
4439 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_row_stride:
4440 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_row:
4441
4442 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_col:
4443 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_col_stride:
4444 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_col_stride:
4445 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_col:
4446 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_row:
4447 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_row_stride:
4448 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_row_stride:
4449 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_row:
4450 case Intrinsic::nvvm_wmma_m8n8k128_load_a_b1_row:
4451 case Intrinsic::nvvm_wmma_m8n8k128_load_a_b1_row_stride:
4452 case Intrinsic::nvvm_wmma_m8n8k128_load_b_b1_col:
4453 case Intrinsic::nvvm_wmma_m8n8k128_load_b_b1_col_stride:
4454 case Intrinsic::nvvm_wmma_m8n8k32_load_a_s4_row:
4455 case Intrinsic::nvvm_wmma_m8n8k32_load_a_s4_row_stride:
4456 case Intrinsic::nvvm_wmma_m8n8k32_load_a_u4_row_stride:
4457 case Intrinsic::nvvm_wmma_m8n8k32_load_a_u4_row:
4458 case Intrinsic::nvvm_wmma_m8n8k32_load_b_s4_col:
4459 case Intrinsic::nvvm_wmma_m8n8k32_load_b_s4_col_stride:
4460 case Intrinsic::nvvm_wmma_m8n8k32_load_b_u4_col_stride:
4461 case Intrinsic::nvvm_wmma_m8n8k32_load_b_u4_col:
4462 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x1_b16:
4463 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x1_trans_b16:
4464 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x1_b8x16_b4x16_p64:
4465 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x1_b8x16_b6x16_p32: {
4466 Info.opc = ISD::INTRINSIC_W_CHAIN;
4467 Info.memVT = MVT::i32;
4468 Info.ptrVal = I.getArgOperand(0);
4469 Info.offset = 0;
4470 Info.flags = MachineMemOperand::MOLoad;
4471 Info.align = Align(4);
4472 Infos.push_back(Info);
4473 return;
4474 }
4475
4476 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_col:
4477 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_row:
4478 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_col_stride:
4479 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_row_stride:
4480 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_col:
4481 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_row:
4482 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_col_stride:
4483 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_row_stride:
4484 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_col:
4485 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_row:
4486 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_col_stride:
4487 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_row_stride: {
4488 Info.opc = ISD::INTRINSIC_W_CHAIN;
4489 Info.memVT = MVT::v4f16;
4490 Info.ptrVal = I.getArgOperand(0);
4491 Info.offset = 0;
4492 Info.flags = MachineMemOperand::MOLoad;
4493 Info.align = Align(16);
4494 Infos.push_back(Info);
4495 return;
4496 }
4497
4498 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_col:
4499 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_row:
4500 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_col_stride:
4501 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_row_stride:
4502 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_col:
4503 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_row:
4504 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_col_stride:
4505 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_row_stride:
4506 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_col:
4507 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_row:
4508 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_col_stride:
4509 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_row_stride:
4510 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_col:
4511 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_row:
4512 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_col_stride:
4513 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_row_stride: {
4514 Info.opc = ISD::INTRINSIC_W_CHAIN;
4515 Info.memVT = MVT::v8f32;
4516 Info.ptrVal = I.getArgOperand(0);
4517 Info.offset = 0;
4518 Info.flags = MachineMemOperand::MOLoad;
4519 Info.align = Align(16);
4520 Infos.push_back(Info);
4521 return;
4522 }
4523
4524 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_col:
4525 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_col_stride:
4526 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_row:
4527 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_row_stride:
4528
4529 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_col:
4530 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_col_stride:
4531 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_row:
4532 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_row_stride:
4533
4534 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_col:
4535 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_col_stride:
4536 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_row:
4537 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_row_stride:
4538 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_col:
4539 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_col_stride:
4540 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_row:
4541 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_row_stride:
4542 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_col:
4543 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_col_stride:
4544 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_row:
4545 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_row_stride: {
4546 Info.opc = ISD::INTRINSIC_W_CHAIN;
4547 Info.memVT = MVT::v8i32;
4548 Info.ptrVal = I.getArgOperand(0);
4549 Info.offset = 0;
4550 Info.flags = MachineMemOperand::MOLoad;
4551 Info.align = Align(16);
4552 Infos.push_back(Info);
4553 return;
4554 }
4555
4556 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_col:
4557 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_col_stride:
4558 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_row:
4559 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_row_stride:
4560 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_col:
4561 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_col_stride:
4562 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_row:
4563 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_row_stride:
4564 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x2_b16:
4565 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x2_trans_b16:
4566 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x1_trans_b8:
4567 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x1_trans_b8x16_b4x16_p64:
4568 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x1_trans_b8x16_b6x16_p32:
4569 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x2_b8x16_b4x16_p64:
4570 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x2_b8x16_b6x16_p32: {
4571 Info.opc = ISD::INTRINSIC_W_CHAIN;
4572 Info.memVT = MVT::v2i32;
4573 Info.ptrVal = I.getArgOperand(0);
4574 Info.offset = 0;
4575 Info.flags = MachineMemOperand::MOLoad;
4576 Info.align = Align(8);
4577 Infos.push_back(Info);
4578 return;
4579 }
4580
4581 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_col:
4582 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_col_stride:
4583 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_row:
4584 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_row_stride:
4585
4586 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_col:
4587 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_col_stride:
4588 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_row:
4589 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_row_stride: {
4590 Info.opc = ISD::INTRINSIC_W_CHAIN;
4591 Info.memVT = MVT::f64;
4592 Info.ptrVal = I.getArgOperand(0);
4593 Info.offset = 0;
4594 Info.flags = MachineMemOperand::MOLoad;
4595 Info.align = Align(8);
4596 Infos.push_back(Info);
4597 return;
4598 }
4599
4600 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_col:
4601 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_col_stride:
4602 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_row:
4603 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_row_stride: {
4604 Info.opc = ISD::INTRINSIC_W_CHAIN;
4605 Info.memVT = MVT::v2f64;
4606 Info.ptrVal = I.getArgOperand(0);
4607 Info.offset = 0;
4608 Info.flags = MachineMemOperand::MOLoad;
4609 Info.align = Align(16);
4610 Infos.push_back(Info);
4611 return;
4612 }
4613
4614 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_col:
4615 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_row:
4616 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_col_stride:
4617 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_row_stride:
4618 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_col:
4619 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_row:
4620 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_col_stride:
4621 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_row_stride:
4622 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_col:
4623 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_row:
4624 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_col_stride:
4625 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_row_stride: {
4626 Info.opc = ISD::INTRINSIC_VOID;
4627 Info.memVT = MVT::v4f16;
4628 Info.ptrVal = I.getArgOperand(0);
4629 Info.offset = 0;
4630 Info.flags = MachineMemOperand::MOStore;
4631 Info.align = Align(16);
4632 Infos.push_back(Info);
4633 return;
4634 }
4635
4636 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_col:
4637 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_row:
4638 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_col_stride:
4639 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_row_stride:
4640 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_col:
4641 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_row:
4642 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_col_stride:
4643 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_row_stride:
4644 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_col:
4645 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_row:
4646 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_col_stride:
4647 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_row_stride:
4648 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_col:
4649 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_row:
4650 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_col_stride:
4651 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_row_stride: {
4652 Info.opc = ISD::INTRINSIC_VOID;
4653 Info.memVT = MVT::v8f32;
4654 Info.ptrVal = I.getArgOperand(0);
4655 Info.offset = 0;
4656 Info.flags = MachineMemOperand::MOStore;
4657 Info.align = Align(16);
4658 Infos.push_back(Info);
4659 return;
4660 }
4661
4662 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_col:
4663 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_col_stride:
4664 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_row:
4665 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_row_stride:
4666 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_col:
4667 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_col_stride:
4668 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_row:
4669 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_row_stride:
4670 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_col:
4671 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_col_stride:
4672 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_row:
4673 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_row_stride: {
4674 Info.opc = ISD::INTRINSIC_VOID;
4675 Info.memVT = MVT::v8i32;
4676 Info.ptrVal = I.getArgOperand(0);
4677 Info.offset = 0;
4678 Info.flags = MachineMemOperand::MOStore;
4679 Info.align = Align(16);
4680 Infos.push_back(Info);
4681 return;
4682 }
4683
4684 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_col:
4685 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_col_stride:
4686 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_row:
4687 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_row_stride:
4688 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_col:
4689 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_col_stride:
4690 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_row:
4691 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_row_stride:
4692 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x2_b16:
4693 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x2_trans_b16:
4694 case Intrinsic::nvvm_stmatrix_sync_aligned_m16n8_x2_trans_b8: {
4695 Info.opc = ISD::INTRINSIC_VOID;
4696 Info.memVT = MVT::v2i32;
4697 Info.ptrVal = I.getArgOperand(0);
4698 Info.offset = 0;
4699 Info.flags = MachineMemOperand::MOStore;
4700 Info.align = Align(8);
4701 Infos.push_back(Info);
4702 return;
4703 }
4704
4705 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_col:
4706 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_col_stride:
4707 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_row:
4708 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_row_stride: {
4709 Info.opc = ISD::INTRINSIC_VOID;
4710 Info.memVT = MVT::v2f64;
4711 Info.ptrVal = I.getArgOperand(0);
4712 Info.offset = 0;
4713 Info.flags = MachineMemOperand::MOStore;
4714 Info.align = Align(16);
4715 Infos.push_back(Info);
4716 return;
4717 }
4718
4719 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x1_b16:
4720 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x1_trans_b16:
4721 case Intrinsic::nvvm_stmatrix_sync_aligned_m16n8_x1_trans_b8: {
4722 Info.opc = ISD::INTRINSIC_VOID;
4723 Info.memVT = MVT::i32;
4724 Info.ptrVal = I.getArgOperand(0);
4725 Info.offset = 0;
4726 Info.flags = MachineMemOperand::MOStore;
4727 Info.align = Align(4);
4728 Infos.push_back(Info);
4729 return;
4730 }
4731
4732 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x4_b16:
4733 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x4_trans_b16:
4734 case Intrinsic::nvvm_stmatrix_sync_aligned_m16n8_x4_trans_b8: {
4735 Info.opc = ISD::INTRINSIC_VOID;
4736 Info.memVT = MVT::v4i32;
4737 Info.ptrVal = I.getArgOperand(0);
4738 Info.offset = 0;
4739 Info.flags = MachineMemOperand::MOStore;
4740 Info.align = Align(16);
4741 Infos.push_back(Info);
4742 return;
4743 }
4744
4745 case Intrinsic::nvvm_prefetch_tensormap: {
4746 auto &DL = I.getDataLayout();
4747 Info.opc = ISD::INTRINSIC_VOID;
4748 Info.memVT = getPointerTy(DL);
4749 Info.ptrVal = I.getArgOperand(0);
4750 Info.offset = 0;
4751 Info.flags =
4753 Info.align.reset();
4754 Infos.push_back(Info);
4755 return;
4756 }
4757
4758 case Intrinsic::nvvm_tensormap_replace_global_address:
4759 case Intrinsic::nvvm_tensormap_replace_global_stride: {
4760 Info.opc = ISD::INTRINSIC_VOID;
4761 Info.memVT = MVT::i64;
4762 Info.ptrVal = I.getArgOperand(0);
4763 Info.offset = 0;
4764 Info.flags = MachineMemOperand::MOStore;
4765 Info.align.reset();
4766 Infos.push_back(Info);
4767 return;
4768 }
4769
4770 case Intrinsic::nvvm_tensormap_replace_rank:
4771 case Intrinsic::nvvm_tensormap_replace_box_dim:
4772 case Intrinsic::nvvm_tensormap_replace_global_dim:
4773 case Intrinsic::nvvm_tensormap_replace_element_stride:
4774 case Intrinsic::nvvm_tensormap_replace_elemtype:
4775 case Intrinsic::nvvm_tensormap_replace_interleave_layout:
4776 case Intrinsic::nvvm_tensormap_replace_swizzle_mode:
4777 case Intrinsic::nvvm_tensormap_replace_swizzle_atomicity:
4778 case Intrinsic::nvvm_tensormap_replace_fill_mode: {
4779 Info.opc = ISD::INTRINSIC_VOID;
4780 Info.memVT = MVT::i32;
4781 Info.ptrVal = I.getArgOperand(0);
4782 Info.offset = 0;
4783 Info.flags = MachineMemOperand::MOStore;
4784 Info.align.reset();
4785 Infos.push_back(Info);
4786 return;
4787 }
4788
4789 case Intrinsic::nvvm_ldu_global_i:
4790 case Intrinsic::nvvm_ldu_global_f:
4791 case Intrinsic::nvvm_ldu_global_p: {
4792 Info.opc = ISD::INTRINSIC_W_CHAIN;
4793 Info.memVT = getValueType(I.getDataLayout(), I.getType());
4794 Info.ptrVal = I.getArgOperand(0);
4795 Info.offset = 0;
4796 Info.flags = MachineMemOperand::MOLoad;
4797 Info.align = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4798
4799 Infos.push_back(Info);
4800 return;
4801 }
4802 case Intrinsic::nvvm_tex_1d_v4f32_s32:
4803 case Intrinsic::nvvm_tex_1d_v4f32_f32:
4804 case Intrinsic::nvvm_tex_1d_level_v4f32_f32:
4805 case Intrinsic::nvvm_tex_1d_grad_v4f32_f32:
4806 case Intrinsic::nvvm_tex_1d_array_v4f32_s32:
4807 case Intrinsic::nvvm_tex_1d_array_v4f32_f32:
4808 case Intrinsic::nvvm_tex_1d_array_level_v4f32_f32:
4809 case Intrinsic::nvvm_tex_1d_array_grad_v4f32_f32:
4810 case Intrinsic::nvvm_tex_2d_v4f32_s32:
4811 case Intrinsic::nvvm_tex_2d_v4f32_f32:
4812 case Intrinsic::nvvm_tex_2d_level_v4f32_f32:
4813 case Intrinsic::nvvm_tex_2d_grad_v4f32_f32:
4814 case Intrinsic::nvvm_tex_2d_array_v4f32_s32:
4815 case Intrinsic::nvvm_tex_2d_array_v4f32_f32:
4816 case Intrinsic::nvvm_tex_2d_array_level_v4f32_f32:
4817 case Intrinsic::nvvm_tex_2d_array_grad_v4f32_f32:
4818 case Intrinsic::nvvm_tex_3d_v4f32_s32:
4819 case Intrinsic::nvvm_tex_3d_v4f32_f32:
4820 case Intrinsic::nvvm_tex_3d_level_v4f32_f32:
4821 case Intrinsic::nvvm_tex_3d_grad_v4f32_f32:
4822 case Intrinsic::nvvm_tex_cube_v4f32_f32:
4823 case Intrinsic::nvvm_tex_cube_level_v4f32_f32:
4824 case Intrinsic::nvvm_tex_cube_array_v4f32_f32:
4825 case Intrinsic::nvvm_tex_cube_array_level_v4f32_f32:
4826 case Intrinsic::nvvm_tld4_r_2d_v4f32_f32:
4827 case Intrinsic::nvvm_tld4_g_2d_v4f32_f32:
4828 case Intrinsic::nvvm_tld4_b_2d_v4f32_f32:
4829 case Intrinsic::nvvm_tld4_a_2d_v4f32_f32:
4830 case Intrinsic::nvvm_tex_unified_1d_v4f32_s32:
4831 case Intrinsic::nvvm_tex_unified_1d_v4f32_f32:
4832 case Intrinsic::nvvm_tex_unified_1d_level_v4f32_f32:
4833 case Intrinsic::nvvm_tex_unified_1d_grad_v4f32_f32:
4834 case Intrinsic::nvvm_tex_unified_1d_array_v4f32_s32:
4835 case Intrinsic::nvvm_tex_unified_1d_array_v4f32_f32:
4836 case Intrinsic::nvvm_tex_unified_1d_array_level_v4f32_f32:
4837 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4f32_f32:
4838 case Intrinsic::nvvm_tex_unified_2d_v4f32_s32:
4839 case Intrinsic::nvvm_tex_unified_2d_v4f32_f32:
4840 case Intrinsic::nvvm_tex_unified_2d_level_v4f32_f32:
4841 case Intrinsic::nvvm_tex_unified_2d_grad_v4f32_f32:
4842 case Intrinsic::nvvm_tex_unified_2d_array_v4f32_s32:
4843 case Intrinsic::nvvm_tex_unified_2d_array_v4f32_f32:
4844 case Intrinsic::nvvm_tex_unified_2d_array_level_v4f32_f32:
4845 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4f32_f32:
4846 case Intrinsic::nvvm_tex_unified_3d_v4f32_s32:
4847 case Intrinsic::nvvm_tex_unified_3d_v4f32_f32:
4848 case Intrinsic::nvvm_tex_unified_3d_level_v4f32_f32:
4849 case Intrinsic::nvvm_tex_unified_3d_grad_v4f32_f32:
4850 case Intrinsic::nvvm_tex_unified_cube_v4f32_f32:
4851 case Intrinsic::nvvm_tex_unified_cube_level_v4f32_f32:
4852 case Intrinsic::nvvm_tex_unified_cube_array_v4f32_f32:
4853 case Intrinsic::nvvm_tex_unified_cube_array_level_v4f32_f32:
4854 case Intrinsic::nvvm_tex_unified_cube_grad_v4f32_f32:
4855 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4f32_f32:
4856 case Intrinsic::nvvm_tld4_unified_r_2d_v4f32_f32:
4857 case Intrinsic::nvvm_tld4_unified_g_2d_v4f32_f32:
4858 case Intrinsic::nvvm_tld4_unified_b_2d_v4f32_f32:
4859 case Intrinsic::nvvm_tld4_unified_a_2d_v4f32_f32:
4860 Info.opc = ISD::INTRINSIC_W_CHAIN;
4861 Info.memVT = MVT::v4f32;
4862 Info.ptrVal = nullptr;
4863 Info.offset = 0;
4864 Info.flags = MachineMemOperand::MOLoad;
4865 Info.align = Align(16);
4866 Infos.push_back(Info);
4867 return;
4868
4869 case Intrinsic::nvvm_tex_1d_v4s32_s32:
4870 case Intrinsic::nvvm_tex_1d_v4s32_f32:
4871 case Intrinsic::nvvm_tex_1d_level_v4s32_f32:
4872 case Intrinsic::nvvm_tex_1d_grad_v4s32_f32:
4873 case Intrinsic::nvvm_tex_1d_array_v4s32_s32:
4874 case Intrinsic::nvvm_tex_1d_array_v4s32_f32:
4875 case Intrinsic::nvvm_tex_1d_array_level_v4s32_f32:
4876 case Intrinsic::nvvm_tex_1d_array_grad_v4s32_f32:
4877 case Intrinsic::nvvm_tex_2d_v4s32_s32:
4878 case Intrinsic::nvvm_tex_2d_v4s32_f32:
4879 case Intrinsic::nvvm_tex_2d_level_v4s32_f32:
4880 case Intrinsic::nvvm_tex_2d_grad_v4s32_f32:
4881 case Intrinsic::nvvm_tex_2d_array_v4s32_s32:
4882 case Intrinsic::nvvm_tex_2d_array_v4s32_f32:
4883 case Intrinsic::nvvm_tex_2d_array_level_v4s32_f32:
4884 case Intrinsic::nvvm_tex_2d_array_grad_v4s32_f32:
4885 case Intrinsic::nvvm_tex_3d_v4s32_s32:
4886 case Intrinsic::nvvm_tex_3d_v4s32_f32:
4887 case Intrinsic::nvvm_tex_3d_level_v4s32_f32:
4888 case Intrinsic::nvvm_tex_3d_grad_v4s32_f32:
4889 case Intrinsic::nvvm_tex_cube_v4s32_f32:
4890 case Intrinsic::nvvm_tex_cube_level_v4s32_f32:
4891 case Intrinsic::nvvm_tex_cube_array_v4s32_f32:
4892 case Intrinsic::nvvm_tex_cube_array_level_v4s32_f32:
4893 case Intrinsic::nvvm_tex_cube_v4u32_f32:
4894 case Intrinsic::nvvm_tex_cube_level_v4u32_f32:
4895 case Intrinsic::nvvm_tex_cube_array_v4u32_f32:
4896 case Intrinsic::nvvm_tex_cube_array_level_v4u32_f32:
4897 case Intrinsic::nvvm_tex_1d_v4u32_s32:
4898 case Intrinsic::nvvm_tex_1d_v4u32_f32:
4899 case Intrinsic::nvvm_tex_1d_level_v4u32_f32:
4900 case Intrinsic::nvvm_tex_1d_grad_v4u32_f32:
4901 case Intrinsic::nvvm_tex_1d_array_v4u32_s32:
4902 case Intrinsic::nvvm_tex_1d_array_v4u32_f32:
4903 case Intrinsic::nvvm_tex_1d_array_level_v4u32_f32:
4904 case Intrinsic::nvvm_tex_1d_array_grad_v4u32_f32:
4905 case Intrinsic::nvvm_tex_2d_v4u32_s32:
4906 case Intrinsic::nvvm_tex_2d_v4u32_f32:
4907 case Intrinsic::nvvm_tex_2d_level_v4u32_f32:
4908 case Intrinsic::nvvm_tex_2d_grad_v4u32_f32:
4909 case Intrinsic::nvvm_tex_2d_array_v4u32_s32:
4910 case Intrinsic::nvvm_tex_2d_array_v4u32_f32:
4911 case Intrinsic::nvvm_tex_2d_array_level_v4u32_f32:
4912 case Intrinsic::nvvm_tex_2d_array_grad_v4u32_f32:
4913 case Intrinsic::nvvm_tex_3d_v4u32_s32:
4914 case Intrinsic::nvvm_tex_3d_v4u32_f32:
4915 case Intrinsic::nvvm_tex_3d_level_v4u32_f32:
4916 case Intrinsic::nvvm_tex_3d_grad_v4u32_f32:
4917 case Intrinsic::nvvm_tld4_r_2d_v4s32_f32:
4918 case Intrinsic::nvvm_tld4_g_2d_v4s32_f32:
4919 case Intrinsic::nvvm_tld4_b_2d_v4s32_f32:
4920 case Intrinsic::nvvm_tld4_a_2d_v4s32_f32:
4921 case Intrinsic::nvvm_tld4_r_2d_v4u32_f32:
4922 case Intrinsic::nvvm_tld4_g_2d_v4u32_f32:
4923 case Intrinsic::nvvm_tld4_b_2d_v4u32_f32:
4924 case Intrinsic::nvvm_tld4_a_2d_v4u32_f32:
4925 case Intrinsic::nvvm_tex_unified_1d_v4s32_s32:
4926 case Intrinsic::nvvm_tex_unified_1d_v4s32_f32:
4927 case Intrinsic::nvvm_tex_unified_1d_level_v4s32_f32:
4928 case Intrinsic::nvvm_tex_unified_1d_grad_v4s32_f32:
4929 case Intrinsic::nvvm_tex_unified_1d_array_v4s32_s32:
4930 case Intrinsic::nvvm_tex_unified_1d_array_v4s32_f32:
4931 case Intrinsic::nvvm_tex_unified_1d_array_level_v4s32_f32:
4932 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4s32_f32:
4933 case Intrinsic::nvvm_tex_unified_2d_v4s32_s32:
4934 case Intrinsic::nvvm_tex_unified_2d_v4s32_f32:
4935 case Intrinsic::nvvm_tex_unified_2d_level_v4s32_f32:
4936 case Intrinsic::nvvm_tex_unified_2d_grad_v4s32_f32:
4937 case Intrinsic::nvvm_tex_unified_2d_array_v4s32_s32:
4938 case Intrinsic::nvvm_tex_unified_2d_array_v4s32_f32:
4939 case Intrinsic::nvvm_tex_unified_2d_array_level_v4s32_f32:
4940 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4s32_f32:
4941 case Intrinsic::nvvm_tex_unified_3d_v4s32_s32:
4942 case Intrinsic::nvvm_tex_unified_3d_v4s32_f32:
4943 case Intrinsic::nvvm_tex_unified_3d_level_v4s32_f32:
4944 case Intrinsic::nvvm_tex_unified_3d_grad_v4s32_f32:
4945 case Intrinsic::nvvm_tex_unified_1d_v4u32_s32:
4946 case Intrinsic::nvvm_tex_unified_1d_v4u32_f32:
4947 case Intrinsic::nvvm_tex_unified_1d_level_v4u32_f32:
4948 case Intrinsic::nvvm_tex_unified_1d_grad_v4u32_f32:
4949 case Intrinsic::nvvm_tex_unified_1d_array_v4u32_s32:
4950 case Intrinsic::nvvm_tex_unified_1d_array_v4u32_f32:
4951 case Intrinsic::nvvm_tex_unified_1d_array_level_v4u32_f32:
4952 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4u32_f32:
4953 case Intrinsic::nvvm_tex_unified_2d_v4u32_s32:
4954 case Intrinsic::nvvm_tex_unified_2d_v4u32_f32:
4955 case Intrinsic::nvvm_tex_unified_2d_level_v4u32_f32:
4956 case Intrinsic::nvvm_tex_unified_2d_grad_v4u32_f32:
4957 case Intrinsic::nvvm_tex_unified_2d_array_v4u32_s32:
4958 case Intrinsic::nvvm_tex_unified_2d_array_v4u32_f32:
4959 case Intrinsic::nvvm_tex_unified_2d_array_level_v4u32_f32:
4960 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4u32_f32:
4961 case Intrinsic::nvvm_tex_unified_3d_v4u32_s32:
4962 case Intrinsic::nvvm_tex_unified_3d_v4u32_f32:
4963 case Intrinsic::nvvm_tex_unified_3d_level_v4u32_f32:
4964 case Intrinsic::nvvm_tex_unified_3d_grad_v4u32_f32:
4965 case Intrinsic::nvvm_tex_unified_cube_v4s32_f32:
4966 case Intrinsic::nvvm_tex_unified_cube_level_v4s32_f32:
4967 case Intrinsic::nvvm_tex_unified_cube_array_v4s32_f32:
4968 case Intrinsic::nvvm_tex_unified_cube_array_level_v4s32_f32:
4969 case Intrinsic::nvvm_tex_unified_cube_v4u32_f32:
4970 case Intrinsic::nvvm_tex_unified_cube_level_v4u32_f32:
4971 case Intrinsic::nvvm_tex_unified_cube_array_v4u32_f32:
4972 case Intrinsic::nvvm_tex_unified_cube_array_level_v4u32_f32:
4973 case Intrinsic::nvvm_tex_unified_cube_grad_v4s32_f32:
4974 case Intrinsic::nvvm_tex_unified_cube_grad_v4u32_f32:
4975 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4s32_f32:
4976 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4u32_f32:
4977 case Intrinsic::nvvm_tld4_unified_r_2d_v4s32_f32:
4978 case Intrinsic::nvvm_tld4_unified_g_2d_v4s32_f32:
4979 case Intrinsic::nvvm_tld4_unified_b_2d_v4s32_f32:
4980 case Intrinsic::nvvm_tld4_unified_a_2d_v4s32_f32:
4981 case Intrinsic::nvvm_tld4_unified_r_2d_v4u32_f32:
4982 case Intrinsic::nvvm_tld4_unified_g_2d_v4u32_f32:
4983 case Intrinsic::nvvm_tld4_unified_b_2d_v4u32_f32:
4984 case Intrinsic::nvvm_tld4_unified_a_2d_v4u32_f32:
4985 Info.opc = ISD::INTRINSIC_W_CHAIN;
4986 Info.memVT = MVT::v4i32;
4987 Info.ptrVal = nullptr;
4988 Info.offset = 0;
4989 Info.flags = MachineMemOperand::MOLoad;
4990 Info.align = Align(16);
4991 Infos.push_back(Info);
4992 return;
4993
4994 case Intrinsic::nvvm_suld_1d_i8_clamp:
4995 case Intrinsic::nvvm_suld_1d_v2i8_clamp:
4996 case Intrinsic::nvvm_suld_1d_v4i8_clamp:
4997 case Intrinsic::nvvm_suld_1d_array_i8_clamp:
4998 case Intrinsic::nvvm_suld_1d_array_v2i8_clamp:
4999 case Intrinsic::nvvm_suld_1d_array_v4i8_clamp:
5000 case Intrinsic::nvvm_suld_2d_i8_clamp:
5001 case Intrinsic::nvvm_suld_2d_v2i8_clamp:
5002 case Intrinsic::nvvm_suld_2d_v4i8_clamp:
5003 case Intrinsic::nvvm_suld_2d_array_i8_clamp:
5004 case Intrinsic::nvvm_suld_2d_array_v2i8_clamp:
5005 case Intrinsic::nvvm_suld_2d_array_v4i8_clamp:
5006 case Intrinsic::nvvm_suld_3d_i8_clamp:
5007 case Intrinsic::nvvm_suld_3d_v2i8_clamp:
5008 case Intrinsic::nvvm_suld_3d_v4i8_clamp:
5009 case Intrinsic::nvvm_suld_1d_i8_trap:
5010 case Intrinsic::nvvm_suld_1d_v2i8_trap:
5011 case Intrinsic::nvvm_suld_1d_v4i8_trap:
5012 case Intrinsic::nvvm_suld_1d_array_i8_trap:
5013 case Intrinsic::nvvm_suld_1d_array_v2i8_trap:
5014 case Intrinsic::nvvm_suld_1d_array_v4i8_trap:
5015 case Intrinsic::nvvm_suld_2d_i8_trap:
5016 case Intrinsic::nvvm_suld_2d_v2i8_trap:
5017 case Intrinsic::nvvm_suld_2d_v4i8_trap:
5018 case Intrinsic::nvvm_suld_2d_array_i8_trap:
5019 case Intrinsic::nvvm_suld_2d_array_v2i8_trap:
5020 case Intrinsic::nvvm_suld_2d_array_v4i8_trap:
5021 case Intrinsic::nvvm_suld_3d_i8_trap:
5022 case Intrinsic::nvvm_suld_3d_v2i8_trap:
5023 case Intrinsic::nvvm_suld_3d_v4i8_trap:
5024 case Intrinsic::nvvm_suld_1d_i8_zero:
5025 case Intrinsic::nvvm_suld_1d_v2i8_zero:
5026 case Intrinsic::nvvm_suld_1d_v4i8_zero:
5027 case Intrinsic::nvvm_suld_1d_array_i8_zero:
5028 case Intrinsic::nvvm_suld_1d_array_v2i8_zero:
5029 case Intrinsic::nvvm_suld_1d_array_v4i8_zero:
5030 case Intrinsic::nvvm_suld_2d_i8_zero:
5031 case Intrinsic::nvvm_suld_2d_v2i8_zero:
5032 case Intrinsic::nvvm_suld_2d_v4i8_zero:
5033 case Intrinsic::nvvm_suld_2d_array_i8_zero:
5034 case Intrinsic::nvvm_suld_2d_array_v2i8_zero:
5035 case Intrinsic::nvvm_suld_2d_array_v4i8_zero:
5036 case Intrinsic::nvvm_suld_3d_i8_zero:
5037 case Intrinsic::nvvm_suld_3d_v2i8_zero:
5038 case Intrinsic::nvvm_suld_3d_v4i8_zero:
5039 Info.opc = ISD::INTRINSIC_W_CHAIN;
5040 Info.memVT = MVT::i8;
5041 Info.ptrVal = nullptr;
5042 Info.offset = 0;
5043 Info.flags = MachineMemOperand::MOLoad;
5044 Info.align = Align(16);
5045 Infos.push_back(Info);
5046 return;
5047
5048 case Intrinsic::nvvm_suld_1d_i16_clamp:
5049 case Intrinsic::nvvm_suld_1d_v2i16_clamp:
5050 case Intrinsic::nvvm_suld_1d_v4i16_clamp:
5051 case Intrinsic::nvvm_suld_1d_array_i16_clamp:
5052 case Intrinsic::nvvm_suld_1d_array_v2i16_clamp:
5053 case Intrinsic::nvvm_suld_1d_array_v4i16_clamp:
5054 case Intrinsic::nvvm_suld_2d_i16_clamp:
5055 case Intrinsic::nvvm_suld_2d_v2i16_clamp:
5056 case Intrinsic::nvvm_suld_2d_v4i16_clamp:
5057 case Intrinsic::nvvm_suld_2d_array_i16_clamp:
5058 case Intrinsic::nvvm_suld_2d_array_v2i16_clamp:
5059 case Intrinsic::nvvm_suld_2d_array_v4i16_clamp:
5060 case Intrinsic::nvvm_suld_3d_i16_clamp:
5061 case Intrinsic::nvvm_suld_3d_v2i16_clamp:
5062 case Intrinsic::nvvm_suld_3d_v4i16_clamp:
5063 case Intrinsic::nvvm_suld_1d_i16_trap:
5064 case Intrinsic::nvvm_suld_1d_v2i16_trap:
5065 case Intrinsic::nvvm_suld_1d_v4i16_trap:
5066 case Intrinsic::nvvm_suld_1d_array_i16_trap:
5067 case Intrinsic::nvvm_suld_1d_array_v2i16_trap:
5068 case Intrinsic::nvvm_suld_1d_array_v4i16_trap:
5069 case Intrinsic::nvvm_suld_2d_i16_trap:
5070 case Intrinsic::nvvm_suld_2d_v2i16_trap:
5071 case Intrinsic::nvvm_suld_2d_v4i16_trap:
5072 case Intrinsic::nvvm_suld_2d_array_i16_trap:
5073 case Intrinsic::nvvm_suld_2d_array_v2i16_trap:
5074 case Intrinsic::nvvm_suld_2d_array_v4i16_trap:
5075 case Intrinsic::nvvm_suld_3d_i16_trap:
5076 case Intrinsic::nvvm_suld_3d_v2i16_trap:
5077 case Intrinsic::nvvm_suld_3d_v4i16_trap:
5078 case Intrinsic::nvvm_suld_1d_i16_zero:
5079 case Intrinsic::nvvm_suld_1d_v2i16_zero:
5080 case Intrinsic::nvvm_suld_1d_v4i16_zero:
5081 case Intrinsic::nvvm_suld_1d_array_i16_zero:
5082 case Intrinsic::nvvm_suld_1d_array_v2i16_zero:
5083 case Intrinsic::nvvm_suld_1d_array_v4i16_zero:
5084 case Intrinsic::nvvm_suld_2d_i16_zero:
5085 case Intrinsic::nvvm_suld_2d_v2i16_zero:
5086 case Intrinsic::nvvm_suld_2d_v4i16_zero:
5087 case Intrinsic::nvvm_suld_2d_array_i16_zero:
5088 case Intrinsic::nvvm_suld_2d_array_v2i16_zero:
5089 case Intrinsic::nvvm_suld_2d_array_v4i16_zero:
5090 case Intrinsic::nvvm_suld_3d_i16_zero:
5091 case Intrinsic::nvvm_suld_3d_v2i16_zero:
5092 case Intrinsic::nvvm_suld_3d_v4i16_zero:
5093 Info.opc = ISD::INTRINSIC_W_CHAIN;
5094 Info.memVT = MVT::i16;
5095 Info.ptrVal = nullptr;
5096 Info.offset = 0;
5097 Info.flags = MachineMemOperand::MOLoad;
5098 Info.align = Align(16);
5099 Infos.push_back(Info);
5100 return;
5101
5102 case Intrinsic::nvvm_suld_1d_i32_clamp:
5103 case Intrinsic::nvvm_suld_1d_v2i32_clamp:
5104 case Intrinsic::nvvm_suld_1d_v4i32_clamp:
5105 case Intrinsic::nvvm_suld_1d_array_i32_clamp:
5106 case Intrinsic::nvvm_suld_1d_array_v2i32_clamp:
5107 case Intrinsic::nvvm_suld_1d_array_v4i32_clamp:
5108 case Intrinsic::nvvm_suld_2d_i32_clamp:
5109 case Intrinsic::nvvm_suld_2d_v2i32_clamp:
5110 case Intrinsic::nvvm_suld_2d_v4i32_clamp:
5111 case Intrinsic::nvvm_suld_2d_array_i32_clamp:
5112 case Intrinsic::nvvm_suld_2d_array_v2i32_clamp:
5113 case Intrinsic::nvvm_suld_2d_array_v4i32_clamp:
5114 case Intrinsic::nvvm_suld_3d_i32_clamp:
5115 case Intrinsic::nvvm_suld_3d_v2i32_clamp:
5116 case Intrinsic::nvvm_suld_3d_v4i32_clamp:
5117 case Intrinsic::nvvm_suld_1d_i32_trap:
5118 case Intrinsic::nvvm_suld_1d_v2i32_trap:
5119 case Intrinsic::nvvm_suld_1d_v4i32_trap:
5120 case Intrinsic::nvvm_suld_1d_array_i32_trap:
5121 case Intrinsic::nvvm_suld_1d_array_v2i32_trap:
5122 case Intrinsic::nvvm_suld_1d_array_v4i32_trap:
5123 case Intrinsic::nvvm_suld_2d_i32_trap:
5124 case Intrinsic::nvvm_suld_2d_v2i32_trap:
5125 case Intrinsic::nvvm_suld_2d_v4i32_trap:
5126 case Intrinsic::nvvm_suld_2d_array_i32_trap:
5127 case Intrinsic::nvvm_suld_2d_array_v2i32_trap:
5128 case Intrinsic::nvvm_suld_2d_array_v4i32_trap:
5129 case Intrinsic::nvvm_suld_3d_i32_trap:
5130 case Intrinsic::nvvm_suld_3d_v2i32_trap:
5131 case Intrinsic::nvvm_suld_3d_v4i32_trap:
5132 case Intrinsic::nvvm_suld_1d_i32_zero:
5133 case Intrinsic::nvvm_suld_1d_v2i32_zero:
5134 case Intrinsic::nvvm_suld_1d_v4i32_zero:
5135 case Intrinsic::nvvm_suld_1d_array_i32_zero:
5136 case Intrinsic::nvvm_suld_1d_array_v2i32_zero:
5137 case Intrinsic::nvvm_suld_1d_array_v4i32_zero:
5138 case Intrinsic::nvvm_suld_2d_i32_zero:
5139 case Intrinsic::nvvm_suld_2d_v2i32_zero:
5140 case Intrinsic::nvvm_suld_2d_v4i32_zero:
5141 case Intrinsic::nvvm_suld_2d_array_i32_zero:
5142 case Intrinsic::nvvm_suld_2d_array_v2i32_zero:
5143 case Intrinsic::nvvm_suld_2d_array_v4i32_zero:
5144 case Intrinsic::nvvm_suld_3d_i32_zero:
5145 case Intrinsic::nvvm_suld_3d_v2i32_zero:
5146 case Intrinsic::nvvm_suld_3d_v4i32_zero:
5147 Info.opc = ISD::INTRINSIC_W_CHAIN;
5148 Info.memVT = MVT::i32;
5149 Info.ptrVal = nullptr;
5150 Info.offset = 0;
5151 Info.flags = MachineMemOperand::MOLoad;
5152 Info.align = Align(16);
5153 Infos.push_back(Info);
5154 return;
5155
5156 case Intrinsic::nvvm_suld_1d_i64_clamp:
5157 case Intrinsic::nvvm_suld_1d_v2i64_clamp:
5158 case Intrinsic::nvvm_suld_1d_array_i64_clamp:
5159 case Intrinsic::nvvm_suld_1d_array_v2i64_clamp:
5160 case Intrinsic::nvvm_suld_2d_i64_clamp:
5161 case Intrinsic::nvvm_suld_2d_v2i64_clamp:
5162 case Intrinsic::nvvm_suld_2d_array_i64_clamp:
5163 case Intrinsic::nvvm_suld_2d_array_v2i64_clamp:
5164 case Intrinsic::nvvm_suld_3d_i64_clamp:
5165 case Intrinsic::nvvm_suld_3d_v2i64_clamp:
5166 case Intrinsic::nvvm_suld_1d_i64_trap:
5167 case Intrinsic::nvvm_suld_1d_v2i64_trap:
5168 case Intrinsic::nvvm_suld_1d_array_i64_trap:
5169 case Intrinsic::nvvm_suld_1d_array_v2i64_trap:
5170 case Intrinsic::nvvm_suld_2d_i64_trap:
5171 case Intrinsic::nvvm_suld_2d_v2i64_trap:
5172 case Intrinsic::nvvm_suld_2d_array_i64_trap:
5173 case Intrinsic::nvvm_suld_2d_array_v2i64_trap:
5174 case Intrinsic::nvvm_suld_3d_i64_trap:
5175 case Intrinsic::nvvm_suld_3d_v2i64_trap:
5176 case Intrinsic::nvvm_suld_1d_i64_zero:
5177 case Intrinsic::nvvm_suld_1d_v2i64_zero:
5178 case Intrinsic::nvvm_suld_1d_array_i64_zero:
5179 case Intrinsic::nvvm_suld_1d_array_v2i64_zero:
5180 case Intrinsic::nvvm_suld_2d_i64_zero:
5181 case Intrinsic::nvvm_suld_2d_v2i64_zero:
5182 case Intrinsic::nvvm_suld_2d_array_i64_zero:
5183 case Intrinsic::nvvm_suld_2d_array_v2i64_zero:
5184 case Intrinsic::nvvm_suld_3d_i64_zero:
5185 case Intrinsic::nvvm_suld_3d_v2i64_zero:
5186 Info.opc = ISD::INTRINSIC_W_CHAIN;
5187 Info.memVT = MVT::i64;
5188 Info.ptrVal = nullptr;
5189 Info.offset = 0;
5190 Info.flags = MachineMemOperand::MOLoad;
5191 Info.align = Align(16);
5192 Infos.push_back(Info);
5193 return;
5194
5195 case Intrinsic::nvvm_tcgen05_ld_16x64b_x1:
5196 case Intrinsic::nvvm_tcgen05_ld_32x32b_x1:
5197 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x1: {
5198 Info.opc = ISD::INTRINSIC_W_CHAIN;
5199 Info.memVT = MVT::v1i32;
5200 Info.ptrVal = I.getArgOperand(0);
5201 Info.offset = 0;
5202 Info.flags = MachineMemOperand::MOLoad;
5203 Info.align.reset();
5204 Infos.push_back(Info);
5205 return;
5206 }
5207
5208 case Intrinsic::nvvm_tcgen05_ld_16x64b_x2:
5209 case Intrinsic::nvvm_tcgen05_ld_16x128b_x1:
5210 case Intrinsic::nvvm_tcgen05_ld_32x32b_x2:
5211 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x2:
5212 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x2_i32:
5213 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x2_i32: {
5214 Info.opc = ISD::INTRINSIC_W_CHAIN;
5215 Info.memVT = MVT::v2i32;
5216 Info.ptrVal = I.getArgOperand(0);
5217 Info.offset = 0;
5218 Info.flags = MachineMemOperand::MOLoad;
5219 Info.align.reset();
5220 Infos.push_back(Info);
5221 return;
5222 }
5223
5224 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x2_f32:
5225 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x2_f32: {
5226 Info.opc = ISD::INTRINSIC_W_CHAIN;
5227 Info.memVT = MVT::v2f32;
5228 Info.ptrVal = I.getArgOperand(0);
5229 Info.offset = 0;
5230 Info.flags = MachineMemOperand::MOLoad;
5231 Info.align.reset();
5232 Infos.push_back(Info);
5233 return;
5234 }
5235
5236 case Intrinsic::nvvm_tcgen05_ld_16x64b_x4:
5237 case Intrinsic::nvvm_tcgen05_ld_16x128b_x2:
5238 case Intrinsic::nvvm_tcgen05_ld_32x32b_x4:
5239 case Intrinsic::nvvm_tcgen05_ld_16x256b_x1:
5240 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x4:
5241 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_i32:
5242 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_i32: {
5243 Info.opc = ISD::INTRINSIC_W_CHAIN;
5244 Info.memVT = MVT::v4i32;
5245 Info.ptrVal = I.getArgOperand(0);
5246 Info.offset = 0;
5247 Info.flags = MachineMemOperand::MOLoad;
5248 Info.align.reset();
5249 Infos.push_back(Info);
5250 return;
5251 }
5252
5253 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_f32:
5254 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_f32: {
5255 Info.opc = ISD::INTRINSIC_W_CHAIN;
5256 Info.memVT = MVT::v4f32;
5257 Info.ptrVal = I.getArgOperand(0);
5258 Info.offset = 0;
5259 Info.flags = MachineMemOperand::MOLoad;
5260 Info.align.reset();
5261 Infos.push_back(Info);
5262 return;
5263 }
5264
5265 case Intrinsic::nvvm_tcgen05_ld_16x64b_x8:
5266 case Intrinsic::nvvm_tcgen05_ld_16x128b_x4:
5267 case Intrinsic::nvvm_tcgen05_ld_16x256b_x2:
5268 case Intrinsic::nvvm_tcgen05_ld_32x32b_x8:
5269 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x8:
5270 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_i32:
5271 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_i32: {
5272 Info.opc = ISD::INTRINSIC_W_CHAIN;
5273 Info.memVT = MVT::v8i32;
5274 Info.ptrVal = I.getArgOperand(0);
5275 Info.offset = 0;
5276 Info.flags = MachineMemOperand::MOLoad;
5277 Info.align.reset();
5278 Infos.push_back(Info);
5279 return;
5280 }
5281
5282 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_f32:
5283 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_f32: {
5284 Info.opc = ISD::INTRINSIC_W_CHAIN;
5285 Info.memVT = MVT::v8f32;
5286 Info.ptrVal = I.getArgOperand(0);
5287 Info.offset = 0;
5288 Info.flags = MachineMemOperand::MOLoad;
5289 Info.align.reset();
5290 Infos.push_back(Info);
5291 return;
5292 }
5293
5294 case Intrinsic::nvvm_tcgen05_ld_16x64b_x16:
5295 case Intrinsic::nvvm_tcgen05_ld_16x128b_x8:
5296 case Intrinsic::nvvm_tcgen05_ld_16x256b_x4:
5297 case Intrinsic::nvvm_tcgen05_ld_32x32b_x16:
5298 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x16:
5299 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_i32:
5300 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_i32: {
5301 Info.opc = ISD::INTRINSIC_W_CHAIN;
5302 Info.memVT = MVT::v16i32;
5303 Info.ptrVal = I.getArgOperand(0);
5304 Info.offset = 0;
5305 Info.flags = MachineMemOperand::MOLoad;
5306 Info.align.reset();
5307 Infos.push_back(Info);
5308 return;
5309 }
5310
5311 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_f32:
5312 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_f32: {
5313 Info.opc = ISD::INTRINSIC_W_CHAIN;
5314 Info.memVT = MVT::v16f32;
5315 Info.ptrVal = I.getArgOperand(0);
5316 Info.offset = 0;
5317 Info.flags = MachineMemOperand::MOLoad;
5318 Info.align.reset();
5319 Infos.push_back(Info);
5320 return;
5321 }
5322
5323 case Intrinsic::nvvm_tcgen05_ld_16x64b_x32:
5324 case Intrinsic::nvvm_tcgen05_ld_16x128b_x16:
5325 case Intrinsic::nvvm_tcgen05_ld_16x256b_x8:
5326 case Intrinsic::nvvm_tcgen05_ld_32x32b_x32:
5327 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x32:
5328 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_i32:
5329 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_i32: {
5330 Info.opc = ISD::INTRINSIC_W_CHAIN;
5331 Info.memVT = MVT::v32i32;
5332 Info.ptrVal = I.getArgOperand(0);
5333 Info.offset = 0;
5334 Info.flags = MachineMemOperand::MOLoad;
5335 Info.align.reset();
5336 Infos.push_back(Info);
5337 return;
5338 }
5339
5340 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_f32:
5341 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_f32: {
5342 Info.opc = ISD::INTRINSIC_W_CHAIN;
5343 Info.memVT = MVT::v32f32;
5344 Info.ptrVal = I.getArgOperand(0);
5345 Info.offset = 0;
5346 Info.flags = MachineMemOperand::MOLoad;
5347 Info.align.reset();
5348 Infos.push_back(Info);
5349 return;
5350 }
5351
5352 case Intrinsic::nvvm_tcgen05_ld_16x64b_x64:
5353 case Intrinsic::nvvm_tcgen05_ld_16x128b_x32:
5354 case Intrinsic::nvvm_tcgen05_ld_16x256b_x16:
5355 case Intrinsic::nvvm_tcgen05_ld_32x32b_x64:
5356 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x64:
5357 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_i32:
5358 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_i32: {
5359 Info.opc = ISD::INTRINSIC_W_CHAIN;
5360 Info.memVT = MVT::v64i32;
5361 Info.ptrVal = I.getArgOperand(0);
5362 Info.offset = 0;
5363 Info.flags = MachineMemOperand::MOLoad;
5364 Info.align.reset();
5365 Infos.push_back(Info);
5366 return;
5367 }
5368
5369 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_f32:
5370 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_f32: {
5371 Info.opc = ISD::INTRINSIC_W_CHAIN;
5372 Info.memVT = MVT::v64f32;
5373 Info.ptrVal = I.getArgOperand(0);
5374 Info.offset = 0;
5375 Info.flags = MachineMemOperand::MOLoad;
5376 Info.align.reset();
5377 Infos.push_back(Info);
5378 return;
5379 }
5380
5381 case Intrinsic::nvvm_tcgen05_ld_16x64b_x128:
5382 case Intrinsic::nvvm_tcgen05_ld_16x128b_x64:
5383 case Intrinsic::nvvm_tcgen05_ld_16x256b_x32:
5384 case Intrinsic::nvvm_tcgen05_ld_32x32b_x128:
5385 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x128:
5386 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_i32:
5387 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_i32: {
5388 Info.opc = ISD::INTRINSIC_W_CHAIN;
5389 Info.memVT = MVT::v128i32;
5390 Info.ptrVal = I.getArgOperand(0);
5391 Info.offset = 0;
5392 Info.flags = MachineMemOperand::MOLoad;
5393 Info.align.reset();
5394 Infos.push_back(Info);
5395 return;
5396 }
5397
5398 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_f32:
5399 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_f32: {
5400 Info.opc = ISD::INTRINSIC_W_CHAIN;
5401 Info.memVT = MVT::v128f32;
5402 Info.ptrVal = I.getArgOperand(0);
5403 Info.offset = 0;
5404 Info.flags = MachineMemOperand::MOLoad;
5405 Info.align.reset();
5406 Infos.push_back(Info);
5407 return;
5408 }
5409
5410 case Intrinsic::nvvm_tcgen05_st_16x64b_x1:
5411 case Intrinsic::nvvm_tcgen05_st_32x32b_x1:
5412 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x1: {
5413 Info.opc = ISD::INTRINSIC_VOID;
5414 Info.memVT = MVT::v1i32;
5415 Info.ptrVal = I.getArgOperand(0);
5416 Info.offset = 0;
5417 Info.flags = MachineMemOperand::MOStore;
5418 Info.align.reset();
5419 Infos.push_back(Info);
5420 return;
5421 }
5422
5423 case Intrinsic::nvvm_tcgen05_st_16x64b_x2:
5424 case Intrinsic::nvvm_tcgen05_st_16x128b_x1:
5425 case Intrinsic::nvvm_tcgen05_st_32x32b_x2:
5426 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x2: {
5427 Info.opc = ISD::INTRINSIC_VOID;
5428 Info.memVT = MVT::v2i32;
5429 Info.ptrVal = I.getArgOperand(0);
5430 Info.offset = 0;
5431 Info.flags = MachineMemOperand::MOStore;
5432 Info.align.reset();
5433 Infos.push_back(Info);
5434 return;
5435 }
5436
5437 case Intrinsic::nvvm_tcgen05_st_16x64b_x4:
5438 case Intrinsic::nvvm_tcgen05_st_16x128b_x2:
5439 case Intrinsic::nvvm_tcgen05_st_16x256b_x1:
5440 case Intrinsic::nvvm_tcgen05_st_32x32b_x4:
5441 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x4: {
5442 Info.opc = ISD::INTRINSIC_VOID;
5443 Info.memVT = MVT::v4i32;
5444 Info.ptrVal = I.getArgOperand(0);
5445 Info.offset = 0;
5446 Info.flags = MachineMemOperand::MOStore;
5447 Info.align.reset();
5448 Infos.push_back(Info);
5449 return;
5450 }
5451
5452 case Intrinsic::nvvm_tcgen05_st_16x64b_x8:
5453 case Intrinsic::nvvm_tcgen05_st_16x128b_x4:
5454 case Intrinsic::nvvm_tcgen05_st_16x256b_x2:
5455 case Intrinsic::nvvm_tcgen05_st_32x32b_x8:
5456 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x8: {
5457 Info.opc = ISD::INTRINSIC_VOID;
5458 Info.memVT = MVT::v8i32;
5459 Info.ptrVal = I.getArgOperand(0);
5460 Info.offset = 0;
5461 Info.flags = MachineMemOperand::MOStore;
5462 Info.align.reset();
5463 Infos.push_back(Info);
5464 return;
5465 }
5466
5467 case Intrinsic::nvvm_tcgen05_st_16x64b_x16:
5468 case Intrinsic::nvvm_tcgen05_st_16x128b_x8:
5469 case Intrinsic::nvvm_tcgen05_st_16x256b_x4:
5470 case Intrinsic::nvvm_tcgen05_st_32x32b_x16:
5471 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x16: {
5472 Info.opc = ISD::INTRINSIC_VOID;
5473 Info.memVT = MVT::v16i32;
5474 Info.ptrVal = I.getArgOperand(0);
5475 Info.offset = 0;
5476 Info.flags = MachineMemOperand::MOStore;
5477 Info.align.reset();
5478 Infos.push_back(Info);
5479 return;
5480 }
5481
5482 case Intrinsic::nvvm_tcgen05_st_16x64b_x32:
5483 case Intrinsic::nvvm_tcgen05_st_16x128b_x16:
5484 case Intrinsic::nvvm_tcgen05_st_16x256b_x8:
5485 case Intrinsic::nvvm_tcgen05_st_32x32b_x32:
5486 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x32: {
5487 Info.opc = ISD::INTRINSIC_VOID;
5488 Info.memVT = MVT::v32i32;
5489 Info.ptrVal = I.getArgOperand(0);
5490 Info.offset = 0;
5491 Info.flags = MachineMemOperand::MOStore;
5492 Info.align.reset();
5493 Infos.push_back(Info);
5494 return;
5495 }
5496
5497 case Intrinsic::nvvm_tcgen05_st_16x64b_x64:
5498 case Intrinsic::nvvm_tcgen05_st_16x128b_x32:
5499 case Intrinsic::nvvm_tcgen05_st_16x256b_x16:
5500 case Intrinsic::nvvm_tcgen05_st_32x32b_x64:
5501 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x64: {
5502 Info.opc = ISD::INTRINSIC_VOID;
5503 Info.memVT = MVT::v64i32;
5504 Info.ptrVal = I.getArgOperand(0);
5505 Info.offset = 0;
5506 Info.flags = MachineMemOperand::MOStore;
5507 Info.align.reset();
5508 Infos.push_back(Info);
5509 return;
5510 }
5511
5512 case Intrinsic::nvvm_tcgen05_st_16x64b_x128:
5513 case Intrinsic::nvvm_tcgen05_st_16x128b_x64:
5514 case Intrinsic::nvvm_tcgen05_st_16x256b_x32:
5515 case Intrinsic::nvvm_tcgen05_st_32x32b_x128:
5516 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x128: {
5517 Info.opc = ISD::INTRINSIC_VOID;
5518 Info.memVT = MVT::v128i32;
5519 Info.ptrVal = I.getArgOperand(0);
5520 Info.offset = 0;
5521 Info.flags = MachineMemOperand::MOStore;
5522 Info.align.reset();
5523 Infos.push_back(Info);
5524 return;
5525 }
5526 case Intrinsic::
5527 nvvm_tcgen05_mma_shared_f8f6f4_disable_output_lane_cg1_decompress_b:
5528 case Intrinsic::
5529 nvvm_tcgen05_mma_tensor_f8f6f4_disable_output_lane_cg1_decompress_b:
5530 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg1:
5531 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg1:
5532 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg1:
5533 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg1:
5534 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1:
5535 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1:
5536 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1_ashift:
5537 case Intrinsic::
5538 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1_ashift:
5539 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1:
5540 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1:
5541 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1_ashift:
5542 case Intrinsic::
5543 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1_ashift: {
5544 // We are reading and writing back to TMem
5545 Info.opc = ISD::INTRINSIC_VOID;
5546 Info.memVT = MVT::v4i32;
5547 Info.ptrVal = I.getArgOperand(0);
5548 Info.offset = 0;
5550 Info.align = Align(16);
5551 Infos.push_back(Info);
5552 return;
5553 }
5554
5555 case Intrinsic::
5556 nvvm_tcgen05_mma_shared_f8f6f4_disable_output_lane_cg2_decompress_b:
5557 case Intrinsic::
5558 nvvm_tcgen05_mma_tensor_f8f6f4_disable_output_lane_cg2_decompress_b:
5559 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg2:
5560 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg2:
5561 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg2:
5562 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg2:
5563 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2:
5564 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2:
5565 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2:
5566 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2:
5567 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2_ashift:
5568 case Intrinsic::
5569 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2_ashift:
5570 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2_ashift:
5571 case Intrinsic::
5572 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2_ashift: {
5573 // We are reading and writing back to TMem
5574 Info.opc = ISD::INTRINSIC_VOID;
5575 Info.memVT = MVT::v8i32;
5576 Info.ptrVal = I.getArgOperand(0);
5577 Info.offset = 0;
5579 Info.align = Align(16);
5580 Infos.push_back(Info);
5581 return;
5582 }
5583 case Intrinsic::nvvm_tcgen05_alloc_cg1:
5584 case Intrinsic::nvvm_tcgen05_alloc_cg2:
5585 Info.opc = ISD::INTRINSIC_VOID;
5586 Info.memVT = MVT::i32;
5587 Info.ptrVal = I.getArgOperand(0);
5588 Info.offset = 0;
5589 Info.flags = MachineMemOperand::MOStore;
5590 Info.align = Align(4);
5591 Infos.push_back(Info);
5592 return;
5593 }
5594}
5595
5596// Helper for getting a function parameter symbol. Its name is composed from
5597// the function name and the parameter index. Negative index corresponds to the
5598// special parameter (unsized array) used for passing variable arguments.
5600 int Idx) const {
5601 const StringRef FuncName = getTargetMachine().getSymbol(F)->getName();
5602 if (Idx < 0)
5603 return Ctx.getOrCreateSymbol(FuncName + "_vararg");
5604 return Ctx.getOrCreateSymbol(FuncName + "_param_" + Twine(Idx));
5605}
5606
5607/// isLegalAddressingMode - Return true if the addressing mode represented
5608/// by AM is legal for this target, for a load/store of the specified type.
5609/// Used to guide target specific optimizations, like loop strength reduction
5610/// (LoopStrengthReduce.cpp) and memory optimization for address mode
5611/// (CodeGenPrepare.cpp)
5613 const AddrMode &AM, Type *Ty,
5614 unsigned AS, Instruction *I) const {
5615 // AddrMode - This represents an addressing mode of:
5616 // BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
5617 //
5618 // The legal address modes are
5619 // - [avar]
5620 // - [areg]
5621 // - [areg+immoff]
5622 // - [immAddr]
5623
5624 // immoff must fit in a signed 32-bit int
5625 if (!APInt(64, AM.BaseOffs).isSignedIntN(32))
5626 return false;
5627
5628 if (AM.BaseGV)
5629 return !AM.BaseOffs && !AM.HasBaseReg && !AM.Scale;
5630
5631 switch (AM.Scale) {
5632 case 0: // "r", "r+i" or "i" is allowed
5633 break;
5634 case 1:
5635 if (AM.HasBaseReg) // "r+r+i" or "r+r" is not allowed.
5636 return false;
5637 // Otherwise we have r+i.
5638 break;
5639 default:
5640 // No scale > 1 is allowed
5641 return false;
5642 }
5643 return true;
5644}
5645
5646//===----------------------------------------------------------------------===//
5647// NVPTX Inline Assembly Support
5648//===----------------------------------------------------------------------===//
5649
5650/// getConstraintType - Given a constraint letter, return the type of
5651/// constraint it is for this target.
5654 if (Constraint.size() == 1) {
5655 switch (Constraint[0]) {
5656 default:
5657 break;
5658 case 'b':
5659 case 'r':
5660 case 'h':
5661 case 'c':
5662 case 'l':
5663 case 'f':
5664 case 'd':
5665 case 'q':
5666 case '0':
5667 case 'N':
5668 return C_RegisterClass;
5669 }
5670 }
5671 return TargetLowering::getConstraintType(Constraint);
5672}
5673
5674std::pair<unsigned, const TargetRegisterClass *>
5676 StringRef Constraint,
5677 MVT VT) const {
5678 if (Constraint.size() == 1) {
5679 switch (Constraint[0]) {
5680 case 'b':
5681 return std::make_pair(0U, &NVPTX::B1RegClass);
5682 case 'c':
5683 case 'h':
5684 return std::make_pair(0U, &NVPTX::B16RegClass);
5685 case 'r':
5686 case 'f':
5687 return std::make_pair(0U, &NVPTX::B32RegClass);
5688 case 'l':
5689 case 'N':
5690 case 'd':
5691 return std::make_pair(0U, &NVPTX::B64RegClass);
5692 case 'q': {
5693 if (!STI.hasFeature(NVPTX::SM70))
5694 report_fatal_error("Inline asm with 128 bit operands is only "
5695 "supported for sm_70 and higher!");
5696 return std::make_pair(0U, &NVPTX::B128RegClass);
5697 }
5698 }
5699 }
5700 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5701}
5702
5703//===----------------------------------------------------------------------===//
5704// NVPTX DAG Combining
5705//===----------------------------------------------------------------------===//
5706
5708 CodeGenOptLevel OptLevel) const {
5709 // Always honor command-line argument
5710 if (FMAContractLevelOpt.getNumOccurrences() > 0)
5711 return FMAContractLevelOpt > 0;
5712
5713 // Do not contract if we're not optimizing the code.
5714 if (OptLevel == CodeGenOptLevel::None)
5715 return false;
5716
5717 return false;
5718}
5719
5720static bool isConstZero(const SDValue &Operand) {
5721 const auto *Const = dyn_cast<ConstantSDNode>(Operand);
5722 return Const && Const->getZExtValue() == 0;
5723}
5724
5725/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
5726/// operands N0 and N1. This is a helper for PerformADDCombine that is
5727/// called with the default operands, and if that fails, with commuted
5728/// operands.
5729static SDValue
5732 EVT VT = N0.getValueType();
5733
5734 // Since integer multiply-add costs the same as integer multiply
5735 // but is more costly than integer add, do the fusion only when
5736 // the mul is only used in the add.
5737 // TODO: this may not be true for later architectures, consider relaxing this
5738 if (!N0.getNode()->hasOneUse())
5739 return SDValue();
5740
5741 // fold (add (select cond, 0, (mul a, b)), c)
5742 // -> (select cond, c, (add (mul a, b), c))
5743 //
5744 if (N0.getOpcode() == ISD::SELECT) {
5745 unsigned ZeroOpNum;
5746 if (isConstZero(N0->getOperand(1)))
5747 ZeroOpNum = 1;
5748 else if (isConstZero(N0->getOperand(2)))
5749 ZeroOpNum = 2;
5750 else
5751 return SDValue();
5752
5753 SDValue M = N0->getOperand((ZeroOpNum == 1) ? 2 : 1);
5754 if (M->getOpcode() != ISD::MUL || !M.getNode()->hasOneUse())
5755 return SDValue();
5756
5757 SDLoc DL(N);
5758 SDValue Mul =
5759 DCI.DAG.getNode(ISD::MUL, DL, VT, M->getOperand(0), M->getOperand(1));
5760 SDValue MAD = DCI.DAG.getNode(ISD::ADD, DL, VT, Mul, N1);
5761 return DCI.DAG.getSelect(SDLoc(N), VT, N0->getOperand(0),
5762 ((ZeroOpNum == 1) ? N1 : MAD),
5763 ((ZeroOpNum == 1) ? MAD : N1));
5764 }
5765
5766 return SDValue();
5767}
5768
5769SDValue NVPTXTargetLowering::performFADDCombineWithOperands(
5771 CodeGenOptLevel OptLevel) const {
5772 EVT VT = N0.getValueType();
5773 if (N0.getOpcode() == ISD::FMUL) {
5774 if (!(allowFMA(DCI.DAG.getMachineFunction(), OptLevel) ||
5775 (N->getFlags().hasAllowContract() &&
5776 N0->getFlags().hasAllowContract())))
5777 return SDValue();
5778
5779 // For floating point:
5780 // Do the fusion only when the mul has less than 5 uses and all
5781 // are add.
5782 // The heuristic is that if a use is not an add, then that use
5783 // cannot be fused into fma, therefore mul is still needed anyway.
5784 // If there are more than 4 uses, even if they are all add, fusing
5785 // them will increase register pressue.
5786 //
5787 int numUses = 0;
5788 int nonAddCount = 0;
5789 for (const SDNode *User : N0.getNode()->users()) {
5790 numUses++;
5791 if (User->getOpcode() != ISD::FADD)
5792 ++nonAddCount;
5793 if (numUses >= 5)
5794 return SDValue();
5795 }
5796 if (nonAddCount) {
5797 int orderNo = N->getIROrder();
5798 int orderNo2 = N0.getNode()->getIROrder();
5799 // simple heuristics here for considering potential register
5800 // pressure, the logics here is that the differnce are used
5801 // to measure the distance between def and use, the longer distance
5802 // more likely cause register pressure.
5803 if (orderNo - orderNo2 < 500)
5804 return SDValue();
5805
5806 // Now, check if at least one of the FMUL's operands is live beyond the
5807 // node N, which guarantees that the FMA will not increase register
5808 // pressure at node N.
5809 bool opIsLive = false;
5810 const SDNode *left = N0.getOperand(0).getNode();
5811 const SDNode *right = N0.getOperand(1).getNode();
5812
5813 if (isa<ConstantSDNode>(left) || isa<ConstantSDNode>(right))
5814 opIsLive = true;
5815
5816 if (!opIsLive)
5817 for (const SDNode *User : left->users()) {
5818 int orderNo3 = User->getIROrder();
5819 if (orderNo3 > orderNo) {
5820 opIsLive = true;
5821 break;
5822 }
5823 }
5824
5825 if (!opIsLive)
5826 for (const SDNode *User : right->users()) {
5827 int orderNo3 = User->getIROrder();
5828 if (orderNo3 > orderNo) {
5829 opIsLive = true;
5830 break;
5831 }
5832 }
5833
5834 if (!opIsLive)
5835 return SDValue();
5836 }
5837
5838 return DCI.DAG.getNode(ISD::FMA, SDLoc(N), VT, N0.getOperand(0),
5839 N0.getOperand(1), N1);
5840 }
5841
5842 return SDValue();
5843}
5844
5845/// Fold unpacking movs into a load by increasing the number of return values.
5846///
5847/// ex:
5848/// L: v2f16,ch = load <p>
5849/// a: f16 = extractelt L:0, 0
5850/// b: f16 = extractelt L:0, 1
5851/// use(a, b)
5852///
5853/// ...is turned into...
5854///
5855/// L: f16,f16,ch = LoadV2 <p>
5856/// use(L:0, L:1)
5857static SDValue
5859 // Don't run this optimization before the legalizer
5860 if (!DCI.isAfterLegalizeDAG())
5861 return SDValue();
5862
5863 EVT ElementVT = N->getValueType(0);
5864 // Avoid non-packed types and v4i8
5865 if (!NVPTX::isPackedVectorTy(ElementVT) || ElementVT == MVT::v4i8)
5866 return SDValue();
5867
5868 // Check whether all outputs are either used by an extractelt or are
5869 // glue/chain nodes
5870 if (!all_of(N->uses(), [&](SDUse &U) {
5871 // Skip glue, chain nodes
5872 if (U.getValueType() == MVT::Glue || U.getValueType() == MVT::Other)
5873 return true;
5874 if (U.getUser()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
5875 if (N->getOpcode() != ISD::LOAD)
5876 return true;
5877 // Since this is an ISD::LOAD, check all extractelts are used. If
5878 // any are not used, we don't want to defeat another optimization that
5879 // will narrow the load.
5880 //
5881 // For example:
5882 //
5883 // L: v2f16,ch = load <p>
5884 // e0: f16 = extractelt L:0, 0
5885 // e1: f16 = extractelt L:0, 1 <-- unused
5886 // store e0
5887 //
5888 // Can be optimized by DAGCombiner to:
5889 //
5890 // L: f16,ch = load <p>
5891 // store L:0
5892 return !U.getUser()->use_empty();
5893 }
5894
5895 // Otherwise, this use prevents us from splitting a value.
5896 return false;
5897 }))
5898 return SDValue();
5899
5900 auto *LD = cast<MemSDNode>(N);
5901 SDLoc DL(LD);
5902
5903 // the new opcode after we double the number of operands
5904 unsigned Opcode;
5906 unsigned OldNumOutputs; // non-glue, non-chain outputs
5907 switch (LD->getOpcode()) {
5908 case ISD::LOAD:
5909 OldNumOutputs = 1;
5910 // Any packed type is legal, so the legalizer will not have lowered
5911 // ISD::LOAD -> NVPTXISD::Load (unless it's under-aligned). We have to do it
5912 // here.
5913 Opcode = NVPTXISD::LoadV2;
5914 // append a "full" used bytes mask operand right before the extension type
5915 // operand, signifying that all bytes are used.
5916 Operands.push_back(DCI.DAG.getConstant(UINT32_MAX, DL, MVT::i32));
5917 Operands.push_back(DCI.DAG.getIntPtrConstant(
5918 cast<LoadSDNode>(LD)->getExtensionType(), DL));
5919 break;
5920 case NVPTXISD::LoadV2:
5921 OldNumOutputs = 2;
5922 Opcode = NVPTXISD::LoadV4;
5923 break;
5924 case NVPTXISD::LoadV4:
5925 // V8 is only supported for f32/i32. Don't forget, we're not changing the
5926 // load size here. This is already a 256-bit load.
5927 if (ElementVT != MVT::v2f32 && ElementVT != MVT::v2i32)
5928 return SDValue();
5929 OldNumOutputs = 4;
5930 Opcode = NVPTXISD::LoadV8;
5931 break;
5932 case NVPTXISD::LoadV8:
5933 // PTX doesn't support the next doubling of outputs
5934 return SDValue();
5935 }
5936
5937 // the non-glue, non-chain outputs in the new load
5938 const unsigned NewNumOutputs = OldNumOutputs * 2;
5939 SmallVector<EVT> NewVTs(NewNumOutputs, ElementVT.getVectorElementType());
5940 // add remaining chain and glue values
5941 NewVTs.append(LD->value_begin() + OldNumOutputs, LD->value_end());
5942
5943 // Create the new load
5944 SDValue NewLoad = DCI.DAG.getMemIntrinsicNode(
5945 Opcode, DL, DCI.DAG.getVTList(NewVTs), Operands, LD->getMemoryVT(),
5946 LD->getMemOperand());
5947
5948 // Now we use a combination of BUILD_VECTORs and a MERGE_VALUES node to keep
5949 // the outputs the same. These nodes will be optimized away in later
5950 // DAGCombiner iterations.
5952 for (unsigned I : seq(OldNumOutputs))
5953 Results.push_back(DCI.DAG.getBuildVector(
5954 ElementVT, DL, {NewLoad.getValue(I * 2), NewLoad.getValue(I * 2 + 1)}));
5955 // Add remaining chain and glue nodes
5956 for (unsigned I : seq(NewLoad->getNumValues() - NewNumOutputs))
5957 Results.push_back(NewLoad.getValue(NewNumOutputs + I));
5958
5959 return DCI.DAG.getMergeValues(Results, DL);
5960}
5961
5962/// Fold packing movs into a store.
5963///
5964/// ex:
5965/// v1: v2f16 = BUILD_VECTOR a:f16, b:f16
5966/// v2: v2f16 = BUILD_VECTOR c:f16, d:f16
5967/// StoreV2 v1, v2
5968///
5969/// ...is turned into...
5970///
5971/// StoreV4 a, b, c, d
5974 unsigned Front, unsigned Back) {
5975 // We want to run this as late as possible since other optimizations may
5976 // eliminate the BUILD_VECTORs.
5977 if (!DCI.isAfterLegalizeDAG())
5978 return SDValue();
5979
5980 // Get the type of the operands being stored.
5981 EVT ElementVT = N->getOperand(Front).getValueType();
5982
5983 // Avoid non-packed types and v4i8
5984 if (!NVPTX::isPackedVectorTy(ElementVT) || ElementVT == MVT::v4i8)
5985 return SDValue();
5986
5987 auto *ST = cast<MemSDNode>(N);
5988
5989 // The new opcode after we double the number of operands.
5990 unsigned Opcode;
5991 switch (N->getOpcode()) {
5992 case ISD::STORE:
5993 // Any packed type is legal, so the legalizer will not have lowered
5994 // ISD::STORE -> NVPTXISD::Store (unless it's under-aligned). We have to do
5995 // it here.
5996 Opcode = NVPTXISD::StoreV2;
5997 break;
5998 case NVPTXISD::StoreV2:
5999 Opcode = NVPTXISD::StoreV4;
6000 break;
6001 case NVPTXISD::StoreV4:
6002 // V8 is only supported for f32/i32. Don't forget, we're not changing the
6003 // store size here. This is already a 256-bit store.
6004 if (ElementVT != MVT::v2f32 && ElementVT != MVT::v2i32)
6005 return SDValue();
6006 Opcode = NVPTXISD::StoreV8;
6007 break;
6008 case NVPTXISD::StoreV8:
6009 // PTX doesn't support the next doubling of operands
6010 return SDValue();
6011 default:
6012 llvm_unreachable("Unhandled store opcode");
6013 }
6014
6015 // Scan the operands and if they're all BUILD_VECTORs, we'll have gathered
6016 // their elements.
6017 SmallVector<SDValue, 4> Operands(N->ops().take_front(Front));
6018 for (SDValue BV : N->ops().drop_front(Front).drop_back(Back)) {
6019 if (BV.getOpcode() != ISD::BUILD_VECTOR)
6020 return SDValue();
6021
6022 // If the operand has multiple uses, this optimization can increase register
6023 // pressure.
6024 if (!BV.hasOneUse())
6025 return SDValue();
6026
6027 // DAGCombiner visits nodes bottom-up. Check the BUILD_VECTOR operands for
6028 // any signs they may be folded by some other pattern or rule.
6029 for (SDValue Op : BV->ops()) {
6030 // Peek through bitcasts
6031 if (Op.getOpcode() == ISD::BITCAST)
6032 Op = Op.getOperand(0);
6033
6034 // This may be folded into a PRMT.
6035 if (Op.getValueType() == MVT::i16 && Op.getOpcode() == ISD::TRUNCATE &&
6036 Op->getOperand(0).getValueType() == MVT::i32)
6037 return SDValue();
6038
6039 // This may be folded into cvt.bf16x2
6040 if (Op.getOpcode() == ISD::FP_ROUND)
6041 return SDValue();
6042 }
6043 Operands.append({BV.getOperand(0), BV.getOperand(1)});
6044 }
6045 Operands.append(N->op_end() - Back, N->op_end());
6046
6047 // Now we replace the store
6048 return DCI.DAG.getMemIntrinsicNode(Opcode, SDLoc(N), N->getVTList(), Operands,
6049 ST->getMemoryVT(), ST->getMemOperand());
6050}
6051
6053 const NVPTXSubtarget &STI) {
6054
6055 if (DCI.isBeforeLegalize() && N->getOpcode() == ISD::STORE) {
6056 // Here is our chance to custom lower a store with a non-simple type.
6057 // Unfortunately, we can't do this in the legalizer because there is no
6058 // way to setOperationAction for an non-simple type.
6060 if (!ST->getValue().getValueType().isSimple())
6061 return lowerSTOREVector(SDValue(ST, 0), DCI.DAG, STI);
6062 }
6063
6064 return combinePackingMovIntoStore(N, DCI, 1, 2);
6065}
6066
6068 const NVPTXSubtarget &STI) {
6069 if (DCI.isBeforeLegalize() && N->getOpcode() == ISD::LOAD) {
6070 // Here is our chance to custom lower a load with a non-simple type.
6071 // Unfortunately, we can't do this in the legalizer because there is no
6072 // way to setOperationAction for an non-simple type.
6073 if (!N->getValueType(0).isSimple())
6074 return lowerLoadVector(N, DCI.DAG, STI);
6075 }
6076
6077 return combineUnpackingMovIntoLoad(N, DCI);
6078}
6079
6080/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6081///
6084 CodeGenOptLevel OptLevel) {
6085 if (OptLevel == CodeGenOptLevel::None)
6086 return SDValue();
6087
6088 SDValue N0 = N->getOperand(0);
6089 SDValue N1 = N->getOperand(1);
6090
6091 // Skip non-integer, non-scalar case
6092 EVT VT = N0.getValueType();
6093 if (VT.isVector() || VT != MVT::i32)
6094 return SDValue();
6095
6096 // First try with the default operand order.
6097 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI))
6098 return Result;
6099
6100 // If that didn't work, try again with the operands commuted.
6101 return PerformADDCombineWithOperands(N, N1, N0, DCI);
6102}
6103
6104/// Check if a v2f32 BUILD_VECTOR provably packs values from non-adjacent
6105/// register pairs (non-coalescable).
6106static bool isNonCoalescableBuildVector(const SDValue &BV) {
6107 if (BV.getOpcode() != ISD::BUILD_VECTOR || BV.getValueType() != MVT::v2f32)
6108 return false;
6109
6110 SDValue Elt0 = BV.getOperand(0);
6111 SDValue Elt1 = BV.getOperand(1);
6112
6113 bool IsExt0 = Elt0.getOpcode() == ISD::EXTRACT_VECTOR_ELT;
6114 bool IsExt1 = Elt1.getOpcode() == ISD::EXTRACT_VECTOR_ELT;
6115
6116 // If neither element is an EXTRACT_VECTOR_ELT they are free-standing
6117 // scalars and the register allocator can still place them side-by-side.
6118 if (!IsExt0 && !IsExt1)
6119 return false;
6120
6121 // If exactly one element is an EXTRACT_VECTOR_ELT, the other is a scalar
6122 // that cannot generally occupy the adjacent register slot.
6123 if (IsExt0 != IsExt1)
6124 return true;
6125
6126 // At this point both sources are extracting from vectors. If they are from
6127 // different vectors, then the BUILD_VECTOR is non-coalescable.
6128 SDValue Src0 = Elt0.getOperand(0);
6129 SDValue Src1 = Elt1.getOperand(0);
6130 if (Src0 != Src1)
6131 return true;
6132
6133 auto *Idx0 = dyn_cast<ConstantSDNode>(Elt0.getOperand(1));
6134 auto *Idx1 = dyn_cast<ConstantSDNode>(Elt1.getOperand(1));
6135 // If both indices are dynamic they will be lowered to
6136 // loads and the vector will be spilled to local memory. The register
6137 // allocator can easily place the results in adjacent registers.
6138 if (!Idx0 && !Idx1)
6139 return false;
6140
6141 // If one index is dynamic and the other is constant, the value from the
6142 // constant load will result in an additional register to pair with the result
6143 // from the dynamic load. We consider this non-coalescable.
6144 if ((Idx0 && !Idx1) || (!Idx0 && Idx1))
6145 return true;
6146
6147 // Both are constant, adjacent pairs are coalescable
6148 return std::abs(Idx0->getSExtValue() - Idx1->getSExtValue()) != 1;
6149}
6150
6151/// Return true if FMUL v2f32 node \p N may be scalarized to fold each lane's
6152/// product into a scalar FMA.
6153bool NVPTXTargetLowering::mayFoldFMULIntoFMA(SDNode *N, MachineFunction &MF,
6154 CodeGenOptLevel OptLevel) const {
6155 if (N->getOpcode() != ISD::FMUL || N->getValueType(0) != MVT::v2f32)
6156 return false;
6157 const bool GlobalFMA = allowFMA(MF, OptLevel);
6158 if (!N->getFlags().hasAllowContract() && !GlobalFMA)
6159 return false;
6160
6161 const SDNode *FirstFAdd = nullptr;
6162 unsigned NumScalarFAdd = 0;
6163
6164 // Both lanes must feed unique FADDs
6165 for (SDNode *EE : N->users()) {
6166 if (NumScalarFAdd == 2)
6167 return false;
6168
6169 if (EE->getOpcode() != ISD::EXTRACT_VECTOR_ELT || !EE->hasOneUse() ||
6170 !isa<ConstantSDNode>(EE->getOperand(1)))
6171 return false;
6172
6173 const SDNode *const FAdd = *EE->users().begin();
6174 if (FAdd->getOpcode() != ISD::FADD ||
6175 (!GlobalFMA && !FAdd->getFlags().hasAllowContract()))
6176 return false;
6177
6178 if (!FirstFAdd)
6179 FirstFAdd = FAdd;
6180 else if (FAdd == FirstFAdd)
6181 return false;
6182
6183 NumScalarFAdd++;
6184 }
6185
6186 return NumScalarFAdd == 2;
6187}
6188
6189/// Scalarize a v2f32 arithmetic node (FADD, FMUL, FSUB, FMA) when at least
6190/// one operand is a BUILD_VECTOR that repacks values from non-adjacent register
6191/// pairs. Without this combine the BUILD_VECTOR forces allocation of a
6192/// temporary 64-bit register, increasing register pressure.
6193///
6194/// Example - before:
6195/// t0: v2f32,v2f32,ch = LoadV2 ...
6196/// t1: f32 = extract_vector_elt t0, 0
6197/// t2: f32 = extract_vector_elt t0:1, 0
6198/// t3: v2f32 = BUILD_VECTOR t1, t2 ;; non-coalescable repack
6199/// t4: v2f32 = fma t_a, t3, t_c
6200///
6201/// After:
6202/// t0: v2f32,v2f32,ch = LoadV2 ...
6203/// t1: f32 = extract_vector_elt t0, 0
6204/// t2: f32 = extract_vector_elt t0:1, 0
6205/// a0: f32 = extract_vector_elt t_a, 0
6206/// a1: f32 = extract_vector_elt t_a, 1
6207/// c0: f32 = extract_vector_elt t_c, 0
6208/// c1: f32 = extract_vector_elt t_c, 1
6209/// r0: f32 = fma a0, t1, c0
6210/// r1: f32 = fma a1, t2, c1
6211/// t4: v2f32 = BUILD_VECTOR r0, r1
6212///
6213/// Also scalarizes an FMUL when all output lanes feed into scalar FADDs
6214/// to enable scalar FMA combining.
6215SDValue NVPTXTargetLowering::performScalarizeV2F32Op(
6217 CodeGenOptLevel OptLevel) const {
6218 EVT VT = N->getValueType(0);
6219 if (VT != MVT::v2f32)
6220 return SDValue();
6221
6222 if (none_of(N->ops(), isNonCoalescableBuildVector) &&
6223 !mayFoldFMULIntoFMA(N, DCI.DAG.getMachineFunction(), OptLevel))
6224 return SDValue();
6225
6226 SelectionDAG &DAG = DCI.DAG;
6227 SDLoc DL(N);
6228 EVT EltVT = VT.getVectorElementType();
6229 unsigned Opc = N->getOpcode();
6230
6231 // For each operand, get the scalar element at the given index: if the operand
6232 // is a BUILD_VECTOR, grab the element directly; otherwise, emit an
6233 // EXTRACT_VECTOR_ELT.
6234 auto GetElement = [&](SDValue Op, unsigned Index) -> SDValue {
6235 if (Op.getOpcode() == ISD::BUILD_VECTOR)
6236 return Op.getOperand(Index);
6237 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Op,
6238 DAG.getVectorIdxConstant(Index, DL));
6239 };
6240
6241 // Build scalar operand lists for element 0 and element 1.
6242 SmallVector<SDValue, 3> Ops0, Ops1;
6243 for (const SDValue &Op : N->ops()) {
6244 Ops0.push_back(GetElement(Op, 0));
6245 Ops1.push_back(GetElement(Op, 1));
6246 }
6247
6248 SDValue Res0 = DAG.getNode(Opc, DL, EltVT, Ops0, N->getFlags());
6249 SDValue Res1 = DAG.getNode(Opc, DL, EltVT, Ops1, N->getFlags());
6250
6251 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Res0, Res1);
6252}
6253
6254/// Target-specific dag combine xforms for ISD::FADD.
6255SDValue
6256NVPTXTargetLowering::performFADDCombine(SDNode *N,
6258 CodeGenOptLevel OptLevel) const {
6259 if (SDValue Result = performScalarizeV2F32Op(N, DCI, OptLevel))
6260 return Result;
6261
6262 SDValue N0 = N->getOperand(0);
6263 SDValue N1 = N->getOperand(1);
6264
6265 EVT VT = N0.getValueType();
6266 if (VT.isVector() || !(VT == MVT::f32 || VT == MVT::f64))
6267 return SDValue();
6268
6269 // First try with the default operand order.
6270 if (SDValue Result = performFADDCombineWithOperands(N, N0, N1, DCI, OptLevel))
6271 return Result;
6272
6273 // If that didn't work, try again with the operands commuted.
6274 return performFADDCombineWithOperands(N, N1, N0, DCI, OptLevel);
6275}
6276
6277/// Get 3-input version of a 2-input min/max opcode
6278static unsigned getMinMax3Opcode(unsigned MinMax2Opcode) {
6279 switch (MinMax2Opcode) {
6280 case ISD::FMAXNUM:
6281 case ISD::FMAXIMUMNUM:
6282 return NVPTXISD::FMAXNUM3;
6283 case ISD::FMINNUM:
6284 case ISD::FMINIMUMNUM:
6285 return NVPTXISD::FMINNUM3;
6286 case ISD::FMAXIMUM:
6287 return NVPTXISD::FMAXIMUM3;
6288 case ISD::FMINIMUM:
6289 return NVPTXISD::FMINIMUM3;
6290 default:
6291 llvm_unreachable("Invalid 2-input min/max opcode");
6292 }
6293}
6294
6295/// PerformFMinMaxCombine - Combine (fmaxnum (fmaxnum a, b), c) into
6296/// (fmaxnum3 a, b, c). Also covers other llvm min/max intrinsics.
6299 const NVPTXSubtarget &STI) {
6300
6301 // 3-input min/max requires PTX 8.8+ and SM_100+, and only supports f32s
6302 EVT VT = N->getValueType(0);
6303 if (VT != MVT::f32 || !STI.hasFeature(NVPTX::PTX88) ||
6304 !STI.hasFeature(NVPTX::SM100))
6305 return SDValue();
6306
6307 SDValue Op0 = N->getOperand(0);
6308 SDValue Op1 = N->getOperand(1);
6309 unsigned MinMaxOp2 = N->getOpcode();
6310 unsigned MinMaxOp3 = getMinMax3Opcode(MinMaxOp2);
6311
6312 if (Op0.getOpcode() == MinMaxOp2 && Op0.hasOneUse()) {
6313 // (maxnum (maxnum a, b), c) -> (maxnum3 a, b, c)
6314 SDValue A = Op0.getOperand(0);
6315 SDValue B = Op0.getOperand(1);
6316 SDValue C = Op1;
6317 return DCI.DAG.getNode(MinMaxOp3, SDLoc(N), VT, A, B, C, N->getFlags());
6318 } else if (Op1.getOpcode() == MinMaxOp2 && Op1.hasOneUse()) {
6319 // (maxnum a, (maxnum b, c)) -> (maxnum3 a, b, c)
6320 SDValue A = Op0;
6321 SDValue B = Op1.getOperand(0);
6322 SDValue C = Op1.getOperand(1);
6323 return DCI.DAG.getNode(MinMaxOp3, SDLoc(N), VT, A, B, C, N->getFlags());
6324 }
6325 return SDValue();
6326}
6327
6330 CodeGenOptLevel OptLevel) {
6331 assert(N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM);
6332
6333 // Don't do anything at less than -O2.
6334 if (OptLevel < CodeGenOptLevel::Default)
6335 return SDValue();
6336
6337 SelectionDAG &DAG = DCI.DAG;
6338 SDLoc DL(N);
6339 EVT VT = N->getValueType(0);
6340 bool IsSigned = N->getOpcode() == ISD::SREM;
6341 unsigned DivOpc = IsSigned ? ISD::SDIV : ISD::UDIV;
6342
6343 const SDValue &Num = N->getOperand(0);
6344 const SDValue &Den = N->getOperand(1);
6345
6346 for (const SDNode *U : Num->users()) {
6347 if (U->getOpcode() == DivOpc && U->getOperand(0) == Num &&
6348 U->getOperand(1) == Den) {
6349 // Num % Den -> Num - (Num / Den) * Den
6350 return DAG.getNode(ISD::SUB, DL, VT, Num,
6351 DAG.getNode(ISD::MUL, DL, VT,
6352 DAG.getNode(DivOpc, DL, VT, Num, Den),
6353 Den));
6354 }
6355 }
6356 return SDValue();
6357}
6358
6359// sext (mul.iN nsw x, y) => mul.wide.sN x, y
6360// zext (mul.iN nuw x, y) => mul.wide.uN x, y
6361// sext (shl.iN nsw x, const) => mul.wide.sN x, (1 << const)
6362// zext (shl.iN nuw x, const) => mul.wide.uN x, (1 << const)
6365 CodeGenOptLevel OptLevel) {
6366 assert(N->getOpcode() == ISD::SIGN_EXTEND ||
6367 N->getOpcode() == ISD::ZERO_EXTEND);
6368
6369 if (OptLevel == CodeGenOptLevel::None)
6370 return SDValue();
6371
6372 SDValue Op = N->getOperand(0);
6373 if (!Op.hasOneUse())
6374 return SDValue();
6375
6376 EVT ToVT = N->getValueType(0);
6377 EVT FromVT = Op.getValueType();
6378 if (!((ToVT == MVT::i32 && FromVT == MVT::i16) ||
6379 (ToVT == MVT::i64 && FromVT == MVT::i32)))
6380 return SDValue();
6381
6382 bool IsSigned = N->getOpcode() == ISD::SIGN_EXTEND;
6383 if ((IsSigned && !Op->getFlags().hasNoSignedWrap()) ||
6384 (!IsSigned && !Op->getFlags().hasNoUnsignedWrap()))
6385 return SDValue();
6386
6387 SDLoc DL(N);
6388 SDValue LHS = Op.getOperand(0);
6389 SDValue RHS = Op.getOperand(1);
6390 unsigned MulWideOpcode =
6391 IsSigned ? NVPTXISD::MUL_WIDE_SIGNED : NVPTXISD::MUL_WIDE_UNSIGNED;
6392 if (Op.getOpcode() == ISD::MUL) {
6393 return DCI.DAG.getNode(MulWideOpcode, DL, ToVT, LHS, RHS);
6394 } else if (Op.getOpcode() == ISD::SHL && isa<ConstantSDNode>(RHS)) {
6395 const auto ShiftAmt = Op.getConstantOperandVal(1);
6396 const auto MulVal = APInt(FromVT.getSizeInBits(), 1) << ShiftAmt;
6397
6398 // Note that the sext (shl nsw ...) case doesn't work if 1 << const
6399 // overflows to a negative value! The only valid input values in this
6400 // case are 0 and -1 (all other values yield poison because of the nsw),
6401 // and mul.wide.sN would give us the wrong sign for -1. We could use
6402 // mul.wide.uN, but since this is a weird case anyway, we might as well not
6403 // apply this transformation at all.
6404 if (IsSigned && MulVal.isNegative())
6405 return SDValue();
6406
6407 RHS = DCI.DAG.getConstant(MulVal, DL, FromVT);
6408 return DCI.DAG.getNode(MulWideOpcode, DL, ToVT, LHS, RHS);
6409 }
6410
6411 return SDValue();
6412}
6413
6419
6420/// IsMulWideOperandDemotable - Checks if the provided DAG node is an operand
6421/// that can be demoted to \p OptSize bits without loss of information. The
6422/// signedness of the operand, if determinable, is placed in \p S.
6424 unsigned OptSize,
6425 OperandSignedness &S) {
6426 S = Unknown;
6427
6428 if (Op.getOpcode() == ISD::SIGN_EXTEND ||
6429 Op.getOpcode() == ISD::SIGN_EXTEND_INREG) {
6430 EVT OrigVT = Op.getOperand(0).getValueType();
6431 if (OrigVT.getFixedSizeInBits() <= OptSize) {
6432 S = Signed;
6433 return true;
6434 }
6435 } else if (Op.getOpcode() == ISD::ZERO_EXTEND) {
6436 EVT OrigVT = Op.getOperand(0).getValueType();
6437 if (OrigVT.getFixedSizeInBits() <= OptSize) {
6438 S = Unsigned;
6439 return true;
6440 }
6441 }
6442
6443 return false;
6444}
6445
6446/// AreMulWideOperandsDemotable - Checks if the given LHS and RHS operands can
6447/// be demoted to \p OptSize bits without loss of information. If the operands
6448/// contain a constant, it should appear as the RHS operand. The signedness of
6449/// the operands is placed in \p IsSigned.
6451 unsigned OptSize,
6452 bool &IsSigned) {
6453 OperandSignedness LHSSign;
6454
6455 // The LHS operand must be a demotable op
6456 if (!IsMulWideOperandDemotable(LHS, OptSize, LHSSign))
6457 return false;
6458
6459 // We should have been able to determine the signedness from the LHS
6460 if (LHSSign == Unknown)
6461 return false;
6462
6463 IsSigned = (LHSSign == Signed);
6464
6465 // The RHS can be a demotable op or a constant
6467 const APInt &Val = CI->getAPIntValue();
6468 if (LHSSign == Unsigned) {
6469 return Val.isIntN(OptSize);
6470 } else {
6471 return Val.isSignedIntN(OptSize);
6472 }
6473 } else {
6474 OperandSignedness RHSSign;
6475 if (!IsMulWideOperandDemotable(RHS, OptSize, RHSSign))
6476 return false;
6477
6478 return LHSSign == RHSSign;
6479 }
6480}
6481
6482/// TryMULWIDECombine - Attempt to replace a multiply of M bits with a multiply
6483/// of M/2 bits that produces an M-bit result (i.e. mul.wide). This transform
6484/// works on both multiply DAG nodes and SHL DAG nodes with a constant shift
6485/// amount.
6488 EVT MulType = N->getValueType(0);
6489 if (MulType != MVT::i32 && MulType != MVT::i64) {
6490 return SDValue();
6491 }
6492
6493 SDLoc DL(N);
6494 unsigned OptSize = MulType.getSizeInBits() >> 1;
6495 SDValue LHS = N->getOperand(0);
6496 SDValue RHS = N->getOperand(1);
6497
6498 // Canonicalize the multiply so the constant (if any) is on the right
6499 if (N->getOpcode() == ISD::MUL) {
6500 if (isa<ConstantSDNode>(LHS)) {
6501 std::swap(LHS, RHS);
6502 }
6503 }
6504
6505 // If we have a SHL, determine the actual multiply amount
6506 if (N->getOpcode() == ISD::SHL) {
6508 if (!ShlRHS) {
6509 return SDValue();
6510 }
6511
6512 APInt ShiftAmt = ShlRHS->getAPIntValue();
6513 unsigned BitWidth = MulType.getSizeInBits();
6514 if (ShiftAmt.sge(0) && ShiftAmt.slt(BitWidth)) {
6515 APInt MulVal = APInt(BitWidth, 1) << ShiftAmt;
6516 RHS = DCI.DAG.getConstant(MulVal, DL, MulType);
6517 } else {
6518 return SDValue();
6519 }
6520 }
6521
6522 bool Signed;
6523 // Verify that our operands are demotable
6524 if (!AreMulWideOperandsDemotable(LHS, RHS, OptSize, Signed)) {
6525 return SDValue();
6526 }
6527
6528 EVT DemotedVT;
6529 if (MulType == MVT::i32) {
6530 DemotedVT = MVT::i16;
6531 } else {
6532 DemotedVT = MVT::i32;
6533 }
6534
6535 // Truncate the operands to the correct size. Note that these are just for
6536 // type consistency and will (likely) be eliminated in later phases.
6537 SDValue TruncLHS =
6538 DCI.DAG.getNode(ISD::TRUNCATE, DL, DemotedVT, LHS);
6539 SDValue TruncRHS =
6540 DCI.DAG.getNode(ISD::TRUNCATE, DL, DemotedVT, RHS);
6541
6542 unsigned Opc;
6543 if (Signed) {
6544 Opc = NVPTXISD::MUL_WIDE_SIGNED;
6545 } else {
6546 Opc = NVPTXISD::MUL_WIDE_UNSIGNED;
6547 }
6548
6549 return DCI.DAG.getNode(Opc, DL, MulType, TruncLHS, TruncRHS);
6550}
6551
6552static bool isConstOne(const SDValue &Operand) {
6553 const auto *Const = dyn_cast<ConstantSDNode>(Operand);
6554 return Const && Const->getZExtValue() == 1;
6555}
6556
6558 if (Add->getOpcode() != ISD::ADD)
6559 return SDValue();
6560
6561 if (isConstOne(Add->getOperand(0)))
6562 return Add->getOperand(1);
6563
6564 if (isConstOne(Add->getOperand(1)))
6565 return Add->getOperand(0);
6566
6567 return SDValue();
6568}
6569
6572
6574 SDValue Mul = DCI.DAG.getNode(ISD::MUL, DL, VT, X, Y);
6575 return DCI.DAG.getNode(ISD::ADD, DL, VT, Mul, X);
6576 }
6577
6578 return SDValue();
6579}
6580
6582 SDLoc DL,
6584 if (Select->getOpcode() != ISD::SELECT)
6585 return SDValue();
6586
6587 SDValue Cond = Select->getOperand(0);
6588
6589 unsigned ConstOpNo;
6590 if (isConstOne(Select->getOperand(1)))
6591 ConstOpNo = 1;
6592 else if (isConstOne(Select->getOperand(2)))
6593 ConstOpNo = 2;
6594 else
6595 return SDValue();
6596
6597 SDValue Y = Select->getOperand((ConstOpNo == 1) ? 2 : 1);
6598
6599 // Do not combine if the resulting sequence is not obviously profitable.
6601 return SDValue();
6602
6603 SDValue NewMul = DCI.DAG.getNode(ISD::MUL, DL, VT, X, Y);
6604
6605 return DCI.DAG.getNode(ISD::SELECT, DL, VT, Cond,
6606 (ConstOpNo == 1) ? X : NewMul,
6607 (ConstOpNo == 1) ? NewMul : X);
6608}
6609
6610static SDValue
6613
6614 EVT VT = N0.getValueType();
6615 if (VT.isVector())
6616 return SDValue();
6617
6618 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
6619 return SDValue();
6620
6621 SDLoc DL(N);
6622
6623 // (mul x, (add y, 1)) -> (add (mul x, y), x)
6624 if (SDValue Res = combineMADConstOne(N0, N1, VT, DL, DCI))
6625 return Res;
6626 if (SDValue Res = combineMADConstOne(N1, N0, VT, DL, DCI))
6627 return Res;
6628
6629 // (mul x, (select y, 1)) -> (select (mul x, y), x)
6630 if (SDValue Res = combineMulSelectConstOne(N0, N1, VT, DL, DCI))
6631 return Res;
6632 if (SDValue Res = combineMulSelectConstOne(N1, N0, VT, DL, DCI))
6633 return Res;
6634
6635 return SDValue();
6636}
6637
6638/// PerformMULCombine - Runs PTX-specific DAG combine patterns on MUL nodes.
6641 CodeGenOptLevel OptLevel) {
6642 if (OptLevel == CodeGenOptLevel::None)
6643 return SDValue();
6644
6645 if (SDValue Ret = TryMULWIDECombine(N, DCI))
6646 return Ret;
6647
6648 SDValue N0 = N->getOperand(0);
6649 SDValue N1 = N->getOperand(1);
6650 return PerformMULCombineWithOperands(N, N0, N1, DCI);
6651}
6652
6653/// Commute SHL with a bitwise logic operation when doing so exposes a common
6654/// shifted operand. For example:
6655///
6656/// Before:
6657/// N = shl (zext (LogicOp X, C)), ShiftAmount
6658/// OtherShift = shl (zext (OtherLogicOp X, OtherC)), ShiftAmount
6659///
6660/// After:
6661/// ShiftedX = shl (zext X), ShiftAmount
6662/// N = LogicOp ShiftedX, ShiftedC
6663/// OtherShift = OtherLogicOp ShiftedX, ShiftedOtherC
6664///
6665/// ShiftedC = (zext C) << ShiftAmount and ShiftedOtherC =
6666/// (zext OtherC) << ShiftAmount are folded constants. This replaces two
6667/// variable shifts with the single shared ShiftedX. Requiring another matching
6668/// shift avoids disrupting isolated address calculations where a shift may be
6669/// folded into the addressing mode.
6672 using namespace SDPatternMatch;
6673
6674 struct ShiftOfLogicOp {
6675 SDNode *Shift;
6676 SDValue LogicOp;
6677 SDValue X;
6679 unsigned ExtendOpcode;
6680 };
6681
6682 // Match a logic operation, with an optional extension, inside a SHL.
6683 auto matchShiftOfLogicOp =
6684 [&](SDNode *Shift) -> std::optional<ShiftOfLogicOp> {
6685 if (Shift->getOpcode() != ISD::SHL || !Shift->getOperand(0).hasOneUse())
6686 return std::nullopt;
6687 ShiftOfLogicOp Match;
6688 Match.Shift = Shift;
6689 Match.LogicOp = Shift->getOperand(0);
6690 Match.ExtendOpcode = 0;
6691 if (ISD::isExtOpcode(Match.LogicOp.getOpcode())) {
6692 Match.ExtendOpcode = Match.LogicOp.getOpcode();
6693 Match.LogicOp = Match.LogicOp.getOperand(0);
6694 }
6695
6696 if (!sd_match(Match.LogicOp, m_OneUse(m_BitwiseLogic(
6697 m_Value(Match.X),
6698 m_Value(Match.Constant, m_ConstInt())))))
6699 return std::nullopt;
6700
6701 return Match;
6702 };
6703
6704 // Match N as the root shift-of-logic; bail if it does not fit the pattern.
6705 const std::optional<ShiftOfLogicOp> Root = matchShiftOfLogicOp(N);
6706 if (!Root)
6707 return SDValue();
6708
6709 // Only profitable for a constant shift amount: the per-op constant shift then
6710 // folds away instead of becoming an extra variable shift.
6711 if (!isConstOrConstSplat(N->getOperand(1)))
6712 return SDValue();
6713
6714 // Collect candidate shifts that share X. Reached through another user of X,
6715 // the logic result feeds the shift directly or through an optional extend.
6716 SmallVector<SDNode *, 4> CandidateShifts;
6717 for (const SDNode *CandidateLogicOp : Root->X->users()) {
6718 if (CandidateLogicOp == Root->LogicOp.getNode())
6719 continue;
6720 for (SDNode *LogicUser : CandidateLogicOp->users()) {
6721 if (ISD::isExtOpcode(LogicUser->getOpcode())) {
6722 // shl (ext (logic X, C)): step through the extend to find the shift.
6723 for (SDNode *ExtendUser : LogicUser->users())
6724 if (ExtendUser->getOpcode() == ISD::SHL)
6725 CandidateShifts.push_back(ExtendUser);
6726 } else if (LogicUser->getOpcode() == ISD::SHL) {
6727 // shl (logic X, C): the user is already the shift.
6728 CandidateShifts.push_back(LogicUser);
6729 }
6730 }
6731 }
6732
6733 // Verify each candidate against the root's pattern: the same X, extension,
6734 // type, and shift amount.
6735 const EVT VT = N->getValueType(0);
6736 const SDValue ShiftAmount = N->getOperand(1);
6738 for (SDNode *CandidateShift : CandidateShifts) {
6739 const std::optional<ShiftOfLogicOp> Candidate =
6740 matchShiftOfLogicOp(CandidateShift);
6741 if (Candidate && Candidate->X == Root->X &&
6742 Candidate->ExtendOpcode == Root->ExtendOpcode &&
6743 CandidateShift->getValueType(0) == VT &&
6744 CandidateShift->getOperand(1) == ShiftAmount)
6745 Matches.push_back(*Candidate);
6746 }
6747 if (Matches.empty())
6748 return SDValue();
6749
6750 // Build the shared shifted X once, then rewrite the root and every match
6751 // into a logic op over it so the shift is CSE'd.
6752 SelectionDAG &DAG = DCI.DAG;
6753 const SDValue ShiftedX =
6754 DAG.getNode(ISD::SHL, SDLoc(N), VT,
6755 Root->ExtendOpcode
6756 ? DAG.getNode(Root->ExtendOpcode, SDLoc(N), VT, Root->X)
6757 : Root->X,
6758 ShiftAmount);
6759
6760 // Rebuild the logic op from shared ShiftedX and a folded constant shift.
6761 auto buildCommutedLogicOp = [&](const SDValue LogicOp, SDValue C,
6762 const SDLoc &DL) {
6763 if (Root->ExtendOpcode)
6764 C = DAG.getNode(Root->ExtendOpcode, DL, VT, C);
6765 const SDValue ShiftedC = DAG.getNode(ISD::SHL, DL, VT, C, ShiftAmount);
6766 return DAG.getNode(LogicOp.getOpcode(), DL, VT, ShiftedX, ShiftedC,
6767 LogicOp->getFlags());
6768 };
6769
6770 for (const ShiftOfLogicOp &Match : Matches)
6771 DCI.CombineTo(Match.Shift,
6772 buildCommutedLogicOp(Match.LogicOp, Match.Constant,
6773 SDLoc(Match.Shift)));
6774 return buildCommutedLogicOp(Root->LogicOp, Root->Constant, SDLoc(N));
6775}
6776
6777/// PerformSHLCombine - Runs PTX-specific DAG combine patterns on SHL nodes.
6780 CodeGenOptLevel OptLevel) {
6781 if (OptLevel > CodeGenOptLevel::None) {
6782 // Expose a shared shifted operand for CSE before mul.wide folding, which
6783 // would otherwise consume the shift.
6784 if (SDValue Ret = combineShiftOfLogicOp(N, DCI))
6785 return Ret;
6786
6787 // Try mul.wide combining at OptLevel > 0
6788 if (SDValue Ret = TryMULWIDECombine(N, DCI))
6789 return Ret;
6790 }
6791
6792 return SDValue();
6793}
6794
6797 const NVPTXSubtarget &STI) {
6798 EVT CCType = N->getValueType(0);
6799 SDValue A = N->getOperand(0);
6800 SDValue B = N->getOperand(1);
6801
6802 EVT AType = A.getValueType();
6803 if (!(CCType == MVT::v2i1 && (AType == MVT::v2f16 || AType == MVT::v2bf16)))
6804 return SDValue();
6805
6806 if (A.getValueType() == MVT::v2bf16 && !STI.hasFeature(NVPTX::SM90))
6807 return SDValue();
6808
6809 SDLoc DL(N);
6810 // setp.f16x2 returns two scalar predicates, which we need to
6811 // convert back to v2i1. The returned result will be scalarized by
6812 // the legalizer, but the comparison will remain a single vector
6813 // instruction.
6814 SDValue CCNode = DCI.DAG.getNode(
6815 A.getValueType() == MVT::v2f16 ? NVPTXISD::SETP_F16X2
6817 DL, DCI.DAG.getVTList(MVT::i1, MVT::i1), {A, B, N->getOperand(2)});
6818 return DCI.DAG.getNode(ISD::BUILD_VECTOR, DL, CCType, CCNode.getValue(0),
6819 CCNode.getValue(1));
6820}
6821
6824 SDValue Vector = peekThroughFreeze(N->getOperand(0));
6825 SDLoc DL(N);
6826 EVT VectorVT = Vector.getValueType();
6827 if (Vector->getOpcode() == ISD::LOAD && VectorVT.isSimple() &&
6828 IsPTXVectorType(VectorVT.getSimpleVT()))
6829 return SDValue(); // Native vector loads already combine nicely w/
6830 // extract_vector_elt.
6831 // Don't mess with singletons or packed types (v2*32, v2*16, v4i8 and v8i8),
6832 // we already handle them OK.
6833 if (VectorVT.getVectorNumElements() == 1 ||
6834 NVPTX::isPackedVectorTy(VectorVT) || VectorVT == MVT::v8i8)
6835 return SDValue();
6836
6837 // Don't mess with undef values as sra may be simplified to 0, not undef.
6838 if (Vector->isUndef() || ISD::allOperandsUndef(Vector.getNode()))
6839 return SDValue();
6840
6841 uint64_t VectorBits = VectorVT.getSizeInBits();
6842 // We only handle the types we can extract in-register.
6843 if (!(VectorBits == 16 || VectorBits == 32 || VectorBits == 64))
6844 return SDValue();
6845
6846 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(N->getOperand(1));
6847 // Index == 0 is handled by generic DAG combiner.
6848 if (!Index || Index->getZExtValue() == 0)
6849 return SDValue();
6850
6851 MVT IVT = MVT::getIntegerVT(VectorBits);
6852 EVT EltVT = VectorVT.getVectorElementType();
6853 EVT EltIVT = EltVT.changeTypeToInteger();
6854 uint64_t EltBits = EltVT.getScalarSizeInBits();
6855
6856 SDValue Result = DCI.DAG.getNode(
6857 ISD::TRUNCATE, DL, EltIVT,
6858 DCI.DAG.getNode(
6859 ISD::SRA, DL, IVT, DCI.DAG.getNode(ISD::BITCAST, DL, IVT, Vector),
6860 DCI.DAG.getConstant(Index->getZExtValue() * EltBits, DL, IVT)));
6861
6862 // If element has non-integer type, bitcast it back to the expected type.
6863 if (EltVT != EltIVT)
6864 Result = DCI.DAG.getNode(ISD::BITCAST, DL, EltVT, Result);
6865 // Past legalizer, we may need to extent i8 -> i16 to match the register type.
6866 if (EltVT != N->getValueType(0))
6867 Result = DCI.DAG.getNode(ISD::ANY_EXTEND, DL, N->getValueType(0), Result);
6868
6869 return Result;
6870}
6871
6872/// Transform patterns like:
6873/// (select (ugt shift_amt, BitWidth-1), 0, (srl/shl x, shift_amt))
6874/// (select (ult shift_amt, BitWidth), (srl/shl x, shift_amt), 0)
6875/// Into:
6876/// (NVPTXISD::SRL_CLAMP x, shift_amt) or (NVPTXISD::SHL_CLAMP x, shift_amt)
6877///
6878/// These patterns arise from code like `s >= 32 ? 0 : x >> s`. In LLVM,
6879/// over-shifting a value results in poison, but PTX shr/shl instructions clamp
6880/// the shift amount to BitWidth, making the guard redundant.
6881///
6882/// Note: We only handle SRL and SHL, not SRA, because arithmetic right shifts
6883/// can produce 0 or -1 when shift >= BitWidth.
6884/// Note: We don't handle uge or ule. These don't appear because of
6885/// canonicalization.
6888 if (!DCI.isAfterLegalizeDAG())
6889 return SDValue();
6890
6891 using namespace SDPatternMatch;
6892 unsigned BitWidth = N->getValueType(0).getSizeInBits();
6893 SDValue ShiftAmt, ShiftOp;
6894
6895 // Match logical shifts where the shift amount in the guard matches the shift
6896 // amount in the operation.
6897 auto LogicalShift =
6898 m_AllOf(m_Value(ShiftOp),
6899 m_AnyOf(m_Srl(m_Value(), m_TruncOrSelf(m_Deferred(ShiftAmt))),
6900 m_Shl(m_Value(), m_TruncOrSelf(m_Deferred(ShiftAmt)))));
6901
6902 // shift_amt > BitWidth-1 ? 0 : shift_op
6903 bool MatchedUGT =
6904 sd_match(N, m_Select(m_SetCC(m_Value(ShiftAmt),
6906 m_SpecificCondCode(ISD::SETUGT)),
6907 m_Zero(), LogicalShift));
6908 // shift_amt < BitWidth ? shift_op : 0
6909 bool MatchedULT =
6910 !MatchedUGT &&
6911 sd_match(N, m_Select(m_SetCC(m_Value(ShiftAmt),
6913 m_SpecificCondCode(ISD::SETULT)),
6914 LogicalShift, m_Zero()));
6915
6916 if (!MatchedUGT && !MatchedULT)
6917 return SDValue();
6918
6919 // In LLVM IR, the shift amount and the value-to-be-shifted are the same
6920 // type, whereas in PTX the shift amount is always i32. Therefore when
6921 // shifting types larger than i32, we can only do this transformation if we
6922 // know that the upper bits of the shift amount are known zero.
6923 SDValue ClampAmt = ShiftOp.getOperand(1);
6924 unsigned ClampAmtBits = ClampAmt.getValueSizeInBits();
6925 if (ShiftAmt.getValueSizeInBits() > ClampAmtBits &&
6926 DCI.DAG.computeKnownBits(ShiftAmt).countMaxActiveBits() > ClampAmtBits)
6927 return SDValue();
6928
6929 // Return a clamp shift operation, which has the same semantics as PTX shift.
6930 unsigned ClampOpc = ShiftOp.getOpcode() == ISD::SRL ? NVPTXISD::SRL_CLAMP
6931 : NVPTXISD::SHL_CLAMP;
6932 return DCI.DAG.getNode(ClampOpc, SDLoc(N), ShiftOp.getValueType(),
6933 ShiftOp.getOperand(0), ClampAmt);
6934}
6935
6938 SDValue VA = N->getOperand(1);
6939 EVT VectorVT = VA.getValueType();
6940 if (VectorVT != MVT::v4i8)
6941 return SDValue();
6942
6943 // We need to split vselect into individual per-element operations Because we
6944 // use BFE/BFI instruction for byte extraction/insertion, we do end up with
6945 // 32-bit values, so we may as well do comparison as i32 to avoid conversions
6946 // to/from i16 normally used for i8 values.
6948 SDLoc DL(N);
6949 SDValue VCond = N->getOperand(0);
6950 SDValue VB = N->getOperand(2);
6951 for (int I = 0; I < 4; ++I) {
6952 SDValue C = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i1, VCond,
6953 DCI.DAG.getConstant(I, DL, MVT::i32));
6954 SDValue EA = DCI.DAG.getAnyExtOrTrunc(
6955 DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i8, VA,
6956 DCI.DAG.getConstant(I, DL, MVT::i32)),
6957 DL, MVT::i32);
6958 SDValue EB = DCI.DAG.getAnyExtOrTrunc(
6959 DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i8, VB,
6960 DCI.DAG.getConstant(I, DL, MVT::i32)),
6961 DL, MVT::i32);
6962 E.push_back(DCI.DAG.getAnyExtOrTrunc(
6963 DCI.DAG.getNode(ISD::SELECT, DL, MVT::i32, C, EA, EB), DL, MVT::i8));
6964 }
6965 return DCI.DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i8, E);
6966}
6967
6968static SDValue
6970 auto VT = N->getValueType(0);
6971 if (!DCI.isAfterLegalizeDAG() ||
6972 // only process v2*16 types
6973 !(NVPTX::isPackedVectorTy(VT) && VT.is32BitVector() &&
6974 VT.getVectorNumElements() == 2))
6975 return SDValue();
6976
6977 auto Op0 = N->getOperand(0);
6978 auto Op1 = N->getOperand(1);
6979
6980 // Start out by assuming we want to take the lower 2 bytes of each i32
6981 // operand.
6982 uint64_t Op0Bytes = 0x10;
6983 uint64_t Op1Bytes = 0x54;
6984
6985 std::pair<SDValue *, uint64_t *> OpData[2] = {{&Op0, &Op0Bytes},
6986 {&Op1, &Op1Bytes}};
6987
6988 // Check that each operand is an i16, truncated from an i32 operand. We'll
6989 // select individual bytes from those original operands. Optionally, fold in a
6990 // shift right of that original operand.
6991 for (auto &[Op, OpBytes] : OpData) {
6992 // Eat up any bitcast
6993 if (Op->getOpcode() == ISD::BITCAST)
6994 *Op = Op->getOperand(0);
6995
6996 if (!(Op->getValueType() == MVT::i16 && Op->getOpcode() == ISD::TRUNCATE &&
6997 Op->getOperand(0).getValueType() == MVT::i32))
6998 return SDValue();
6999
7000 // If the truncate has multiple uses, this optimization can increase
7001 // register pressure
7002 if (!Op->hasOneUse())
7003 return SDValue();
7004
7005 *Op = Op->getOperand(0);
7006
7007 // Optionally, fold in a shift-right of the original operand and let permute
7008 // pick the two higher bytes of the original value directly.
7009 if (Op->getOpcode() == ISD::SRL && isa<ConstantSDNode>(Op->getOperand(1))) {
7010 if (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue() == 16) {
7011 // Shift the PRMT byte selector to pick upper bytes from each respective
7012 // value, instead of the lower ones: 0x10 -> 0x32, 0x54 -> 0x76
7013 assert((*OpBytes == 0x10 || *OpBytes == 0x54) &&
7014 "PRMT selector values out of range");
7015 *OpBytes += 0x22;
7016 *Op = Op->getOperand(0);
7017 }
7018 }
7019 }
7020
7021 SDLoc DL(N);
7022 auto &DAG = DCI.DAG;
7023
7024 auto PRMT =
7025 getPRMT(DAG.getBitcast(MVT::i32, Op0), DAG.getBitcast(MVT::i32, Op1),
7026 (Op1Bytes << 8) | Op0Bytes, DL, DAG);
7027 return DAG.getBitcast(VT, PRMT);
7028}
7029
7032 auto *ASCN1 = cast<AddrSpaceCastSDNode>(N);
7033
7034 if (auto *ASCN2 = dyn_cast<AddrSpaceCastSDNode>(ASCN1->getOperand(0))) {
7035 assert(ASCN2->getDestAddressSpace() == ASCN1->getSrcAddressSpace());
7036
7037 // Fold asc[B -> A](asc[A -> B](x)) -> x
7038 if (ASCN1->getDestAddressSpace() == ASCN2->getSrcAddressSpace())
7039 return ASCN2->getOperand(0);
7040 }
7041
7042 return SDValue();
7043}
7044
7045// Given a constant selector value and a prmt mode, return the selector value
7046// normalized to the generic prmt mode. See the PTX ISA documentation for more
7047// details:
7048// https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#data-movement-and-conversion-instructions-prmt
7049static APInt getPRMTSelector(const APInt &Selector, unsigned Mode) {
7050 assert(Selector.getBitWidth() == 32 && "PRMT must have i32 operands");
7051
7053 return Selector;
7054
7055 const unsigned V = Selector.trunc(2).getZExtValue();
7056
7057 const auto GetSelector = [](unsigned S0, unsigned S1, unsigned S2,
7058 unsigned S3) {
7059 return APInt(32, S0 | (S1 << 4) | (S2 << 8) | (S3 << 12));
7060 };
7061
7062 switch (Mode) {
7064 return GetSelector(V, V + 1, V + 2, V + 3);
7066 return GetSelector(V, (V - 1) & 7, (V - 2) & 7, (V - 3) & 7);
7068 return GetSelector(V, V, V, V);
7070 return GetSelector(V, std::max(V, 1U), std::max(V, 2U), 3U);
7072 return GetSelector(0, std::min(V, 1U), std::min(V, 2U), V);
7074 unsigned V1 = (V & 1) << 1;
7075 return GetSelector(V1, V1 + 1, V1, V1 + 1);
7076 }
7077 default:
7078 llvm_unreachable("Invalid PRMT mode");
7079 }
7080}
7081
7082static APInt computePRMT(APInt A, APInt B, APInt Selector, unsigned Mode) {
7083 assert(A.getBitWidth() == 32 && B.getBitWidth() == 32 &&
7084 Selector.getBitWidth() == 32 && "PRMT must have i32 operands");
7085 // {b, a} = {{b7, b6, b5, b4}, {b3, b2, b1, b0}}
7086 APInt BitField = B.concat(A);
7087 APInt SelectorVal = getPRMTSelector(Selector, Mode);
7088 APInt Result(32, 0);
7089 for (unsigned I : llvm::seq(4U)) {
7090 APInt Sel = SelectorVal.extractBits(4, I * 4);
7091 unsigned Idx = Sel.getLoBits(3).getZExtValue();
7092 unsigned Sign = Sel.getHiBits(1).getZExtValue();
7093 APInt Byte = BitField.extractBits(8, Idx * 8);
7094 if (Sign)
7095 Byte = Byte.ashr(8);
7096 Result.insertBits(Byte, I * 8);
7097 }
7098 return Result;
7099}
7100
7102 CodeGenOptLevel OptLevel) {
7103 if (OptLevel == CodeGenOptLevel::None)
7104 return SDValue();
7105
7106 // Constant fold PRMT
7107 if (isa<ConstantSDNode>(N->getOperand(0)) &&
7108 isa<ConstantSDNode>(N->getOperand(1)) &&
7109 isa<ConstantSDNode>(N->getOperand(2)))
7110 return DCI.DAG.getConstant(computePRMT(N->getConstantOperandAPInt(0),
7111 N->getConstantOperandAPInt(1),
7112 N->getConstantOperandAPInt(2),
7113 N->getConstantOperandVal(3)),
7114 SDLoc(N), N->getValueType(0));
7115 return SDValue();
7116}
7117
7118// During call lowering we wrap the return values in a ProxyReg node which
7119// depend on the chain value produced by the completed call. This ensures that
7120// the full call is emitted in cases where libcalls are used to legalize
7121// operations. To improve the functioning of other DAG combines we pull all
7122// operations we can through one of these nodes, ensuring that the ProxyReg
7123// directly wraps a load. That is:
7124//
7125// (ProxyReg (zext (load retval0))) => (zext (ProxyReg (load retval0)))
7126//
7129 switch (R.getOpcode()) {
7130 case ISD::TRUNCATE:
7131 case ISD::ANY_EXTEND:
7132 case ISD::SIGN_EXTEND:
7133 case ISD::ZERO_EXTEND:
7134 case ISD::BITCAST: {
7135 if (SDValue V = sinkProxyReg(R.getOperand(0), Chain, DCI))
7136 return DCI.DAG.getNode(R.getOpcode(), SDLoc(R), R.getValueType(), V);
7137 return SDValue();
7138 }
7139 case ISD::SHL:
7140 case ISD::SRL:
7141 case ISD::SRA:
7142 case ISD::OR: {
7143 if (SDValue A = sinkProxyReg(R.getOperand(0), Chain, DCI))
7144 if (SDValue B = sinkProxyReg(R.getOperand(1), Chain, DCI))
7145 return DCI.DAG.getNode(R.getOpcode(), SDLoc(R), R.getValueType(), A, B);
7146 return SDValue();
7147 }
7148 case ISD::Constant:
7149 return R;
7150 case ISD::LOAD:
7151 case NVPTXISD::LoadV2:
7152 case NVPTXISD::LoadV4: {
7153 return DCI.DAG.getNode(NVPTXISD::ProxyReg, SDLoc(R), R.getValueType(),
7154 {Chain, R});
7155 }
7156 case ISD::BUILD_VECTOR: {
7157 if (DCI.isBeforeLegalize())
7158 return SDValue();
7159
7161 for (auto &Op : R->ops()) {
7162 SDValue V = sinkProxyReg(Op, Chain, DCI);
7163 if (!V)
7164 return SDValue();
7165 Ops.push_back(V);
7166 }
7167 return DCI.DAG.getNode(ISD::BUILD_VECTOR, SDLoc(R), R.getValueType(), Ops);
7168 }
7170 if (DCI.isBeforeLegalize())
7171 return SDValue();
7172
7173 if (SDValue V = sinkProxyReg(R.getOperand(0), Chain, DCI))
7175 R.getValueType(), V, R.getOperand(1));
7176 return SDValue();
7177 }
7178 default:
7179 return SDValue();
7180 }
7181}
7182
7185 const bool IsFTZ =
7186 IID == Intrinsic::nvvm_fadd_ftz || IID == Intrinsic::nvvm_fadd_ftz_sat;
7187 const bool IsSat =
7188 IID == Intrinsic::nvvm_fadd_sat || IID == Intrinsic::nvvm_fadd_ftz_sat;
7189 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
7190 case MVT::f16: {
7191 static constexpr unsigned SubRNOpcodes[2][2] = {
7192 {NVPTXISD::SUB_RN, NVPTXISD::SUB_RN_SAT},
7193 {NVPTXISD::SUB_RN_FTZ, NVPTXISD::SUB_RN_FTZ_SAT}};
7194 return SubRNOpcodes[IsFTZ][IsSat];
7195 }
7196 case MVT::bf16:
7197 return NVPTXISD::SUB_RN;
7198 case MVT::f32: {
7199 // for f32x2 inputs
7200 if (!VT.isVector() || IsSat)
7201 return 0;
7202 static constexpr unsigned SubF32x2Opcodes[4][2] = {
7203 {NVPTXISD::SUB_RZ, NVPTXISD::SUB_RZ_FTZ}, // RZ
7204 {NVPTXISD::SUB_RN, NVPTXISD::SUB_RN_FTZ}, // RN
7205 {NVPTXISD::SUB_RP, NVPTXISD::SUB_RP_FTZ}, // RP
7206 {NVPTXISD::SUB_RM, NVPTXISD::SUB_RM_FTZ}}; // RM
7207 return SubF32x2Opcodes[static_cast<unsigned>(RoundingMode)][IsFTZ];
7208 }
7209 default:
7210 return 0;
7211 }
7212}
7213
7215 Intrinsic::ID AddIntrinsicID,
7217 const EVT VT = N->getValueType(0);
7218 const unsigned Opc = getFAddWithNegOpcode(VT, AddIntrinsicID, RoundingMode);
7219 if (!Opc)
7220 return SDValue();
7221
7222 SDValue Op1 = N->getOperand(1);
7223 SDValue Op2 = N->getOperand(2);
7224
7225 SDValue SubOp1, SubOp2;
7226
7227 if (Op1.getOpcode() == ISD::FNEG) {
7228 SubOp1 = Op2;
7229 SubOp2 = Op1.getOperand(0);
7230 } else if (Op2.getOpcode() == ISD::FNEG) {
7231 SubOp1 = Op1;
7232 SubOp2 = Op2.getOperand(0);
7233 } else {
7234 return SDValue();
7235 }
7236
7237 return DAG.getNode(Opc, SDLoc(N), VT, SubOp1, SubOp2);
7238}
7239
7240// TODO: Remove the type-legality checks here once
7241// https://github.com/llvm/llvm-project/pull/172442 lands, adding support for
7242// explicit type constraints for overloaded intrinsics in tablegen.
7243static bool isSupportedFAdd(EVT VT, const NVPTXSubtarget &STI,
7244 Intrinsic::ID IID,
7247 return false;
7248
7249 const bool IsRN = RoundingMode == APFloat::rmNearestTiesToEven;
7250 const bool IsFTZ =
7251 IID == Intrinsic::nvvm_fadd_ftz || IID == Intrinsic::nvvm_fadd_ftz_sat;
7252 const bool IsSat =
7253 IID == Intrinsic::nvvm_fadd_sat || IID == Intrinsic::nvvm_fadd_ftz_sat;
7254 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
7255 case MVT::f16:
7256 return IsRN;
7257 case MVT::bf16:
7258 return IsRN && !IsSat && !IsFTZ && STI.hasNativeBF16Support(ISD::FADD);
7259 case MVT::f32:
7260 return !VT.isVector() || (!IsSat && STI.hasF32x2Instructions());
7261 case MVT::f64:
7262 return !VT.isVector() && !IsSat && !IsFTZ;
7263 default:
7264 return false;
7265 }
7266}
7267
7269 Intrinsic::ID IID,
7271 const EVT VT = N->getValueType(0);
7274 Twine(Intrinsic::getBaseName(IID)) + " with rounding mode " +
7275 nvvm::GetRoundingModeName(RoundingMode) + " and operand type " +
7276 VT.getEVTString() + " is not supported on this target",
7277 SDLoc(N).getDebugLoc()));
7278 return DAG.getPOISON(VT);
7279}
7280
7283 const NVPTXSubtarget &STI) {
7284 const Intrinsic::ID IID =
7285 static_cast<Intrinsic::ID>(N->getConstantOperandVal(0));
7286
7287 switch (IID) {
7288 default:
7289 break;
7290 case Intrinsic::nvvm_fadd:
7291 case Intrinsic::nvvm_fadd_ftz:
7292 case Intrinsic::nvvm_fadd_sat:
7293 case Intrinsic::nvvm_fadd_ftz_sat: {
7294 const auto RoundingMode = static_cast<APFloat::roundingMode>(
7295 N->getConstantOperandAPInt(3).getSExtValue());
7296 if (!isSupportedFAdd(N->getValueType(0), STI, IID, RoundingMode))
7297 return diagnoseUnsupportedFAdd(N, DCI.DAG, IID, RoundingMode);
7298 return combineFAddWithNeg(N, DCI.DAG, IID, RoundingMode);
7299 }
7300 }
7301 return SDValue();
7302}
7303
7306
7307 SDValue Chain = N->getOperand(0);
7308 SDValue Reg = N->getOperand(1);
7309
7310 // If the ProxyReg is not wrapping a load, try to pull the operations through
7311 // the ProxyReg.
7312 if (Reg.getOpcode() != ISD::LOAD) {
7313 if (SDValue V = sinkProxyReg(Reg, Chain, DCI))
7314 return V;
7315 }
7316
7317 return SDValue();
7318}
7319
7320SDValue NVPTXTargetLowering::PerformDAGCombine(SDNode *N,
7321 DAGCombinerInfo &DCI) const {
7323 switch (N->getOpcode()) {
7324 default:
7325 break;
7326 case ISD::ADD:
7327 return PerformADDCombine(N, DCI, OptLevel);
7328 case ISD::ADDRSPACECAST:
7329 return combineADDRSPACECAST(N, DCI);
7330 case ISD::SIGN_EXTEND:
7331 case ISD::ZERO_EXTEND:
7332 return combineSZExtToMulWide(N, DCI, OptLevel);
7333 case ISD::BUILD_VECTOR:
7334 return PerformBUILD_VECTORCombine(N, DCI);
7336 return PerformEXTRACTCombine(N, DCI);
7337 case ISD::FADD:
7338 return performFADDCombine(N, DCI, OptLevel);
7339 case ISD::FMA:
7340 case ISD::FMUL:
7341 case ISD::FSUB:
7342 return performScalarizeV2F32Op(N, DCI, OptLevel);
7343 case ISD::FMAXNUM:
7344 case ISD::FMINNUM:
7345 case ISD::FMAXIMUM:
7346 case ISD::FMINIMUM:
7347 case ISD::FMAXIMUMNUM:
7348 case ISD::FMINIMUMNUM:
7349 return PerformFMinMaxCombine(N, DCI, STI);
7350 case ISD::LOAD:
7351 case NVPTXISD::LoadV2:
7352 case NVPTXISD::LoadV4:
7353 return combineLOAD(N, DCI, STI);
7354 case ISD::MUL:
7355 return PerformMULCombine(N, DCI, OptLevel);
7356 case NVPTXISD::PRMT:
7357 return combinePRMT(N, DCI, OptLevel);
7358 case NVPTXISD::ProxyReg:
7359 return combineProxyReg(N, DCI);
7360 case ISD::SETCC:
7361 return PerformSETCCCombine(N, DCI, STI);
7362 case ISD::SHL:
7363 return PerformSHLCombine(N, DCI, OptLevel);
7364 case ISD::SREM:
7365 case ISD::UREM:
7366 return PerformREMCombine(N, DCI, OptLevel);
7367 case ISD::STORE:
7368 case NVPTXISD::StoreV2:
7369 case NVPTXISD::StoreV4:
7370 return combineSTORE(N, DCI, STI);
7371 case ISD::SELECT:
7372 return PerformSELECTShiftCombine(N, DCI);
7373 case ISD::VSELECT:
7374 return PerformVSELECTCombine(N, DCI);
7376 return combineIntrinsicWOChain(N, DCI, STI);
7377 }
7378 return SDValue();
7379}
7380
7383 // Handle bitcasting to v2i8 without hitting the default promotion
7384 // strategy which goes through stack memory.
7385 SDValue Op(Node, 0);
7386 EVT ToVT = Op->getValueType(0);
7387 if (ToVT != MVT::v2i8) {
7388 return;
7389 }
7390
7391 // Bitcast to i16 and unpack elements into a vector
7392 SDLoc DL(Node);
7393 SDValue AsInt = DAG.getBitcast(MVT::i16, Op->getOperand(0));
7394 SDValue Vec0 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, AsInt);
7395 SDValue Const8 = DAG.getConstant(8, DL, MVT::i16);
7396 SDValue Vec1 =
7397 DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
7398 DAG.getNode(ISD::SRL, DL, MVT::i16, {AsInt, Const8}));
7399 Results.push_back(
7400 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i8, {Vec0, Vec1}));
7401}
7402
7405 SDValue Chain = N->getOperand(0);
7406 SDValue Intrin = N->getOperand(1);
7407 SDLoc DL(N);
7408
7409 // Get the intrinsic ID
7410 unsigned IntrinNo = Intrin.getNode()->getAsZExtVal();
7411 switch (IntrinNo) {
7412 default:
7413 return;
7414 case Intrinsic::nvvm_ldu_global_i:
7415 case Intrinsic::nvvm_ldu_global_f:
7416 case Intrinsic::nvvm_ldu_global_p: {
7417 EVT ResVT = N->getValueType(0);
7418
7419 if (ResVT.isVector()) {
7420 // Vector LDG/LDU
7421
7422 unsigned NumElts = ResVT.getVectorNumElements();
7423 EVT EltVT = ResVT.getVectorElementType();
7424
7425 // Since LDU/LDG are target nodes, we cannot rely on DAG type
7426 // legalization.
7427 // Therefore, we must ensure the type is legal. For i1 and i8, we set the
7428 // loaded type to i16 and propagate the "real" type as the memory type.
7429 bool NeedTrunc = false;
7430 if (EltVT.getSizeInBits() < 16) {
7431 EltVT = MVT::i16;
7432 NeedTrunc = true;
7433 }
7434
7435 unsigned Opcode = 0;
7436 SDVTList LdResVTs;
7437
7438 switch (NumElts) {
7439 default:
7440 return;
7441 case 2:
7442 Opcode = NVPTXISD::LDUV2;
7443 LdResVTs = DAG.getVTList(EltVT, EltVT, MVT::Other);
7444 break;
7445 case 4: {
7446 Opcode = NVPTXISD::LDUV4;
7447 EVT ListVTs[] = { EltVT, EltVT, EltVT, EltVT, MVT::Other };
7448 LdResVTs = DAG.getVTList(ListVTs);
7449 break;
7450 }
7451 }
7452
7453 SmallVector<SDValue, 8> OtherOps;
7454
7455 // Copy regular operands
7456
7457 OtherOps.push_back(Chain); // Chain
7458 // Skip operand 1 (intrinsic ID)
7459 // Others
7460 OtherOps.append(N->op_begin() + 2, N->op_end());
7461
7463
7464 SDValue NewLD = DAG.getMemIntrinsicNode(Opcode, DL, LdResVTs, OtherOps,
7465 MemSD->getMemoryVT(),
7466 MemSD->getMemOperand());
7467
7468 SmallVector<SDValue, 4> ScalarRes;
7469
7470 for (unsigned i = 0; i < NumElts; ++i) {
7471 SDValue Res = NewLD.getValue(i);
7472 if (NeedTrunc)
7473 Res =
7474 DAG.getNode(ISD::TRUNCATE, DL, ResVT.getVectorElementType(), Res);
7475 ScalarRes.push_back(Res);
7476 }
7477
7478 SDValue LoadChain = NewLD.getValue(NumElts);
7479
7480 SDValue BuildVec =
7481 DAG.getBuildVector(ResVT, DL, ScalarRes);
7482
7483 Results.push_back(BuildVec);
7484 Results.push_back(LoadChain);
7485 } else {
7486 // i8 LDG/LDU
7487 assert(ResVT.isSimple() && ResVT.getSimpleVT().SimpleTy == MVT::i8 &&
7488 "Custom handling of non-i8 ldu/ldg?");
7489
7490 // Just copy all operands as-is
7492
7493 // Force output to i16
7494 SDVTList LdResVTs = DAG.getVTList(MVT::i16, MVT::Other);
7495
7497
7498 // We make sure the memory type is i8, which will be used during isel
7499 // to select the proper instruction.
7500 SDValue NewLD =
7502 MVT::i8, MemSD->getMemOperand());
7503
7504 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
7505 NewLD.getValue(0)));
7506 Results.push_back(NewLD.getValue(1));
7507 }
7508 return;
7509 }
7510
7511 case Intrinsic::nvvm_tcgen05_ld_16x64b_x1:
7512 case Intrinsic::nvvm_tcgen05_ld_16x64b_x4:
7513 case Intrinsic::nvvm_tcgen05_ld_16x64b_x8:
7514 case Intrinsic::nvvm_tcgen05_ld_16x64b_x16:
7515 case Intrinsic::nvvm_tcgen05_ld_16x64b_x32:
7516 case Intrinsic::nvvm_tcgen05_ld_16x64b_x64:
7517 case Intrinsic::nvvm_tcgen05_ld_16x64b_x128:
7518 case Intrinsic::nvvm_tcgen05_ld_32x32b_x1:
7519 case Intrinsic::nvvm_tcgen05_ld_32x32b_x4:
7520 case Intrinsic::nvvm_tcgen05_ld_32x32b_x8:
7521 case Intrinsic::nvvm_tcgen05_ld_32x32b_x16:
7522 case Intrinsic::nvvm_tcgen05_ld_32x32b_x32:
7523 case Intrinsic::nvvm_tcgen05_ld_32x32b_x64:
7524 case Intrinsic::nvvm_tcgen05_ld_32x32b_x128:
7525 case Intrinsic::nvvm_tcgen05_ld_16x128b_x2:
7526 case Intrinsic::nvvm_tcgen05_ld_16x128b_x4:
7527 case Intrinsic::nvvm_tcgen05_ld_16x128b_x8:
7528 case Intrinsic::nvvm_tcgen05_ld_16x128b_x16:
7529 case Intrinsic::nvvm_tcgen05_ld_16x128b_x32:
7530 case Intrinsic::nvvm_tcgen05_ld_16x128b_x64:
7531 case Intrinsic::nvvm_tcgen05_ld_16x256b_x1:
7532 case Intrinsic::nvvm_tcgen05_ld_16x256b_x2:
7533 case Intrinsic::nvvm_tcgen05_ld_16x256b_x4:
7534 case Intrinsic::nvvm_tcgen05_ld_16x256b_x8:
7535 case Intrinsic::nvvm_tcgen05_ld_16x256b_x16:
7536 case Intrinsic::nvvm_tcgen05_ld_16x256b_x32:
7537 if (auto Res = lowerTcgen05Ld(N, DAG)) {
7538 Results.push_back(Res->first);
7539 Results.push_back(Res->second);
7540 }
7541 return;
7542
7543 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x1:
7544 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x4:
7545 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x8:
7546 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x16:
7547 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x32:
7548 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x64:
7549 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x128:
7550 if (auto Res = lowerTcgen05Ld(N, DAG, /*HasOffset=*/true)) {
7551 Results.push_back(Res->first);
7552 Results.push_back(Res->second);
7553 }
7554 return;
7555
7556 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_i32:
7557 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_f32:
7558 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_i32:
7559 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_f32:
7560 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_i32:
7561 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_f32:
7562 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_i32:
7563 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_f32:
7564 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_i32:
7565 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_f32:
7566 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_i32:
7567 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_f32:
7568 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_i32:
7569 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_f32:
7570 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_i32:
7571 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_f32:
7572 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_i32:
7573 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_f32:
7574 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_i32:
7575 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_f32:
7576 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_i32:
7577 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_f32:
7578 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_i32:
7579 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_f32:
7580 if (auto Res = lowerTcgen05LdRed(N, DAG)) {
7581 Results.push_back(std::get<0>(*Res));
7582 Results.push_back(std::get<1>(*Res));
7583 Results.push_back(std::get<2>(*Res));
7584 }
7585 return;
7586 }
7587}
7588
7591 // Change the CopyFromReg to output 2 64-bit results instead of a 128-bit
7592 // result so that it can pass the legalization
7593 SDLoc DL(N);
7594 SDValue Chain = N->getOperand(0);
7595 SDValue Reg = N->getOperand(1);
7596 SDValue Glue = N->getOperand(2);
7597
7598 assert(Reg.getValueType() == MVT::i128 &&
7599 "Custom lowering for CopyFromReg with 128-bit reg only");
7600 SmallVector<EVT, 4> ResultsType = {MVT::i64, MVT::i64, N->getValueType(1),
7601 N->getValueType(2)};
7602 SmallVector<SDValue, 3> NewOps = {Chain, Reg, Glue};
7603
7604 SDValue NewValue = DAG.getNode(ISD::CopyFromReg, DL, ResultsType, NewOps);
7605 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128,
7606 {NewValue.getValue(0), NewValue.getValue(1)});
7607
7608 Results.push_back(Pair);
7609 Results.push_back(NewValue.getValue(2));
7610 Results.push_back(NewValue.getValue(3));
7611}
7612
7614 const TargetLowering &TLI,
7616 SDValue Chain = N->getOperand(0);
7617 SDValue Reg = N->getOperand(1);
7618
7619 MVT VT = TLI.getRegisterType(*DAG.getContext(), Reg.getValueType());
7620
7621 SDValue NewReg = DAG.getAnyExtOrTrunc(Reg, SDLoc(N), VT);
7622 SDValue NewProxy =
7623 DAG.getNode(NVPTXISD::ProxyReg, SDLoc(N), VT, {Chain, NewReg});
7624 SDValue Res = DAG.getAnyExtOrTrunc(NewProxy, SDLoc(N), N->getValueType(0));
7625
7626 Results.push_back(Res);
7627}
7628
7630 const NVPTXSubtarget &STI,
7632 assert(N->getValueType(0) == MVT::i128 &&
7633 "Custom lowering for atomic128 only supports i128");
7634
7636 SDLoc dl(N);
7637
7638 if (!STI.hasAtomSwap128()) {
7641 "Support for b128 atomics introduced in PTX ISA version 8.3 and "
7642 "requires target sm_90.",
7643 dl.getDebugLoc()));
7644
7645 Results.push_back(DAG.getUNDEF(MVT::i128));
7646 Results.push_back(AN->getOperand(0)); // Chain
7647 return;
7648 }
7649
7651 Ops.push_back(AN->getOperand(0)); // Chain
7652 Ops.push_back(AN->getOperand(1)); // Ptr
7653 for (const auto &Op : AN->ops().drop_front(2)) {
7654 // Low part
7655 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i64, Op,
7656 DAG.getIntPtrConstant(0, dl)));
7657 // High part
7658 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i64, Op,
7659 DAG.getIntPtrConstant(1, dl)));
7660 }
7661 unsigned Opcode = N->getOpcode() == ISD::ATOMIC_SWAP
7664 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
7665 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, MVT::i128,
7666 AN->getMemOperand());
7667 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i128,
7668 {Result.getValue(0), Result.getValue(1)}));
7669 Results.push_back(Result.getValue(2));
7670}
7671
7672void NVPTXTargetLowering::ReplaceNodeResults(
7674 switch (N->getOpcode()) {
7675 default:
7676 report_fatal_error("Unhandled custom legalization");
7677 case ISD::BITCAST:
7678 ReplaceBITCAST(N, DAG, Results);
7679 return;
7680 case ISD::LOAD:
7681 case ISD::MLOAD:
7682 replaceLoadVector(N, DAG, Results, STI);
7683 return;
7686 return;
7687 case ISD::CopyFromReg:
7689 return;
7690 case NVPTXISD::ProxyReg:
7691 replaceProxyReg(N, DAG, *this, Results);
7692 return;
7694 case ISD::ATOMIC_SWAP:
7695 replaceAtomicSwap128(N, DAG, STI, Results);
7696 return;
7697 }
7698}
7699
7702 Type *Ty = AI->getValOperand()->getType();
7703
7704 // Try to lower LLVM atomicrmw fadd to PTX atomic.add. This is complicated
7705 // by the weird FTZ behavior PTX atom.add has:
7706 // - atom.add.f32 on global memory flushes denormals
7707 // - atom.add.f32 on shared memory does not flush denormals
7708 // - atom.add.f16 and atomic.add.bf16 never flush denormals
7709 //
7710 // We lower to atom.add only if the function's FTZ behavior matches that of
7711 // atom.add; otherwise, we lower to a CAS loop. But we always allow
7712 // atomic.add.bf16; even though it never flushes denormals, we never flush
7713 // bf16 denormals when doing regular arithmetic, even when FTZ is enabled.
7714 if (AI->isFloatingPointOperation() &&
7716 const Function *F = AI->getFunction();
7717
7718 // AllowFTZAtomics forces atom.add regardless of the FTZ mismatch.
7719 if (Ty->isFloatTy()) {
7720 const bool FTZ = F->getDenormalMode(APFloat::IEEEsingle()).Output ==
7723 switch (AI->getPointerAddressSpace()) {
7725 UseNative |= FTZ;
7726 break;
7729 UseNative |= !FTZ;
7730 break;
7731 }
7732 if (UseNative)
7734 }
7735
7736 if (Ty->isHalfTy()) {
7737 // atom.add.f16 never flushes denormals, so it only agrees with a
7738 // function that is not in FTZ mode for f16.
7739 const bool FTZ = F->getDenormalMode(APFloat::IEEEhalf()).Output ==
7741 if ((!FTZ || AllowFTZAtomics) && STI.hasFeature(NVPTX::SM70) &&
7742 STI.hasFeature(NVPTX::PTX63))
7744 }
7745
7746 if (Ty->isBFloatTy() && STI.hasFeature(NVPTX::SM90))
7748
7749 if (Ty->isDoubleTy() && STI.hasAtomAddF64())
7751 }
7752
7753 // PTX's only atomic fp op is `add`; all other ops expand to a CAS loop.
7754 if (AI->isFloatingPointOperation())
7756
7757 if (Ty->isVectorTy())
7759
7760 assert(Ty->isIntegerTy() && "Ty should be integer at this point");
7761 const unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
7762
7763 switch (AI->getOperation()) {
7764 default:
7767 if (BitWidth == 128)
7769 [[fallthrough]];
7773 switch (BitWidth) {
7774 case 8:
7775 case 16:
7777 case 32:
7779 case 64:
7780 if (STI.hasAtomBitwise64())
7783 case 128:
7785 default:
7786 llvm_unreachable("unsupported width encountered");
7787 }
7794 switch (BitWidth) {
7795 case 8:
7796 case 16:
7798 case 32:
7800 case 64:
7801 if (STI.hasAtomMinMax64())
7804 case 128:
7806 default:
7807 llvm_unreachable("unsupported width encountered");
7808 }
7811 switch (BitWidth) {
7812 case 32:
7814 case 8:
7815 case 16:
7816 case 64:
7817 case 128:
7819 default:
7820 llvm_unreachable("unsupported width encountered");
7821 }
7822 }
7823
7825}
7826
7828 const Instruction *I) const {
7829 // This function returns true iff the operation is emulated using a CAS-loop,
7830 // or if it has the memory order seq_cst (which is not natively supported in
7831 // the PTX `atom` instruction).
7832 //
7833 // atomicrmw and cmpxchg instructions not efficiently supported by PTX
7834 // are lowered to CAS emulation loops that preserve their memory order,
7835 // syncscope, and volatile semantics. For PTX, it is more efficient to use
7836 // atom.cas.relaxed.sco instructions within the loop, and fences before and
7837 // after the loop to restore order.
7838 //
7839 // Atomic instructions efficiently supported by PTX are lowered to
7840 // `atom.<op>.<sem>.<scope` instruction with their corresponding memory order
7841 // and scope. Since PTX does not support seq_cst, we emulate it by lowering to
7842 // a fence.sc followed by an atom according to the PTX atomics ABI
7843 // https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/atomic-abi.html
7844 if (auto *CI = dyn_cast<AtomicCmpXchgInst>(I))
7845 return (cast<IntegerType>(CI->getCompareOperand()->getType())
7846 ->getBitWidth() < STI.getMinCmpXchgSizeInBits()) ||
7847 CI->getMergedOrdering() == AtomicOrdering::SequentiallyConsistent;
7848 if (auto *RI = dyn_cast<AtomicRMWInst>(I))
7850 RI->getOrdering() == AtomicOrdering::SequentiallyConsistent;
7851 return false;
7852}
7853
7855 const Instruction *I) const {
7856 // If the operation is emulated by a CAS-loop, we lower the instruction to
7857 // atom.<op>.relaxed, since AtomicExpandPass will insert fences for enforcing
7858 // the correct memory ordering around the CAS loop.
7859 //
7860 // When the operation is not emulated, but the memory order is seq_cst,
7861 // we must lower to "fence.sc.<scope>; atom.<op>.acquire.<scope>;" to conform
7862 // to the PTX atomics ABI.
7863 // https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/atomic-abi.html
7864 // For such cases, emitLeadingFence() will separately insert the leading
7865 // "fence.sc.<scope>;". Here, we only set the memory order to acquire.
7866 //
7867 // Otherwise, the operation is not emulated, and the memory order is not
7868 // seq_cst. In this case, the LLVM memory order is natively supported by the
7869 // PTX `atom` instruction, and we just lower to the corresponding
7870 // `atom.<op>.relaxed|acquire|release|acq_rel". For such cases, this function
7871 // will NOT be called.
7872 // prerequisite: shouldInsertFencesForAtomic() should have returned `true` for
7873 // I before its memory order was modified.
7874 if (auto *CI = dyn_cast<AtomicCmpXchgInst>(I);
7875 CI && CI->getMergedOrdering() == AtomicOrdering::SequentiallyConsistent &&
7876 cast<IntegerType>(CI->getCompareOperand()->getType())->getBitWidth() >=
7877 STI.getMinCmpXchgSizeInBits())
7879 else if (auto *RI = dyn_cast<AtomicRMWInst>(I);
7880 RI && RI->getOrdering() == AtomicOrdering::SequentiallyConsistent &&
7883
7885}
7886
7888 Instruction *Inst,
7889 AtomicOrdering Ord) const {
7890 // prerequisite: shouldInsertFencesForAtomic() should have returned `true` for
7891 // `Inst` before its memory order was modified. We cannot enforce this with an
7892 // assert, because AtomicExpandPass will have modified the memory order
7893 // between the initial call to shouldInsertFencesForAtomic() and the call to
7894 // this function.
7895 if (!isa<AtomicCmpXchgInst>(Inst) && !isa<AtomicRMWInst>(Inst))
7896 return TargetLoweringBase::emitLeadingFence(Builder, Inst, Ord);
7897
7898 // Specialize for cmpxchg and atomicrmw
7899 auto SSID = getAtomicSyncScopeID(Inst);
7900 assert(SSID.has_value() && "Expected an atomic operation");
7901
7902 if (isReleaseOrStronger(Ord))
7903 return Builder.CreateFence(Ord == AtomicOrdering::SequentiallyConsistent
7906 SSID.value());
7907
7908 return nullptr;
7909}
7910
7912 Instruction *Inst,
7913 AtomicOrdering Ord) const {
7914 // prerequisite: shouldInsertFencesForAtomic() should have returned `true` for
7915 // `Inst` before its memory order was modified. See `emitLeadingFence` for why
7916 // this cannot be enforced with an assert. Specialize for cmpxchg and
7917 // atomicrmw
7918 auto *CI = dyn_cast<AtomicCmpXchgInst>(Inst);
7919 auto *RI = dyn_cast<AtomicRMWInst>(Inst);
7920 if (!CI && !RI)
7921 return TargetLoweringBase::emitTrailingFence(Builder, Inst, Ord);
7922
7923 auto SSID = getAtomicSyncScopeID(Inst);
7924 assert(SSID.has_value() && "Expected an atomic operation");
7925
7926 bool IsEmulated =
7927 CI ? cast<IntegerType>(CI->getCompareOperand()->getType())
7928 ->getBitWidth() < STI.getMinCmpXchgSizeInBits()
7930
7931 if (isAcquireOrStronger(Ord) && IsEmulated)
7932 return Builder.CreateFence(AtomicOrdering::Acquire, SSID.value());
7933
7934 return nullptr;
7935}
7936
7937// Rather than default to SINT when both UINT and SINT are custom, we only
7938// change the opcode when UINT is not legal and SINT is. UINT is preferred when
7939// both are custom since unsigned CVT instructions can lead to slightly better
7940// SASS code with fewer instructions.
7942 EVT ToVT) const {
7943 if (isOperationLegal(Op, ToVT))
7944 return Op;
7945 switch (Op) {
7946 case ISD::FP_TO_UINT:
7948 return ISD::FP_TO_SINT;
7949 break;
7953 break;
7954 default:
7955 break;
7956 }
7957 return Op;
7958}
7959
7960// Pin NVPTXTargetObjectFile's vtables to this file.
7962
7967
7969 const SelectionDAG &DAG, unsigned Depth) {
7970 SDValue A = Op.getOperand(0);
7971 SDValue B = Op.getOperand(1);
7972 ConstantSDNode *Selector = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7973 unsigned Mode = Op.getConstantOperandVal(3);
7974
7975 if (!Selector)
7976 return;
7977
7978 KnownBits AKnown = DAG.computeKnownBits(A, Depth);
7979 KnownBits BKnown = DAG.computeKnownBits(B, Depth);
7980
7981 // {b, a} = {{b7, b6, b5, b4}, {b3, b2, b1, b0}}
7982 assert(AKnown.getBitWidth() == 32 && BKnown.getBitWidth() == 32 &&
7983 "PRMT must have i32 operands");
7984 assert(Known.getBitWidth() == 32 && "PRMT must have i32 result");
7985 KnownBits BitField = BKnown.concat(AKnown);
7986
7987 APInt SelectorVal = getPRMTSelector(Selector->getAPIntValue(), Mode);
7988 for (unsigned I : llvm::seq(4)) {
7989 APInt Sel = SelectorVal.extractBits(4, I * 4);
7990 unsigned Idx = Sel.getLoBits(3).getZExtValue();
7991 unsigned Sign = Sel.getHiBits(1).getZExtValue();
7992 KnownBits Byte = BitField.extractBits(8, Idx * 8);
7993 if (Sign)
7994 Byte = KnownBits::ashr(Byte, KnownBits::makeConstant(APInt(8, 7)));
7995 Known.insertBits(Byte, I * 8);
7996 }
7997}
7998
8001
8002 // We can't do anything without knowing the sign bit.
8003 auto ExtType = LD->getConstantOperandVal(LD->getNumOperands() - 1);
8004 if (ExtType == ISD::SEXTLOAD)
8005 return;
8006
8007 // ExtLoading to vector types is weird and may not work well with known bits.
8008 auto DestVT = LD->getValueType(0);
8009 if (DestVT.isVector())
8010 return;
8011
8012 assert(Known.getBitWidth() == DestVT.getSizeInBits());
8013 auto ElementBitWidth = getFromTypeWidthForLoad(LD);
8014 Known.Zero.setHighBits(Known.getBitWidth() - ElementBitWidth);
8015}
8016
8018 const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
8019 const SelectionDAG &DAG, unsigned Depth) const {
8020 Known.resetAll();
8021
8022 switch (Op.getOpcode()) {
8023 case NVPTXISD::PRMT:
8025 break;
8026 case NVPTXISD::LoadV2:
8027 case NVPTXISD::LoadV4:
8028 case NVPTXISD::LoadV8:
8030 break;
8031 default:
8032 break;
8033 }
8034}
8035
8036static std::pair<APInt, APInt> getPRMTDemandedBits(const APInt &SelectorVal,
8037 const APInt &DemandedBits) {
8038 APInt DemandedLHS = APInt(32, 0);
8039 APInt DemandedRHS = APInt(32, 0);
8040
8041 for (unsigned I : llvm::seq(4)) {
8042 if (DemandedBits.extractBits(8, I * 8).isZero())
8043 continue;
8044
8045 APInt Sel = SelectorVal.extractBits(4, I * 4);
8046 unsigned Idx = Sel.getLoBits(3).getZExtValue();
8047 unsigned Sign = Sel.getHiBits(1).getZExtValue();
8048
8049 APInt &Src = Idx < 4 ? DemandedLHS : DemandedRHS;
8050 unsigned ByteStart = (Idx % 4) * 8;
8051 if (Sign)
8052 Src.setBit(ByteStart + 7);
8053 else
8054 Src.setBits(ByteStart, ByteStart + 8);
8055 }
8056
8057 return {DemandedLHS, DemandedRHS};
8058}
8059
8060// Replace undef with 0 as this is easier for other optimizations such as
8061// known bits.
8063 if (!Op)
8064 return SDValue();
8065 if (Op.isUndef())
8066 return DAG.getConstant(0, SDLoc(), MVT::i32);
8067 return Op;
8068}
8069
8071 const APInt &DemandedBits,
8072 SelectionDAG &DAG,
8073 const TargetLowering &TLI,
8074 unsigned Depth) {
8075 assert(PRMT.getOpcode() == NVPTXISD::PRMT);
8076 SDValue Op0 = PRMT.getOperand(0);
8077 SDValue Op1 = PRMT.getOperand(1);
8078 auto *SelectorConst = dyn_cast<ConstantSDNode>(PRMT.getOperand(2));
8079 if (!SelectorConst)
8080 return SDValue();
8081
8082 unsigned Mode = PRMT.getConstantOperandVal(3);
8083 const APInt Selector = getPRMTSelector(SelectorConst->getAPIntValue(), Mode);
8084
8085 // Try to simplify the PRMT to one of the inputs if the used bytes are all
8086 // from the same input in the correct order.
8087 const unsigned LeadingBytes = DemandedBits.countLeadingZeros() / 8;
8088 const unsigned SelBits = (4 - LeadingBytes) * 4;
8089 if (Selector.getLoBits(SelBits) == APInt(32, 0x3210).getLoBits(SelBits))
8090 return Op0;
8091 if (Selector.getLoBits(SelBits) == APInt(32, 0x7654).getLoBits(SelBits))
8092 return Op1;
8093
8094 auto [DemandedLHS, DemandedRHS] = getPRMTDemandedBits(Selector, DemandedBits);
8095
8096 // Attempt to avoid multi-use ops if we don't need anything from them.
8097 SDValue DemandedOp0 =
8098 TLI.SimplifyMultipleUseDemandedBits(Op0, DemandedLHS, DAG, Depth + 1);
8099 SDValue DemandedOp1 =
8100 TLI.SimplifyMultipleUseDemandedBits(Op1, DemandedRHS, DAG, Depth + 1);
8101
8102 DemandedOp0 = canonicalizePRMTInput(DemandedOp0, DAG);
8103 DemandedOp1 = canonicalizePRMTInput(DemandedOp1, DAG);
8104 if ((DemandedOp0 && DemandedOp0 != Op0) ||
8105 (DemandedOp1 && DemandedOp1 != Op1)) {
8106 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
8107 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
8108 return getPRMT(Op0, Op1, Selector.getZExtValue(), SDLoc(PRMT), DAG);
8109 }
8110
8111 return SDValue();
8112}
8113
8115 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8116 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
8117 Known.resetAll();
8118
8119 switch (Op.getOpcode()) {
8120 case NVPTXISD::PRMT:
8122 *this, Depth)) {
8123 TLO.CombineTo(Op, Result);
8124 return true;
8125 }
8126 break;
8127 default:
8128 break;
8129 }
8130
8131 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
8132 return false;
8133}
return SDValue()
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
constexpr LLT S1
constexpr LLT F32
static cl::list< std::string > UseNative("amdgpu-use-native", cl::desc("Comma separated list of functions to replace with native, or all"), cl::CommaSeparated, cl::ValueOptional, cl::Hidden)
AMDGPU Register Bank Select
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformADDCombineWithOperands - Try DAG combinations for an ADD with operands N0 and N1.
static SDValue PerformADDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
static SDValue PerformVSELECTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue PerformMULCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue PerformBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformBUILD_VECTORCombine - Target-specific dag combine xforms for ISD::BUILD_VECTOR.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file contains the declarations of entities that describe floating point environment and related ...
static bool IsIndirectCall(const MachineInstr *MI)
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#define T
NVPTX address space definition.
static SDValue reportInvalidTensormapReplaceUsage(SDValue Op, SelectionDAG &DAG, unsigned Val)
static SDValue combineShiftOfLogicOp(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
Commute SHL with a bitwise logic operation when doing so exposes a common shifted operand.
static SDValue combineADDRSPACECAST(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static cl::opt< bool > sched4reg("nvptx-sched4reg", cl::desc("NVPTX Specific: schedule for register pressue"), cl::init(false))
static SDValue lowerTcgen05St(SDValue Op, SelectionDAG &DAG, bool hasOffset=false)
static SDValue PerformEXTRACTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static cl::opt< NVPTX::DivPrecisionLevel > UsePrecDivF32("nvptx-prec-divf32", cl::Hidden, cl::desc("NVPTX Specific: Override the precision of the lowering for f32 fdiv"), cl::values(clEnumValN(NVPTX::DivPrecisionLevel::Approx, "0", "Use div.approx"), clEnumValN(NVPTX::DivPrecisionLevel::Full, "1", "Use div.full"), clEnumValN(NVPTX::DivPrecisionLevel::IEEE754, "2", "Use IEEE Compliant F32 div.rnd if available (default)"), clEnumValN(NVPTX::DivPrecisionLevel::IEEE754_NoFTZ, "3", "Use IEEE Compliant F32 div.rnd if available, no FTZ")), cl::init(NVPTX::DivPrecisionLevel::IEEE754))
static bool isConstOne(const SDValue &Operand)
static cl::opt< unsigned > FMAContractLevelOpt("nvptx-fma-level", cl::Hidden, cl::desc("NVPTX Specific: FMA contraction (0: don't do it" " 1: do it 2: do it aggressively"), cl::init(2))
static bool IsPTXVectorType(MVT VT)
static SDValue PerformSELECTShiftCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
Transform patterns like: (select (ugt shift_amt, BitWidth-1), 0, (srl/shl x, shift_amt)) (select (ult...
static SDValue lowerLOADi1(LoadSDNode *LD, SelectionDAG &DAG)
static SDValue lowerIntrinsicVoid(SDValue Op, SelectionDAG &DAG)
static SDValue lowerROT(SDValue Op, SelectionDAG &DAG)
static SDValue PerformFMinMaxCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const NVPTXSubtarget &STI)
PerformFMinMaxCombine - Combine (fmaxnum (fmaxnum a, b), c) into (fmaxnum3 a, b, c).
static void ComputePTXValueVTs(const TargetLowering &TLI, const DataLayout &DL, LLVMContext &Ctx, CallingConv::ID CallConv, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< uint64_t > &Offsets, uint64_t StartingOffset=0)
ComputePTXValueVTs - For the given Type Ty, returns the set of primitive legal-ish MVTs that compose ...
static void ReplaceBITCAST(SDNode *Node, SelectionDAG &DAG, SmallVectorImpl< SDValue > &Results)
static void replaceAtomicSwap128(SDNode *N, SelectionDAG &DAG, const NVPTXSubtarget &STI, SmallVectorImpl< SDValue > &Results)
static unsigned getMinMax3Opcode(unsigned MinMax2Opcode)
Get 3-input version of a 2-input min/max opcode.
static SDValue lowerStAsyncWithMbarrier(SDValue Op, SelectionDAG &DAG)
static SDValue lowerSTOREVector(SDValue Op, SelectionDAG &DAG, const NVPTXSubtarget &STI)
static SDValue lowerLoadVector(SDNode *N, SelectionDAG &DAG, const NVPTXSubtarget &STI)
static void replaceProxyReg(SDNode *N, SelectionDAG &DAG, const TargetLowering &TLI, SmallVectorImpl< SDValue > &Results)
static SDValue lowerStAsyncRelease(SDValue Op, SelectionDAG &DAG)
static void ReplaceCopyFromReg_128(SDNode *N, SelectionDAG &DAG, SmallVectorImpl< SDValue > &Results)
#define TCGEN05_LD_RED_INST(SHAPE, NUM, TYPE)
static SDValue getSymbolNode(SelectionDAG &DAG, MCSymbol *Sym, EVT T)
static SDValue lowerCTLZCTPOP(SDValue Op, SelectionDAG &DAG)
static SDValue combineMADConstOne(SDValue X, SDValue Add, EVT VT, SDLoc DL, TargetLowering::DAGCombinerInfo &DCI)
static unsigned getTcgen05LdRedID(Intrinsic::ID IID)
static SDValue combinePRMT(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, CodeGenOptLevel OptLevel)
static SDValue combinePackingMovIntoStore(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, unsigned Front, unsigned Back)
Fold packing movs into a store.
static void ReplaceINTRINSIC_W_CHAIN(SDNode *N, SelectionDAG &DAG, SmallVectorImpl< SDValue > &Results)
static SDValue getBuildVectorizedValue(unsigned N, const SDLoc &dl, SelectionDAG &DAG, T GetElement)
static SDValue getExtractVectorizedValue(SDValue V, unsigned I, EVT VT, const SDLoc &dl, SelectionDAG &DAG)
static SDValue combineSZExtToMulWide(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, CodeGenOptLevel OptLevel)
static unsigned canMergeParamLoadStoresStartingAt(unsigned Idx, uint32_t AccessSize, const SmallVectorImpl< EVT > &ValueVTs, const SmallVectorImpl< T > &Offsets, Align ParamAlignment)
static EVT getVectorizedVT(EVT VT, unsigned N, LLVMContext &C)
static SDValue lowerIntrinsicWOChain(SDValue Op, SelectionDAG &DAG)
static std::optional< unsigned > getScalar3OpcodeForReduction(unsigned ReductionOpcode)
Get 3-input scalar reduction opcode.
static SDValue lowerIntrinsicWChain(SDValue Op, SelectionDAG &DAG)
static bool isNonCoalescableBuildVector(const SDValue &BV)
Check if a v2f32 BUILD_VECTOR provably packs values from non-adjacent register pairs (non-coalescable...
static bool isConstZero(const SDValue &Operand)
static SDValue LowerVectorArith(SDValue Op, SelectionDAG &DAG)
static SDValue LowerTcgen05MMADisableOutputLane(SDValue Op, SelectionDAG &DAG)
static bool IsMulWideOperandDemotable(SDValue Op, unsigned OptSize, OperandSignedness &S)
IsMulWideOperandDemotable - Checks if the provided DAG node is an operand that can be demoted to OptS...
static unsigned getTcgen05MMADisableOutputLane(unsigned IID)
static std::pair< APInt, APInt > getPRMTDemandedBits(const APInt &SelectorVal, const APInt &DemandedBits)
static APInt computePRMT(APInt A, APInt B, APInt Selector, unsigned Mode)
static ISD::NodeType getScalarOpcodeForReduction(unsigned ReductionOpcode)
static SDValue PerformREMCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, CodeGenOptLevel OptLevel)
static SDValue lowerBSWAP(SDValue Op, SelectionDAG &DAG)
static SDValue lowerMSTORE(SDValue Op, SelectionDAG &DAG)
static SDValue PerformMULCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, TargetLowering::DAGCombinerInfo &DCI)
static void computeKnownBitsForPRMT(const SDValue Op, KnownBits &Known, const SelectionDAG &DAG, unsigned Depth)
static SDValue combineUnpackingMovIntoLoad(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
Fold unpacking movs into a load by increasing the number of return values.
#define TCGEN05_LD_RED_INTR(SHAPE, NUM, TYPE)
static SDValue lowerTensormapReplaceElemtype(SDValue Op, SelectionDAG &DAG)
static SDValue LowerClusterLaunchControlQueryCancel(SDValue Op, SelectionDAG &DAG)
static SDValue PerformSETCCCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const NVPTXSubtarget &STI)
static std::optional< std::pair< SDValue, SDValue > > lowerTcgen05Ld(SDNode *N, SelectionDAG &DAG, bool HasOffset=false)
static SDValue lowerCvtRSIntrinsics(SDValue Op, SelectionDAG &DAG)
static std::optional< std::pair< SDValue, SDValue > > replaceLoadVector(SDNode *N, SelectionDAG &DAG, const NVPTXSubtarget &STI)
replaceLoadVector - Convert vector loads into multi-output scalar loads.
static SDValue expandFSH64(SDValue A, SDValue B, SDValue ShiftAmount, SDLoc DL, unsigned Opcode, SelectionDAG &DAG)
static cl::opt< bool > AllowFTZAtomics("nvptx-allow-ftz-atomics", cl::Hidden, cl::desc("NVPTX Specific: Lower atomicrmw fadd to atom.add even when its " "FTZ behavior does not match the function's denormal mode."), cl::init(true))
static bool AreMulWideOperandsDemotable(SDValue LHS, SDValue RHS, unsigned OptSize, bool &IsSigned)
AreMulWideOperandsDemotable - Checks if the given LHS and RHS operands can be demoted to OptSize bits...
static std::pair< MemSDNode *, uint32_t > convertMLOADToLoadWithUsedBytesMask(MemSDNode *N, SelectionDAG &DAG, const NVPTXSubtarget &STI)
static SDValue TryMULWIDECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
TryMULWIDECombine - Attempt to replace a multiply of M bits with a multiply of M/2 bits that produces...
static SDValue lowerPrmtIntrinsic(SDValue Op, SelectionDAG &DAG)
static SDValue diagnoseUnsupportedFAdd(SDNode *N, SelectionDAG &DAG, Intrinsic::ID IID, APFloat::roundingMode RoundingMode)
static SDValue combineMulSelectConstOne(SDValue X, SDValue Select, EVT VT, SDLoc DL, TargetLowering::DAGCombinerInfo &DCI)
static SDValue buildTreeReduction(const SmallVector< SDValue > &Elements, EVT EltTy, ArrayRef< std::pair< unsigned, unsigned > > Ops, const SDLoc &DL, const SDNodeFlags Flags, SelectionDAG &DAG)
Reduces the elements using the scalar operations provided.
static SDValue combineProxyReg(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static SmallVector< unsigned, 16 > VectorizePTXValueVTs(const SmallVectorImpl< EVT > &ValueVTs, const SmallVectorImpl< T > &Offsets, Align ParamAlignment, bool IsVAArg=false)
static SDValue combineFAddWithNeg(SDNode *N, SelectionDAG &DAG, Intrinsic::ID AddIntrinsicID, APFloat::roundingMode RoundingMode)
static SDValue getPRMT(SDValue A, SDValue B, SDValue Selector, SDLoc DL, SelectionDAG &DAG, unsigned Mode=NVPTX::PTXPrmtMode::NONE)
static SDValue matchMADConstOnePattern(SDValue Add)
static SDValue correctParamType(SDValue V, EVT ExpectedVT, ISD::ArgFlagsTy Flags, SelectionDAG &DAG, SDLoc dl)
static ISD::NodeType getExtOpcode(const ISD::ArgFlagsTy &Flags)
static cl::opt< bool > UsePrecSqrtF32("nvptx-prec-sqrtf32", cl::Hidden, cl::desc("NVPTX Specific: 0 use sqrt.approx, 1 use sqrt.rn."), cl::init(true))
static MachinePointerInfo refinePtrAS(SDValue &Ptr, SelectionDAG &DAG)
static void computeKnownBitsForLoadV(const SDValue Op, KnownBits &Known)
static APInt getPRMTSelector(const APInt &Selector, unsigned Mode)
static EVT promoteScalarIntegerPTX(const EVT VT)
PromoteScalarIntegerPTX Used to make sure the arguments/returns are suitable for passing and promote ...
static std::optional< std::tuple< SDValue, SDValue, SDValue > > lowerTcgen05LdRed(SDNode *N, SelectionDAG &DAG)
static SDValue simplifyDemandedBitsForPRMT(SDValue PRMT, const APInt &DemandedBits, SelectionDAG &DAG, const TargetLowering &TLI, unsigned Depth)
static SDValue lowerFREM(SDValue Op, SelectionDAG &DAG)
static SDValue canonicalizePRMTInput(SDValue Op, SelectionDAG &DAG)
static SDValue sinkProxyReg(SDValue R, SDValue Chain, TargetLowering::DAGCombinerInfo &DCI)
static SDValue lowerFSH(SDValue Op, SelectionDAG &DAG)
static SDValue lowerTensormapReplaceSwizzleMode(SDValue Op, SelectionDAG &DAG)
static SDValue combineIntrinsicWOChain(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const NVPTXSubtarget &STI)
static SDValue PromoteBinOpToF32(SDNode *N, SelectionDAG &DAG)
static unsigned getFAddWithNegOpcode(EVT VT, Intrinsic::ID IID, APFloat::roundingMode RoundingMode)
static std::optional< std::pair< unsigned int, MVT > > getVectorLoweringShape(EVT VectorEVT, const NVPTXSubtarget &STI, unsigned AddressSpace)
static cl::opt< bool > UseApproxLog2F32("nvptx-approx-log2f32", cl::desc("NVPTX Specific: whether to use lg2.approx for log2"), cl::init(false))
Whereas CUDA's implementation (see libdevice) uses ex2.approx for exp2(), it does NOT use lg2....
static SDValue lowerSELECT(SDValue Op, SelectionDAG &DAG)
static bool isSupportedFAdd(EVT VT, const NVPTXSubtarget &STI, Intrinsic::ID IID, APFloat::roundingMode RoundingMode)
static SDValue combineLOAD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const NVPTXSubtarget &STI)
static SDValue combineSTORE(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const NVPTXSubtarget &STI)
static SDValue PerformSHLCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, CodeGenOptLevel OptLevel)
PerformSHLCombine - Runs PTX-specific DAG combine patterns on SHL nodes.
uint64_t High
This file contains the definitions of the enumerations and flags associated with NVVM Intrinsics,...
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
Contains matchers for matching SelectionDAG nodes and values.
SI Fold Operands
Func MI getDebugLoc()))
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
Value * RHS
Value * LHS
BinaryOperator * Mul
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
llvm::RoundingMode roundingMode
IEEE-754R 4.3: Rounding-direction attributes.
Definition APFloat.h:359
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt getLoBits(unsigned numBits) const
Compute an APInt containing numBits lowbits from this APInt.
Definition APInt.cpp:641
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
LLVM_ABI APInt getHiBits(unsigned numBits) const
Compute an APInt containing numBits highbits from this APInt.
Definition APInt.cpp:636
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:432
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:429
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
an instruction that atomically reads a memory location, combines it with another value,...
@ Add
*p = old + v
@ FAdd
*p = old + v
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ UMax
*p = old >unsigned v ? old : v
@ UDecWrap
Decrement one until a minimum value or zero.
bool isFloatingPointOperation() const
BinOp getOperation() const
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
This is an SDNode representing atomic operations.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
FunctionType * getFunctionType() const
const APInt & getAPIntValue() const
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Diagnostic information for unsupported feature in backend.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:640
Module * getParent()
Get the module that this global value is contained inside of...
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This class is used to represent ISD::LOAD nodes.
Context object for machine code objects.
Definition MCContext.h:83
MCSection * getDataSection() const
static constexpr unsigned NoRegister
Definition MCRegister.h:60
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:580
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
Machine Value Type.
static auto integer_fixedlen_vector_valuetypes()
SimpleValueType SimpleTy
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isScalableVector() const
Return true if this is a vector value type where the runtime length is machine dependent.
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
static MVT getVectorVT(MVT VT, unsigned NumElements)
MVT getVectorElementType() const
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
static auto fp_fixedlen_vector_valuetypes()
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
MCContext & getContext() const
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
@ EK_Inline
EK_Inline - Jump table entries are emitted inline at their point of use.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
This SDNode is used for target intrinsics that touch memory and need an associated MachineMemOperand.
This is an abstract virtual class for memory operations.
Align getAlign() const
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
EVT getMemoryVT() const
Return the type of the in-memory value.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
bool hasTensormapReplaceElemtypeSupport(unsigned ElemType) const
bool hasTensormapReplaceSwizzleModeSupport(unsigned SwizzleMode) const
bool hasNativeBF16Support(unsigned Opcode) const
bool hasUsedBytesMaskPragma() const
bool hasAtomSwap128() const
bool hasF32x2Instructions() const
bool has256BitVectorLoadStore(unsigned AS) const
AtomicOrdering atomicOperationOrderAfterFenceSplit(const Instruction *I) const override
ConstraintType getConstraintType(StringRef Constraint) const override
getConstraintType - Given a constraint letter, return the type of constraint it is for this target.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
bool SimplifyDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0) const override
Attempt to simplify any target nodes based on the demanded bits/elts, returning true on success.
AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *AI) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
NVPTXTargetLowering(const NVPTXTargetMachine &TM, const NVPTXSubtarget &STI)
unsigned getPreferredFPToIntOpcode(unsigned Op, EVT FromVT, EVT ToVT) const override
bool useF32FTZ(const MachineFunction &MF) const
SDValue LowerSTACKSAVE(SDValue Op, SelectionDAG &DAG) const
SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &ExtraSteps, bool &UseOneConst, bool Reciprocal) const override
Hooks for building estimates in place of slower divisions and square roots.
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &dl, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
MCSymbol * getParamSymbol(MCContext &Ctx, const Function *F, int Idx) const
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
SDValue LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG) const
Instruction * emitTrailingFence(IRBuilderBase &Builder, Instruction *Inst, AtomicOrdering Ord) const override
TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const override
Return the preferred vector type legalization action.
NVPTX::DivPrecisionLevel getDivF32Level(const MachineFunction &MF, const SDNode &N) const
bool shouldInsertFencesForAtomic(const Instruction *) const override
Whether AtomicExpandPass should automatically insert fences and reduce ordering for this atomic.
SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, EVT VT) const override
Return the ValueType of the result of SETCC operations.
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
isLegalAddressingMode - Return true if the addressing mode represented by AM is legal for this target...
Instruction * emitLeadingFence(IRBuilderBase &Builder, Instruction *Inst, AtomicOrdering Ord) const override
Inserts in the IR a target-specific intrinsic specifying a fence.
void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const override
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
bool allowFMA(MachineFunction &MF, CodeGenOptLevel OptLevel) const
bool usePrecSqrtF32(const SDNode *N=nullptr) const
unsigned getJumpTableEncoding() const override
Return the entry encoding for a jump table in the current function.
SDValue LowerCall(CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower calls into the specified DAG.
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:911
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
Represents one node in the SelectionDAG.
ArrayRef< SDUse > ops() const
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
unsigned getIROrder() const
Return the node ordering.
SDNodeFlags getFlags() const
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
SDVTList getVTList() const
const SDValue & getOperand(unsigned Num) const
bool isUndef() const
Returns true if the node type is UNDEF or POISON.
iterator_range< user_iterator > users()
void setFlags(SDNodeFlags NewFlags)
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
uint64_t getScalarValueSizeInBits() const
uint64_t getConstantOperandVal(unsigned i) const
unsigned getOpcode() const
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition SectionKind.h:22
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
const TargetSubtargetInfo & getSubtarget() const
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
LLVM_ABI SDValue getSymbolFunctionGlobalAddress(SDValue Op, Function **TargetFunction=nullptr)
Return a GlobalAddress of the function from the current module with name matching the given ExternalS...
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
MachineFunction & getMachineFunction() const
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI SDValue getMCSymbol(MCSymbol *Sym, EVT VT)
ArrayRef< int > getMask() const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
void setMaxDivRemBitWidthSupported(unsigned SizeInBits)
Set the size in bits of the maximum div/rem the backend supports.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
const TargetMachine & getTargetMachine() const
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
Convenience method to set an operation to Promote and specify the type in a single call.
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth)
Tells the code generator which bitwidths to bypass.
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
void setMaxLargeFPConvertBitWidthSupported(unsigned SizeInBits)
Set the size in bits of the maximum fp to/from int conversion the backend supports.
virtual unsigned getNumRegisters(LLVMContext &Context, EVT VT, std::optional< MVT > RegisterVT=std::nullopt) const
Return the number of registers that this ValueType will eventually require.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const
Return the preferred vector type legalization action.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Sets the minimum cmpxchg or ll/sc size supported by the backend.
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setCondCodeAction(ArrayRef< ISD::CondCode > CCs, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn't supported on the target and indicate what to d...
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
Align getMinStackArgumentAlignment() const
Return the minimum stack alignment of an argument.
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
std::vector< ArgListEntry > ArgListTy
virtual Instruction * emitTrailingFence(IRBuilderBase &Builder, Instruction *Inst, AtomicOrdering Ord) const
virtual Instruction * emitLeadingFence(IRBuilderBase &Builder, Instruction *Inst, AtomicOrdering Ord) const
Inserts in the IR a target-specific intrinsic specifying a fence.
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
void setJumpIsExpensive(bool isExpensive=true)
Tells the code generator not to expand logic operations on comparison predicates into separate sequen...
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth=0) const
More limited version of SimplifyDemandedBits that can be used to "lookthrough" ops that don't contrib...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
SDValue expandRoundInexactToOdd(EVT ResultVT, SDValue Op, const SDLoc &DL, SelectionDAG &DAG) const
Truncate Op to ResultVT.
SDValue expandFP_ROUND(SDNode *Node, SelectionDAG &DAG) const
Expand round(fp) to fp conversion.
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
MCSymbol * getSymbol(const GlobalValue *GV) const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetFrameLowering * getFrameLowering() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt pow(const APInt &X, int64_t N)
Compute X^N for N>=0.
Definition APInt.cpp:3189
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:236
@ MLOAD
Masked load and store - consecutive vector load and store operations with additional mask operand tha...
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:789
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:294
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:863
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:520
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:220
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:890
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:586
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:417
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:749
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:280
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:254
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:798
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ READSTEADYCOUNTER
READSTEADYCOUNTER - This corresponds to the readfixedcounter intrinsic.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:352
@ BRIND
BRIND - Indirect branch.
@ BR_JT
BR_JT - Jumptable branch.
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:374
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:233
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:348
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:706
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:771
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:651
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:616
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimumNumber or maximumNumber on two values,...
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:578
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:224
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:821
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:386
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:356
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:898
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:729
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:988
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:815
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:328
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:110
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:480
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:479
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:936
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:741
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:304
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:567
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:969
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ VECREDUCE_FMINIMUM
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:843
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:536
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:365
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ SADDO_CARRY
Carry-using overflow-aware nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:338
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:753
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:558
bool isExtOpcode(unsigned Opcode)
LLVM_ABI bool allOperandsUndef(const SDNode *N)
Return true if the node has at least one operand and all operands of the specified node are ISD::UNDE...
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
@ Bitcast
Perform the operation on a different, but equivalently sized type.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
@ ATOMIC_CMP_SWAP_B128
These nodes are used to lower atomic instructions with i128 type.
@ DeviceParam
Definition NVPTX.h:334
@ EntryParam
Definition NVPTX.h:328
bool isPackedVectorTy(EVT VT)
DivPrecisionLevel
Definition NVPTX.h:465
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinOpPred_match< LHS, RHS, is_bitwiselogic_op > m_BitwiseLogic(const LHS &L, const RHS &R)
Matches bitwise logic operations.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
StringRef GetRoundingModeName(APFloat::roundingMode RM)
@ User
could "use" a pointer
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:830
Align getDeviceByValParamAlign(const Function *F, Type *ArgTy, unsigned AttrIdx, const DataLayout &DL)
The .param-space alignment for a byval parameter or call argument: the (possibly promoted) parameter ...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
SDValue peekThroughFreeze(SDValue V)
Return the non-frozen source operand of V if it exists.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
LLVM_ABI void ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< EVT > *MemVTs=nullptr, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
ComputeValueVTs - Given an LLVM IR type, compute a sequence of EVTs that represent all the individual...
Definition Analysis.cpp:119
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Store
The extracted value is stored (ExtractElement only).
Align getPTXParamTypeAlign(Type *ArgTy, const DataLayout &DL)
ABI alignment of ArgTy in .param space, capped at the PTX maximum of 128.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
bool isReleaseOrStronger(AtomicOrdering AO)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2026
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
std::optional< SyncScope::ID > getAtomicSyncScopeID(const Instruction *I)
A helper function that returns an atomic operation's sync scope; returns std::nullopt if it is not an...
unsigned promoteScalarArgumentSize(unsigned size)
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
bool shouldPassAsArray(Type *Ty)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:551
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:149
@ Default
-O2, -Os, -Oz
Definition CodeGen.h:152
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.
DWARFExpression::Operation Op
RoundingMode
Rounding mode.
Align getPTXParamAlign(const Function *F, Type *Ty, unsigned AttrIdx, const DataLayout &DL)
Alignment for a function parameter or return value at AttributeList index AttrIdx (FirstArgIndex + ar...
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
bool isAcquireOrStronger(AtomicOrdering AO)
constexpr unsigned BitWidth
bool isKernelFunction(const Function &F)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
unsigned getFromTypeWidthForLoad(const MemSDNode *Mem)
The bit-width of a single element loaded by Mem, i.e.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
DenormalModeKind Output
Denormal flushing mode for floating point instruction results in the default floating point environme...
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:129
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
bool is32BitVector() const
Return true if this is a 32-bit vector type.
Definition ValueTypes.h:220
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
LLVM_ABI std::string getEVTString() const
This function returns value type as a string, e.g. "i32".
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:279
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
EVT changeElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a type whose attributes match ourselves with the exception of the element type that i...
Definition ValueTypes.h:121
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
KnownBits concat(const KnownBits &Lo) const
Concatenate the bits from Lo onto the bottom of *this.
Definition KnownBits.h:247
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
unsigned countMaxActiveBits() const
Returns the maximum number of bits needed to represent all possible unsigned values with these known ...
Definition KnownBits.h:310
This class contains a discriminated union of information about pointers in memory operands,...
MachinePointerInfo getWithOffset(int64_t O) const
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
These are IR-level optimization flags that may be propagated to SDNodes.
bool hasAllowContract() const
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
SmallVector< ISD::OutputArg, 32 > Outs
Type * RetTy
Same as OrigRetTy, or partially legalized for soft float libcalls.
LLVM_ABI SDValue CombineTo(SDNode *N, ArrayRef< SDValue > To, bool AddTo=true)
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...