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_mbarrier_init: {
4759 Info.opc = ISD::INTRINSIC_VOID;
4760 Info.memVT = MVT::i64;
4761 Info.ptrVal = I.getArgOperand(0);
4762 Info.offset = 0;
4763 Info.flags = MachineMemOperand::MOStore;
4764 Info.align = Align(8);
4765 Infos.push_back(Info);
4766 return;
4767 }
4768
4769 case Intrinsic::nvvm_mbarrier_check_layout: {
4770 Info.opc = ISD::INTRINSIC_W_CHAIN;
4771 Info.memVT = MVT::i64;
4772 Info.ptrVal = I.getArgOperand(0);
4773 Info.offset = 0;
4774 Info.flags = MachineMemOperand::MOLoad;
4775 Info.align = Align(8);
4776 Infos.push_back(Info);
4777 return;
4778 }
4779
4780 case Intrinsic::nvvm_tensormap_replace_global_address:
4781 case Intrinsic::nvvm_tensormap_replace_global_stride: {
4782 Info.opc = ISD::INTRINSIC_VOID;
4783 Info.memVT = MVT::i64;
4784 Info.ptrVal = I.getArgOperand(0);
4785 Info.offset = 0;
4786 Info.flags = MachineMemOperand::MOStore;
4787 Info.align.reset();
4788 Infos.push_back(Info);
4789 return;
4790 }
4791
4792 case Intrinsic::nvvm_tensormap_replace_rank:
4793 case Intrinsic::nvvm_tensormap_replace_box_dim:
4794 case Intrinsic::nvvm_tensormap_replace_global_dim:
4795 case Intrinsic::nvvm_tensormap_replace_element_stride:
4796 case Intrinsic::nvvm_tensormap_replace_elemtype:
4797 case Intrinsic::nvvm_tensormap_replace_interleave_layout:
4798 case Intrinsic::nvvm_tensormap_replace_swizzle_mode:
4799 case Intrinsic::nvvm_tensormap_replace_swizzle_atomicity:
4800 case Intrinsic::nvvm_tensormap_replace_fill_mode: {
4801 Info.opc = ISD::INTRINSIC_VOID;
4802 Info.memVT = MVT::i32;
4803 Info.ptrVal = I.getArgOperand(0);
4804 Info.offset = 0;
4805 Info.flags = MachineMemOperand::MOStore;
4806 Info.align.reset();
4807 Infos.push_back(Info);
4808 return;
4809 }
4810
4811 case Intrinsic::nvvm_ldu_global_i:
4812 case Intrinsic::nvvm_ldu_global_f:
4813 case Intrinsic::nvvm_ldu_global_p: {
4814 Info.opc = ISD::INTRINSIC_W_CHAIN;
4815 Info.memVT = getValueType(I.getDataLayout(), I.getType());
4816 Info.ptrVal = I.getArgOperand(0);
4817 Info.offset = 0;
4818 Info.flags = MachineMemOperand::MOLoad;
4819 Info.align = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4820
4821 Infos.push_back(Info);
4822 return;
4823 }
4824 case Intrinsic::nvvm_tex_1d_v4f32_s32:
4825 case Intrinsic::nvvm_tex_1d_v4f32_f32:
4826 case Intrinsic::nvvm_tex_1d_level_v4f32_f32:
4827 case Intrinsic::nvvm_tex_1d_grad_v4f32_f32:
4828 case Intrinsic::nvvm_tex_1d_array_v4f32_s32:
4829 case Intrinsic::nvvm_tex_1d_array_v4f32_f32:
4830 case Intrinsic::nvvm_tex_1d_array_level_v4f32_f32:
4831 case Intrinsic::nvvm_tex_1d_array_grad_v4f32_f32:
4832 case Intrinsic::nvvm_tex_2d_v4f32_s32:
4833 case Intrinsic::nvvm_tex_2d_v4f32_f32:
4834 case Intrinsic::nvvm_tex_2d_level_v4f32_f32:
4835 case Intrinsic::nvvm_tex_2d_grad_v4f32_f32:
4836 case Intrinsic::nvvm_tex_2d_array_v4f32_s32:
4837 case Intrinsic::nvvm_tex_2d_array_v4f32_f32:
4838 case Intrinsic::nvvm_tex_2d_array_level_v4f32_f32:
4839 case Intrinsic::nvvm_tex_2d_array_grad_v4f32_f32:
4840 case Intrinsic::nvvm_tex_3d_v4f32_s32:
4841 case Intrinsic::nvvm_tex_3d_v4f32_f32:
4842 case Intrinsic::nvvm_tex_3d_level_v4f32_f32:
4843 case Intrinsic::nvvm_tex_3d_grad_v4f32_f32:
4844 case Intrinsic::nvvm_tex_cube_v4f32_f32:
4845 case Intrinsic::nvvm_tex_cube_level_v4f32_f32:
4846 case Intrinsic::nvvm_tex_cube_array_v4f32_f32:
4847 case Intrinsic::nvvm_tex_cube_array_level_v4f32_f32:
4848 case Intrinsic::nvvm_tld4_r_2d_v4f32_f32:
4849 case Intrinsic::nvvm_tld4_g_2d_v4f32_f32:
4850 case Intrinsic::nvvm_tld4_b_2d_v4f32_f32:
4851 case Intrinsic::nvvm_tld4_a_2d_v4f32_f32:
4852 case Intrinsic::nvvm_tex_unified_1d_v4f32_s32:
4853 case Intrinsic::nvvm_tex_unified_1d_v4f32_f32:
4854 case Intrinsic::nvvm_tex_unified_1d_level_v4f32_f32:
4855 case Intrinsic::nvvm_tex_unified_1d_grad_v4f32_f32:
4856 case Intrinsic::nvvm_tex_unified_1d_array_v4f32_s32:
4857 case Intrinsic::nvvm_tex_unified_1d_array_v4f32_f32:
4858 case Intrinsic::nvvm_tex_unified_1d_array_level_v4f32_f32:
4859 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4f32_f32:
4860 case Intrinsic::nvvm_tex_unified_2d_v4f32_s32:
4861 case Intrinsic::nvvm_tex_unified_2d_v4f32_f32:
4862 case Intrinsic::nvvm_tex_unified_2d_level_v4f32_f32:
4863 case Intrinsic::nvvm_tex_unified_2d_grad_v4f32_f32:
4864 case Intrinsic::nvvm_tex_unified_2d_array_v4f32_s32:
4865 case Intrinsic::nvvm_tex_unified_2d_array_v4f32_f32:
4866 case Intrinsic::nvvm_tex_unified_2d_array_level_v4f32_f32:
4867 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4f32_f32:
4868 case Intrinsic::nvvm_tex_unified_3d_v4f32_s32:
4869 case Intrinsic::nvvm_tex_unified_3d_v4f32_f32:
4870 case Intrinsic::nvvm_tex_unified_3d_level_v4f32_f32:
4871 case Intrinsic::nvvm_tex_unified_3d_grad_v4f32_f32:
4872 case Intrinsic::nvvm_tex_unified_cube_v4f32_f32:
4873 case Intrinsic::nvvm_tex_unified_cube_level_v4f32_f32:
4874 case Intrinsic::nvvm_tex_unified_cube_array_v4f32_f32:
4875 case Intrinsic::nvvm_tex_unified_cube_array_level_v4f32_f32:
4876 case Intrinsic::nvvm_tex_unified_cube_grad_v4f32_f32:
4877 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4f32_f32:
4878 case Intrinsic::nvvm_tld4_unified_r_2d_v4f32_f32:
4879 case Intrinsic::nvvm_tld4_unified_g_2d_v4f32_f32:
4880 case Intrinsic::nvvm_tld4_unified_b_2d_v4f32_f32:
4881 case Intrinsic::nvvm_tld4_unified_a_2d_v4f32_f32:
4882 Info.opc = ISD::INTRINSIC_W_CHAIN;
4883 Info.memVT = MVT::v4f32;
4884 Info.ptrVal = nullptr;
4885 Info.offset = 0;
4886 Info.flags = MachineMemOperand::MOLoad;
4887 Info.align = Align(16);
4888 Infos.push_back(Info);
4889 return;
4890
4891 case Intrinsic::nvvm_tex_1d_v4s32_s32:
4892 case Intrinsic::nvvm_tex_1d_v4s32_f32:
4893 case Intrinsic::nvvm_tex_1d_level_v4s32_f32:
4894 case Intrinsic::nvvm_tex_1d_grad_v4s32_f32:
4895 case Intrinsic::nvvm_tex_1d_array_v4s32_s32:
4896 case Intrinsic::nvvm_tex_1d_array_v4s32_f32:
4897 case Intrinsic::nvvm_tex_1d_array_level_v4s32_f32:
4898 case Intrinsic::nvvm_tex_1d_array_grad_v4s32_f32:
4899 case Intrinsic::nvvm_tex_2d_v4s32_s32:
4900 case Intrinsic::nvvm_tex_2d_v4s32_f32:
4901 case Intrinsic::nvvm_tex_2d_level_v4s32_f32:
4902 case Intrinsic::nvvm_tex_2d_grad_v4s32_f32:
4903 case Intrinsic::nvvm_tex_2d_array_v4s32_s32:
4904 case Intrinsic::nvvm_tex_2d_array_v4s32_f32:
4905 case Intrinsic::nvvm_tex_2d_array_level_v4s32_f32:
4906 case Intrinsic::nvvm_tex_2d_array_grad_v4s32_f32:
4907 case Intrinsic::nvvm_tex_3d_v4s32_s32:
4908 case Intrinsic::nvvm_tex_3d_v4s32_f32:
4909 case Intrinsic::nvvm_tex_3d_level_v4s32_f32:
4910 case Intrinsic::nvvm_tex_3d_grad_v4s32_f32:
4911 case Intrinsic::nvvm_tex_cube_v4s32_f32:
4912 case Intrinsic::nvvm_tex_cube_level_v4s32_f32:
4913 case Intrinsic::nvvm_tex_cube_array_v4s32_f32:
4914 case Intrinsic::nvvm_tex_cube_array_level_v4s32_f32:
4915 case Intrinsic::nvvm_tex_cube_v4u32_f32:
4916 case Intrinsic::nvvm_tex_cube_level_v4u32_f32:
4917 case Intrinsic::nvvm_tex_cube_array_v4u32_f32:
4918 case Intrinsic::nvvm_tex_cube_array_level_v4u32_f32:
4919 case Intrinsic::nvvm_tex_1d_v4u32_s32:
4920 case Intrinsic::nvvm_tex_1d_v4u32_f32:
4921 case Intrinsic::nvvm_tex_1d_level_v4u32_f32:
4922 case Intrinsic::nvvm_tex_1d_grad_v4u32_f32:
4923 case Intrinsic::nvvm_tex_1d_array_v4u32_s32:
4924 case Intrinsic::nvvm_tex_1d_array_v4u32_f32:
4925 case Intrinsic::nvvm_tex_1d_array_level_v4u32_f32:
4926 case Intrinsic::nvvm_tex_1d_array_grad_v4u32_f32:
4927 case Intrinsic::nvvm_tex_2d_v4u32_s32:
4928 case Intrinsic::nvvm_tex_2d_v4u32_f32:
4929 case Intrinsic::nvvm_tex_2d_level_v4u32_f32:
4930 case Intrinsic::nvvm_tex_2d_grad_v4u32_f32:
4931 case Intrinsic::nvvm_tex_2d_array_v4u32_s32:
4932 case Intrinsic::nvvm_tex_2d_array_v4u32_f32:
4933 case Intrinsic::nvvm_tex_2d_array_level_v4u32_f32:
4934 case Intrinsic::nvvm_tex_2d_array_grad_v4u32_f32:
4935 case Intrinsic::nvvm_tex_3d_v4u32_s32:
4936 case Intrinsic::nvvm_tex_3d_v4u32_f32:
4937 case Intrinsic::nvvm_tex_3d_level_v4u32_f32:
4938 case Intrinsic::nvvm_tex_3d_grad_v4u32_f32:
4939 case Intrinsic::nvvm_tld4_r_2d_v4s32_f32:
4940 case Intrinsic::nvvm_tld4_g_2d_v4s32_f32:
4941 case Intrinsic::nvvm_tld4_b_2d_v4s32_f32:
4942 case Intrinsic::nvvm_tld4_a_2d_v4s32_f32:
4943 case Intrinsic::nvvm_tld4_r_2d_v4u32_f32:
4944 case Intrinsic::nvvm_tld4_g_2d_v4u32_f32:
4945 case Intrinsic::nvvm_tld4_b_2d_v4u32_f32:
4946 case Intrinsic::nvvm_tld4_a_2d_v4u32_f32:
4947 case Intrinsic::nvvm_tex_unified_1d_v4s32_s32:
4948 case Intrinsic::nvvm_tex_unified_1d_v4s32_f32:
4949 case Intrinsic::nvvm_tex_unified_1d_level_v4s32_f32:
4950 case Intrinsic::nvvm_tex_unified_1d_grad_v4s32_f32:
4951 case Intrinsic::nvvm_tex_unified_1d_array_v4s32_s32:
4952 case Intrinsic::nvvm_tex_unified_1d_array_v4s32_f32:
4953 case Intrinsic::nvvm_tex_unified_1d_array_level_v4s32_f32:
4954 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4s32_f32:
4955 case Intrinsic::nvvm_tex_unified_2d_v4s32_s32:
4956 case Intrinsic::nvvm_tex_unified_2d_v4s32_f32:
4957 case Intrinsic::nvvm_tex_unified_2d_level_v4s32_f32:
4958 case Intrinsic::nvvm_tex_unified_2d_grad_v4s32_f32:
4959 case Intrinsic::nvvm_tex_unified_2d_array_v4s32_s32:
4960 case Intrinsic::nvvm_tex_unified_2d_array_v4s32_f32:
4961 case Intrinsic::nvvm_tex_unified_2d_array_level_v4s32_f32:
4962 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4s32_f32:
4963 case Intrinsic::nvvm_tex_unified_3d_v4s32_s32:
4964 case Intrinsic::nvvm_tex_unified_3d_v4s32_f32:
4965 case Intrinsic::nvvm_tex_unified_3d_level_v4s32_f32:
4966 case Intrinsic::nvvm_tex_unified_3d_grad_v4s32_f32:
4967 case Intrinsic::nvvm_tex_unified_1d_v4u32_s32:
4968 case Intrinsic::nvvm_tex_unified_1d_v4u32_f32:
4969 case Intrinsic::nvvm_tex_unified_1d_level_v4u32_f32:
4970 case Intrinsic::nvvm_tex_unified_1d_grad_v4u32_f32:
4971 case Intrinsic::nvvm_tex_unified_1d_array_v4u32_s32:
4972 case Intrinsic::nvvm_tex_unified_1d_array_v4u32_f32:
4973 case Intrinsic::nvvm_tex_unified_1d_array_level_v4u32_f32:
4974 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4u32_f32:
4975 case Intrinsic::nvvm_tex_unified_2d_v4u32_s32:
4976 case Intrinsic::nvvm_tex_unified_2d_v4u32_f32:
4977 case Intrinsic::nvvm_tex_unified_2d_level_v4u32_f32:
4978 case Intrinsic::nvvm_tex_unified_2d_grad_v4u32_f32:
4979 case Intrinsic::nvvm_tex_unified_2d_array_v4u32_s32:
4980 case Intrinsic::nvvm_tex_unified_2d_array_v4u32_f32:
4981 case Intrinsic::nvvm_tex_unified_2d_array_level_v4u32_f32:
4982 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4u32_f32:
4983 case Intrinsic::nvvm_tex_unified_3d_v4u32_s32:
4984 case Intrinsic::nvvm_tex_unified_3d_v4u32_f32:
4985 case Intrinsic::nvvm_tex_unified_3d_level_v4u32_f32:
4986 case Intrinsic::nvvm_tex_unified_3d_grad_v4u32_f32:
4987 case Intrinsic::nvvm_tex_unified_cube_v4s32_f32:
4988 case Intrinsic::nvvm_tex_unified_cube_level_v4s32_f32:
4989 case Intrinsic::nvvm_tex_unified_cube_array_v4s32_f32:
4990 case Intrinsic::nvvm_tex_unified_cube_array_level_v4s32_f32:
4991 case Intrinsic::nvvm_tex_unified_cube_v4u32_f32:
4992 case Intrinsic::nvvm_tex_unified_cube_level_v4u32_f32:
4993 case Intrinsic::nvvm_tex_unified_cube_array_v4u32_f32:
4994 case Intrinsic::nvvm_tex_unified_cube_array_level_v4u32_f32:
4995 case Intrinsic::nvvm_tex_unified_cube_grad_v4s32_f32:
4996 case Intrinsic::nvvm_tex_unified_cube_grad_v4u32_f32:
4997 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4s32_f32:
4998 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4u32_f32:
4999 case Intrinsic::nvvm_tld4_unified_r_2d_v4s32_f32:
5000 case Intrinsic::nvvm_tld4_unified_g_2d_v4s32_f32:
5001 case Intrinsic::nvvm_tld4_unified_b_2d_v4s32_f32:
5002 case Intrinsic::nvvm_tld4_unified_a_2d_v4s32_f32:
5003 case Intrinsic::nvvm_tld4_unified_r_2d_v4u32_f32:
5004 case Intrinsic::nvvm_tld4_unified_g_2d_v4u32_f32:
5005 case Intrinsic::nvvm_tld4_unified_b_2d_v4u32_f32:
5006 case Intrinsic::nvvm_tld4_unified_a_2d_v4u32_f32:
5007 Info.opc = ISD::INTRINSIC_W_CHAIN;
5008 Info.memVT = MVT::v4i32;
5009 Info.ptrVal = nullptr;
5010 Info.offset = 0;
5011 Info.flags = MachineMemOperand::MOLoad;
5012 Info.align = Align(16);
5013 Infos.push_back(Info);
5014 return;
5015
5016 case Intrinsic::nvvm_suld_1d_i8_clamp:
5017 case Intrinsic::nvvm_suld_1d_v2i8_clamp:
5018 case Intrinsic::nvvm_suld_1d_v4i8_clamp:
5019 case Intrinsic::nvvm_suld_1d_array_i8_clamp:
5020 case Intrinsic::nvvm_suld_1d_array_v2i8_clamp:
5021 case Intrinsic::nvvm_suld_1d_array_v4i8_clamp:
5022 case Intrinsic::nvvm_suld_2d_i8_clamp:
5023 case Intrinsic::nvvm_suld_2d_v2i8_clamp:
5024 case Intrinsic::nvvm_suld_2d_v4i8_clamp:
5025 case Intrinsic::nvvm_suld_2d_array_i8_clamp:
5026 case Intrinsic::nvvm_suld_2d_array_v2i8_clamp:
5027 case Intrinsic::nvvm_suld_2d_array_v4i8_clamp:
5028 case Intrinsic::nvvm_suld_3d_i8_clamp:
5029 case Intrinsic::nvvm_suld_3d_v2i8_clamp:
5030 case Intrinsic::nvvm_suld_3d_v4i8_clamp:
5031 case Intrinsic::nvvm_suld_1d_i8_trap:
5032 case Intrinsic::nvvm_suld_1d_v2i8_trap:
5033 case Intrinsic::nvvm_suld_1d_v4i8_trap:
5034 case Intrinsic::nvvm_suld_1d_array_i8_trap:
5035 case Intrinsic::nvvm_suld_1d_array_v2i8_trap:
5036 case Intrinsic::nvvm_suld_1d_array_v4i8_trap:
5037 case Intrinsic::nvvm_suld_2d_i8_trap:
5038 case Intrinsic::nvvm_suld_2d_v2i8_trap:
5039 case Intrinsic::nvvm_suld_2d_v4i8_trap:
5040 case Intrinsic::nvvm_suld_2d_array_i8_trap:
5041 case Intrinsic::nvvm_suld_2d_array_v2i8_trap:
5042 case Intrinsic::nvvm_suld_2d_array_v4i8_trap:
5043 case Intrinsic::nvvm_suld_3d_i8_trap:
5044 case Intrinsic::nvvm_suld_3d_v2i8_trap:
5045 case Intrinsic::nvvm_suld_3d_v4i8_trap:
5046 case Intrinsic::nvvm_suld_1d_i8_zero:
5047 case Intrinsic::nvvm_suld_1d_v2i8_zero:
5048 case Intrinsic::nvvm_suld_1d_v4i8_zero:
5049 case Intrinsic::nvvm_suld_1d_array_i8_zero:
5050 case Intrinsic::nvvm_suld_1d_array_v2i8_zero:
5051 case Intrinsic::nvvm_suld_1d_array_v4i8_zero:
5052 case Intrinsic::nvvm_suld_2d_i8_zero:
5053 case Intrinsic::nvvm_suld_2d_v2i8_zero:
5054 case Intrinsic::nvvm_suld_2d_v4i8_zero:
5055 case Intrinsic::nvvm_suld_2d_array_i8_zero:
5056 case Intrinsic::nvvm_suld_2d_array_v2i8_zero:
5057 case Intrinsic::nvvm_suld_2d_array_v4i8_zero:
5058 case Intrinsic::nvvm_suld_3d_i8_zero:
5059 case Intrinsic::nvvm_suld_3d_v2i8_zero:
5060 case Intrinsic::nvvm_suld_3d_v4i8_zero:
5061 Info.opc = ISD::INTRINSIC_W_CHAIN;
5062 Info.memVT = MVT::i8;
5063 Info.ptrVal = nullptr;
5064 Info.offset = 0;
5065 Info.flags = MachineMemOperand::MOLoad;
5066 Info.align = Align(16);
5067 Infos.push_back(Info);
5068 return;
5069
5070 case Intrinsic::nvvm_suld_1d_i16_clamp:
5071 case Intrinsic::nvvm_suld_1d_v2i16_clamp:
5072 case Intrinsic::nvvm_suld_1d_v4i16_clamp:
5073 case Intrinsic::nvvm_suld_1d_array_i16_clamp:
5074 case Intrinsic::nvvm_suld_1d_array_v2i16_clamp:
5075 case Intrinsic::nvvm_suld_1d_array_v4i16_clamp:
5076 case Intrinsic::nvvm_suld_2d_i16_clamp:
5077 case Intrinsic::nvvm_suld_2d_v2i16_clamp:
5078 case Intrinsic::nvvm_suld_2d_v4i16_clamp:
5079 case Intrinsic::nvvm_suld_2d_array_i16_clamp:
5080 case Intrinsic::nvvm_suld_2d_array_v2i16_clamp:
5081 case Intrinsic::nvvm_suld_2d_array_v4i16_clamp:
5082 case Intrinsic::nvvm_suld_3d_i16_clamp:
5083 case Intrinsic::nvvm_suld_3d_v2i16_clamp:
5084 case Intrinsic::nvvm_suld_3d_v4i16_clamp:
5085 case Intrinsic::nvvm_suld_1d_i16_trap:
5086 case Intrinsic::nvvm_suld_1d_v2i16_trap:
5087 case Intrinsic::nvvm_suld_1d_v4i16_trap:
5088 case Intrinsic::nvvm_suld_1d_array_i16_trap:
5089 case Intrinsic::nvvm_suld_1d_array_v2i16_trap:
5090 case Intrinsic::nvvm_suld_1d_array_v4i16_trap:
5091 case Intrinsic::nvvm_suld_2d_i16_trap:
5092 case Intrinsic::nvvm_suld_2d_v2i16_trap:
5093 case Intrinsic::nvvm_suld_2d_v4i16_trap:
5094 case Intrinsic::nvvm_suld_2d_array_i16_trap:
5095 case Intrinsic::nvvm_suld_2d_array_v2i16_trap:
5096 case Intrinsic::nvvm_suld_2d_array_v4i16_trap:
5097 case Intrinsic::nvvm_suld_3d_i16_trap:
5098 case Intrinsic::nvvm_suld_3d_v2i16_trap:
5099 case Intrinsic::nvvm_suld_3d_v4i16_trap:
5100 case Intrinsic::nvvm_suld_1d_i16_zero:
5101 case Intrinsic::nvvm_suld_1d_v2i16_zero:
5102 case Intrinsic::nvvm_suld_1d_v4i16_zero:
5103 case Intrinsic::nvvm_suld_1d_array_i16_zero:
5104 case Intrinsic::nvvm_suld_1d_array_v2i16_zero:
5105 case Intrinsic::nvvm_suld_1d_array_v4i16_zero:
5106 case Intrinsic::nvvm_suld_2d_i16_zero:
5107 case Intrinsic::nvvm_suld_2d_v2i16_zero:
5108 case Intrinsic::nvvm_suld_2d_v4i16_zero:
5109 case Intrinsic::nvvm_suld_2d_array_i16_zero:
5110 case Intrinsic::nvvm_suld_2d_array_v2i16_zero:
5111 case Intrinsic::nvvm_suld_2d_array_v4i16_zero:
5112 case Intrinsic::nvvm_suld_3d_i16_zero:
5113 case Intrinsic::nvvm_suld_3d_v2i16_zero:
5114 case Intrinsic::nvvm_suld_3d_v4i16_zero:
5115 Info.opc = ISD::INTRINSIC_W_CHAIN;
5116 Info.memVT = MVT::i16;
5117 Info.ptrVal = nullptr;
5118 Info.offset = 0;
5119 Info.flags = MachineMemOperand::MOLoad;
5120 Info.align = Align(16);
5121 Infos.push_back(Info);
5122 return;
5123
5124 case Intrinsic::nvvm_suld_1d_i32_clamp:
5125 case Intrinsic::nvvm_suld_1d_v2i32_clamp:
5126 case Intrinsic::nvvm_suld_1d_v4i32_clamp:
5127 case Intrinsic::nvvm_suld_1d_array_i32_clamp:
5128 case Intrinsic::nvvm_suld_1d_array_v2i32_clamp:
5129 case Intrinsic::nvvm_suld_1d_array_v4i32_clamp:
5130 case Intrinsic::nvvm_suld_2d_i32_clamp:
5131 case Intrinsic::nvvm_suld_2d_v2i32_clamp:
5132 case Intrinsic::nvvm_suld_2d_v4i32_clamp:
5133 case Intrinsic::nvvm_suld_2d_array_i32_clamp:
5134 case Intrinsic::nvvm_suld_2d_array_v2i32_clamp:
5135 case Intrinsic::nvvm_suld_2d_array_v4i32_clamp:
5136 case Intrinsic::nvvm_suld_3d_i32_clamp:
5137 case Intrinsic::nvvm_suld_3d_v2i32_clamp:
5138 case Intrinsic::nvvm_suld_3d_v4i32_clamp:
5139 case Intrinsic::nvvm_suld_1d_i32_trap:
5140 case Intrinsic::nvvm_suld_1d_v2i32_trap:
5141 case Intrinsic::nvvm_suld_1d_v4i32_trap:
5142 case Intrinsic::nvvm_suld_1d_array_i32_trap:
5143 case Intrinsic::nvvm_suld_1d_array_v2i32_trap:
5144 case Intrinsic::nvvm_suld_1d_array_v4i32_trap:
5145 case Intrinsic::nvvm_suld_2d_i32_trap:
5146 case Intrinsic::nvvm_suld_2d_v2i32_trap:
5147 case Intrinsic::nvvm_suld_2d_v4i32_trap:
5148 case Intrinsic::nvvm_suld_2d_array_i32_trap:
5149 case Intrinsic::nvvm_suld_2d_array_v2i32_trap:
5150 case Intrinsic::nvvm_suld_2d_array_v4i32_trap:
5151 case Intrinsic::nvvm_suld_3d_i32_trap:
5152 case Intrinsic::nvvm_suld_3d_v2i32_trap:
5153 case Intrinsic::nvvm_suld_3d_v4i32_trap:
5154 case Intrinsic::nvvm_suld_1d_i32_zero:
5155 case Intrinsic::nvvm_suld_1d_v2i32_zero:
5156 case Intrinsic::nvvm_suld_1d_v4i32_zero:
5157 case Intrinsic::nvvm_suld_1d_array_i32_zero:
5158 case Intrinsic::nvvm_suld_1d_array_v2i32_zero:
5159 case Intrinsic::nvvm_suld_1d_array_v4i32_zero:
5160 case Intrinsic::nvvm_suld_2d_i32_zero:
5161 case Intrinsic::nvvm_suld_2d_v2i32_zero:
5162 case Intrinsic::nvvm_suld_2d_v4i32_zero:
5163 case Intrinsic::nvvm_suld_2d_array_i32_zero:
5164 case Intrinsic::nvvm_suld_2d_array_v2i32_zero:
5165 case Intrinsic::nvvm_suld_2d_array_v4i32_zero:
5166 case Intrinsic::nvvm_suld_3d_i32_zero:
5167 case Intrinsic::nvvm_suld_3d_v2i32_zero:
5168 case Intrinsic::nvvm_suld_3d_v4i32_zero:
5169 Info.opc = ISD::INTRINSIC_W_CHAIN;
5170 Info.memVT = MVT::i32;
5171 Info.ptrVal = nullptr;
5172 Info.offset = 0;
5173 Info.flags = MachineMemOperand::MOLoad;
5174 Info.align = Align(16);
5175 Infos.push_back(Info);
5176 return;
5177
5178 case Intrinsic::nvvm_suld_1d_i64_clamp:
5179 case Intrinsic::nvvm_suld_1d_v2i64_clamp:
5180 case Intrinsic::nvvm_suld_1d_array_i64_clamp:
5181 case Intrinsic::nvvm_suld_1d_array_v2i64_clamp:
5182 case Intrinsic::nvvm_suld_2d_i64_clamp:
5183 case Intrinsic::nvvm_suld_2d_v2i64_clamp:
5184 case Intrinsic::nvvm_suld_2d_array_i64_clamp:
5185 case Intrinsic::nvvm_suld_2d_array_v2i64_clamp:
5186 case Intrinsic::nvvm_suld_3d_i64_clamp:
5187 case Intrinsic::nvvm_suld_3d_v2i64_clamp:
5188 case Intrinsic::nvvm_suld_1d_i64_trap:
5189 case Intrinsic::nvvm_suld_1d_v2i64_trap:
5190 case Intrinsic::nvvm_suld_1d_array_i64_trap:
5191 case Intrinsic::nvvm_suld_1d_array_v2i64_trap:
5192 case Intrinsic::nvvm_suld_2d_i64_trap:
5193 case Intrinsic::nvvm_suld_2d_v2i64_trap:
5194 case Intrinsic::nvvm_suld_2d_array_i64_trap:
5195 case Intrinsic::nvvm_suld_2d_array_v2i64_trap:
5196 case Intrinsic::nvvm_suld_3d_i64_trap:
5197 case Intrinsic::nvvm_suld_3d_v2i64_trap:
5198 case Intrinsic::nvvm_suld_1d_i64_zero:
5199 case Intrinsic::nvvm_suld_1d_v2i64_zero:
5200 case Intrinsic::nvvm_suld_1d_array_i64_zero:
5201 case Intrinsic::nvvm_suld_1d_array_v2i64_zero:
5202 case Intrinsic::nvvm_suld_2d_i64_zero:
5203 case Intrinsic::nvvm_suld_2d_v2i64_zero:
5204 case Intrinsic::nvvm_suld_2d_array_i64_zero:
5205 case Intrinsic::nvvm_suld_2d_array_v2i64_zero:
5206 case Intrinsic::nvvm_suld_3d_i64_zero:
5207 case Intrinsic::nvvm_suld_3d_v2i64_zero:
5208 Info.opc = ISD::INTRINSIC_W_CHAIN;
5209 Info.memVT = MVT::i64;
5210 Info.ptrVal = nullptr;
5211 Info.offset = 0;
5212 Info.flags = MachineMemOperand::MOLoad;
5213 Info.align = Align(16);
5214 Infos.push_back(Info);
5215 return;
5216
5217 case Intrinsic::nvvm_tcgen05_ld_16x64b_x1:
5218 case Intrinsic::nvvm_tcgen05_ld_32x32b_x1:
5219 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x1: {
5220 Info.opc = ISD::INTRINSIC_W_CHAIN;
5221 Info.memVT = MVT::v1i32;
5222 Info.ptrVal = I.getArgOperand(0);
5223 Info.offset = 0;
5224 Info.flags = MachineMemOperand::MOLoad;
5225 Info.align.reset();
5226 Infos.push_back(Info);
5227 return;
5228 }
5229
5230 case Intrinsic::nvvm_tcgen05_ld_16x64b_x2:
5231 case Intrinsic::nvvm_tcgen05_ld_16x128b_x1:
5232 case Intrinsic::nvvm_tcgen05_ld_32x32b_x2:
5233 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x2:
5234 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x2_i32:
5235 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x2_i32: {
5236 Info.opc = ISD::INTRINSIC_W_CHAIN;
5237 Info.memVT = MVT::v2i32;
5238 Info.ptrVal = I.getArgOperand(0);
5239 Info.offset = 0;
5240 Info.flags = MachineMemOperand::MOLoad;
5241 Info.align.reset();
5242 Infos.push_back(Info);
5243 return;
5244 }
5245
5246 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x2_f32:
5247 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x2_f32: {
5248 Info.opc = ISD::INTRINSIC_W_CHAIN;
5249 Info.memVT = MVT::v2f32;
5250 Info.ptrVal = I.getArgOperand(0);
5251 Info.offset = 0;
5252 Info.flags = MachineMemOperand::MOLoad;
5253 Info.align.reset();
5254 Infos.push_back(Info);
5255 return;
5256 }
5257
5258 case Intrinsic::nvvm_tcgen05_ld_16x64b_x4:
5259 case Intrinsic::nvvm_tcgen05_ld_16x128b_x2:
5260 case Intrinsic::nvvm_tcgen05_ld_32x32b_x4:
5261 case Intrinsic::nvvm_tcgen05_ld_16x256b_x1:
5262 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x4:
5263 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_i32:
5264 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_i32: {
5265 Info.opc = ISD::INTRINSIC_W_CHAIN;
5266 Info.memVT = MVT::v4i32;
5267 Info.ptrVal = I.getArgOperand(0);
5268 Info.offset = 0;
5269 Info.flags = MachineMemOperand::MOLoad;
5270 Info.align.reset();
5271 Infos.push_back(Info);
5272 return;
5273 }
5274
5275 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_f32:
5276 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_f32: {
5277 Info.opc = ISD::INTRINSIC_W_CHAIN;
5278 Info.memVT = MVT::v4f32;
5279 Info.ptrVal = I.getArgOperand(0);
5280 Info.offset = 0;
5281 Info.flags = MachineMemOperand::MOLoad;
5282 Info.align.reset();
5283 Infos.push_back(Info);
5284 return;
5285 }
5286
5287 case Intrinsic::nvvm_tcgen05_ld_16x64b_x8:
5288 case Intrinsic::nvvm_tcgen05_ld_16x128b_x4:
5289 case Intrinsic::nvvm_tcgen05_ld_16x256b_x2:
5290 case Intrinsic::nvvm_tcgen05_ld_32x32b_x8:
5291 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x8:
5292 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_i32:
5293 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_i32: {
5294 Info.opc = ISD::INTRINSIC_W_CHAIN;
5295 Info.memVT = MVT::v8i32;
5296 Info.ptrVal = I.getArgOperand(0);
5297 Info.offset = 0;
5298 Info.flags = MachineMemOperand::MOLoad;
5299 Info.align.reset();
5300 Infos.push_back(Info);
5301 return;
5302 }
5303
5304 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_f32:
5305 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_f32: {
5306 Info.opc = ISD::INTRINSIC_W_CHAIN;
5307 Info.memVT = MVT::v8f32;
5308 Info.ptrVal = I.getArgOperand(0);
5309 Info.offset = 0;
5310 Info.flags = MachineMemOperand::MOLoad;
5311 Info.align.reset();
5312 Infos.push_back(Info);
5313 return;
5314 }
5315
5316 case Intrinsic::nvvm_tcgen05_ld_16x64b_x16:
5317 case Intrinsic::nvvm_tcgen05_ld_16x128b_x8:
5318 case Intrinsic::nvvm_tcgen05_ld_16x256b_x4:
5319 case Intrinsic::nvvm_tcgen05_ld_32x32b_x16:
5320 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x16:
5321 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_i32:
5322 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_i32: {
5323 Info.opc = ISD::INTRINSIC_W_CHAIN;
5324 Info.memVT = MVT::v16i32;
5325 Info.ptrVal = I.getArgOperand(0);
5326 Info.offset = 0;
5327 Info.flags = MachineMemOperand::MOLoad;
5328 Info.align.reset();
5329 Infos.push_back(Info);
5330 return;
5331 }
5332
5333 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_f32:
5334 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_f32: {
5335 Info.opc = ISD::INTRINSIC_W_CHAIN;
5336 Info.memVT = MVT::v16f32;
5337 Info.ptrVal = I.getArgOperand(0);
5338 Info.offset = 0;
5339 Info.flags = MachineMemOperand::MOLoad;
5340 Info.align.reset();
5341 Infos.push_back(Info);
5342 return;
5343 }
5344
5345 case Intrinsic::nvvm_tcgen05_ld_16x64b_x32:
5346 case Intrinsic::nvvm_tcgen05_ld_16x128b_x16:
5347 case Intrinsic::nvvm_tcgen05_ld_16x256b_x8:
5348 case Intrinsic::nvvm_tcgen05_ld_32x32b_x32:
5349 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x32:
5350 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_i32:
5351 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_i32: {
5352 Info.opc = ISD::INTRINSIC_W_CHAIN;
5353 Info.memVT = MVT::v32i32;
5354 Info.ptrVal = I.getArgOperand(0);
5355 Info.offset = 0;
5356 Info.flags = MachineMemOperand::MOLoad;
5357 Info.align.reset();
5358 Infos.push_back(Info);
5359 return;
5360 }
5361
5362 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_f32:
5363 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_f32: {
5364 Info.opc = ISD::INTRINSIC_W_CHAIN;
5365 Info.memVT = MVT::v32f32;
5366 Info.ptrVal = I.getArgOperand(0);
5367 Info.offset = 0;
5368 Info.flags = MachineMemOperand::MOLoad;
5369 Info.align.reset();
5370 Infos.push_back(Info);
5371 return;
5372 }
5373
5374 case Intrinsic::nvvm_tcgen05_ld_16x64b_x64:
5375 case Intrinsic::nvvm_tcgen05_ld_16x128b_x32:
5376 case Intrinsic::nvvm_tcgen05_ld_16x256b_x16:
5377 case Intrinsic::nvvm_tcgen05_ld_32x32b_x64:
5378 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x64:
5379 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_i32:
5380 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_i32: {
5381 Info.opc = ISD::INTRINSIC_W_CHAIN;
5382 Info.memVT = MVT::v64i32;
5383 Info.ptrVal = I.getArgOperand(0);
5384 Info.offset = 0;
5385 Info.flags = MachineMemOperand::MOLoad;
5386 Info.align.reset();
5387 Infos.push_back(Info);
5388 return;
5389 }
5390
5391 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_f32:
5392 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_f32: {
5393 Info.opc = ISD::INTRINSIC_W_CHAIN;
5394 Info.memVT = MVT::v64f32;
5395 Info.ptrVal = I.getArgOperand(0);
5396 Info.offset = 0;
5397 Info.flags = MachineMemOperand::MOLoad;
5398 Info.align.reset();
5399 Infos.push_back(Info);
5400 return;
5401 }
5402
5403 case Intrinsic::nvvm_tcgen05_ld_16x64b_x128:
5404 case Intrinsic::nvvm_tcgen05_ld_16x128b_x64:
5405 case Intrinsic::nvvm_tcgen05_ld_16x256b_x32:
5406 case Intrinsic::nvvm_tcgen05_ld_32x32b_x128:
5407 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x128:
5408 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_i32:
5409 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_i32: {
5410 Info.opc = ISD::INTRINSIC_W_CHAIN;
5411 Info.memVT = MVT::v128i32;
5412 Info.ptrVal = I.getArgOperand(0);
5413 Info.offset = 0;
5414 Info.flags = MachineMemOperand::MOLoad;
5415 Info.align.reset();
5416 Infos.push_back(Info);
5417 return;
5418 }
5419
5420 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_f32:
5421 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_f32: {
5422 Info.opc = ISD::INTRINSIC_W_CHAIN;
5423 Info.memVT = MVT::v128f32;
5424 Info.ptrVal = I.getArgOperand(0);
5425 Info.offset = 0;
5426 Info.flags = MachineMemOperand::MOLoad;
5427 Info.align.reset();
5428 Infos.push_back(Info);
5429 return;
5430 }
5431
5432 case Intrinsic::nvvm_tcgen05_st_16x64b_x1:
5433 case Intrinsic::nvvm_tcgen05_st_32x32b_x1:
5434 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x1: {
5435 Info.opc = ISD::INTRINSIC_VOID;
5436 Info.memVT = MVT::v1i32;
5437 Info.ptrVal = I.getArgOperand(0);
5438 Info.offset = 0;
5439 Info.flags = MachineMemOperand::MOStore;
5440 Info.align.reset();
5441 Infos.push_back(Info);
5442 return;
5443 }
5444
5445 case Intrinsic::nvvm_tcgen05_st_16x64b_x2:
5446 case Intrinsic::nvvm_tcgen05_st_16x128b_x1:
5447 case Intrinsic::nvvm_tcgen05_st_32x32b_x2:
5448 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x2: {
5449 Info.opc = ISD::INTRINSIC_VOID;
5450 Info.memVT = MVT::v2i32;
5451 Info.ptrVal = I.getArgOperand(0);
5452 Info.offset = 0;
5453 Info.flags = MachineMemOperand::MOStore;
5454 Info.align.reset();
5455 Infos.push_back(Info);
5456 return;
5457 }
5458
5459 case Intrinsic::nvvm_tcgen05_st_16x64b_x4:
5460 case Intrinsic::nvvm_tcgen05_st_16x128b_x2:
5461 case Intrinsic::nvvm_tcgen05_st_16x256b_x1:
5462 case Intrinsic::nvvm_tcgen05_st_32x32b_x4:
5463 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x4: {
5464 Info.opc = ISD::INTRINSIC_VOID;
5465 Info.memVT = MVT::v4i32;
5466 Info.ptrVal = I.getArgOperand(0);
5467 Info.offset = 0;
5468 Info.flags = MachineMemOperand::MOStore;
5469 Info.align.reset();
5470 Infos.push_back(Info);
5471 return;
5472 }
5473
5474 case Intrinsic::nvvm_tcgen05_st_16x64b_x8:
5475 case Intrinsic::nvvm_tcgen05_st_16x128b_x4:
5476 case Intrinsic::nvvm_tcgen05_st_16x256b_x2:
5477 case Intrinsic::nvvm_tcgen05_st_32x32b_x8:
5478 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x8: {
5479 Info.opc = ISD::INTRINSIC_VOID;
5480 Info.memVT = MVT::v8i32;
5481 Info.ptrVal = I.getArgOperand(0);
5482 Info.offset = 0;
5483 Info.flags = MachineMemOperand::MOStore;
5484 Info.align.reset();
5485 Infos.push_back(Info);
5486 return;
5487 }
5488
5489 case Intrinsic::nvvm_tcgen05_st_16x64b_x16:
5490 case Intrinsic::nvvm_tcgen05_st_16x128b_x8:
5491 case Intrinsic::nvvm_tcgen05_st_16x256b_x4:
5492 case Intrinsic::nvvm_tcgen05_st_32x32b_x16:
5493 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x16: {
5494 Info.opc = ISD::INTRINSIC_VOID;
5495 Info.memVT = MVT::v16i32;
5496 Info.ptrVal = I.getArgOperand(0);
5497 Info.offset = 0;
5498 Info.flags = MachineMemOperand::MOStore;
5499 Info.align.reset();
5500 Infos.push_back(Info);
5501 return;
5502 }
5503
5504 case Intrinsic::nvvm_tcgen05_st_16x64b_x32:
5505 case Intrinsic::nvvm_tcgen05_st_16x128b_x16:
5506 case Intrinsic::nvvm_tcgen05_st_16x256b_x8:
5507 case Intrinsic::nvvm_tcgen05_st_32x32b_x32:
5508 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x32: {
5509 Info.opc = ISD::INTRINSIC_VOID;
5510 Info.memVT = MVT::v32i32;
5511 Info.ptrVal = I.getArgOperand(0);
5512 Info.offset = 0;
5513 Info.flags = MachineMemOperand::MOStore;
5514 Info.align.reset();
5515 Infos.push_back(Info);
5516 return;
5517 }
5518
5519 case Intrinsic::nvvm_tcgen05_st_16x64b_x64:
5520 case Intrinsic::nvvm_tcgen05_st_16x128b_x32:
5521 case Intrinsic::nvvm_tcgen05_st_16x256b_x16:
5522 case Intrinsic::nvvm_tcgen05_st_32x32b_x64:
5523 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x64: {
5524 Info.opc = ISD::INTRINSIC_VOID;
5525 Info.memVT = MVT::v64i32;
5526 Info.ptrVal = I.getArgOperand(0);
5527 Info.offset = 0;
5528 Info.flags = MachineMemOperand::MOStore;
5529 Info.align.reset();
5530 Infos.push_back(Info);
5531 return;
5532 }
5533
5534 case Intrinsic::nvvm_tcgen05_st_16x64b_x128:
5535 case Intrinsic::nvvm_tcgen05_st_16x128b_x64:
5536 case Intrinsic::nvvm_tcgen05_st_16x256b_x32:
5537 case Intrinsic::nvvm_tcgen05_st_32x32b_x128:
5538 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x128: {
5539 Info.opc = ISD::INTRINSIC_VOID;
5540 Info.memVT = MVT::v128i32;
5541 Info.ptrVal = I.getArgOperand(0);
5542 Info.offset = 0;
5543 Info.flags = MachineMemOperand::MOStore;
5544 Info.align.reset();
5545 Infos.push_back(Info);
5546 return;
5547 }
5548 case Intrinsic::
5549 nvvm_tcgen05_mma_shared_f8f6f4_disable_output_lane_cg1_decompress_b:
5550 case Intrinsic::
5551 nvvm_tcgen05_mma_tensor_f8f6f4_disable_output_lane_cg1_decompress_b:
5552 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg1:
5553 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg1:
5554 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg1:
5555 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg1:
5556 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1:
5557 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1:
5558 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1_ashift:
5559 case Intrinsic::
5560 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1_ashift:
5561 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1:
5562 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1:
5563 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1_ashift:
5564 case Intrinsic::
5565 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1_ashift: {
5566 // We are reading and writing back to TMem
5567 Info.opc = ISD::INTRINSIC_VOID;
5568 Info.memVT = MVT::v4i32;
5569 Info.ptrVal = I.getArgOperand(0);
5570 Info.offset = 0;
5572 Info.align = Align(16);
5573 Infos.push_back(Info);
5574 return;
5575 }
5576
5577 case Intrinsic::
5578 nvvm_tcgen05_mma_shared_f8f6f4_disable_output_lane_cg2_decompress_b:
5579 case Intrinsic::
5580 nvvm_tcgen05_mma_tensor_f8f6f4_disable_output_lane_cg2_decompress_b:
5581 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg2:
5582 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg2:
5583 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg2:
5584 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg2:
5585 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2:
5586 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2:
5587 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2:
5588 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2:
5589 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2_ashift:
5590 case Intrinsic::
5591 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2_ashift:
5592 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2_ashift:
5593 case Intrinsic::
5594 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2_ashift: {
5595 // We are reading and writing back to TMem
5596 Info.opc = ISD::INTRINSIC_VOID;
5597 Info.memVT = MVT::v8i32;
5598 Info.ptrVal = I.getArgOperand(0);
5599 Info.offset = 0;
5601 Info.align = Align(16);
5602 Infos.push_back(Info);
5603 return;
5604 }
5605 case Intrinsic::nvvm_tcgen05_alloc_cg1:
5606 case Intrinsic::nvvm_tcgen05_alloc_cg2:
5607 Info.opc = ISD::INTRINSIC_VOID;
5608 Info.memVT = MVT::i32;
5609 Info.ptrVal = I.getArgOperand(0);
5610 Info.offset = 0;
5611 Info.flags = MachineMemOperand::MOStore;
5612 Info.align = Align(4);
5613 Infos.push_back(Info);
5614 return;
5615 }
5616}
5617
5618// Helper for getting a function parameter symbol. Its name is composed from
5619// the function name and the parameter index. Negative index corresponds to the
5620// special parameter (unsized array) used for passing variable arguments.
5622 int Idx) const {
5623 const StringRef FuncName = getTargetMachine().getSymbol(F)->getName();
5624 if (Idx < 0)
5625 return Ctx.getOrCreateSymbol(FuncName + "_vararg");
5626 return Ctx.getOrCreateSymbol(FuncName + "_param_" + Twine(Idx));
5627}
5628
5629/// isLegalAddressingMode - Return true if the addressing mode represented
5630/// by AM is legal for this target, for a load/store of the specified type.
5631/// Used to guide target specific optimizations, like loop strength reduction
5632/// (LoopStrengthReduce.cpp) and memory optimization for address mode
5633/// (CodeGenPrepare.cpp)
5635 const AddrMode &AM, Type *Ty,
5636 unsigned AS, Instruction *I) const {
5637 // AddrMode - This represents an addressing mode of:
5638 // BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
5639 //
5640 // The legal address modes are
5641 // - [avar]
5642 // - [areg]
5643 // - [areg+immoff]
5644 // - [immAddr]
5645
5646 // immoff must fit in a signed 32-bit int
5647 if (!APInt(64, AM.BaseOffs).isSignedIntN(32))
5648 return false;
5649
5650 if (AM.BaseGV)
5651 return !AM.BaseOffs && !AM.HasBaseReg && !AM.Scale;
5652
5653 switch (AM.Scale) {
5654 case 0: // "r", "r+i" or "i" is allowed
5655 break;
5656 case 1:
5657 if (AM.HasBaseReg) // "r+r+i" or "r+r" is not allowed.
5658 return false;
5659 // Otherwise we have r+i.
5660 break;
5661 default:
5662 // No scale > 1 is allowed
5663 return false;
5664 }
5665 return true;
5666}
5667
5668//===----------------------------------------------------------------------===//
5669// NVPTX Inline Assembly Support
5670//===----------------------------------------------------------------------===//
5671
5672/// getConstraintType - Given a constraint letter, return the type of
5673/// constraint it is for this target.
5676 if (Constraint.size() == 1) {
5677 switch (Constraint[0]) {
5678 default:
5679 break;
5680 case 'b':
5681 case 'r':
5682 case 'h':
5683 case 'c':
5684 case 'l':
5685 case 'f':
5686 case 'd':
5687 case 'q':
5688 case '0':
5689 case 'N':
5690 return C_RegisterClass;
5691 }
5692 }
5693 return TargetLowering::getConstraintType(Constraint);
5694}
5695
5696std::pair<unsigned, const TargetRegisterClass *>
5698 StringRef Constraint,
5699 MVT VT) const {
5700 if (Constraint.size() == 1) {
5701 switch (Constraint[0]) {
5702 case 'b':
5703 return std::make_pair(0U, &NVPTX::B1RegClass);
5704 case 'c':
5705 case 'h':
5706 return std::make_pair(0U, &NVPTX::B16RegClass);
5707 case 'r':
5708 case 'f':
5709 return std::make_pair(0U, &NVPTX::B32RegClass);
5710 case 'l':
5711 case 'N':
5712 case 'd':
5713 return std::make_pair(0U, &NVPTX::B64RegClass);
5714 case 'q': {
5715 if (!STI.hasFeature(NVPTX::SM70))
5716 report_fatal_error("Inline asm with 128 bit operands is only "
5717 "supported for sm_70 and higher!");
5718 return std::make_pair(0U, &NVPTX::B128RegClass);
5719 }
5720 }
5721 }
5722 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5723}
5724
5725//===----------------------------------------------------------------------===//
5726// NVPTX DAG Combining
5727//===----------------------------------------------------------------------===//
5728
5730 CodeGenOptLevel OptLevel) const {
5731 // Always honor command-line argument
5732 if (FMAContractLevelOpt.getNumOccurrences() > 0)
5733 return FMAContractLevelOpt > 0;
5734
5735 // Do not contract if we're not optimizing the code.
5736 if (OptLevel == CodeGenOptLevel::None)
5737 return false;
5738
5739 return false;
5740}
5741
5742static bool isConstZero(const SDValue &Operand) {
5743 const auto *Const = dyn_cast<ConstantSDNode>(Operand);
5744 return Const && Const->getZExtValue() == 0;
5745}
5746
5747/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
5748/// operands N0 and N1. This is a helper for PerformADDCombine that is
5749/// called with the default operands, and if that fails, with commuted
5750/// operands.
5751static SDValue
5754 EVT VT = N0.getValueType();
5755
5756 // Since integer multiply-add costs the same as integer multiply
5757 // but is more costly than integer add, do the fusion only when
5758 // the mul is only used in the add.
5759 // TODO: this may not be true for later architectures, consider relaxing this
5760 if (!N0.getNode()->hasOneUse())
5761 return SDValue();
5762
5763 // fold (add (select cond, 0, (mul a, b)), c)
5764 // -> (select cond, c, (add (mul a, b), c))
5765 //
5766 if (N0.getOpcode() == ISD::SELECT) {
5767 unsigned ZeroOpNum;
5768 if (isConstZero(N0->getOperand(1)))
5769 ZeroOpNum = 1;
5770 else if (isConstZero(N0->getOperand(2)))
5771 ZeroOpNum = 2;
5772 else
5773 return SDValue();
5774
5775 SDValue M = N0->getOperand((ZeroOpNum == 1) ? 2 : 1);
5776 if (M->getOpcode() != ISD::MUL || !M.getNode()->hasOneUse())
5777 return SDValue();
5778
5779 SDLoc DL(N);
5780 SDValue Mul =
5781 DCI.DAG.getNode(ISD::MUL, DL, VT, M->getOperand(0), M->getOperand(1));
5782 SDValue MAD = DCI.DAG.getNode(ISD::ADD, DL, VT, Mul, N1);
5783 return DCI.DAG.getSelect(SDLoc(N), VT, N0->getOperand(0),
5784 ((ZeroOpNum == 1) ? N1 : MAD),
5785 ((ZeroOpNum == 1) ? MAD : N1));
5786 }
5787
5788 return SDValue();
5789}
5790
5791SDValue NVPTXTargetLowering::performFADDCombineWithOperands(
5793 CodeGenOptLevel OptLevel) const {
5794 EVT VT = N0.getValueType();
5795 if (N0.getOpcode() == ISD::FMUL) {
5796 if (!(allowFMA(DCI.DAG.getMachineFunction(), OptLevel) ||
5797 (N->getFlags().hasAllowContract() &&
5798 N0->getFlags().hasAllowContract())))
5799 return SDValue();
5800
5801 // For floating point:
5802 // Do the fusion only when the mul has less than 5 uses and all
5803 // are add.
5804 // The heuristic is that if a use is not an add, then that use
5805 // cannot be fused into fma, therefore mul is still needed anyway.
5806 // If there are more than 4 uses, even if they are all add, fusing
5807 // them will increase register pressue.
5808 //
5809 int numUses = 0;
5810 int nonAddCount = 0;
5811 for (const SDNode *User : N0.getNode()->users()) {
5812 numUses++;
5813 if (User->getOpcode() != ISD::FADD)
5814 ++nonAddCount;
5815 if (numUses >= 5)
5816 return SDValue();
5817 }
5818 if (nonAddCount) {
5819 int orderNo = N->getIROrder();
5820 int orderNo2 = N0.getNode()->getIROrder();
5821 // simple heuristics here for considering potential register
5822 // pressure, the logics here is that the differnce are used
5823 // to measure the distance between def and use, the longer distance
5824 // more likely cause register pressure.
5825 if (orderNo - orderNo2 < 500)
5826 return SDValue();
5827
5828 // Now, check if at least one of the FMUL's operands is live beyond the
5829 // node N, which guarantees that the FMA will not increase register
5830 // pressure at node N.
5831 bool opIsLive = false;
5832 const SDNode *left = N0.getOperand(0).getNode();
5833 const SDNode *right = N0.getOperand(1).getNode();
5834
5835 if (isa<ConstantSDNode>(left) || isa<ConstantSDNode>(right))
5836 opIsLive = true;
5837
5838 if (!opIsLive)
5839 for (const SDNode *User : left->users()) {
5840 int orderNo3 = User->getIROrder();
5841 if (orderNo3 > orderNo) {
5842 opIsLive = true;
5843 break;
5844 }
5845 }
5846
5847 if (!opIsLive)
5848 for (const SDNode *User : right->users()) {
5849 int orderNo3 = User->getIROrder();
5850 if (orderNo3 > orderNo) {
5851 opIsLive = true;
5852 break;
5853 }
5854 }
5855
5856 if (!opIsLive)
5857 return SDValue();
5858 }
5859
5860 return DCI.DAG.getNode(ISD::FMA, SDLoc(N), VT, N0.getOperand(0),
5861 N0.getOperand(1), N1);
5862 }
5863
5864 return SDValue();
5865}
5866
5867/// Fold unpacking movs into a load by increasing the number of return values.
5868///
5869/// ex:
5870/// L: v2f16,ch = load <p>
5871/// a: f16 = extractelt L:0, 0
5872/// b: f16 = extractelt L:0, 1
5873/// use(a, b)
5874///
5875/// ...is turned into...
5876///
5877/// L: f16,f16,ch = LoadV2 <p>
5878/// use(L:0, L:1)
5879static SDValue
5881 // Don't run this optimization before the legalizer
5882 if (!DCI.isAfterLegalizeDAG())
5883 return SDValue();
5884
5885 EVT ElementVT = N->getValueType(0);
5886 // Avoid non-packed types and v4i8
5887 if (!NVPTX::isPackedVectorTy(ElementVT) || ElementVT == MVT::v4i8)
5888 return SDValue();
5889
5890 // Check whether all outputs are either used by an extractelt or are
5891 // glue/chain nodes
5892 if (!all_of(N->uses(), [&](SDUse &U) {
5893 // Skip glue, chain nodes
5894 if (U.getValueType() == MVT::Glue || U.getValueType() == MVT::Other)
5895 return true;
5896 if (U.getUser()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
5897 if (N->getOpcode() != ISD::LOAD)
5898 return true;
5899 // Since this is an ISD::LOAD, check all extractelts are used. If
5900 // any are not used, we don't want to defeat another optimization that
5901 // will narrow the load.
5902 //
5903 // For example:
5904 //
5905 // L: v2f16,ch = load <p>
5906 // e0: f16 = extractelt L:0, 0
5907 // e1: f16 = extractelt L:0, 1 <-- unused
5908 // store e0
5909 //
5910 // Can be optimized by DAGCombiner to:
5911 //
5912 // L: f16,ch = load <p>
5913 // store L:0
5914 return !U.getUser()->use_empty();
5915 }
5916
5917 // Otherwise, this use prevents us from splitting a value.
5918 return false;
5919 }))
5920 return SDValue();
5921
5922 auto *LD = cast<MemSDNode>(N);
5923 SDLoc DL(LD);
5924
5925 // the new opcode after we double the number of operands
5926 unsigned Opcode;
5928 unsigned OldNumOutputs; // non-glue, non-chain outputs
5929 switch (LD->getOpcode()) {
5930 case ISD::LOAD:
5931 OldNumOutputs = 1;
5932 // Any packed type is legal, so the legalizer will not have lowered
5933 // ISD::LOAD -> NVPTXISD::Load (unless it's under-aligned). We have to do it
5934 // here.
5935 Opcode = NVPTXISD::LoadV2;
5936 // append a "full" used bytes mask operand right before the extension type
5937 // operand, signifying that all bytes are used.
5938 Operands.push_back(DCI.DAG.getConstant(UINT32_MAX, DL, MVT::i32));
5939 Operands.push_back(DCI.DAG.getIntPtrConstant(
5940 cast<LoadSDNode>(LD)->getExtensionType(), DL));
5941 break;
5942 case NVPTXISD::LoadV2:
5943 OldNumOutputs = 2;
5944 Opcode = NVPTXISD::LoadV4;
5945 break;
5946 case NVPTXISD::LoadV4:
5947 // V8 is only supported for f32/i32. Don't forget, we're not changing the
5948 // load size here. This is already a 256-bit load.
5949 if (ElementVT != MVT::v2f32 && ElementVT != MVT::v2i32)
5950 return SDValue();
5951 OldNumOutputs = 4;
5952 Opcode = NVPTXISD::LoadV8;
5953 break;
5954 case NVPTXISD::LoadV8:
5955 // PTX doesn't support the next doubling of outputs
5956 return SDValue();
5957 }
5958
5959 // the non-glue, non-chain outputs in the new load
5960 const unsigned NewNumOutputs = OldNumOutputs * 2;
5961 SmallVector<EVT> NewVTs(NewNumOutputs, ElementVT.getVectorElementType());
5962 // add remaining chain and glue values
5963 NewVTs.append(LD->value_begin() + OldNumOutputs, LD->value_end());
5964
5965 // Create the new load
5966 SDValue NewLoad = DCI.DAG.getMemIntrinsicNode(
5967 Opcode, DL, DCI.DAG.getVTList(NewVTs), Operands, LD->getMemoryVT(),
5968 LD->getMemOperand());
5969
5970 // Now we use a combination of BUILD_VECTORs and a MERGE_VALUES node to keep
5971 // the outputs the same. These nodes will be optimized away in later
5972 // DAGCombiner iterations.
5974 for (unsigned I : seq(OldNumOutputs))
5975 Results.push_back(DCI.DAG.getBuildVector(
5976 ElementVT, DL, {NewLoad.getValue(I * 2), NewLoad.getValue(I * 2 + 1)}));
5977 // Add remaining chain and glue nodes
5978 for (unsigned I : seq(NewLoad->getNumValues() - NewNumOutputs))
5979 Results.push_back(NewLoad.getValue(NewNumOutputs + I));
5980
5981 return DCI.DAG.getMergeValues(Results, DL);
5982}
5983
5984/// Fold packing movs into a store.
5985///
5986/// ex:
5987/// v1: v2f16 = BUILD_VECTOR a:f16, b:f16
5988/// v2: v2f16 = BUILD_VECTOR c:f16, d:f16
5989/// StoreV2 v1, v2
5990///
5991/// ...is turned into...
5992///
5993/// StoreV4 a, b, c, d
5996 unsigned Front, unsigned Back) {
5997 // We want to run this as late as possible since other optimizations may
5998 // eliminate the BUILD_VECTORs.
5999 if (!DCI.isAfterLegalizeDAG())
6000 return SDValue();
6001
6002 // Get the type of the operands being stored.
6003 EVT ElementVT = N->getOperand(Front).getValueType();
6004
6005 // Avoid non-packed types and v4i8
6006 if (!NVPTX::isPackedVectorTy(ElementVT) || ElementVT == MVT::v4i8)
6007 return SDValue();
6008
6009 auto *ST = cast<MemSDNode>(N);
6010
6011 // The new opcode after we double the number of operands.
6012 unsigned Opcode;
6013 switch (N->getOpcode()) {
6014 case ISD::STORE:
6015 // Any packed type is legal, so the legalizer will not have lowered
6016 // ISD::STORE -> NVPTXISD::Store (unless it's under-aligned). We have to do
6017 // it here.
6018 Opcode = NVPTXISD::StoreV2;
6019 break;
6020 case NVPTXISD::StoreV2:
6021 Opcode = NVPTXISD::StoreV4;
6022 break;
6023 case NVPTXISD::StoreV4:
6024 // V8 is only supported for f32/i32. Don't forget, we're not changing the
6025 // store size here. This is already a 256-bit store.
6026 if (ElementVT != MVT::v2f32 && ElementVT != MVT::v2i32)
6027 return SDValue();
6028 Opcode = NVPTXISD::StoreV8;
6029 break;
6030 case NVPTXISD::StoreV8:
6031 // PTX doesn't support the next doubling of operands
6032 return SDValue();
6033 default:
6034 llvm_unreachable("Unhandled store opcode");
6035 }
6036
6037 // Scan the operands and if they're all BUILD_VECTORs, we'll have gathered
6038 // their elements.
6039 SmallVector<SDValue, 4> Operands(N->ops().take_front(Front));
6040 for (SDValue BV : N->ops().drop_front(Front).drop_back(Back)) {
6041 if (BV.getOpcode() != ISD::BUILD_VECTOR)
6042 return SDValue();
6043
6044 // If the operand has multiple uses, this optimization can increase register
6045 // pressure.
6046 if (!BV.hasOneUse())
6047 return SDValue();
6048
6049 // DAGCombiner visits nodes bottom-up. Check the BUILD_VECTOR operands for
6050 // any signs they may be folded by some other pattern or rule.
6051 for (SDValue Op : BV->ops()) {
6052 // Peek through bitcasts
6053 if (Op.getOpcode() == ISD::BITCAST)
6054 Op = Op.getOperand(0);
6055
6056 // This may be folded into a PRMT.
6057 if (Op.getValueType() == MVT::i16 && Op.getOpcode() == ISD::TRUNCATE &&
6058 Op->getOperand(0).getValueType() == MVT::i32)
6059 return SDValue();
6060
6061 // This may be folded into cvt.bf16x2
6062 if (Op.getOpcode() == ISD::FP_ROUND)
6063 return SDValue();
6064 }
6065 Operands.append({BV.getOperand(0), BV.getOperand(1)});
6066 }
6067 Operands.append(N->op_end() - Back, N->op_end());
6068
6069 // Now we replace the store
6070 return DCI.DAG.getMemIntrinsicNode(Opcode, SDLoc(N), N->getVTList(), Operands,
6071 ST->getMemoryVT(), ST->getMemOperand());
6072}
6073
6075 const NVPTXSubtarget &STI) {
6076
6077 if (DCI.isBeforeLegalize() && N->getOpcode() == ISD::STORE) {
6078 // Here is our chance to custom lower a store with a non-simple type.
6079 // Unfortunately, we can't do this in the legalizer because there is no
6080 // way to setOperationAction for an non-simple type.
6082 if (!ST->getValue().getValueType().isSimple())
6083 return lowerSTOREVector(SDValue(ST, 0), DCI.DAG, STI);
6084 }
6085
6086 return combinePackingMovIntoStore(N, DCI, 1, 2);
6087}
6088
6090 const NVPTXSubtarget &STI) {
6091 if (DCI.isBeforeLegalize() && N->getOpcode() == ISD::LOAD) {
6092 // Here is our chance to custom lower a load with a non-simple type.
6093 // Unfortunately, we can't do this in the legalizer because there is no
6094 // way to setOperationAction for an non-simple type.
6095 if (!N->getValueType(0).isSimple())
6096 return lowerLoadVector(N, DCI.DAG, STI);
6097 }
6098
6099 return combineUnpackingMovIntoLoad(N, DCI);
6100}
6101
6102/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6103///
6106 CodeGenOptLevel OptLevel) {
6107 if (OptLevel == CodeGenOptLevel::None)
6108 return SDValue();
6109
6110 SDValue N0 = N->getOperand(0);
6111 SDValue N1 = N->getOperand(1);
6112
6113 // Skip non-integer, non-scalar case
6114 EVT VT = N0.getValueType();
6115 if (VT.isVector() || VT != MVT::i32)
6116 return SDValue();
6117
6118 // First try with the default operand order.
6119 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI))
6120 return Result;
6121
6122 // If that didn't work, try again with the operands commuted.
6123 return PerformADDCombineWithOperands(N, N1, N0, DCI);
6124}
6125
6126/// Check if a v2f32 BUILD_VECTOR provably packs values from non-adjacent
6127/// register pairs (non-coalescable).
6128static bool isNonCoalescableBuildVector(const SDValue &BV) {
6129 if (BV.getOpcode() != ISD::BUILD_VECTOR || BV.getValueType() != MVT::v2f32)
6130 return false;
6131
6132 SDValue Elt0 = BV.getOperand(0);
6133 SDValue Elt1 = BV.getOperand(1);
6134
6135 bool IsExt0 = Elt0.getOpcode() == ISD::EXTRACT_VECTOR_ELT;
6136 bool IsExt1 = Elt1.getOpcode() == ISD::EXTRACT_VECTOR_ELT;
6137
6138 // If neither element is an EXTRACT_VECTOR_ELT they are free-standing
6139 // scalars and the register allocator can still place them side-by-side.
6140 if (!IsExt0 && !IsExt1)
6141 return false;
6142
6143 // If exactly one element is an EXTRACT_VECTOR_ELT, the other is a scalar
6144 // that cannot generally occupy the adjacent register slot.
6145 if (IsExt0 != IsExt1)
6146 return true;
6147
6148 // At this point both sources are extracting from vectors. If they are from
6149 // different vectors, then the BUILD_VECTOR is non-coalescable.
6150 SDValue Src0 = Elt0.getOperand(0);
6151 SDValue Src1 = Elt1.getOperand(0);
6152 if (Src0 != Src1)
6153 return true;
6154
6155 auto *Idx0 = dyn_cast<ConstantSDNode>(Elt0.getOperand(1));
6156 auto *Idx1 = dyn_cast<ConstantSDNode>(Elt1.getOperand(1));
6157 // If both indices are dynamic they will be lowered to
6158 // loads and the vector will be spilled to local memory. The register
6159 // allocator can easily place the results in adjacent registers.
6160 if (!Idx0 && !Idx1)
6161 return false;
6162
6163 // If one index is dynamic and the other is constant, the value from the
6164 // constant load will result in an additional register to pair with the result
6165 // from the dynamic load. We consider this non-coalescable.
6166 if ((Idx0 && !Idx1) || (!Idx0 && Idx1))
6167 return true;
6168
6169 // Both are constant, adjacent pairs are coalescable
6170 return std::abs(Idx0->getSExtValue() - Idx1->getSExtValue()) != 1;
6171}
6172
6173/// Return true if FMUL v2f32 node \p N may be scalarized to fold each lane's
6174/// product into a scalar FMA.
6175bool NVPTXTargetLowering::mayFoldFMULIntoFMA(SDNode *N, MachineFunction &MF,
6176 CodeGenOptLevel OptLevel) const {
6177 if (N->getOpcode() != ISD::FMUL || N->getValueType(0) != MVT::v2f32)
6178 return false;
6179 const bool GlobalFMA = allowFMA(MF, OptLevel);
6180 if (!N->getFlags().hasAllowContract() && !GlobalFMA)
6181 return false;
6182
6183 const SDNode *FirstFAdd = nullptr;
6184 unsigned NumScalarFAdd = 0;
6185
6186 // Both lanes must feed unique FADDs
6187 for (SDNode *EE : N->users()) {
6188 if (NumScalarFAdd == 2)
6189 return false;
6190
6191 if (EE->getOpcode() != ISD::EXTRACT_VECTOR_ELT || !EE->hasOneUse() ||
6192 !isa<ConstantSDNode>(EE->getOperand(1)))
6193 return false;
6194
6195 const SDNode *const FAdd = *EE->users().begin();
6196 if (FAdd->getOpcode() != ISD::FADD ||
6197 (!GlobalFMA && !FAdd->getFlags().hasAllowContract()))
6198 return false;
6199
6200 if (!FirstFAdd)
6201 FirstFAdd = FAdd;
6202 else if (FAdd == FirstFAdd)
6203 return false;
6204
6205 NumScalarFAdd++;
6206 }
6207
6208 return NumScalarFAdd == 2;
6209}
6210
6211/// Scalarize a v2f32 arithmetic node (FADD, FMUL, FSUB, FMA) when at least
6212/// one operand is a BUILD_VECTOR that repacks values from non-adjacent register
6213/// pairs. Without this combine the BUILD_VECTOR forces allocation of a
6214/// temporary 64-bit register, increasing register pressure.
6215///
6216/// Example - before:
6217/// t0: v2f32,v2f32,ch = LoadV2 ...
6218/// t1: f32 = extract_vector_elt t0, 0
6219/// t2: f32 = extract_vector_elt t0:1, 0
6220/// t3: v2f32 = BUILD_VECTOR t1, t2 ;; non-coalescable repack
6221/// t4: v2f32 = fma t_a, t3, t_c
6222///
6223/// After:
6224/// t0: v2f32,v2f32,ch = LoadV2 ...
6225/// t1: f32 = extract_vector_elt t0, 0
6226/// t2: f32 = extract_vector_elt t0:1, 0
6227/// a0: f32 = extract_vector_elt t_a, 0
6228/// a1: f32 = extract_vector_elt t_a, 1
6229/// c0: f32 = extract_vector_elt t_c, 0
6230/// c1: f32 = extract_vector_elt t_c, 1
6231/// r0: f32 = fma a0, t1, c0
6232/// r1: f32 = fma a1, t2, c1
6233/// t4: v2f32 = BUILD_VECTOR r0, r1
6234///
6235/// Also scalarizes an FMUL when all output lanes feed into scalar FADDs
6236/// to enable scalar FMA combining.
6237SDValue NVPTXTargetLowering::performScalarizeV2F32Op(
6239 CodeGenOptLevel OptLevel) const {
6240 EVT VT = N->getValueType(0);
6241 if (VT != MVT::v2f32)
6242 return SDValue();
6243
6244 if (none_of(N->ops(), isNonCoalescableBuildVector) &&
6245 !mayFoldFMULIntoFMA(N, DCI.DAG.getMachineFunction(), OptLevel))
6246 return SDValue();
6247
6248 SelectionDAG &DAG = DCI.DAG;
6249 SDLoc DL(N);
6250 EVT EltVT = VT.getVectorElementType();
6251 unsigned Opc = N->getOpcode();
6252
6253 // For each operand, get the scalar element at the given index: if the operand
6254 // is a BUILD_VECTOR, grab the element directly; otherwise, emit an
6255 // EXTRACT_VECTOR_ELT.
6256 auto GetElement = [&](SDValue Op, unsigned Index) -> SDValue {
6257 if (Op.getOpcode() == ISD::BUILD_VECTOR)
6258 return Op.getOperand(Index);
6259 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Op,
6260 DAG.getVectorIdxConstant(Index, DL));
6261 };
6262
6263 // Build scalar operand lists for element 0 and element 1.
6264 SmallVector<SDValue, 3> Ops0, Ops1;
6265 for (const SDValue &Op : N->ops()) {
6266 Ops0.push_back(GetElement(Op, 0));
6267 Ops1.push_back(GetElement(Op, 1));
6268 }
6269
6270 SDValue Res0 = DAG.getNode(Opc, DL, EltVT, Ops0, N->getFlags());
6271 SDValue Res1 = DAG.getNode(Opc, DL, EltVT, Ops1, N->getFlags());
6272
6273 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Res0, Res1);
6274}
6275
6276/// Target-specific dag combine xforms for ISD::FADD.
6277SDValue
6278NVPTXTargetLowering::performFADDCombine(SDNode *N,
6280 CodeGenOptLevel OptLevel) const {
6281 if (SDValue Result = performScalarizeV2F32Op(N, DCI, OptLevel))
6282 return Result;
6283
6284 SDValue N0 = N->getOperand(0);
6285 SDValue N1 = N->getOperand(1);
6286
6287 EVT VT = N0.getValueType();
6288 if (VT.isVector() || !(VT == MVT::f32 || VT == MVT::f64))
6289 return SDValue();
6290
6291 // First try with the default operand order.
6292 if (SDValue Result = performFADDCombineWithOperands(N, N0, N1, DCI, OptLevel))
6293 return Result;
6294
6295 // If that didn't work, try again with the operands commuted.
6296 return performFADDCombineWithOperands(N, N1, N0, DCI, OptLevel);
6297}
6298
6299/// Get 3-input version of a 2-input min/max opcode
6300static unsigned getMinMax3Opcode(unsigned MinMax2Opcode) {
6301 switch (MinMax2Opcode) {
6302 case ISD::FMAXNUM:
6303 case ISD::FMAXIMUMNUM:
6304 return NVPTXISD::FMAXNUM3;
6305 case ISD::FMINNUM:
6306 case ISD::FMINIMUMNUM:
6307 return NVPTXISD::FMINNUM3;
6308 case ISD::FMAXIMUM:
6309 return NVPTXISD::FMAXIMUM3;
6310 case ISD::FMINIMUM:
6311 return NVPTXISD::FMINIMUM3;
6312 default:
6313 llvm_unreachable("Invalid 2-input min/max opcode");
6314 }
6315}
6316
6317/// PerformFMinMaxCombine - Combine (fmaxnum (fmaxnum a, b), c) into
6318/// (fmaxnum3 a, b, c). Also covers other llvm min/max intrinsics.
6321 const NVPTXSubtarget &STI) {
6322
6323 // 3-input min/max requires PTX 8.8+ and SM_100+, and only supports f32s
6324 EVT VT = N->getValueType(0);
6325 if (VT != MVT::f32 || !STI.hasFeature(NVPTX::PTX88) ||
6326 !STI.hasFeature(NVPTX::SM100))
6327 return SDValue();
6328
6329 SDValue Op0 = N->getOperand(0);
6330 SDValue Op1 = N->getOperand(1);
6331 unsigned MinMaxOp2 = N->getOpcode();
6332 unsigned MinMaxOp3 = getMinMax3Opcode(MinMaxOp2);
6333
6334 if (Op0.getOpcode() == MinMaxOp2 && Op0.hasOneUse()) {
6335 // (maxnum (maxnum a, b), c) -> (maxnum3 a, b, c)
6336 SDValue A = Op0.getOperand(0);
6337 SDValue B = Op0.getOperand(1);
6338 SDValue C = Op1;
6339 return DCI.DAG.getNode(MinMaxOp3, SDLoc(N), VT, A, B, C, N->getFlags());
6340 } else if (Op1.getOpcode() == MinMaxOp2 && Op1.hasOneUse()) {
6341 // (maxnum a, (maxnum b, c)) -> (maxnum3 a, b, c)
6342 SDValue A = Op0;
6343 SDValue B = Op1.getOperand(0);
6344 SDValue C = Op1.getOperand(1);
6345 return DCI.DAG.getNode(MinMaxOp3, SDLoc(N), VT, A, B, C, N->getFlags());
6346 }
6347 return SDValue();
6348}
6349
6352 CodeGenOptLevel OptLevel) {
6353 assert(N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM);
6354
6355 // Don't do anything at less than -O2.
6356 if (OptLevel < CodeGenOptLevel::Default)
6357 return SDValue();
6358
6359 SelectionDAG &DAG = DCI.DAG;
6360 SDLoc DL(N);
6361 EVT VT = N->getValueType(0);
6362 bool IsSigned = N->getOpcode() == ISD::SREM;
6363 unsigned DivOpc = IsSigned ? ISD::SDIV : ISD::UDIV;
6364
6365 const SDValue &Num = N->getOperand(0);
6366 const SDValue &Den = N->getOperand(1);
6367
6368 for (const SDNode *U : Num->users()) {
6369 if (U->getOpcode() == DivOpc && U->getOperand(0) == Num &&
6370 U->getOperand(1) == Den) {
6371 // Num % Den -> Num - (Num / Den) * Den
6372 return DAG.getNode(ISD::SUB, DL, VT, Num,
6373 DAG.getNode(ISD::MUL, DL, VT,
6374 DAG.getNode(DivOpc, DL, VT, Num, Den),
6375 Den));
6376 }
6377 }
6378 return SDValue();
6379}
6380
6381// sext (mul.iN nsw x, y) => mul.wide.sN x, y
6382// zext (mul.iN nuw x, y) => mul.wide.uN x, y
6383// sext (shl.iN nsw x, const) => mul.wide.sN x, (1 << const)
6384// zext (shl.iN nuw x, const) => mul.wide.uN x, (1 << const)
6387 CodeGenOptLevel OptLevel) {
6388 assert(N->getOpcode() == ISD::SIGN_EXTEND ||
6389 N->getOpcode() == ISD::ZERO_EXTEND);
6390
6391 if (OptLevel == CodeGenOptLevel::None)
6392 return SDValue();
6393
6394 SDValue Op = N->getOperand(0);
6395 if (!Op.hasOneUse())
6396 return SDValue();
6397
6398 EVT ToVT = N->getValueType(0);
6399 EVT FromVT = Op.getValueType();
6400 if (!((ToVT == MVT::i32 && FromVT == MVT::i16) ||
6401 (ToVT == MVT::i64 && FromVT == MVT::i32)))
6402 return SDValue();
6403
6404 bool IsSigned = N->getOpcode() == ISD::SIGN_EXTEND;
6405 if ((IsSigned && !Op->getFlags().hasNoSignedWrap()) ||
6406 (!IsSigned && !Op->getFlags().hasNoUnsignedWrap()))
6407 return SDValue();
6408
6409 SDLoc DL(N);
6410 SDValue LHS = Op.getOperand(0);
6411 SDValue RHS = Op.getOperand(1);
6412 unsigned MulWideOpcode =
6413 IsSigned ? NVPTXISD::MUL_WIDE_SIGNED : NVPTXISD::MUL_WIDE_UNSIGNED;
6414 if (Op.getOpcode() == ISD::MUL) {
6415 return DCI.DAG.getNode(MulWideOpcode, DL, ToVT, LHS, RHS);
6416 } else if (Op.getOpcode() == ISD::SHL && isa<ConstantSDNode>(RHS)) {
6417 const auto ShiftAmt = Op.getConstantOperandVal(1);
6418 const auto MulVal = APInt(FromVT.getSizeInBits(), 1) << ShiftAmt;
6419
6420 // Note that the sext (shl nsw ...) case doesn't work if 1 << const
6421 // overflows to a negative value! The only valid input values in this
6422 // case are 0 and -1 (all other values yield poison because of the nsw),
6423 // and mul.wide.sN would give us the wrong sign for -1. We could use
6424 // mul.wide.uN, but since this is a weird case anyway, we might as well not
6425 // apply this transformation at all.
6426 if (IsSigned && MulVal.isNegative())
6427 return SDValue();
6428
6429 RHS = DCI.DAG.getConstant(MulVal, DL, FromVT);
6430 return DCI.DAG.getNode(MulWideOpcode, DL, ToVT, LHS, RHS);
6431 }
6432
6433 return SDValue();
6434}
6435
6441
6442/// IsMulWideOperandDemotable - Checks if the provided DAG node is an operand
6443/// that can be demoted to \p OptSize bits without loss of information. The
6444/// signedness of the operand, if determinable, is placed in \p S.
6446 unsigned OptSize,
6447 OperandSignedness &S) {
6448 S = Unknown;
6449
6450 if (Op.getOpcode() == ISD::SIGN_EXTEND ||
6451 Op.getOpcode() == ISD::SIGN_EXTEND_INREG) {
6452 EVT OrigVT = Op.getOperand(0).getValueType();
6453 if (OrigVT.getFixedSizeInBits() <= OptSize) {
6454 S = Signed;
6455 return true;
6456 }
6457 } else if (Op.getOpcode() == ISD::ZERO_EXTEND) {
6458 EVT OrigVT = Op.getOperand(0).getValueType();
6459 if (OrigVT.getFixedSizeInBits() <= OptSize) {
6460 S = Unsigned;
6461 return true;
6462 }
6463 }
6464
6465 return false;
6466}
6467
6468/// AreMulWideOperandsDemotable - Checks if the given LHS and RHS operands can
6469/// be demoted to \p OptSize bits without loss of information. If the operands
6470/// contain a constant, it should appear as the RHS operand. The signedness of
6471/// the operands is placed in \p IsSigned.
6473 unsigned OptSize,
6474 bool &IsSigned) {
6475 OperandSignedness LHSSign;
6476
6477 // The LHS operand must be a demotable op
6478 if (!IsMulWideOperandDemotable(LHS, OptSize, LHSSign))
6479 return false;
6480
6481 // We should have been able to determine the signedness from the LHS
6482 if (LHSSign == Unknown)
6483 return false;
6484
6485 IsSigned = (LHSSign == Signed);
6486
6487 // The RHS can be a demotable op or a constant
6489 const APInt &Val = CI->getAPIntValue();
6490 if (LHSSign == Unsigned) {
6491 return Val.isIntN(OptSize);
6492 } else {
6493 return Val.isSignedIntN(OptSize);
6494 }
6495 } else {
6496 OperandSignedness RHSSign;
6497 if (!IsMulWideOperandDemotable(RHS, OptSize, RHSSign))
6498 return false;
6499
6500 return LHSSign == RHSSign;
6501 }
6502}
6503
6504/// TryMULWIDECombine - Attempt to replace a multiply of M bits with a multiply
6505/// of M/2 bits that produces an M-bit result (i.e. mul.wide). This transform
6506/// works on both multiply DAG nodes and SHL DAG nodes with a constant shift
6507/// amount.
6510 EVT MulType = N->getValueType(0);
6511 if (MulType != MVT::i32 && MulType != MVT::i64) {
6512 return SDValue();
6513 }
6514
6515 SDLoc DL(N);
6516 unsigned OptSize = MulType.getSizeInBits() >> 1;
6517 SDValue LHS = N->getOperand(0);
6518 SDValue RHS = N->getOperand(1);
6519
6520 // Canonicalize the multiply so the constant (if any) is on the right
6521 if (N->getOpcode() == ISD::MUL) {
6522 if (isa<ConstantSDNode>(LHS)) {
6523 std::swap(LHS, RHS);
6524 }
6525 }
6526
6527 // If we have a SHL, determine the actual multiply amount
6528 if (N->getOpcode() == ISD::SHL) {
6530 if (!ShlRHS) {
6531 return SDValue();
6532 }
6533
6534 APInt ShiftAmt = ShlRHS->getAPIntValue();
6535 unsigned BitWidth = MulType.getSizeInBits();
6536 if (ShiftAmt.sge(0) && ShiftAmt.slt(BitWidth)) {
6537 APInt MulVal = APInt(BitWidth, 1) << ShiftAmt;
6538 RHS = DCI.DAG.getConstant(MulVal, DL, MulType);
6539 } else {
6540 return SDValue();
6541 }
6542 }
6543
6544 bool Signed;
6545 // Verify that our operands are demotable
6546 if (!AreMulWideOperandsDemotable(LHS, RHS, OptSize, Signed)) {
6547 return SDValue();
6548 }
6549
6550 EVT DemotedVT;
6551 if (MulType == MVT::i32) {
6552 DemotedVT = MVT::i16;
6553 } else {
6554 DemotedVT = MVT::i32;
6555 }
6556
6557 // Truncate the operands to the correct size. Note that these are just for
6558 // type consistency and will (likely) be eliminated in later phases.
6559 SDValue TruncLHS =
6560 DCI.DAG.getNode(ISD::TRUNCATE, DL, DemotedVT, LHS);
6561 SDValue TruncRHS =
6562 DCI.DAG.getNode(ISD::TRUNCATE, DL, DemotedVT, RHS);
6563
6564 unsigned Opc;
6565 if (Signed) {
6566 Opc = NVPTXISD::MUL_WIDE_SIGNED;
6567 } else {
6568 Opc = NVPTXISD::MUL_WIDE_UNSIGNED;
6569 }
6570
6571 return DCI.DAG.getNode(Opc, DL, MulType, TruncLHS, TruncRHS);
6572}
6573
6574static bool isConstOne(const SDValue &Operand) {
6575 const auto *Const = dyn_cast<ConstantSDNode>(Operand);
6576 return Const && Const->getZExtValue() == 1;
6577}
6578
6580 if (Add->getOpcode() != ISD::ADD)
6581 return SDValue();
6582
6583 if (isConstOne(Add->getOperand(0)))
6584 return Add->getOperand(1);
6585
6586 if (isConstOne(Add->getOperand(1)))
6587 return Add->getOperand(0);
6588
6589 return SDValue();
6590}
6591
6594
6596 SDValue Mul = DCI.DAG.getNode(ISD::MUL, DL, VT, X, Y);
6597 return DCI.DAG.getNode(ISD::ADD, DL, VT, Mul, X);
6598 }
6599
6600 return SDValue();
6601}
6602
6604 SDLoc DL,
6606 if (Select->getOpcode() != ISD::SELECT)
6607 return SDValue();
6608
6609 SDValue Cond = Select->getOperand(0);
6610
6611 unsigned ConstOpNo;
6612 if (isConstOne(Select->getOperand(1)))
6613 ConstOpNo = 1;
6614 else if (isConstOne(Select->getOperand(2)))
6615 ConstOpNo = 2;
6616 else
6617 return SDValue();
6618
6619 SDValue Y = Select->getOperand((ConstOpNo == 1) ? 2 : 1);
6620
6621 // Do not combine if the resulting sequence is not obviously profitable.
6623 return SDValue();
6624
6625 SDValue NewMul = DCI.DAG.getNode(ISD::MUL, DL, VT, X, Y);
6626
6627 return DCI.DAG.getNode(ISD::SELECT, DL, VT, Cond,
6628 (ConstOpNo == 1) ? X : NewMul,
6629 (ConstOpNo == 1) ? NewMul : X);
6630}
6631
6632static SDValue
6635
6636 EVT VT = N0.getValueType();
6637 if (VT.isVector())
6638 return SDValue();
6639
6640 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
6641 return SDValue();
6642
6643 SDLoc DL(N);
6644
6645 // (mul x, (add y, 1)) -> (add (mul x, y), x)
6646 if (SDValue Res = combineMADConstOne(N0, N1, VT, DL, DCI))
6647 return Res;
6648 if (SDValue Res = combineMADConstOne(N1, N0, VT, DL, DCI))
6649 return Res;
6650
6651 // (mul x, (select y, 1)) -> (select (mul x, y), x)
6652 if (SDValue Res = combineMulSelectConstOne(N0, N1, VT, DL, DCI))
6653 return Res;
6654 if (SDValue Res = combineMulSelectConstOne(N1, N0, VT, DL, DCI))
6655 return Res;
6656
6657 return SDValue();
6658}
6659
6660/// PerformMULCombine - Runs PTX-specific DAG combine patterns on MUL nodes.
6663 CodeGenOptLevel OptLevel) {
6664 if (OptLevel == CodeGenOptLevel::None)
6665 return SDValue();
6666
6667 if (SDValue Ret = TryMULWIDECombine(N, DCI))
6668 return Ret;
6669
6670 SDValue N0 = N->getOperand(0);
6671 SDValue N1 = N->getOperand(1);
6672 return PerformMULCombineWithOperands(N, N0, N1, DCI);
6673}
6674
6675/// Commute SHL with a bitwise logic operation when doing so exposes a common
6676/// shifted operand. For example:
6677///
6678/// Before:
6679/// N = shl (zext (LogicOp X, C)), ShiftAmount
6680/// OtherShift = shl (zext (OtherLogicOp X, OtherC)), ShiftAmount
6681///
6682/// After:
6683/// ShiftedX = shl (zext X), ShiftAmount
6684/// N = LogicOp ShiftedX, ShiftedC
6685/// OtherShift = OtherLogicOp ShiftedX, ShiftedOtherC
6686///
6687/// ShiftedC = (zext C) << ShiftAmount and ShiftedOtherC =
6688/// (zext OtherC) << ShiftAmount are folded constants. This replaces two
6689/// variable shifts with the single shared ShiftedX. Requiring another matching
6690/// shift avoids disrupting isolated address calculations where a shift may be
6691/// folded into the addressing mode.
6694 using namespace SDPatternMatch;
6695
6696 struct ShiftOfLogicOp {
6697 SDNode *Shift;
6698 SDValue LogicOp;
6699 SDValue X;
6701 unsigned ExtendOpcode;
6702 };
6703
6704 // Match a logic operation, with an optional extension, inside a SHL.
6705 auto matchShiftOfLogicOp =
6706 [&](SDNode *Shift) -> std::optional<ShiftOfLogicOp> {
6707 if (Shift->getOpcode() != ISD::SHL || !Shift->getOperand(0).hasOneUse())
6708 return std::nullopt;
6709 ShiftOfLogicOp Match;
6710 Match.Shift = Shift;
6711 Match.LogicOp = Shift->getOperand(0);
6712 Match.ExtendOpcode = 0;
6713 if (ISD::isExtOpcode(Match.LogicOp.getOpcode())) {
6714 Match.ExtendOpcode = Match.LogicOp.getOpcode();
6715 Match.LogicOp = Match.LogicOp.getOperand(0);
6716 }
6717
6718 if (!sd_match(Match.LogicOp, m_OneUse(m_BitwiseLogic(
6719 m_Value(Match.X),
6720 m_Value(Match.Constant, m_ConstInt())))))
6721 return std::nullopt;
6722
6723 return Match;
6724 };
6725
6726 // Match N as the root shift-of-logic; bail if it does not fit the pattern.
6727 const std::optional<ShiftOfLogicOp> Root = matchShiftOfLogicOp(N);
6728 if (!Root)
6729 return SDValue();
6730
6731 // Only profitable for a constant shift amount: the per-op constant shift then
6732 // folds away instead of becoming an extra variable shift.
6733 if (!isConstOrConstSplat(N->getOperand(1)))
6734 return SDValue();
6735
6736 // Collect candidate shifts that share X. Reached through another user of X,
6737 // the logic result feeds the shift directly or through an optional extend.
6738 SmallVector<SDNode *, 4> CandidateShifts;
6739 for (const SDNode *CandidateLogicOp : Root->X->users()) {
6740 if (CandidateLogicOp == Root->LogicOp.getNode())
6741 continue;
6742 for (SDNode *LogicUser : CandidateLogicOp->users()) {
6743 if (ISD::isExtOpcode(LogicUser->getOpcode())) {
6744 // shl (ext (logic X, C)): step through the extend to find the shift.
6745 for (SDNode *ExtendUser : LogicUser->users())
6746 if (ExtendUser->getOpcode() == ISD::SHL)
6747 CandidateShifts.push_back(ExtendUser);
6748 } else if (LogicUser->getOpcode() == ISD::SHL) {
6749 // shl (logic X, C): the user is already the shift.
6750 CandidateShifts.push_back(LogicUser);
6751 }
6752 }
6753 }
6754
6755 // Verify each candidate against the root's pattern: the same X, extension,
6756 // type, and shift amount.
6757 const EVT VT = N->getValueType(0);
6758 const SDValue ShiftAmount = N->getOperand(1);
6760 for (SDNode *CandidateShift : CandidateShifts) {
6761 const std::optional<ShiftOfLogicOp> Candidate =
6762 matchShiftOfLogicOp(CandidateShift);
6763 if (Candidate && Candidate->X == Root->X &&
6764 Candidate->ExtendOpcode == Root->ExtendOpcode &&
6765 CandidateShift->getValueType(0) == VT &&
6766 CandidateShift->getOperand(1) == ShiftAmount)
6767 Matches.push_back(*Candidate);
6768 }
6769 if (Matches.empty())
6770 return SDValue();
6771
6772 // Build the shared shifted X once, then rewrite the root and every match
6773 // into a logic op over it so the shift is CSE'd.
6774 SelectionDAG &DAG = DCI.DAG;
6775 const SDValue ShiftedX =
6776 DAG.getNode(ISD::SHL, SDLoc(N), VT,
6777 Root->ExtendOpcode
6778 ? DAG.getNode(Root->ExtendOpcode, SDLoc(N), VT, Root->X)
6779 : Root->X,
6780 ShiftAmount);
6781
6782 // Rebuild the logic op from shared ShiftedX and a folded constant shift.
6783 auto buildCommutedLogicOp = [&](const SDValue LogicOp, SDValue C,
6784 const SDLoc &DL) {
6785 if (Root->ExtendOpcode)
6786 C = DAG.getNode(Root->ExtendOpcode, DL, VT, C);
6787 const SDValue ShiftedC = DAG.getNode(ISD::SHL, DL, VT, C, ShiftAmount);
6788 return DAG.getNode(LogicOp.getOpcode(), DL, VT, ShiftedX, ShiftedC,
6789 LogicOp->getFlags());
6790 };
6791
6792 for (const ShiftOfLogicOp &Match : Matches)
6793 DCI.CombineTo(Match.Shift,
6794 buildCommutedLogicOp(Match.LogicOp, Match.Constant,
6795 SDLoc(Match.Shift)));
6796 return buildCommutedLogicOp(Root->LogicOp, Root->Constant, SDLoc(N));
6797}
6798
6799/// PerformSHLCombine - Runs PTX-specific DAG combine patterns on SHL nodes.
6802 CodeGenOptLevel OptLevel) {
6803 if (OptLevel > CodeGenOptLevel::None) {
6804 // Expose a shared shifted operand for CSE before mul.wide folding, which
6805 // would otherwise consume the shift.
6806 if (SDValue Ret = combineShiftOfLogicOp(N, DCI))
6807 return Ret;
6808
6809 // Try mul.wide combining at OptLevel > 0
6810 if (SDValue Ret = TryMULWIDECombine(N, DCI))
6811 return Ret;
6812 }
6813
6814 return SDValue();
6815}
6816
6819 const NVPTXSubtarget &STI) {
6820 EVT CCType = N->getValueType(0);
6821 SDValue A = N->getOperand(0);
6822 SDValue B = N->getOperand(1);
6823
6824 EVT AType = A.getValueType();
6825 if (!(CCType == MVT::v2i1 && (AType == MVT::v2f16 || AType == MVT::v2bf16)))
6826 return SDValue();
6827
6828 if (A.getValueType() == MVT::v2bf16 && !STI.hasFeature(NVPTX::SM90))
6829 return SDValue();
6830
6831 SDLoc DL(N);
6832 // setp.f16x2 returns two scalar predicates, which we need to
6833 // convert back to v2i1. The returned result will be scalarized by
6834 // the legalizer, but the comparison will remain a single vector
6835 // instruction.
6836 SDValue CCNode = DCI.DAG.getNode(
6837 A.getValueType() == MVT::v2f16 ? NVPTXISD::SETP_F16X2
6839 DL, DCI.DAG.getVTList(MVT::i1, MVT::i1), {A, B, N->getOperand(2)});
6840 return DCI.DAG.getNode(ISD::BUILD_VECTOR, DL, CCType, CCNode.getValue(0),
6841 CCNode.getValue(1));
6842}
6843
6846 SDValue Vector = peekThroughFreeze(N->getOperand(0));
6847 SDLoc DL(N);
6848 EVT VectorVT = Vector.getValueType();
6849 if (Vector->getOpcode() == ISD::LOAD && VectorVT.isSimple() &&
6850 IsPTXVectorType(VectorVT.getSimpleVT()))
6851 return SDValue(); // Native vector loads already combine nicely w/
6852 // extract_vector_elt.
6853 // Don't mess with singletons or packed types (v2*32, v2*16, v4i8 and v8i8),
6854 // we already handle them OK.
6855 if (VectorVT.getVectorNumElements() == 1 ||
6856 NVPTX::isPackedVectorTy(VectorVT) || VectorVT == MVT::v8i8)
6857 return SDValue();
6858
6859 // Don't mess with undef values as sra may be simplified to 0, not undef.
6860 if (Vector->isUndef() || ISD::allOperandsUndef(Vector.getNode()))
6861 return SDValue();
6862
6863 uint64_t VectorBits = VectorVT.getSizeInBits();
6864 // We only handle the types we can extract in-register.
6865 if (!(VectorBits == 16 || VectorBits == 32 || VectorBits == 64))
6866 return SDValue();
6867
6868 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(N->getOperand(1));
6869 // Index == 0 is handled by generic DAG combiner.
6870 if (!Index || Index->getZExtValue() == 0)
6871 return SDValue();
6872
6873 MVT IVT = MVT::getIntegerVT(VectorBits);
6874 EVT EltVT = VectorVT.getVectorElementType();
6875 EVT EltIVT = EltVT.changeTypeToInteger();
6876 uint64_t EltBits = EltVT.getScalarSizeInBits();
6877
6878 SDValue Result = DCI.DAG.getNode(
6879 ISD::TRUNCATE, DL, EltIVT,
6880 DCI.DAG.getNode(
6881 ISD::SRA, DL, IVT, DCI.DAG.getNode(ISD::BITCAST, DL, IVT, Vector),
6882 DCI.DAG.getConstant(Index->getZExtValue() * EltBits, DL, IVT)));
6883
6884 // If element has non-integer type, bitcast it back to the expected type.
6885 if (EltVT != EltIVT)
6886 Result = DCI.DAG.getNode(ISD::BITCAST, DL, EltVT, Result);
6887 // Past legalizer, we may need to extent i8 -> i16 to match the register type.
6888 if (EltVT != N->getValueType(0))
6889 Result = DCI.DAG.getNode(ISD::ANY_EXTEND, DL, N->getValueType(0), Result);
6890
6891 return Result;
6892}
6893
6894/// Transform patterns like:
6895/// (select (ugt shift_amt, BitWidth-1), 0, (srl/shl x, shift_amt))
6896/// (select (ult shift_amt, BitWidth), (srl/shl x, shift_amt), 0)
6897/// Into:
6898/// (NVPTXISD::SRL_CLAMP x, shift_amt) or (NVPTXISD::SHL_CLAMP x, shift_amt)
6899///
6900/// These patterns arise from code like `s >= 32 ? 0 : x >> s`. In LLVM,
6901/// over-shifting a value results in poison, but PTX shr/shl instructions clamp
6902/// the shift amount to BitWidth, making the guard redundant.
6903///
6904/// Note: We only handle SRL and SHL, not SRA, because arithmetic right shifts
6905/// can produce 0 or -1 when shift >= BitWidth.
6906/// Note: We don't handle uge or ule. These don't appear because of
6907/// canonicalization.
6910 if (!DCI.isAfterLegalizeDAG())
6911 return SDValue();
6912
6913 using namespace SDPatternMatch;
6914 unsigned BitWidth = N->getValueType(0).getSizeInBits();
6915 SDValue ShiftAmt, ShiftOp;
6916
6917 // Match logical shifts where the shift amount in the guard matches the shift
6918 // amount in the operation.
6919 auto LogicalShift =
6920 m_AllOf(m_Value(ShiftOp),
6921 m_AnyOf(m_Srl(m_Value(), m_TruncOrSelf(m_Deferred(ShiftAmt))),
6922 m_Shl(m_Value(), m_TruncOrSelf(m_Deferred(ShiftAmt)))));
6923
6924 // shift_amt > BitWidth-1 ? 0 : shift_op
6925 bool MatchedUGT =
6926 sd_match(N, m_Select(m_SetCC(m_Value(ShiftAmt),
6928 m_SpecificCondCode(ISD::SETUGT)),
6929 m_Zero(), LogicalShift));
6930 // shift_amt < BitWidth ? shift_op : 0
6931 bool MatchedULT =
6932 !MatchedUGT &&
6933 sd_match(N, m_Select(m_SetCC(m_Value(ShiftAmt),
6935 m_SpecificCondCode(ISD::SETULT)),
6936 LogicalShift, m_Zero()));
6937
6938 if (!MatchedUGT && !MatchedULT)
6939 return SDValue();
6940
6941 // In LLVM IR, the shift amount and the value-to-be-shifted are the same
6942 // type, whereas in PTX the shift amount is always i32. Therefore when
6943 // shifting types larger than i32, we can only do this transformation if we
6944 // know that the upper bits of the shift amount are known zero.
6945 SDValue ClampAmt = ShiftOp.getOperand(1);
6946 unsigned ClampAmtBits = ClampAmt.getValueSizeInBits();
6947 if (ShiftAmt.getValueSizeInBits() > ClampAmtBits &&
6948 DCI.DAG.computeKnownBits(ShiftAmt).countMaxActiveBits() > ClampAmtBits)
6949 return SDValue();
6950
6951 // Return a clamp shift operation, which has the same semantics as PTX shift.
6952 unsigned ClampOpc = ShiftOp.getOpcode() == ISD::SRL ? NVPTXISD::SRL_CLAMP
6953 : NVPTXISD::SHL_CLAMP;
6954 return DCI.DAG.getNode(ClampOpc, SDLoc(N), ShiftOp.getValueType(),
6955 ShiftOp.getOperand(0), ClampAmt);
6956}
6957
6960 SDValue VA = N->getOperand(1);
6961 EVT VectorVT = VA.getValueType();
6962 if (VectorVT != MVT::v4i8)
6963 return SDValue();
6964
6965 // We need to split vselect into individual per-element operations Because we
6966 // use BFE/BFI instruction for byte extraction/insertion, we do end up with
6967 // 32-bit values, so we may as well do comparison as i32 to avoid conversions
6968 // to/from i16 normally used for i8 values.
6970 SDLoc DL(N);
6971 SDValue VCond = N->getOperand(0);
6972 SDValue VB = N->getOperand(2);
6973 for (int I = 0; I < 4; ++I) {
6974 SDValue C = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i1, VCond,
6975 DCI.DAG.getConstant(I, DL, MVT::i32));
6976 SDValue EA = DCI.DAG.getAnyExtOrTrunc(
6977 DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i8, VA,
6978 DCI.DAG.getConstant(I, DL, MVT::i32)),
6979 DL, MVT::i32);
6980 SDValue EB = DCI.DAG.getAnyExtOrTrunc(
6981 DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i8, VB,
6982 DCI.DAG.getConstant(I, DL, MVT::i32)),
6983 DL, MVT::i32);
6984 E.push_back(DCI.DAG.getAnyExtOrTrunc(
6985 DCI.DAG.getNode(ISD::SELECT, DL, MVT::i32, C, EA, EB), DL, MVT::i8));
6986 }
6987 return DCI.DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i8, E);
6988}
6989
6990static SDValue
6992 auto VT = N->getValueType(0);
6993 if (!DCI.isAfterLegalizeDAG() ||
6994 // only process v2*16 types
6995 !(NVPTX::isPackedVectorTy(VT) && VT.is32BitVector() &&
6996 VT.getVectorNumElements() == 2))
6997 return SDValue();
6998
6999 auto Op0 = N->getOperand(0);
7000 auto Op1 = N->getOperand(1);
7001
7002 // Start out by assuming we want to take the lower 2 bytes of each i32
7003 // operand.
7004 uint64_t Op0Bytes = 0x10;
7005 uint64_t Op1Bytes = 0x54;
7006
7007 std::pair<SDValue *, uint64_t *> OpData[2] = {{&Op0, &Op0Bytes},
7008 {&Op1, &Op1Bytes}};
7009
7010 // Check that each operand is an i16, truncated from an i32 operand. We'll
7011 // select individual bytes from those original operands. Optionally, fold in a
7012 // shift right of that original operand.
7013 for (auto &[Op, OpBytes] : OpData) {
7014 // Eat up any bitcast
7015 if (Op->getOpcode() == ISD::BITCAST)
7016 *Op = Op->getOperand(0);
7017
7018 if (!(Op->getValueType() == MVT::i16 && Op->getOpcode() == ISD::TRUNCATE &&
7019 Op->getOperand(0).getValueType() == MVT::i32))
7020 return SDValue();
7021
7022 // If the truncate has multiple uses, this optimization can increase
7023 // register pressure
7024 if (!Op->hasOneUse())
7025 return SDValue();
7026
7027 *Op = Op->getOperand(0);
7028
7029 // Optionally, fold in a shift-right of the original operand and let permute
7030 // pick the two higher bytes of the original value directly.
7031 if (Op->getOpcode() == ISD::SRL && isa<ConstantSDNode>(Op->getOperand(1))) {
7032 if (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue() == 16) {
7033 // Shift the PRMT byte selector to pick upper bytes from each respective
7034 // value, instead of the lower ones: 0x10 -> 0x32, 0x54 -> 0x76
7035 assert((*OpBytes == 0x10 || *OpBytes == 0x54) &&
7036 "PRMT selector values out of range");
7037 *OpBytes += 0x22;
7038 *Op = Op->getOperand(0);
7039 }
7040 }
7041 }
7042
7043 SDLoc DL(N);
7044 auto &DAG = DCI.DAG;
7045
7046 auto PRMT =
7047 getPRMT(DAG.getBitcast(MVT::i32, Op0), DAG.getBitcast(MVT::i32, Op1),
7048 (Op1Bytes << 8) | Op0Bytes, DL, DAG);
7049 return DAG.getBitcast(VT, PRMT);
7050}
7051
7054 auto *ASCN1 = cast<AddrSpaceCastSDNode>(N);
7055
7056 if (auto *ASCN2 = dyn_cast<AddrSpaceCastSDNode>(ASCN1->getOperand(0))) {
7057 assert(ASCN2->getDestAddressSpace() == ASCN1->getSrcAddressSpace());
7058
7059 // Fold asc[B -> A](asc[A -> B](x)) -> x
7060 if (ASCN1->getDestAddressSpace() == ASCN2->getSrcAddressSpace())
7061 return ASCN2->getOperand(0);
7062 }
7063
7064 return SDValue();
7065}
7066
7067// Given a constant selector value and a prmt mode, return the selector value
7068// normalized to the generic prmt mode. See the PTX ISA documentation for more
7069// details:
7070// https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#data-movement-and-conversion-instructions-prmt
7071static APInt getPRMTSelector(const APInt &Selector, unsigned Mode) {
7072 assert(Selector.getBitWidth() == 32 && "PRMT must have i32 operands");
7073
7075 return Selector;
7076
7077 const unsigned V = Selector.trunc(2).getZExtValue();
7078
7079 const auto GetSelector = [](unsigned S0, unsigned S1, unsigned S2,
7080 unsigned S3) {
7081 return APInt(32, S0 | (S1 << 4) | (S2 << 8) | (S3 << 12));
7082 };
7083
7084 switch (Mode) {
7086 return GetSelector(V, V + 1, V + 2, V + 3);
7088 return GetSelector(V, (V - 1) & 7, (V - 2) & 7, (V - 3) & 7);
7090 return GetSelector(V, V, V, V);
7092 return GetSelector(V, std::max(V, 1U), std::max(V, 2U), 3U);
7094 return GetSelector(0, std::min(V, 1U), std::min(V, 2U), V);
7096 unsigned V1 = (V & 1) << 1;
7097 return GetSelector(V1, V1 + 1, V1, V1 + 1);
7098 }
7099 default:
7100 llvm_unreachable("Invalid PRMT mode");
7101 }
7102}
7103
7104static APInt computePRMT(APInt A, APInt B, APInt Selector, unsigned Mode) {
7105 assert(A.getBitWidth() == 32 && B.getBitWidth() == 32 &&
7106 Selector.getBitWidth() == 32 && "PRMT must have i32 operands");
7107 // {b, a} = {{b7, b6, b5, b4}, {b3, b2, b1, b0}}
7108 APInt BitField = B.concat(A);
7109 APInt SelectorVal = getPRMTSelector(Selector, Mode);
7110 APInt Result(32, 0);
7111 for (unsigned I : llvm::seq(4U)) {
7112 APInt Sel = SelectorVal.extractBits(4, I * 4);
7113 unsigned Idx = Sel.getLoBits(3).getZExtValue();
7114 unsigned Sign = Sel.getHiBits(1).getZExtValue();
7115 APInt Byte = BitField.extractBits(8, Idx * 8);
7116 if (Sign)
7117 Byte = Byte.ashr(8);
7118 Result.insertBits(Byte, I * 8);
7119 }
7120 return Result;
7121}
7122
7124 CodeGenOptLevel OptLevel) {
7125 if (OptLevel == CodeGenOptLevel::None)
7126 return SDValue();
7127
7128 // Constant fold PRMT
7129 if (isa<ConstantSDNode>(N->getOperand(0)) &&
7130 isa<ConstantSDNode>(N->getOperand(1)) &&
7131 isa<ConstantSDNode>(N->getOperand(2)))
7132 return DCI.DAG.getConstant(computePRMT(N->getConstantOperandAPInt(0),
7133 N->getConstantOperandAPInt(1),
7134 N->getConstantOperandAPInt(2),
7135 N->getConstantOperandVal(3)),
7136 SDLoc(N), N->getValueType(0));
7137 return SDValue();
7138}
7139
7140// During call lowering we wrap the return values in a ProxyReg node which
7141// depend on the chain value produced by the completed call. This ensures that
7142// the full call is emitted in cases where libcalls are used to legalize
7143// operations. To improve the functioning of other DAG combines we pull all
7144// operations we can through one of these nodes, ensuring that the ProxyReg
7145// directly wraps a load. That is:
7146//
7147// (ProxyReg (zext (load retval0))) => (zext (ProxyReg (load retval0)))
7148//
7151 switch (R.getOpcode()) {
7152 case ISD::TRUNCATE:
7153 case ISD::ANY_EXTEND:
7154 case ISD::SIGN_EXTEND:
7155 case ISD::ZERO_EXTEND:
7156 case ISD::BITCAST: {
7157 if (SDValue V = sinkProxyReg(R.getOperand(0), Chain, DCI))
7158 return DCI.DAG.getNode(R.getOpcode(), SDLoc(R), R.getValueType(), V);
7159 return SDValue();
7160 }
7161 case ISD::SHL:
7162 case ISD::SRL:
7163 case ISD::SRA:
7164 case ISD::OR: {
7165 if (SDValue A = sinkProxyReg(R.getOperand(0), Chain, DCI))
7166 if (SDValue B = sinkProxyReg(R.getOperand(1), Chain, DCI))
7167 return DCI.DAG.getNode(R.getOpcode(), SDLoc(R), R.getValueType(), A, B);
7168 return SDValue();
7169 }
7170 case ISD::Constant:
7171 return R;
7172 case ISD::LOAD:
7173 case NVPTXISD::LoadV2:
7174 case NVPTXISD::LoadV4: {
7175 return DCI.DAG.getNode(NVPTXISD::ProxyReg, SDLoc(R), R.getValueType(),
7176 {Chain, R});
7177 }
7178 case ISD::BUILD_VECTOR: {
7179 if (DCI.isBeforeLegalize())
7180 return SDValue();
7181
7183 for (auto &Op : R->ops()) {
7184 SDValue V = sinkProxyReg(Op, Chain, DCI);
7185 if (!V)
7186 return SDValue();
7187 Ops.push_back(V);
7188 }
7189 return DCI.DAG.getNode(ISD::BUILD_VECTOR, SDLoc(R), R.getValueType(), Ops);
7190 }
7192 if (DCI.isBeforeLegalize())
7193 return SDValue();
7194
7195 if (SDValue V = sinkProxyReg(R.getOperand(0), Chain, DCI))
7197 R.getValueType(), V, R.getOperand(1));
7198 return SDValue();
7199 }
7200 default:
7201 return SDValue();
7202 }
7203}
7204
7207 const bool IsFTZ =
7208 IID == Intrinsic::nvvm_fadd_ftz || IID == Intrinsic::nvvm_fadd_ftz_sat;
7209 const bool IsSat =
7210 IID == Intrinsic::nvvm_fadd_sat || IID == Intrinsic::nvvm_fadd_ftz_sat;
7211 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
7212 case MVT::f16: {
7213 static constexpr unsigned SubRNOpcodes[2][2] = {
7214 {NVPTXISD::SUB_RN, NVPTXISD::SUB_RN_SAT},
7215 {NVPTXISD::SUB_RN_FTZ, NVPTXISD::SUB_RN_FTZ_SAT}};
7216 return SubRNOpcodes[IsFTZ][IsSat];
7217 }
7218 case MVT::bf16:
7219 return NVPTXISD::SUB_RN;
7220 case MVT::f32: {
7221 // for f32x2 inputs
7222 if (!VT.isVector() || IsSat)
7223 return 0;
7224 static constexpr unsigned SubF32x2Opcodes[4][2] = {
7225 {NVPTXISD::SUB_RZ, NVPTXISD::SUB_RZ_FTZ}, // RZ
7226 {NVPTXISD::SUB_RN, NVPTXISD::SUB_RN_FTZ}, // RN
7227 {NVPTXISD::SUB_RP, NVPTXISD::SUB_RP_FTZ}, // RP
7228 {NVPTXISD::SUB_RM, NVPTXISD::SUB_RM_FTZ}}; // RM
7229 return SubF32x2Opcodes[static_cast<unsigned>(RoundingMode)][IsFTZ];
7230 }
7231 default:
7232 return 0;
7233 }
7234}
7235
7237 Intrinsic::ID AddIntrinsicID,
7239 const EVT VT = N->getValueType(0);
7240 const unsigned Opc = getFAddWithNegOpcode(VT, AddIntrinsicID, RoundingMode);
7241 if (!Opc)
7242 return SDValue();
7243
7244 SDValue Op1 = N->getOperand(1);
7245 SDValue Op2 = N->getOperand(2);
7246
7247 SDValue SubOp1, SubOp2;
7248
7249 if (Op1.getOpcode() == ISD::FNEG) {
7250 SubOp1 = Op2;
7251 SubOp2 = Op1.getOperand(0);
7252 } else if (Op2.getOpcode() == ISD::FNEG) {
7253 SubOp1 = Op1;
7254 SubOp2 = Op2.getOperand(0);
7255 } else {
7256 return SDValue();
7257 }
7258
7259 return DAG.getNode(Opc, SDLoc(N), VT, SubOp1, SubOp2);
7260}
7261
7262// TODO: Remove the type-legality checks here once
7263// https://github.com/llvm/llvm-project/pull/172442 lands, adding support for
7264// explicit type constraints for overloaded intrinsics in tablegen.
7265static bool isSupportedFAdd(EVT VT, const NVPTXSubtarget &STI,
7266 Intrinsic::ID IID,
7269 return false;
7270
7271 const bool IsRN = RoundingMode == APFloat::rmNearestTiesToEven;
7272 const bool IsFTZ =
7273 IID == Intrinsic::nvvm_fadd_ftz || IID == Intrinsic::nvvm_fadd_ftz_sat;
7274 const bool IsSat =
7275 IID == Intrinsic::nvvm_fadd_sat || IID == Intrinsic::nvvm_fadd_ftz_sat;
7276 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
7277 case MVT::f16:
7278 return IsRN;
7279 case MVT::bf16:
7280 return IsRN && !IsSat && !IsFTZ && STI.hasNativeBF16Support(ISD::FADD);
7281 case MVT::f32:
7282 return !VT.isVector() || (!IsSat && STI.hasF32x2Instructions());
7283 case MVT::f64:
7284 return !VT.isVector() && !IsSat && !IsFTZ;
7285 default:
7286 return false;
7287 }
7288}
7289
7291 Intrinsic::ID IID,
7293 const EVT VT = N->getValueType(0);
7296 Twine(Intrinsic::getBaseName(IID)) + " with rounding mode " +
7297 nvvm::GetRoundingModeName(RoundingMode) + " and operand type " +
7298 VT.getEVTString() + " is not supported on this target",
7299 SDLoc(N).getDebugLoc()));
7300 return DAG.getPOISON(VT);
7301}
7302
7305 const NVPTXSubtarget &STI) {
7306 const Intrinsic::ID IID =
7307 static_cast<Intrinsic::ID>(N->getConstantOperandVal(0));
7308
7309 switch (IID) {
7310 default:
7311 break;
7312 case Intrinsic::nvvm_fadd:
7313 case Intrinsic::nvvm_fadd_ftz:
7314 case Intrinsic::nvvm_fadd_sat:
7315 case Intrinsic::nvvm_fadd_ftz_sat: {
7316 const auto RoundingMode = static_cast<APFloat::roundingMode>(
7317 N->getConstantOperandAPInt(3).getSExtValue());
7318 if (!isSupportedFAdd(N->getValueType(0), STI, IID, RoundingMode))
7319 return diagnoseUnsupportedFAdd(N, DCI.DAG, IID, RoundingMode);
7320 return combineFAddWithNeg(N, DCI.DAG, IID, RoundingMode);
7321 }
7322 }
7323 return SDValue();
7324}
7325
7328
7329 SDValue Chain = N->getOperand(0);
7330 SDValue Reg = N->getOperand(1);
7331
7332 // If the ProxyReg is not wrapping a load, try to pull the operations through
7333 // the ProxyReg.
7334 if (Reg.getOpcode() != ISD::LOAD) {
7335 if (SDValue V = sinkProxyReg(Reg, Chain, DCI))
7336 return V;
7337 }
7338
7339 return SDValue();
7340}
7341
7342SDValue NVPTXTargetLowering::PerformDAGCombine(SDNode *N,
7343 DAGCombinerInfo &DCI) const {
7345 switch (N->getOpcode()) {
7346 default:
7347 break;
7348 case ISD::ADD:
7349 return PerformADDCombine(N, DCI, OptLevel);
7350 case ISD::ADDRSPACECAST:
7351 return combineADDRSPACECAST(N, DCI);
7352 case ISD::SIGN_EXTEND:
7353 case ISD::ZERO_EXTEND:
7354 return combineSZExtToMulWide(N, DCI, OptLevel);
7355 case ISD::BUILD_VECTOR:
7356 return PerformBUILD_VECTORCombine(N, DCI);
7358 return PerformEXTRACTCombine(N, DCI);
7359 case ISD::FADD:
7360 return performFADDCombine(N, DCI, OptLevel);
7361 case ISD::FMA:
7362 case ISD::FMUL:
7363 case ISD::FSUB:
7364 return performScalarizeV2F32Op(N, DCI, OptLevel);
7365 case ISD::FMAXNUM:
7366 case ISD::FMINNUM:
7367 case ISD::FMAXIMUM:
7368 case ISD::FMINIMUM:
7369 case ISD::FMAXIMUMNUM:
7370 case ISD::FMINIMUMNUM:
7371 return PerformFMinMaxCombine(N, DCI, STI);
7372 case ISD::LOAD:
7373 case NVPTXISD::LoadV2:
7374 case NVPTXISD::LoadV4:
7375 return combineLOAD(N, DCI, STI);
7376 case ISD::MUL:
7377 return PerformMULCombine(N, DCI, OptLevel);
7378 case NVPTXISD::PRMT:
7379 return combinePRMT(N, DCI, OptLevel);
7380 case NVPTXISD::ProxyReg:
7381 return combineProxyReg(N, DCI);
7382 case ISD::SETCC:
7383 return PerformSETCCCombine(N, DCI, STI);
7384 case ISD::SHL:
7385 return PerformSHLCombine(N, DCI, OptLevel);
7386 case ISD::SREM:
7387 case ISD::UREM:
7388 return PerformREMCombine(N, DCI, OptLevel);
7389 case ISD::STORE:
7390 case NVPTXISD::StoreV2:
7391 case NVPTXISD::StoreV4:
7392 return combineSTORE(N, DCI, STI);
7393 case ISD::SELECT:
7394 return PerformSELECTShiftCombine(N, DCI);
7395 case ISD::VSELECT:
7396 return PerformVSELECTCombine(N, DCI);
7398 return combineIntrinsicWOChain(N, DCI, STI);
7399 }
7400 return SDValue();
7401}
7402
7405 // Handle bitcasting to v2i8 without hitting the default promotion
7406 // strategy which goes through stack memory.
7407 SDValue Op(Node, 0);
7408 EVT ToVT = Op->getValueType(0);
7409 if (ToVT != MVT::v2i8) {
7410 return;
7411 }
7412
7413 // Bitcast to i16 and unpack elements into a vector
7414 SDLoc DL(Node);
7415 SDValue AsInt = DAG.getBitcast(MVT::i16, Op->getOperand(0));
7416 SDValue Vec0 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, AsInt);
7417 SDValue Const8 = DAG.getConstant(8, DL, MVT::i16);
7418 SDValue Vec1 =
7419 DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
7420 DAG.getNode(ISD::SRL, DL, MVT::i16, {AsInt, Const8}));
7421 Results.push_back(
7422 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i8, {Vec0, Vec1}));
7423}
7424
7427 SDValue Chain = N->getOperand(0);
7428 SDValue Intrin = N->getOperand(1);
7429 SDLoc DL(N);
7430
7431 // Get the intrinsic ID
7432 unsigned IntrinNo = Intrin.getNode()->getAsZExtVal();
7433 switch (IntrinNo) {
7434 default:
7435 return;
7436 case Intrinsic::nvvm_ldu_global_i:
7437 case Intrinsic::nvvm_ldu_global_f:
7438 case Intrinsic::nvvm_ldu_global_p: {
7439 EVT ResVT = N->getValueType(0);
7440
7441 if (ResVT.isVector()) {
7442 // Vector LDG/LDU
7443
7444 unsigned NumElts = ResVT.getVectorNumElements();
7445 EVT EltVT = ResVT.getVectorElementType();
7446
7447 // Since LDU/LDG are target nodes, we cannot rely on DAG type
7448 // legalization.
7449 // Therefore, we must ensure the type is legal. For i1 and i8, we set the
7450 // loaded type to i16 and propagate the "real" type as the memory type.
7451 bool NeedTrunc = false;
7452 if (EltVT.getSizeInBits() < 16) {
7453 EltVT = MVT::i16;
7454 NeedTrunc = true;
7455 }
7456
7457 unsigned Opcode = 0;
7458 SDVTList LdResVTs;
7459
7460 switch (NumElts) {
7461 default:
7462 return;
7463 case 2:
7464 Opcode = NVPTXISD::LDUV2;
7465 LdResVTs = DAG.getVTList(EltVT, EltVT, MVT::Other);
7466 break;
7467 case 4: {
7468 Opcode = NVPTXISD::LDUV4;
7469 EVT ListVTs[] = { EltVT, EltVT, EltVT, EltVT, MVT::Other };
7470 LdResVTs = DAG.getVTList(ListVTs);
7471 break;
7472 }
7473 }
7474
7475 SmallVector<SDValue, 8> OtherOps;
7476
7477 // Copy regular operands
7478
7479 OtherOps.push_back(Chain); // Chain
7480 // Skip operand 1 (intrinsic ID)
7481 // Others
7482 OtherOps.append(N->op_begin() + 2, N->op_end());
7483
7485
7486 SDValue NewLD = DAG.getMemIntrinsicNode(Opcode, DL, LdResVTs, OtherOps,
7487 MemSD->getMemoryVT(),
7488 MemSD->getMemOperand());
7489
7490 SmallVector<SDValue, 4> ScalarRes;
7491
7492 for (unsigned i = 0; i < NumElts; ++i) {
7493 SDValue Res = NewLD.getValue(i);
7494 if (NeedTrunc)
7495 Res =
7496 DAG.getNode(ISD::TRUNCATE, DL, ResVT.getVectorElementType(), Res);
7497 ScalarRes.push_back(Res);
7498 }
7499
7500 SDValue LoadChain = NewLD.getValue(NumElts);
7501
7502 SDValue BuildVec =
7503 DAG.getBuildVector(ResVT, DL, ScalarRes);
7504
7505 Results.push_back(BuildVec);
7506 Results.push_back(LoadChain);
7507 } else {
7508 // i8 LDG/LDU
7509 assert(ResVT.isSimple() && ResVT.getSimpleVT().SimpleTy == MVT::i8 &&
7510 "Custom handling of non-i8 ldu/ldg?");
7511
7512 // Just copy all operands as-is
7514
7515 // Force output to i16
7516 SDVTList LdResVTs = DAG.getVTList(MVT::i16, MVT::Other);
7517
7519
7520 // We make sure the memory type is i8, which will be used during isel
7521 // to select the proper instruction.
7522 SDValue NewLD =
7524 MVT::i8, MemSD->getMemOperand());
7525
7526 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
7527 NewLD.getValue(0)));
7528 Results.push_back(NewLD.getValue(1));
7529 }
7530 return;
7531 }
7532
7533 case Intrinsic::nvvm_tcgen05_ld_16x64b_x1:
7534 case Intrinsic::nvvm_tcgen05_ld_16x64b_x4:
7535 case Intrinsic::nvvm_tcgen05_ld_16x64b_x8:
7536 case Intrinsic::nvvm_tcgen05_ld_16x64b_x16:
7537 case Intrinsic::nvvm_tcgen05_ld_16x64b_x32:
7538 case Intrinsic::nvvm_tcgen05_ld_16x64b_x64:
7539 case Intrinsic::nvvm_tcgen05_ld_16x64b_x128:
7540 case Intrinsic::nvvm_tcgen05_ld_32x32b_x1:
7541 case Intrinsic::nvvm_tcgen05_ld_32x32b_x4:
7542 case Intrinsic::nvvm_tcgen05_ld_32x32b_x8:
7543 case Intrinsic::nvvm_tcgen05_ld_32x32b_x16:
7544 case Intrinsic::nvvm_tcgen05_ld_32x32b_x32:
7545 case Intrinsic::nvvm_tcgen05_ld_32x32b_x64:
7546 case Intrinsic::nvvm_tcgen05_ld_32x32b_x128:
7547 case Intrinsic::nvvm_tcgen05_ld_16x128b_x2:
7548 case Intrinsic::nvvm_tcgen05_ld_16x128b_x4:
7549 case Intrinsic::nvvm_tcgen05_ld_16x128b_x8:
7550 case Intrinsic::nvvm_tcgen05_ld_16x128b_x16:
7551 case Intrinsic::nvvm_tcgen05_ld_16x128b_x32:
7552 case Intrinsic::nvvm_tcgen05_ld_16x128b_x64:
7553 case Intrinsic::nvvm_tcgen05_ld_16x256b_x1:
7554 case Intrinsic::nvvm_tcgen05_ld_16x256b_x2:
7555 case Intrinsic::nvvm_tcgen05_ld_16x256b_x4:
7556 case Intrinsic::nvvm_tcgen05_ld_16x256b_x8:
7557 case Intrinsic::nvvm_tcgen05_ld_16x256b_x16:
7558 case Intrinsic::nvvm_tcgen05_ld_16x256b_x32:
7559 if (auto Res = lowerTcgen05Ld(N, DAG)) {
7560 Results.push_back(Res->first);
7561 Results.push_back(Res->second);
7562 }
7563 return;
7564
7565 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x1:
7566 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x4:
7567 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x8:
7568 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x16:
7569 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x32:
7570 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x64:
7571 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x128:
7572 if (auto Res = lowerTcgen05Ld(N, DAG, /*HasOffset=*/true)) {
7573 Results.push_back(Res->first);
7574 Results.push_back(Res->second);
7575 }
7576 return;
7577
7578 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_i32:
7579 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_f32:
7580 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_i32:
7581 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_f32:
7582 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_i32:
7583 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_f32:
7584 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_i32:
7585 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_f32:
7586 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_i32:
7587 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_f32:
7588 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_i32:
7589 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_f32:
7590 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_i32:
7591 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_f32:
7592 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_i32:
7593 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_f32:
7594 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_i32:
7595 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_f32:
7596 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_i32:
7597 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_f32:
7598 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_i32:
7599 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_f32:
7600 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_i32:
7601 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_f32:
7602 if (auto Res = lowerTcgen05LdRed(N, DAG)) {
7603 Results.push_back(std::get<0>(*Res));
7604 Results.push_back(std::get<1>(*Res));
7605 Results.push_back(std::get<2>(*Res));
7606 }
7607 return;
7608 }
7609}
7610
7613 // Change the CopyFromReg to output 2 64-bit results instead of a 128-bit
7614 // result so that it can pass the legalization
7615 SDLoc DL(N);
7616 SDValue Chain = N->getOperand(0);
7617 SDValue Reg = N->getOperand(1);
7618 SDValue Glue = N->getOperand(2);
7619
7620 assert(Reg.getValueType() == MVT::i128 &&
7621 "Custom lowering for CopyFromReg with 128-bit reg only");
7622 SmallVector<EVT, 4> ResultsType = {MVT::i64, MVT::i64, N->getValueType(1),
7623 N->getValueType(2)};
7624 SmallVector<SDValue, 3> NewOps = {Chain, Reg, Glue};
7625
7626 SDValue NewValue = DAG.getNode(ISD::CopyFromReg, DL, ResultsType, NewOps);
7627 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128,
7628 {NewValue.getValue(0), NewValue.getValue(1)});
7629
7630 Results.push_back(Pair);
7631 Results.push_back(NewValue.getValue(2));
7632 Results.push_back(NewValue.getValue(3));
7633}
7634
7636 const TargetLowering &TLI,
7638 SDValue Chain = N->getOperand(0);
7639 SDValue Reg = N->getOperand(1);
7640
7641 MVT VT = TLI.getRegisterType(*DAG.getContext(), Reg.getValueType());
7642
7643 SDValue NewReg = DAG.getAnyExtOrTrunc(Reg, SDLoc(N), VT);
7644 SDValue NewProxy =
7645 DAG.getNode(NVPTXISD::ProxyReg, SDLoc(N), VT, {Chain, NewReg});
7646 SDValue Res = DAG.getAnyExtOrTrunc(NewProxy, SDLoc(N), N->getValueType(0));
7647
7648 Results.push_back(Res);
7649}
7650
7652 const NVPTXSubtarget &STI,
7654 assert(N->getValueType(0) == MVT::i128 &&
7655 "Custom lowering for atomic128 only supports i128");
7656
7658 SDLoc dl(N);
7659
7660 if (!STI.hasAtomSwap128()) {
7663 "Support for b128 atomics introduced in PTX ISA version 8.3 and "
7664 "requires target sm_90.",
7665 dl.getDebugLoc()));
7666
7667 Results.push_back(DAG.getUNDEF(MVT::i128));
7668 Results.push_back(AN->getOperand(0)); // Chain
7669 return;
7670 }
7671
7673 Ops.push_back(AN->getOperand(0)); // Chain
7674 Ops.push_back(AN->getOperand(1)); // Ptr
7675 for (const auto &Op : AN->ops().drop_front(2)) {
7676 // Low part
7677 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i64, Op,
7678 DAG.getIntPtrConstant(0, dl)));
7679 // High part
7680 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i64, Op,
7681 DAG.getIntPtrConstant(1, dl)));
7682 }
7683 unsigned Opcode = N->getOpcode() == ISD::ATOMIC_SWAP
7686 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
7687 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, MVT::i128,
7688 AN->getMemOperand());
7689 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i128,
7690 {Result.getValue(0), Result.getValue(1)}));
7691 Results.push_back(Result.getValue(2));
7692}
7693
7694void NVPTXTargetLowering::ReplaceNodeResults(
7696 switch (N->getOpcode()) {
7697 default:
7698 report_fatal_error("Unhandled custom legalization");
7699 case ISD::BITCAST:
7700 ReplaceBITCAST(N, DAG, Results);
7701 return;
7702 case ISD::LOAD:
7703 case ISD::MLOAD:
7704 replaceLoadVector(N, DAG, Results, STI);
7705 return;
7708 return;
7709 case ISD::CopyFromReg:
7711 return;
7712 case NVPTXISD::ProxyReg:
7713 replaceProxyReg(N, DAG, *this, Results);
7714 return;
7716 case ISD::ATOMIC_SWAP:
7717 replaceAtomicSwap128(N, DAG, STI, Results);
7718 return;
7719 }
7720}
7721
7724 Type *Ty = AI->getValOperand()->getType();
7725
7726 // Try to lower LLVM atomicrmw fadd to PTX atomic.add. This is complicated
7727 // by the weird FTZ behavior PTX atom.add has:
7728 // - atom.add.f32 on global memory flushes denormals
7729 // - atom.add.f32 on shared memory does not flush denormals
7730 // - atom.add.f16 and atomic.add.bf16 never flush denormals
7731 //
7732 // We lower to atom.add only if the function's FTZ behavior matches that of
7733 // atom.add; otherwise, we lower to a CAS loop. But we always allow
7734 // atomic.add.bf16; even though it never flushes denormals, we never flush
7735 // bf16 denormals when doing regular arithmetic, even when FTZ is enabled.
7736 if (AI->isFloatingPointOperation() &&
7738 const Function *F = AI->getFunction();
7739
7740 // AllowFTZAtomics forces atom.add regardless of the FTZ mismatch.
7741 if (Ty->isFloatTy()) {
7742 const bool FTZ = F->getDenormalMode(APFloat::IEEEsingle()).Output ==
7745 switch (AI->getPointerAddressSpace()) {
7747 UseNative |= FTZ;
7748 break;
7751 UseNative |= !FTZ;
7752 break;
7753 }
7754 if (UseNative)
7756 }
7757
7758 if (Ty->isHalfTy()) {
7759 // atom.add.f16 never flushes denormals, so it only agrees with a
7760 // function that is not in FTZ mode for f16.
7761 const bool FTZ = F->getDenormalMode(APFloat::IEEEhalf()).Output ==
7763 if ((!FTZ || AllowFTZAtomics) && STI.hasFeature(NVPTX::SM70) &&
7764 STI.hasFeature(NVPTX::PTX63))
7766 }
7767
7768 if (Ty->isBFloatTy() && STI.hasFeature(NVPTX::SM90))
7770
7771 if (Ty->isDoubleTy() && STI.hasAtomAddF64())
7773 }
7774
7775 // PTX's only atomic fp op is `add`; all other ops expand to a CAS loop.
7776 if (AI->isFloatingPointOperation())
7778
7779 if (Ty->isVectorTy())
7781
7782 assert(Ty->isIntegerTy() && "Ty should be integer at this point");
7783 const unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
7784
7785 switch (AI->getOperation()) {
7786 default:
7789 if (BitWidth == 128)
7791 [[fallthrough]];
7795 switch (BitWidth) {
7796 case 8:
7797 case 16:
7799 case 32:
7801 case 64:
7802 if (STI.hasAtomBitwise64())
7805 case 128:
7807 default:
7808 llvm_unreachable("unsupported width encountered");
7809 }
7816 switch (BitWidth) {
7817 case 8:
7818 case 16:
7820 case 32:
7822 case 64:
7823 if (STI.hasAtomMinMax64())
7826 case 128:
7828 default:
7829 llvm_unreachable("unsupported width encountered");
7830 }
7833 switch (BitWidth) {
7834 case 32:
7836 case 8:
7837 case 16:
7838 case 64:
7839 case 128:
7841 default:
7842 llvm_unreachable("unsupported width encountered");
7843 }
7844 }
7845
7847}
7848
7850 const Instruction *I) const {
7851 // This function returns true iff the operation is emulated using a CAS-loop,
7852 // or if it has the memory order seq_cst (which is not natively supported in
7853 // the PTX `atom` instruction).
7854 //
7855 // atomicrmw and cmpxchg instructions not efficiently supported by PTX
7856 // are lowered to CAS emulation loops that preserve their memory order,
7857 // syncscope, and volatile semantics. For PTX, it is more efficient to use
7858 // atom.cas.relaxed.sco instructions within the loop, and fences before and
7859 // after the loop to restore order.
7860 //
7861 // Atomic instructions efficiently supported by PTX are lowered to
7862 // `atom.<op>.<sem>.<scope` instruction with their corresponding memory order
7863 // and scope. Since PTX does not support seq_cst, we emulate it by lowering to
7864 // a fence.sc followed by an atom according to the PTX atomics ABI
7865 // https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/atomic-abi.html
7866 if (auto *CI = dyn_cast<AtomicCmpXchgInst>(I))
7867 return (cast<IntegerType>(CI->getCompareOperand()->getType())
7868 ->getBitWidth() < STI.getMinCmpXchgSizeInBits()) ||
7869 CI->getMergedOrdering() == AtomicOrdering::SequentiallyConsistent;
7870 if (auto *RI = dyn_cast<AtomicRMWInst>(I))
7872 RI->getOrdering() == AtomicOrdering::SequentiallyConsistent;
7873 return false;
7874}
7875
7877 const Instruction *I) const {
7878 // If the operation is emulated by a CAS-loop, we lower the instruction to
7879 // atom.<op>.relaxed, since AtomicExpandPass will insert fences for enforcing
7880 // the correct memory ordering around the CAS loop.
7881 //
7882 // When the operation is not emulated, but the memory order is seq_cst,
7883 // we must lower to "fence.sc.<scope>; atom.<op>.acquire.<scope>;" to conform
7884 // to the PTX atomics ABI.
7885 // https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/atomic-abi.html
7886 // For such cases, emitLeadingFence() will separately insert the leading
7887 // "fence.sc.<scope>;". Here, we only set the memory order to acquire.
7888 //
7889 // Otherwise, the operation is not emulated, and the memory order is not
7890 // seq_cst. In this case, the LLVM memory order is natively supported by the
7891 // PTX `atom` instruction, and we just lower to the corresponding
7892 // `atom.<op>.relaxed|acquire|release|acq_rel". For such cases, this function
7893 // will NOT be called.
7894 // prerequisite: shouldInsertFencesForAtomic() should have returned `true` for
7895 // I before its memory order was modified.
7896 if (auto *CI = dyn_cast<AtomicCmpXchgInst>(I);
7897 CI && CI->getMergedOrdering() == AtomicOrdering::SequentiallyConsistent &&
7898 cast<IntegerType>(CI->getCompareOperand()->getType())->getBitWidth() >=
7899 STI.getMinCmpXchgSizeInBits())
7901 else if (auto *RI = dyn_cast<AtomicRMWInst>(I);
7902 RI && RI->getOrdering() == AtomicOrdering::SequentiallyConsistent &&
7905
7907}
7908
7910 Instruction *Inst,
7911 AtomicOrdering Ord) const {
7912 // prerequisite: shouldInsertFencesForAtomic() should have returned `true` for
7913 // `Inst` before its memory order was modified. We cannot enforce this with an
7914 // assert, because AtomicExpandPass will have modified the memory order
7915 // between the initial call to shouldInsertFencesForAtomic() and the call to
7916 // this function.
7917 if (!isa<AtomicCmpXchgInst>(Inst) && !isa<AtomicRMWInst>(Inst))
7918 return TargetLoweringBase::emitLeadingFence(Builder, Inst, Ord);
7919
7920 // Specialize for cmpxchg and atomicrmw
7921 auto SSID = getAtomicSyncScopeID(Inst);
7922 assert(SSID.has_value() && "Expected an atomic operation");
7923
7924 if (isReleaseOrStronger(Ord))
7925 return Builder.CreateFence(Ord == AtomicOrdering::SequentiallyConsistent
7928 SSID.value());
7929
7930 return nullptr;
7931}
7932
7934 Instruction *Inst,
7935 AtomicOrdering Ord) const {
7936 // prerequisite: shouldInsertFencesForAtomic() should have returned `true` for
7937 // `Inst` before its memory order was modified. See `emitLeadingFence` for why
7938 // this cannot be enforced with an assert. Specialize for cmpxchg and
7939 // atomicrmw
7940 auto *CI = dyn_cast<AtomicCmpXchgInst>(Inst);
7941 auto *RI = dyn_cast<AtomicRMWInst>(Inst);
7942 if (!CI && !RI)
7943 return TargetLoweringBase::emitTrailingFence(Builder, Inst, Ord);
7944
7945 auto SSID = getAtomicSyncScopeID(Inst);
7946 assert(SSID.has_value() && "Expected an atomic operation");
7947
7948 bool IsEmulated =
7949 CI ? cast<IntegerType>(CI->getCompareOperand()->getType())
7950 ->getBitWidth() < STI.getMinCmpXchgSizeInBits()
7952
7953 if (isAcquireOrStronger(Ord) && IsEmulated)
7954 return Builder.CreateFence(AtomicOrdering::Acquire, SSID.value());
7955
7956 return nullptr;
7957}
7958
7959// Rather than default to SINT when both UINT and SINT are custom, we only
7960// change the opcode when UINT is not legal and SINT is. UINT is preferred when
7961// both are custom since unsigned CVT instructions can lead to slightly better
7962// SASS code with fewer instructions.
7964 EVT ToVT) const {
7965 if (isOperationLegal(Op, ToVT))
7966 return Op;
7967 switch (Op) {
7968 case ISD::FP_TO_UINT:
7970 return ISD::FP_TO_SINT;
7971 break;
7975 break;
7976 default:
7977 break;
7978 }
7979 return Op;
7980}
7981
7982// Pin NVPTXTargetObjectFile's vtables to this file.
7984
7989
7991 const SelectionDAG &DAG, unsigned Depth) {
7992 SDValue A = Op.getOperand(0);
7993 SDValue B = Op.getOperand(1);
7994 ConstantSDNode *Selector = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7995 unsigned Mode = Op.getConstantOperandVal(3);
7996
7997 if (!Selector)
7998 return;
7999
8000 KnownBits AKnown = DAG.computeKnownBits(A, Depth);
8001 KnownBits BKnown = DAG.computeKnownBits(B, Depth);
8002
8003 // {b, a} = {{b7, b6, b5, b4}, {b3, b2, b1, b0}}
8004 assert(AKnown.getBitWidth() == 32 && BKnown.getBitWidth() == 32 &&
8005 "PRMT must have i32 operands");
8006 assert(Known.getBitWidth() == 32 && "PRMT must have i32 result");
8007 KnownBits BitField = BKnown.concat(AKnown);
8008
8009 APInt SelectorVal = getPRMTSelector(Selector->getAPIntValue(), Mode);
8010 for (unsigned I : llvm::seq(4)) {
8011 APInt Sel = SelectorVal.extractBits(4, I * 4);
8012 unsigned Idx = Sel.getLoBits(3).getZExtValue();
8013 unsigned Sign = Sel.getHiBits(1).getZExtValue();
8014 KnownBits Byte = BitField.extractBits(8, Idx * 8);
8015 if (Sign)
8016 Byte = KnownBits::ashr(Byte, KnownBits::makeConstant(APInt(8, 7)));
8017 Known.insertBits(Byte, I * 8);
8018 }
8019}
8020
8023
8024 // We can't do anything without knowing the sign bit.
8025 auto ExtType = LD->getConstantOperandVal(LD->getNumOperands() - 1);
8026 if (ExtType == ISD::SEXTLOAD)
8027 return;
8028
8029 // ExtLoading to vector types is weird and may not work well with known bits.
8030 auto DestVT = LD->getValueType(0);
8031 if (DestVT.isVector())
8032 return;
8033
8034 assert(Known.getBitWidth() == DestVT.getSizeInBits());
8035 auto ElementBitWidth = getFromTypeWidthForLoad(LD);
8036 Known.Zero.setHighBits(Known.getBitWidth() - ElementBitWidth);
8037}
8038
8040 const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
8041 const SelectionDAG &DAG, unsigned Depth) const {
8042 Known.resetAll();
8043
8044 switch (Op.getOpcode()) {
8045 case NVPTXISD::PRMT:
8047 break;
8048 case NVPTXISD::LoadV2:
8049 case NVPTXISD::LoadV4:
8050 case NVPTXISD::LoadV8:
8052 break;
8053 default:
8054 break;
8055 }
8056}
8057
8058static std::pair<APInt, APInt> getPRMTDemandedBits(const APInt &SelectorVal,
8059 const APInt &DemandedBits) {
8060 APInt DemandedLHS = APInt(32, 0);
8061 APInt DemandedRHS = APInt(32, 0);
8062
8063 for (unsigned I : llvm::seq(4)) {
8064 if (DemandedBits.extractBits(8, I * 8).isZero())
8065 continue;
8066
8067 APInt Sel = SelectorVal.extractBits(4, I * 4);
8068 unsigned Idx = Sel.getLoBits(3).getZExtValue();
8069 unsigned Sign = Sel.getHiBits(1).getZExtValue();
8070
8071 APInt &Src = Idx < 4 ? DemandedLHS : DemandedRHS;
8072 unsigned ByteStart = (Idx % 4) * 8;
8073 if (Sign)
8074 Src.setBit(ByteStart + 7);
8075 else
8076 Src.setBits(ByteStart, ByteStart + 8);
8077 }
8078
8079 return {DemandedLHS, DemandedRHS};
8080}
8081
8082// Replace undef with 0 as this is easier for other optimizations such as
8083// known bits.
8085 if (!Op)
8086 return SDValue();
8087 if (Op.isUndef())
8088 return DAG.getConstant(0, SDLoc(), MVT::i32);
8089 return Op;
8090}
8091
8093 const APInt &DemandedBits,
8094 SelectionDAG &DAG,
8095 const TargetLowering &TLI,
8096 unsigned Depth) {
8097 assert(PRMT.getOpcode() == NVPTXISD::PRMT);
8098 SDValue Op0 = PRMT.getOperand(0);
8099 SDValue Op1 = PRMT.getOperand(1);
8100 auto *SelectorConst = dyn_cast<ConstantSDNode>(PRMT.getOperand(2));
8101 if (!SelectorConst)
8102 return SDValue();
8103
8104 unsigned Mode = PRMT.getConstantOperandVal(3);
8105 const APInt Selector = getPRMTSelector(SelectorConst->getAPIntValue(), Mode);
8106
8107 // Try to simplify the PRMT to one of the inputs if the used bytes are all
8108 // from the same input in the correct order.
8109 const unsigned LeadingBytes = DemandedBits.countLeadingZeros() / 8;
8110 const unsigned SelBits = (4 - LeadingBytes) * 4;
8111 if (Selector.getLoBits(SelBits) == APInt(32, 0x3210).getLoBits(SelBits))
8112 return Op0;
8113 if (Selector.getLoBits(SelBits) == APInt(32, 0x7654).getLoBits(SelBits))
8114 return Op1;
8115
8116 auto [DemandedLHS, DemandedRHS] = getPRMTDemandedBits(Selector, DemandedBits);
8117
8118 // Attempt to avoid multi-use ops if we don't need anything from them.
8119 SDValue DemandedOp0 =
8120 TLI.SimplifyMultipleUseDemandedBits(Op0, DemandedLHS, DAG, Depth + 1);
8121 SDValue DemandedOp1 =
8122 TLI.SimplifyMultipleUseDemandedBits(Op1, DemandedRHS, DAG, Depth + 1);
8123
8124 DemandedOp0 = canonicalizePRMTInput(DemandedOp0, DAG);
8125 DemandedOp1 = canonicalizePRMTInput(DemandedOp1, DAG);
8126 if ((DemandedOp0 && DemandedOp0 != Op0) ||
8127 (DemandedOp1 && DemandedOp1 != Op1)) {
8128 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
8129 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
8130 return getPRMT(Op0, Op1, Selector.getZExtValue(), SDLoc(PRMT), DAG);
8131 }
8132
8133 return SDValue();
8134}
8135
8137 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8138 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
8139 Known.resetAll();
8140
8141 switch (Op.getOpcode()) {
8142 case NVPTXISD::PRMT:
8144 *this, Depth)) {
8145 TLO.CombineTo(Op, Result);
8146 return true;
8147 }
8148 break;
8149 default:
8150 break;
8151 }
8152
8153 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
8154 return false;
8155}
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:887
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:252
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:257
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:177
@ Default
-O2, -Os, -Oz
Definition CodeGen.h:180
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...