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"
15 #include "MCTargetDesc/NVPTXBaseInfo.h"
16 #include "NVPTX.h"
17 #include "NVPTXSubtarget.h"
18 #include "NVPTXTargetMachine.h"
19 #include "NVPTXTargetObjectFile.h"
20 #include "NVPTXUtilities.h"
21 #include "llvm/ADT/APFloat.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/CodeGen/Analysis.h"
27 #include "llvm/CodeGen/ISDOpcodes.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/Register.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SelectionDAGNodes.h"
34 #include "llvm/CodeGen/TargetCallingConv.h"
35 #include "llvm/CodeGen/TargetLowering.h"
36 #include "llvm/CodeGen/ValueTypes.h"
37 #include "llvm/CodeGenTypes/MachineValueType.h"
38 #include "llvm/IR/Argument.h"
39 #include "llvm/IR/Attributes.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/DiagnosticInfo.h"
44 #include "llvm/IR/FPEnv.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/IRBuilder.h"
48 #include "llvm/IR/Instruction.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/IntrinsicsNVPTX.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/Type.h"
53 #include "llvm/IR/Value.h"
54 #include "llvm/Support/Alignment.h"
55 #include "llvm/Support/AtomicOrdering.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/KnownBits.h"
61 #include "llvm/Support/NVPTXAddrSpace.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include "llvm/Target/TargetOptions.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cmath>
68 #include <cstdint>
69 #include <iterator>
70 #include <optional>
71 #include <string>
72 #include <tuple>
73 #include <utility>
74 #include <vector>
75
76 #define DEBUG_TYPE "nvptx-lower"
77
78 using namespace llvm;
79
80 static cl::opt<bool> sched4reg(
81 "nvptx-sched4reg",
82 cl::desc("NVPTX Specific: schedule for register pressue"), cl::init(false));
83
84 static cl::opt<unsigned> FMAContractLevelOpt(
85 "nvptx-fma-level", cl::Hidden,
86 cl::desc("NVPTX Specific: FMA contraction (0: don't do it"
87 " 1: do it 2: do it aggressively"),
88 cl::init(2));
89
90 static cl::opt<NVPTX::DivPrecisionLevel> UsePrecDivF32(
91 "nvptx-prec-divf32", cl::Hidden,
92 cl::desc(
93 "NVPTX Specific: Override the precision of the lowering for f32 fdiv"),
94 cl::values(
95 clEnumValN(NVPTX::DivPrecisionLevel::Approx, "0", "Use div.approx"),
96 clEnumValN(NVPTX::DivPrecisionLevel::Full, "1", "Use div.full"),
97 clEnumValN(NVPTX::DivPrecisionLevel::IEEE754, "2",
98 "Use IEEE Compliant F32 div.rnd if available (default)"),
99 clEnumValN(NVPTX::DivPrecisionLevel::IEEE754_NoFTZ, "3",
100 "Use IEEE Compliant F32 div.rnd if available, no FTZ")),
101 cl::init(NVPTX::DivPrecisionLevel::IEEE754));
102
103 static cl::opt<bool> UsePrecSqrtF32(
104 "nvptx-prec-sqrtf32", cl::Hidden,
105 cl::desc("NVPTX Specific: 0 use sqrt.approx, 1 use sqrt.rn."),
106 cl::init(true));
107
108 /// Whereas CUDA's implementation (see libdevice) uses ex2.approx for exp2(), it
109 /// does NOT use lg2.approx for log2, so this is disabled by default.
110 static cl::opt<bool> UseApproxLog2F32(
111 "nvptx-approx-log2f32",
112 cl::desc("NVPTX Specific: whether to use lg2.approx for log2"),
113 cl::init(false));
114
115 static cl::opt<bool> ForceMinByValParamAlign(
116 "nvptx-force-min-byval-param-align", cl::Hidden,
117 cl::desc("NVPTX Specific: force 4-byte minimal alignment for byval"
118 " params of device functions."),
119 cl::init(false));
120
121 NVPTX::DivPrecisionLevel
getDivF32Level(const MachineFunction & MF,const SDNode & N) const122 NVPTXTargetLowering::getDivF32Level(const MachineFunction &MF,
123 const SDNode &N) const {
124 // If nvptx-prec-div32=N is used on the command-line, always honor it
125 if (UsePrecDivF32.getNumOccurrences() > 0)
126 return UsePrecDivF32;
127
128 // Otherwise, use div.approx if fast math is enabled
129 if (allowUnsafeFPMath(MF))
130 return NVPTX::DivPrecisionLevel::Approx;
131
132 const SDNodeFlags Flags = N.getFlags();
133 if (Flags.hasApproximateFuncs())
134 return NVPTX::DivPrecisionLevel::Approx;
135
136 return NVPTX::DivPrecisionLevel::IEEE754;
137 }
138
usePrecSqrtF32(const MachineFunction & MF,const SDNode * N) const139 bool NVPTXTargetLowering::usePrecSqrtF32(const MachineFunction &MF,
140 const SDNode *N) const {
141 // If nvptx-prec-sqrtf32 is used on the command-line, always honor it
142 if (UsePrecSqrtF32.getNumOccurrences() > 0)
143 return UsePrecSqrtF32;
144
145 // Otherwise, use sqrt.approx if fast math is enabled
146 if (allowUnsafeFPMath(MF))
147 return false;
148
149 if (N) {
150 const SDNodeFlags Flags = N->getFlags();
151 if (Flags.hasApproximateFuncs())
152 return false;
153 }
154
155 return true;
156 }
157
useF32FTZ(const MachineFunction & MF) const158 bool NVPTXTargetLowering::useF32FTZ(const MachineFunction &MF) const {
159 return MF.getDenormalMode(APFloat::IEEEsingle()).Output ==
160 DenormalMode::PreserveSign;
161 }
162
IsPTXVectorType(MVT VT)163 static bool IsPTXVectorType(MVT VT) {
164 switch (VT.SimpleTy) {
165 default:
166 return false;
167 case MVT::v2i1:
168 case MVT::v4i1:
169 case MVT::v2i8:
170 case MVT::v4i8:
171 case MVT::v8i8: // <2 x i8x4>
172 case MVT::v16i8: // <4 x i8x4>
173 case MVT::v2i16:
174 case MVT::v4i16:
175 case MVT::v8i16: // <4 x i16x2>
176 case MVT::v2i32:
177 case MVT::v4i32:
178 case MVT::v2i64:
179 case MVT::v2f16:
180 case MVT::v4f16:
181 case MVT::v8f16: // <4 x f16x2>
182 case MVT::v2bf16:
183 case MVT::v4bf16:
184 case MVT::v8bf16: // <4 x bf16x2>
185 case MVT::v2f32:
186 case MVT::v4f32:
187 case MVT::v2f64:
188 case MVT::v4i64:
189 case MVT::v4f64:
190 case MVT::v8i32:
191 case MVT::v8f32:
192 case MVT::v16f16: // <8 x f16x2>
193 case MVT::v16bf16: // <8 x bf16x2>
194 case MVT::v16i16: // <8 x i16x2>
195 case MVT::v32i8: // <8 x i8x4>
196 return true;
197 }
198 }
199
200 // When legalizing vector loads/stores, this function is called, which does two
201 // things:
202 // 1. Determines Whether the vector is something we want to custom lower,
203 // std::nullopt is returned if we do not want to custom lower it.
204 // 2. If we do want to handle it, returns two parameters:
205 // - unsigned int NumElts - The number of elements in the final vector
206 // - EVT EltVT - The type of the elements in the final vector
207 static std::optional<std::pair<unsigned int, MVT>>
getVectorLoweringShape(EVT VectorEVT,bool CanLowerTo256Bit)208 getVectorLoweringShape(EVT VectorEVT, bool CanLowerTo256Bit) {
209 if (!VectorEVT.isSimple())
210 return std::nullopt;
211 const MVT VectorVT = VectorEVT.getSimpleVT();
212
213 if (!VectorVT.isVector()) {
214 if (VectorVT == MVT::i128 || VectorVT == MVT::f128)
215 return {{2, MVT::i64}};
216 return std::nullopt;
217 }
218
219 const MVT EltVT = VectorVT.getVectorElementType();
220 const unsigned NumElts = VectorVT.getVectorNumElements();
221
222 // The size of the PTX virtual register that holds a packed type.
223 unsigned PackRegSize;
224
225 // We only handle "native" vector sizes for now, e.g. <4 x double> is not
226 // legal. We can (and should) split that into 2 stores of <2 x double> here
227 // but I'm leaving that as a TODO for now.
228 switch (VectorVT.SimpleTy) {
229 default:
230 return std::nullopt;
231 case MVT::v4i64:
232 case MVT::v4f64:
233 case MVT::v8i32:
234 // This is a "native" vector type iff the address space is global
235 // and the target supports 256-bit loads/stores
236 if (!CanLowerTo256Bit)
237 return std::nullopt;
238 LLVM_FALLTHROUGH;
239 case MVT::v2i8:
240 case MVT::v2i32:
241 case MVT::v2i64:
242 case MVT::v2f64:
243 case MVT::v4i32:
244 // This is a "native" vector type
245 return std::pair(NumElts, EltVT);
246 case MVT::v16f16: // <8 x f16x2>
247 case MVT::v16bf16: // <8 x bf16x2>
248 case MVT::v16i16: // <8 x i16x2>
249 case MVT::v32i8: // <8 x i8x4>
250 // This can be upsized into a "native" vector type iff the address space is
251 // global and the target supports 256-bit loads/stores.
252 if (!CanLowerTo256Bit)
253 return std::nullopt;
254 LLVM_FALLTHROUGH;
255 case MVT::v2i16: // <1 x i16x2>
256 case MVT::v2f16: // <1 x f16x2>
257 case MVT::v2bf16: // <1 x bf16x2>
258 case MVT::v4i8: // <1 x i8x4>
259 case MVT::v4i16: // <2 x i16x2>
260 case MVT::v4f16: // <2 x f16x2>
261 case MVT::v4bf16: // <2 x bf16x2>
262 case MVT::v8i8: // <2 x i8x4>
263 case MVT::v8f16: // <4 x f16x2>
264 case MVT::v8bf16: // <4 x bf16x2>
265 case MVT::v8i16: // <4 x i16x2>
266 case MVT::v16i8: // <4 x i8x4>
267 PackRegSize = 32;
268 break;
269 case MVT::v8f32: // <4 x f32x2>
270 if (!CanLowerTo256Bit)
271 return std::nullopt;
272 LLVM_FALLTHROUGH;
273 case MVT::v2f32: // <1 x f32x2>
274 case MVT::v4f32: // <2 x f32x2>
275 PackRegSize = 64;
276 break;
277 }
278
279 // If we reach here, then we can pack 2 or more elements into a single 32-bit
280 // or 64-bit PTX register and treat the vector as a new vector containing
281 // packed elements.
282
283 // Number of elements to pack in one word.
284 const unsigned NPerReg = PackRegSize / EltVT.getSizeInBits();
285
286 return std::pair(NumElts / NPerReg, MVT::getVectorVT(EltVT, NPerReg));
287 }
288
289 /// ComputePTXValueVTs - For the given Type \p Ty, returns the set of primitive
290 /// EVTs that compose it. Unlike ComputeValueVTs, this will break apart vectors
291 /// into their primitive components.
292 /// NOTE: This is a band-aid for code that expects ComputeValueVTs to return the
293 /// same number of types as the Ins/Outs arrays in LowerFormalArguments,
294 /// LowerCall, and LowerReturn.
ComputePTXValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<uint64_t> * Offsets=nullptr,uint64_t StartingOffset=0)295 static void ComputePTXValueVTs(const TargetLowering &TLI, const DataLayout &DL,
296 Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
297 SmallVectorImpl<uint64_t> *Offsets = nullptr,
298 uint64_t StartingOffset = 0) {
299 SmallVector<EVT, 16> TempVTs;
300 SmallVector<uint64_t, 16> TempOffsets;
301
302 // Special case for i128 - decompose to (i64, i64)
303 if (Ty->isIntegerTy(128) || Ty->isFP128Ty()) {
304 ValueVTs.append({MVT::i64, MVT::i64});
305
306 if (Offsets)
307 Offsets->append({StartingOffset + 0, StartingOffset + 8});
308
309 return;
310 }
311
312 // Given a struct type, recursively traverse the elements with custom ComputePTXValueVTs.
313 if (StructType *STy = dyn_cast<StructType>(Ty)) {
314 auto const *SL = DL.getStructLayout(STy);
315 auto ElementNum = 0;
316 for(auto *EI : STy->elements()) {
317 ComputePTXValueVTs(TLI, DL, EI, ValueVTs, Offsets,
318 StartingOffset + SL->getElementOffset(ElementNum));
319 ++ElementNum;
320 }
321 return;
322 }
323
324 // Given an array type, recursively traverse the elements with custom ComputePTXValueVTs.
325 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
326 Type *EltTy = ATy->getElementType();
327 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
328 for (int I : llvm::seq<int>(ATy->getNumElements()))
329 ComputePTXValueVTs(TLI, DL, EltTy, ValueVTs, Offsets, StartingOffset + I * EltSize);
330 return;
331 }
332
333 // Will split structs and arrays into member types, but will not split vector
334 // types. We do that manually below.
335 ComputeValueVTs(TLI, DL, Ty, TempVTs, &TempOffsets, StartingOffset);
336
337 for (auto [VT, Off] : zip(TempVTs, TempOffsets)) {
338 // Split vectors into individual elements that fit into registers.
339 if (VT.isVector()) {
340 unsigned NumElts = VT.getVectorNumElements();
341 EVT EltVT = VT.getVectorElementType();
342 // Below we must maintain power-of-2 sized vectors because
343 // TargetLoweringBase::getVectorTypeBreakdown() which is invoked in
344 // ComputePTXValueVTs() cannot currently break down non-power-of-2 sized
345 // vectors.
346
347 // If the element type belongs to one of the supported packed vector types
348 // then we can pack multiples of this element into a single register.
349 if (VT == MVT::v2i8) {
350 // We can pack 2 i8s into a single 16-bit register. We only do this for
351 // loads and stores, which is why we have a separate case for it.
352 EltVT = MVT::v2i8;
353 NumElts = 1;
354 } else if (VT == MVT::v3i8) {
355 // We can also pack 3 i8s into 32-bit register, leaving the 4th
356 // element undefined.
357 EltVT = MVT::v4i8;
358 NumElts = 1;
359 } else if (NumElts > 1 && isPowerOf2_32(NumElts)) {
360 // Handle default packed types.
361 for (MVT PackedVT : NVPTX::packed_types()) {
362 const auto NumEltsPerReg = PackedVT.getVectorNumElements();
363 if (NumElts % NumEltsPerReg == 0 &&
364 EltVT == PackedVT.getVectorElementType()) {
365 EltVT = PackedVT;
366 NumElts /= NumEltsPerReg;
367 break;
368 }
369 }
370 }
371
372 for (unsigned J : seq(NumElts)) {
373 ValueVTs.push_back(EltVT);
374 if (Offsets)
375 Offsets->push_back(Off + J * EltVT.getStoreSize());
376 }
377 } else {
378 ValueVTs.push_back(VT);
379 if (Offsets)
380 Offsets->push_back(Off);
381 }
382 }
383 }
384
385 /// PromoteScalarIntegerPTX
386 /// Used to make sure the arguments/returns are suitable for passing
387 /// and promote them to a larger size if they're not.
388 ///
389 /// The promoted type is placed in \p PromoteVT if the function returns true.
promoteScalarIntegerPTX(const EVT VT)390 static EVT promoteScalarIntegerPTX(const EVT VT) {
391 if (VT.isScalarInteger()) {
392 switch (PowerOf2Ceil(VT.getFixedSizeInBits())) {
393 default:
394 llvm_unreachable(
395 "Promotion is not suitable for scalars of size larger than 64-bits");
396 case 1:
397 return MVT::i1;
398 case 2:
399 case 4:
400 case 8:
401 return MVT::i8;
402 case 16:
403 return MVT::i16;
404 case 32:
405 return MVT::i32;
406 case 64:
407 return MVT::i64;
408 }
409 }
410 return VT;
411 }
412
413 // Check whether we can merge loads/stores of some of the pieces of a
414 // flattened function parameter or return value into a single vector
415 // load/store.
416 //
417 // The flattened parameter is represented as a list of EVTs and
418 // offsets, and the whole structure is aligned to ParamAlignment. This
419 // function determines whether we can load/store pieces of the
420 // parameter starting at index Idx using a single vectorized op of
421 // size AccessSize. If so, it returns the number of param pieces
422 // covered by the vector op. Otherwise, it returns 1.
CanMergeParamLoadStoresStartingAt(unsigned Idx,uint32_t AccessSize,const SmallVectorImpl<EVT> & ValueVTs,const SmallVectorImpl<uint64_t> & Offsets,Align ParamAlignment)423 static unsigned CanMergeParamLoadStoresStartingAt(
424 unsigned Idx, uint32_t AccessSize, const SmallVectorImpl<EVT> &ValueVTs,
425 const SmallVectorImpl<uint64_t> &Offsets, Align ParamAlignment) {
426
427 // Can't vectorize if param alignment is not sufficient.
428 if (ParamAlignment < AccessSize)
429 return 1;
430 // Can't vectorize if offset is not aligned.
431 if (Offsets[Idx] & (AccessSize - 1))
432 return 1;
433
434 EVT EltVT = ValueVTs[Idx];
435 unsigned EltSize = EltVT.getStoreSize();
436
437 // Element is too large to vectorize.
438 if (EltSize >= AccessSize)
439 return 1;
440
441 unsigned NumElts = AccessSize / EltSize;
442 // Can't vectorize if AccessBytes if not a multiple of EltSize.
443 if (AccessSize != EltSize * NumElts)
444 return 1;
445
446 // We don't have enough elements to vectorize.
447 if (Idx + NumElts > ValueVTs.size())
448 return 1;
449
450 // PTX ISA can only deal with 2- and 4-element vector ops.
451 if (NumElts != 4 && NumElts != 2)
452 return 1;
453
454 for (unsigned j = Idx + 1; j < Idx + NumElts; ++j) {
455 // Types do not match.
456 if (ValueVTs[j] != EltVT)
457 return 1;
458
459 // Elements are not contiguous.
460 if (Offsets[j] - Offsets[j - 1] != EltSize)
461 return 1;
462 }
463 // OK. We can vectorize ValueVTs[i..i+NumElts)
464 return NumElts;
465 }
466
467 // Computes whether and how we can vectorize the loads/stores of a
468 // flattened function parameter or return value.
469 //
470 // The flattened parameter is represented as the list of ValueVTs and
471 // Offsets, and is aligned to ParamAlignment bytes. We return a vector
472 // of the same size as ValueVTs indicating how each piece should be
473 // loaded/stored (i.e. as a scalar, or as part of a vector
474 // load/store).
475 static SmallVector<unsigned, 16>
VectorizePTXValueVTs(const SmallVectorImpl<EVT> & ValueVTs,const SmallVectorImpl<uint64_t> & Offsets,Align ParamAlignment,bool IsVAArg=false)476 VectorizePTXValueVTs(const SmallVectorImpl<EVT> &ValueVTs,
477 const SmallVectorImpl<uint64_t> &Offsets,
478 Align ParamAlignment, bool IsVAArg = false) {
479 // Set vector size to match ValueVTs and mark all elements as
480 // scalars by default.
481
482 if (IsVAArg)
483 return SmallVector<unsigned>(ValueVTs.size(), 1);
484
485 SmallVector<unsigned, 16> VectorInfo;
486
487 const auto GetNumElts = [&](unsigned I) -> unsigned {
488 for (const unsigned AccessSize : {16, 8, 4, 2}) {
489 const unsigned NumElts = CanMergeParamLoadStoresStartingAt(
490 I, AccessSize, ValueVTs, Offsets, ParamAlignment);
491 assert((NumElts == 1 || NumElts == 2 || NumElts == 4) &&
492 "Unexpected vectorization size");
493 if (NumElts != 1)
494 return NumElts;
495 }
496 return 1;
497 };
498
499 // Check what we can vectorize using 128/64/32-bit accesses.
500 for (unsigned I = 0, E = ValueVTs.size(); I != E;) {
501 const unsigned NumElts = GetNumElts(I);
502 VectorInfo.push_back(NumElts);
503 I += NumElts;
504 }
505 assert(std::accumulate(VectorInfo.begin(), VectorInfo.end(), 0u) ==
506 ValueVTs.size());
507 return VectorInfo;
508 }
509
510 // NVPTXTargetLowering Constructor.
NVPTXTargetLowering(const NVPTXTargetMachine & TM,const NVPTXSubtarget & STI)511 NVPTXTargetLowering::NVPTXTargetLowering(const NVPTXTargetMachine &TM,
512 const NVPTXSubtarget &STI)
513 : TargetLowering(TM), nvTM(&TM), STI(STI), GlobalUniqueCallSite(0) {
514 // always lower memset, memcpy, and memmove intrinsics to load/store
515 // instructions, rather
516 // then generating calls to memset, mempcy or memmove.
517 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = (unsigned)0xFFFFFFFF;
518 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = (unsigned) 0xFFFFFFFF;
519 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = (unsigned) 0xFFFFFFFF;
520
521 setBooleanContents(ZeroOrNegativeOneBooleanContent);
522 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
523
524 // Jump is Expensive. Don't create extra control flow for 'and', 'or'
525 // condition branches.
526 setJumpIsExpensive(true);
527
528 // Wide divides are _very_ slow. Try to reduce the width of the divide if
529 // possible.
530 addBypassSlowDiv(64, 32);
531
532 // By default, use the Source scheduling
533 if (sched4reg)
534 setSchedulingPreference(Sched::RegPressure);
535 else
536 setSchedulingPreference(Sched::Source);
537
538 auto setFP16OperationAction = [&](unsigned Op, MVT VT, LegalizeAction Action,
539 LegalizeAction NoF16Action) {
540 bool IsOpSupported = STI.allowFP16Math();
541 switch (Op) {
542 // Several FP16 instructions are available on sm_80 only.
543 case ISD::FMINNUM:
544 case ISD::FMAXNUM:
545 case ISD::FMAXNUM_IEEE:
546 case ISD::FMINNUM_IEEE:
547 case ISD::FMAXIMUM:
548 case ISD::FMINIMUM:
549 IsOpSupported &= STI.getSmVersion() >= 80 && STI.getPTXVersion() >= 70;
550 break;
551 case ISD::FEXP2:
552 IsOpSupported &= STI.getSmVersion() >= 75 && STI.getPTXVersion() >= 70;
553 break;
554 }
555 setOperationAction(Op, VT, IsOpSupported ? Action : NoF16Action);
556 };
557
558 auto setBF16OperationAction = [&](unsigned Op, MVT VT, LegalizeAction Action,
559 LegalizeAction NoBF16Action) {
560 bool IsOpSupported = STI.hasNativeBF16Support(Op);
561 setOperationAction(
562 Op, VT, IsOpSupported ? Action : NoBF16Action);
563 };
564
565 auto setI16x2OperationAction = [&](unsigned Op, MVT VT, LegalizeAction Action,
566 LegalizeAction NoI16x2Action) {
567 bool IsOpSupported = false;
568 // instructions are available on sm_90 only
569 switch (Op) {
570 case ISD::ADD:
571 case ISD::SMAX:
572 case ISD::SMIN:
573 case ISD::UMIN:
574 case ISD::UMAX:
575 IsOpSupported = STI.getSmVersion() >= 90 && STI.getPTXVersion() >= 80;
576 break;
577 }
578 setOperationAction(Op, VT, IsOpSupported ? Action : NoI16x2Action);
579 };
580
581 addRegisterClass(MVT::i1, &NVPTX::B1RegClass);
582 addRegisterClass(MVT::i16, &NVPTX::B16RegClass);
583 addRegisterClass(MVT::v2i16, &NVPTX::B32RegClass);
584 addRegisterClass(MVT::v4i8, &NVPTX::B32RegClass);
585 addRegisterClass(MVT::i32, &NVPTX::B32RegClass);
586 addRegisterClass(MVT::i64, &NVPTX::B64RegClass);
587 addRegisterClass(MVT::f32, &NVPTX::B32RegClass);
588 addRegisterClass(MVT::f64, &NVPTX::B64RegClass);
589 addRegisterClass(MVT::f16, &NVPTX::B16RegClass);
590 addRegisterClass(MVT::v2f16, &NVPTX::B32RegClass);
591 addRegisterClass(MVT::bf16, &NVPTX::B16RegClass);
592 addRegisterClass(MVT::v2bf16, &NVPTX::B32RegClass);
593 addRegisterClass(MVT::v2f32, &NVPTX::B64RegClass);
594
595 // Conversion to/from FP16/FP16x2 is always legal.
596 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
597 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
598 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Expand);
599 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f16, Expand);
600
601 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
602 if (STI.getSmVersion() >= 30 && STI.getPTXVersion() > 31)
603 setOperationAction(ISD::READSTEADYCOUNTER, MVT::i64, Legal);
604
605 setFP16OperationAction(ISD::SETCC, MVT::f16, Legal, Promote);
606 setFP16OperationAction(ISD::SETCC, MVT::v2f16, Legal, Expand);
607
608 // Conversion to/from BFP16/BFP16x2 is always legal.
609 setOperationAction(ISD::BUILD_VECTOR, MVT::v2bf16, Custom);
610 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2bf16, Custom);
611 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2bf16, Expand);
612 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2bf16, Expand);
613
614 setBF16OperationAction(ISD::SETCC, MVT::v2bf16, Legal, Expand);
615 setBF16OperationAction(ISD::SETCC, MVT::bf16, Legal, Promote);
616 if (getOperationAction(ISD::SETCC, MVT::bf16) == Promote)
617 AddPromotedToType(ISD::SETCC, MVT::bf16, MVT::f32);
618
619 // Conversion to/from i16/i16x2 is always legal.
620 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
621 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
622 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Expand);
623 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i16, Expand);
624
625 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i8, Custom);
626 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
627 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
628 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i8, Custom);
629
630 // No support for these operations with v2f32.
631 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f32, Expand);
632 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f32, Expand);
633
634 // Custom conversions to/from v2i8.
635 setOperationAction(ISD::BITCAST, MVT::v2i8, Custom);
636
637 // Only logical ops can be done on v4i8 directly, others must be done
638 // elementwise.
639 setOperationAction(
640 {ISD::ABS, ISD::ADD, ISD::ADDC, ISD::ADDE,
641 ISD::BITREVERSE, ISD::CTLZ, ISD::CTPOP, ISD::CTTZ,
642 ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::FSHL, ISD::FSHR,
643 ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::PARITY,
644 ISD::ROTL, ISD::ROTR, ISD::SADDO, ISD::SADDO_CARRY,
645 ISD::SADDSAT, ISD::SDIV, ISD::SDIVREM, ISD::SELECT_CC,
646 ISD::SETCC, ISD::SHL, ISD::SINT_TO_FP, ISD::SMAX,
647 ISD::SMIN, ISD::SMULO, ISD::SMUL_LOHI, ISD::SRA,
648 ISD::SREM, ISD::SRL, ISD::SSHLSAT, ISD::SSUBO,
649 ISD::SSUBO_CARRY, ISD::SSUBSAT, ISD::SUB, ISD::SUBC,
650 ISD::SUBE, ISD::UADDO, ISD::UADDO_CARRY, ISD::UADDSAT,
651 ISD::UDIV, ISD::UDIVREM, ISD::UINT_TO_FP, ISD::UMAX,
652 ISD::UMIN, ISD::UMULO, ISD::UMUL_LOHI, ISD::UREM,
653 ISD::USHLSAT, ISD::USUBO, ISD::USUBO_CARRY, ISD::VSELECT,
654 ISD::USUBSAT},
655 MVT::v4i8, Expand);
656
657 // Operations not directly supported by NVPTX.
658 for (MVT VT : {MVT::bf16, MVT::f16, MVT::v2bf16, MVT::v2f16, MVT::f32,
659 MVT::v2f32, MVT::f64, MVT::i1, MVT::i8, MVT::i16, MVT::v2i16,
660 MVT::v4i8, MVT::i32, MVT::i64}) {
661 setOperationAction(ISD::SELECT_CC, VT, Expand);
662 setOperationAction(ISD::BR_CC, VT, Expand);
663 }
664
665 // Not directly supported. TLI would attempt to expand operations like
666 // FMINIMUM(v2f32) using invalid SETCC and VSELECT nodes.
667 setOperationAction(ISD::VSELECT, MVT::v2f32, Expand);
668
669 // Some SIGN_EXTEND_INREG can be done using cvt instruction.
670 // For others we will expand to a SHL/SRA pair.
671 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i64, Legal);
672 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
673 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
674 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
675 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
676 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Expand);
677
678 setOperationAction(ISD::SHL_PARTS, MVT::i32 , Custom);
679 setOperationAction(ISD::SRA_PARTS, MVT::i32 , Custom);
680 setOperationAction(ISD::SRL_PARTS, MVT::i32 , Custom);
681 setOperationAction(ISD::SHL_PARTS, MVT::i64 , Custom);
682 setOperationAction(ISD::SRA_PARTS, MVT::i64 , Custom);
683 setOperationAction(ISD::SRL_PARTS, MVT::i64 , Custom);
684
685 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
686 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
687
688 setOperationAction({ISD::ROTL, ISD::ROTR},
689 {MVT::i8, MVT::i16, MVT::v2i16, MVT::i32, MVT::i64},
690 Expand);
691
692 if (STI.hasHWROT32()) {
693 setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Legal);
694 setOperationAction({ISD::ROTL, ISD::ROTR, ISD::FSHL, ISD::FSHR}, MVT::i64,
695 Custom);
696 }
697
698 setOperationAction(ISD::BSWAP, MVT::i16, Expand);
699
700 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
701 setOperationAction(ISD::BRIND, MVT::Other, Expand);
702
703 // We want to legalize constant related memmove and memcopy
704 // intrinsics.
705 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
706
707 // Turn FP extload into load/fpextend
708 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
709 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
710 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::bf16, Expand);
711 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::bf16, Expand);
712 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
713 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, MVT::v2f16, Expand);
714 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
715 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, MVT::v2bf16, Expand);
716 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2bf16, Expand);
717 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand);
718 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Expand);
719 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Expand);
720 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4bf16, Expand);
721 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4bf16, Expand);
722 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Expand);
723 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Expand);
724 setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Expand);
725 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8bf16, Expand);
726 setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8bf16, Expand);
727 // Turn FP truncstore into trunc + store.
728 // FIXME: vector types should also be expanded
729 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
730 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
731 setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
732 setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
733 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
734
735 // PTX does not support load / store predicate registers
736 setOperationAction(ISD::LOAD, MVT::i1, Custom);
737 setOperationAction(ISD::STORE, MVT::i1, Custom);
738
739 for (MVT VT : MVT::integer_valuetypes()) {
740 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
741 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
742 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
743 setTruncStoreAction(VT, MVT::i1, Expand);
744 }
745
746 setCondCodeAction({ISD::SETNE, ISD::SETEQ, ISD::SETUGE, ISD::SETULE,
747 ISD::SETUGT, ISD::SETULT, ISD::SETGT, ISD::SETLT,
748 ISD::SETGE, ISD::SETLE},
749 MVT::i1, Expand);
750
751 // expand extload of vector of integers.
752 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, MVT::v2i16,
753 MVT::v2i8, Expand);
754 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
755
756 // This is legal in NVPTX
757 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
758 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
759 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
760 setOperationAction(ISD::ConstantFP, MVT::bf16, Legal);
761
762 setOperationAction(ISD::DYNAMIC_STACKALLOC, {MVT::i32, MVT::i64}, Custom);
763 setOperationAction({ISD::STACKRESTORE, ISD::STACKSAVE}, MVT::Other, Custom);
764
765 // TRAP can be lowered to PTX trap
766 setOperationAction(ISD::TRAP, MVT::Other, Legal);
767 // DEBUGTRAP can be lowered to PTX brkpt
768 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
769
770 // Register custom handling for vector loads/stores
771 for (MVT VT : MVT::fixedlen_vector_valuetypes())
772 if (IsPTXVectorType(VT))
773 setOperationAction({ISD::LOAD, ISD::STORE, ISD::INTRINSIC_W_CHAIN}, VT,
774 Custom);
775
776 setOperationAction({ISD::LOAD, ISD::STORE, ISD::INTRINSIC_W_CHAIN},
777 {MVT::i128, MVT::f128}, Custom);
778
779 // Support varargs.
780 setOperationAction(ISD::VASTART, MVT::Other, Custom);
781 setOperationAction(ISD::VAARG, MVT::Other, Custom);
782 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
783 setOperationAction(ISD::VAEND, MVT::Other, Expand);
784
785 // Custom handling for i8 intrinsics
786 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
787
788 setOperationAction({ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX},
789 {MVT::i16, MVT::i32, MVT::i64}, Legal);
790
791 setOperationAction({ISD::CTPOP, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, MVT::i16,
792 Promote);
793 setOperationAction({ISD::CTPOP, ISD::CTLZ}, MVT::i32, Legal);
794 setOperationAction({ISD::CTPOP, ISD::CTLZ}, MVT::i64, Custom);
795
796 setI16x2OperationAction(ISD::ABS, MVT::v2i16, Legal, Custom);
797 setI16x2OperationAction(ISD::SMIN, MVT::v2i16, Legal, Custom);
798 setI16x2OperationAction(ISD::SMAX, MVT::v2i16, Legal, Custom);
799 setI16x2OperationAction(ISD::UMIN, MVT::v2i16, Legal, Custom);
800 setI16x2OperationAction(ISD::UMAX, MVT::v2i16, Legal, Custom);
801 setI16x2OperationAction(ISD::CTPOP, MVT::v2i16, Legal, Expand);
802 setI16x2OperationAction(ISD::CTLZ, MVT::v2i16, Legal, Expand);
803
804 setI16x2OperationAction(ISD::ADD, MVT::v2i16, Legal, Custom);
805 setI16x2OperationAction(ISD::SUB, MVT::v2i16, Legal, Custom);
806 setI16x2OperationAction(ISD::MUL, MVT::v2i16, Legal, Custom);
807 setI16x2OperationAction(ISD::SHL, MVT::v2i16, Legal, Custom);
808 setI16x2OperationAction(ISD::SREM, MVT::v2i16, Legal, Custom);
809 setI16x2OperationAction(ISD::UREM, MVT::v2i16, Legal, Custom);
810
811 // Other arithmetic and logic ops are unsupported.
812 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::SRA, ISD::SRL, ISD::MULHS,
813 ISD::MULHU, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
814 ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::SETCC},
815 MVT::v2i16, Expand);
816
817 setOperationAction(ISD::ADDC, MVT::i32, Legal);
818 setOperationAction(ISD::ADDE, MVT::i32, Legal);
819 setOperationAction(ISD::SUBC, MVT::i32, Legal);
820 setOperationAction(ISD::SUBE, MVT::i32, Legal);
821 if (STI.getPTXVersion() >= 43) {
822 setOperationAction(ISD::ADDC, MVT::i64, Legal);
823 setOperationAction(ISD::ADDE, MVT::i64, Legal);
824 setOperationAction(ISD::SUBC, MVT::i64, Legal);
825 setOperationAction(ISD::SUBE, MVT::i64, Legal);
826 }
827
828 setOperationAction(ISD::CTTZ, MVT::i16, Expand);
829 setOperationAction(ISD::CTTZ, MVT::v2i16, Expand);
830 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
831 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
832
833 // PTX does not directly support SELP of i1, so promote to i32 first
834 setOperationAction(ISD::SELECT, MVT::i1, Custom);
835
836 // PTX cannot multiply two i64s in a single instruction.
837 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
838 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
839
840 // We have some custom DAG combine patterns for these nodes
841 setTargetDAGCombine({ISD::ADD, ISD::AND, ISD::EXTRACT_VECTOR_ELT, ISD::FADD,
842 ISD::MUL, ISD::SHL, ISD::SREM, ISD::UREM, ISD::VSELECT,
843 ISD::BUILD_VECTOR, ISD::ADDRSPACECAST, ISD::LOAD,
844 ISD::STORE});
845
846 // setcc for f16x2 and bf16x2 needs special handling to prevent
847 // legalizer's attempt to scalarize it due to v2i1 not being legal.
848 if (STI.allowFP16Math() || STI.hasBF16Math())
849 setTargetDAGCombine(ISD::SETCC);
850
851 // Promote fp16 arithmetic if fp16 hardware isn't available or the
852 // user passed --nvptx-no-fp16-math. The flag is useful because,
853 // although sm_53+ GPUs have some sort of FP16 support in
854 // hardware, only sm_53 and sm_60 have full implementation. Others
855 // only have token amount of hardware and are likely to run faster
856 // by using fp32 units instead.
857 for (const auto &Op : {ISD::FADD, ISD::FMUL, ISD::FSUB, ISD::FMA}) {
858 setFP16OperationAction(Op, MVT::f16, Legal, Promote);
859 setFP16OperationAction(Op, MVT::v2f16, Legal, Expand);
860 setBF16OperationAction(Op, MVT::v2bf16, Legal, Expand);
861 // bf16 must be promoted to f32.
862 setBF16OperationAction(Op, MVT::bf16, Legal, Promote);
863 if (getOperationAction(Op, MVT::bf16) == Promote)
864 AddPromotedToType(Op, MVT::bf16, MVT::f32);
865 setOperationAction(Op, MVT::v2f32,
866 STI.hasF32x2Instructions() ? Legal : Expand);
867 }
868
869 // On SM80, we select add/mul/sub as fma to avoid promotion to float
870 for (const auto &Op : {ISD::FADD, ISD::FMUL, ISD::FSUB}) {
871 for (const auto &VT : {MVT::bf16, MVT::v2bf16}) {
872 if (!STI.hasNativeBF16Support(Op) && STI.hasNativeBF16Support(ISD::FMA)) {
873 setOperationAction(Op, VT, Custom);
874 }
875 }
876 }
877
878 // f16/f16x2 neg was introduced in PTX 60, SM_53.
879 const bool IsFP16FP16x2NegAvailable = STI.getSmVersion() >= 53 &&
880 STI.getPTXVersion() >= 60 &&
881 STI.allowFP16Math();
882 for (const auto &VT : {MVT::f16, MVT::v2f16})
883 setOperationAction(ISD::FNEG, VT,
884 IsFP16FP16x2NegAvailable ? Legal : Expand);
885
886 setBF16OperationAction(ISD::FNEG, MVT::bf16, Legal, Expand);
887 setBF16OperationAction(ISD::FNEG, MVT::v2bf16, Legal, Expand);
888 setOperationAction(ISD::FNEG, MVT::v2f32, Expand);
889 // (would be) Library functions.
890
891 // These map to conversion instructions for scalar FP types.
892 for (const auto &Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, ISD::FRINT,
893 ISD::FROUNDEVEN, ISD::FTRUNC}) {
894 setOperationAction(Op, MVT::f16, Legal);
895 setOperationAction(Op, MVT::f32, Legal);
896 setOperationAction(Op, MVT::f64, Legal);
897 setOperationAction(Op, MVT::v2f16, Expand);
898 setOperationAction(Op, MVT::v2bf16, Expand);
899 setOperationAction(Op, MVT::v2f32, Expand);
900 setBF16OperationAction(Op, MVT::bf16, Legal, Promote);
901 if (getOperationAction(Op, MVT::bf16) == Promote)
902 AddPromotedToType(Op, MVT::bf16, MVT::f32);
903 }
904
905 if (STI.getSmVersion() < 80 || STI.getPTXVersion() < 71) {
906 setOperationAction(ISD::BF16_TO_FP, MVT::f32, Expand);
907 }
908 if (STI.getSmVersion() < 90 || STI.getPTXVersion() < 78) {
909 for (MVT VT : {MVT::bf16, MVT::f32, MVT::f64}) {
910 setOperationAction(ISD::FP_EXTEND, VT, Custom);
911 setOperationAction(ISD::FP_ROUND, VT, Custom);
912 }
913 }
914
915 // Expand v2f32 = fp_extend
916 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
917 // Expand v2[b]f16 = fp_round v2f32
918 setOperationAction(ISD::FP_ROUND, {MVT::v2bf16, MVT::v2f16}, Expand);
919
920 // sm_80 only has conversions between f32 and bf16. Custom lower all other
921 // bf16 conversions.
922 if (STI.getSmVersion() < 90 || STI.getPTXVersion() < 78) {
923 for (MVT VT : {MVT::i1, MVT::i16, MVT::i32, MVT::i64}) {
924 setOperationAction(
925 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
926 VT, Custom);
927 }
928 setOperationAction(
929 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
930 MVT::bf16, Custom);
931 }
932
933 setOperationAction(ISD::FROUND, MVT::f16, Promote);
934 setOperationAction(ISD::FROUND, MVT::v2f16, Expand);
935 setOperationAction(ISD::FROUND, MVT::v2bf16, Expand);
936 setOperationAction(ISD::FROUND, MVT::f32, Custom);
937 setOperationAction(ISD::FROUND, MVT::f64, Custom);
938 setOperationAction(ISD::FROUND, MVT::bf16, Promote);
939 AddPromotedToType(ISD::FROUND, MVT::bf16, MVT::f32);
940
941 // 'Expand' implements FCOPYSIGN without calling an external library.
942 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
943 setOperationAction(ISD::FCOPYSIGN, MVT::v2f16, Expand);
944 setOperationAction(ISD::FCOPYSIGN, MVT::bf16, Expand);
945 setOperationAction(ISD::FCOPYSIGN, MVT::v2bf16, Expand);
946 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
947 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
948
949 // These map to corresponding instructions for f32/f64. f16 must be
950 // promoted to f32. v2f16 is expanded to f16, which is then promoted
951 // to f32.
952 for (const auto &Op :
953 {ISD::FDIV, ISD::FREM, ISD::FSQRT, ISD::FSIN, ISD::FCOS}) {
954 setOperationAction(Op, MVT::f16, Promote);
955 setOperationAction(Op, MVT::f32, Legal);
956 setOperationAction(Op, MVT::f64, Legal);
957 setOperationAction(Op, {MVT::v2f16, MVT::v2bf16, MVT::v2f32}, Expand);
958 setOperationAction(Op, MVT::bf16, Promote);
959 AddPromotedToType(Op, MVT::bf16, MVT::f32);
960 }
961 setOperationAction(ISD::FREM, {MVT::f32, MVT::f64}, Custom);
962
963 setOperationAction(ISD::FABS, {MVT::f32, MVT::f64}, Legal);
964 setOperationAction(ISD::FABS, MVT::v2f32, Expand);
965 if (STI.getPTXVersion() >= 65) {
966 setFP16OperationAction(ISD::FABS, MVT::f16, Legal, Promote);
967 setFP16OperationAction(ISD::FABS, MVT::v2f16, Legal, Expand);
968 } else {
969 setOperationAction(ISD::FABS, MVT::f16, Promote);
970 setOperationAction(ISD::FABS, MVT::v2f16, Expand);
971 }
972 setBF16OperationAction(ISD::FABS, MVT::v2bf16, Legal, Expand);
973 setBF16OperationAction(ISD::FABS, MVT::bf16, Legal, Promote);
974 if (getOperationAction(ISD::FABS, MVT::bf16) == Promote)
975 AddPromotedToType(ISD::FABS, MVT::bf16, MVT::f32);
976
977 for (const auto &Op : {ISD::FMINNUM, ISD::FMAXNUM}) {
978 setOperationAction(Op, MVT::f32, Legal);
979 setOperationAction(Op, MVT::f64, Legal);
980 setFP16OperationAction(Op, MVT::f16, Legal, Promote);
981 setFP16OperationAction(Op, MVT::v2f16, Legal, Expand);
982 setBF16OperationAction(Op, MVT::v2bf16, Legal, Expand);
983 setBF16OperationAction(Op, MVT::bf16, Legal, Promote);
984 if (getOperationAction(Op, MVT::bf16) == Promote)
985 AddPromotedToType(Op, MVT::bf16, MVT::f32);
986 setOperationAction(Op, MVT::v2f32, Expand);
987 }
988 bool SupportsF32MinMaxNaN =
989 STI.getSmVersion() >= 80 && STI.getPTXVersion() >= 70;
990 for (const auto &Op : {ISD::FMINIMUM, ISD::FMAXIMUM}) {
991 setOperationAction(Op, MVT::f32, SupportsF32MinMaxNaN ? Legal : Expand);
992 setFP16OperationAction(Op, MVT::f16, Legal, Expand);
993 setFP16OperationAction(Op, MVT::v2f16, Legal, Expand);
994 setBF16OperationAction(Op, MVT::bf16, Legal, Expand);
995 setBF16OperationAction(Op, MVT::v2bf16, Legal, Expand);
996 setOperationAction(Op, MVT::v2f32, Expand);
997 }
998
999 // Custom lowering for inline asm with 128-bit operands
1000 setOperationAction(ISD::CopyToReg, MVT::i128, Custom);
1001 setOperationAction(ISD::CopyFromReg, MVT::i128, Custom);
1002
1003 // FEXP2 support:
1004 // - f32
1005 // - f16/f16x2 (sm_70+, PTX 7.0+)
1006 // - bf16/bf16x2 (sm_90+, PTX 7.8+)
1007 // When f16/bf16 types aren't supported, they are promoted/expanded to f32.
1008 setOperationAction(ISD::FEXP2, MVT::f32, Legal);
1009 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
1010 setFP16OperationAction(ISD::FEXP2, MVT::f16, Legal, Promote);
1011 setFP16OperationAction(ISD::FEXP2, MVT::v2f16, Legal, Expand);
1012 setBF16OperationAction(ISD::FEXP2, MVT::bf16, Legal, Promote);
1013 setBF16OperationAction(ISD::FEXP2, MVT::v2bf16, Legal, Expand);
1014
1015 // FLOG2 supports f32 only
1016 // f16/bf16 types aren't supported, but they are promoted/expanded to f32.
1017 if (UseApproxLog2F32) {
1018 setOperationAction(ISD::FLOG2, MVT::f32, Legal);
1019 setOperationPromotedToType(ISD::FLOG2, MVT::f16, MVT::f32);
1020 setOperationPromotedToType(ISD::FLOG2, MVT::bf16, MVT::f32);
1021 setOperationAction(ISD::FLOG2, {MVT::v2f16, MVT::v2bf16, MVT::v2f32},
1022 Expand);
1023 }
1024
1025 setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
1026
1027 setOperationAction(ISD::ATOMIC_LOAD_SUB, {MVT::i32, MVT::i64}, Expand);
1028 // No FPOW or FREM in PTX.
1029
1030 // Now deduce the information based on the above mentioned
1031 // actions
1032 computeRegisterProperties(STI.getRegisterInfo());
1033
1034 // PTX support for 16-bit CAS is emulated. Only use 32+
1035 setMinCmpXchgSizeInBits(STI.getMinCmpXchgSizeInBits());
1036 setMaxAtomicSizeInBitsSupported(64);
1037 setMaxDivRemBitWidthSupported(64);
1038
1039 // Custom lowering for tcgen05.ld vector operands
1040 setOperationAction(ISD::INTRINSIC_W_CHAIN,
1041 {MVT::v2i32, MVT::v4i32, MVT::v8i32, MVT::v16i32,
1042 MVT::v32i32, MVT::v64i32, MVT::v128i32},
1043 Custom);
1044
1045 // Custom lowering for tcgen05.st vector operands
1046 setOperationAction(ISD::INTRINSIC_VOID,
1047 {MVT::v2i32, MVT::v4i32, MVT::v8i32, MVT::v16i32,
1048 MVT::v32i32, MVT::v64i32, MVT::v128i32},
1049 Custom);
1050
1051 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1052 // Enable custom lowering for the i128 bit operand with clusterlaunchcontrol
1053 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i128, Custom);
1054 }
1055
getTargetNodeName(unsigned Opcode) const1056 const char *NVPTXTargetLowering::getTargetNodeName(unsigned Opcode) const {
1057
1058 #define MAKE_CASE(V) \
1059 case V: \
1060 return #V;
1061
1062 switch ((NVPTXISD::NodeType)Opcode) {
1063 case NVPTXISD::FIRST_NUMBER:
1064 break;
1065
1066 MAKE_CASE(NVPTXISD::RET_GLUE)
1067 MAKE_CASE(NVPTXISD::DeclareArrayParam)
1068 MAKE_CASE(NVPTXISD::DeclareScalarParam)
1069 MAKE_CASE(NVPTXISD::CALL)
1070 MAKE_CASE(NVPTXISD::LoadParam)
1071 MAKE_CASE(NVPTXISD::LoadParamV2)
1072 MAKE_CASE(NVPTXISD::LoadParamV4)
1073 MAKE_CASE(NVPTXISD::StoreParam)
1074 MAKE_CASE(NVPTXISD::StoreParamV2)
1075 MAKE_CASE(NVPTXISD::StoreParamV4)
1076 MAKE_CASE(NVPTXISD::MoveParam)
1077 MAKE_CASE(NVPTXISD::UNPACK_VECTOR)
1078 MAKE_CASE(NVPTXISD::BUILD_VECTOR)
1079 MAKE_CASE(NVPTXISD::CallPrototype)
1080 MAKE_CASE(NVPTXISD::ProxyReg)
1081 MAKE_CASE(NVPTXISD::LoadV2)
1082 MAKE_CASE(NVPTXISD::LoadV4)
1083 MAKE_CASE(NVPTXISD::LoadV8)
1084 MAKE_CASE(NVPTXISD::LDUV2)
1085 MAKE_CASE(NVPTXISD::LDUV4)
1086 MAKE_CASE(NVPTXISD::StoreV2)
1087 MAKE_CASE(NVPTXISD::StoreV4)
1088 MAKE_CASE(NVPTXISD::StoreV8)
1089 MAKE_CASE(NVPTXISD::FSHL_CLAMP)
1090 MAKE_CASE(NVPTXISD::FSHR_CLAMP)
1091 MAKE_CASE(NVPTXISD::BFI)
1092 MAKE_CASE(NVPTXISD::PRMT)
1093 MAKE_CASE(NVPTXISD::FCOPYSIGN)
1094 MAKE_CASE(NVPTXISD::DYNAMIC_STACKALLOC)
1095 MAKE_CASE(NVPTXISD::STACKRESTORE)
1096 MAKE_CASE(NVPTXISD::STACKSAVE)
1097 MAKE_CASE(NVPTXISD::SETP_F16X2)
1098 MAKE_CASE(NVPTXISD::SETP_BF16X2)
1099 MAKE_CASE(NVPTXISD::MUL_WIDE_SIGNED)
1100 MAKE_CASE(NVPTXISD::MUL_WIDE_UNSIGNED)
1101 MAKE_CASE(NVPTXISD::BrxEnd)
1102 MAKE_CASE(NVPTXISD::BrxItem)
1103 MAKE_CASE(NVPTXISD::BrxStart)
1104 MAKE_CASE(NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_IS_CANCELED)
1105 MAKE_CASE(NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_X)
1106 MAKE_CASE(NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_Y)
1107 MAKE_CASE(NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_Z)
1108 }
1109 return nullptr;
1110
1111 #undef MAKE_CASE
1112 }
1113
1114 TargetLoweringBase::LegalizeTypeAction
getPreferredVectorAction(MVT VT) const1115 NVPTXTargetLowering::getPreferredVectorAction(MVT VT) const {
1116 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1117 VT.getScalarType() == MVT::i1)
1118 return TypeSplitVector;
1119 return TargetLoweringBase::getPreferredVectorAction(VT);
1120 }
1121
getSqrtEstimate(SDValue Operand,SelectionDAG & DAG,int Enabled,int & ExtraSteps,bool & UseOneConst,bool Reciprocal) const1122 SDValue NVPTXTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
1123 int Enabled, int &ExtraSteps,
1124 bool &UseOneConst,
1125 bool Reciprocal) const {
1126 if (!(Enabled == ReciprocalEstimate::Enabled ||
1127 (Enabled == ReciprocalEstimate::Unspecified &&
1128 !usePrecSqrtF32(DAG.getMachineFunction()))))
1129 return SDValue();
1130
1131 if (ExtraSteps == ReciprocalEstimate::Unspecified)
1132 ExtraSteps = 0;
1133
1134 SDLoc DL(Operand);
1135 EVT VT = Operand.getValueType();
1136 bool Ftz = useF32FTZ(DAG.getMachineFunction());
1137
1138 auto MakeIntrinsicCall = [&](Intrinsic::ID IID) {
1139 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
1140 DAG.getConstant(IID, DL, MVT::i32), Operand);
1141 };
1142
1143 // The sqrt and rsqrt refinement processes assume we always start out with an
1144 // approximation of the rsqrt. Therefore, if we're going to do any refinement
1145 // (i.e. ExtraSteps > 0), we must return an rsqrt. But if we're *not* doing
1146 // any refinement, we must return a regular sqrt.
1147 if (Reciprocal || ExtraSteps > 0) {
1148 if (VT == MVT::f32)
1149 return MakeIntrinsicCall(Ftz ? Intrinsic::nvvm_rsqrt_approx_ftz_f
1150 : Intrinsic::nvvm_rsqrt_approx_f);
1151 else if (VT == MVT::f64)
1152 return MakeIntrinsicCall(Intrinsic::nvvm_rsqrt_approx_d);
1153 else
1154 return SDValue();
1155 } else {
1156 if (VT == MVT::f32)
1157 return MakeIntrinsicCall(Ftz ? Intrinsic::nvvm_sqrt_approx_ftz_f
1158 : Intrinsic::nvvm_sqrt_approx_f);
1159 else {
1160 // There's no sqrt.approx.f64 instruction, so we emit
1161 // reciprocal(rsqrt(x)). This is faster than
1162 // select(x == 0, 0, x * rsqrt(x)). (In fact, it's faster than plain
1163 // x * rsqrt(x).)
1164 return DAG.getNode(
1165 ISD::INTRINSIC_WO_CHAIN, DL, VT,
1166 DAG.getConstant(Intrinsic::nvvm_rcp_approx_ftz_d, DL, MVT::i32),
1167 MakeIntrinsicCall(Intrinsic::nvvm_rsqrt_approx_d));
1168 }
1169 }
1170 }
1171
getPrototype(const DataLayout & DL,Type * RetTy,const ArgListTy & Args,const SmallVectorImpl<ISD::OutputArg> & Outs,std::optional<unsigned> FirstVAArg,const CallBase & CB,unsigned UniqueCallSite) const1172 std::string NVPTXTargetLowering::getPrototype(
1173 const DataLayout &DL, Type *RetTy, const ArgListTy &Args,
1174 const SmallVectorImpl<ISD::OutputArg> &Outs,
1175 std::optional<unsigned> FirstVAArg, const CallBase &CB,
1176 unsigned UniqueCallSite) const {
1177 auto PtrVT = getPointerTy(DL);
1178
1179 std::string Prototype;
1180 raw_string_ostream O(Prototype);
1181 O << "prototype_" << UniqueCallSite << " : .callprototype ";
1182
1183 if (RetTy->isVoidTy()) {
1184 O << "()";
1185 } else {
1186 O << "(";
1187 if (shouldPassAsArray(RetTy)) {
1188 const Align RetAlign = getArgumentAlignment(&CB, RetTy, 0, DL);
1189 O << ".param .align " << RetAlign.value() << " .b8 _["
1190 << DL.getTypeAllocSize(RetTy) << "]";
1191 } else if (RetTy->isFloatingPointTy() || RetTy->isIntegerTy()) {
1192 unsigned size = 0;
1193 if (auto *ITy = dyn_cast<IntegerType>(RetTy)) {
1194 size = ITy->getBitWidth();
1195 } else {
1196 assert(RetTy->isFloatingPointTy() &&
1197 "Floating point type expected here");
1198 size = RetTy->getPrimitiveSizeInBits();
1199 }
1200 // PTX ABI requires all scalar return values to be at least 32
1201 // bits in size. fp16 normally uses .b16 as its storage type in
1202 // PTX, so its size must be adjusted here, too.
1203 size = promoteScalarArgumentSize(size);
1204
1205 O << ".param .b" << size << " _";
1206 } else if (isa<PointerType>(RetTy)) {
1207 O << ".param .b" << PtrVT.getSizeInBits() << " _";
1208 } else {
1209 llvm_unreachable("Unknown return type");
1210 }
1211 O << ") ";
1212 }
1213 O << "_ (";
1214
1215 bool first = true;
1216
1217 const unsigned NumArgs = FirstVAArg.value_or(Args.size());
1218 auto AllOuts = ArrayRef(Outs);
1219 for (const unsigned I : llvm::seq(NumArgs)) {
1220 const auto ArgOuts =
1221 AllOuts.take_while([I](auto O) { return O.OrigArgIndex == I; });
1222 AllOuts = AllOuts.drop_front(ArgOuts.size());
1223
1224 Type *Ty = Args[I].Ty;
1225 if (!first) {
1226 O << ", ";
1227 }
1228 first = false;
1229
1230 if (ArgOuts[0].Flags.isByVal()) {
1231 // Indirect calls need strict ABI alignment so we disable optimizations by
1232 // not providing a function to optimize.
1233 Type *ETy = Args[I].IndirectType;
1234 Align InitialAlign = ArgOuts[0].Flags.getNonZeroByValAlign();
1235 Align ParamByValAlign =
1236 getFunctionByValParamAlign(/*F=*/nullptr, ETy, InitialAlign, DL);
1237
1238 O << ".param .align " << ParamByValAlign.value() << " .b8 _["
1239 << ArgOuts[0].Flags.getByValSize() << "]";
1240 } else {
1241 if (shouldPassAsArray(Ty)) {
1242 Align ParamAlign =
1243 getArgumentAlignment(&CB, Ty, I + AttributeList::FirstArgIndex, DL);
1244 O << ".param .align " << ParamAlign.value() << " .b8 _["
1245 << DL.getTypeAllocSize(Ty) << "]";
1246 continue;
1247 }
1248 // i8 types in IR will be i16 types in SDAG
1249 assert((getValueType(DL, Ty) == ArgOuts[0].VT ||
1250 (getValueType(DL, Ty) == MVT::i8 && ArgOuts[0].VT == MVT::i16)) &&
1251 "type mismatch between callee prototype and arguments");
1252 // scalar type
1253 unsigned sz = 0;
1254 if (auto *ITy = dyn_cast<IntegerType>(Ty)) {
1255 sz = promoteScalarArgumentSize(ITy->getBitWidth());
1256 } else if (isa<PointerType>(Ty)) {
1257 sz = PtrVT.getSizeInBits();
1258 } else {
1259 sz = Ty->getPrimitiveSizeInBits();
1260 }
1261 O << ".param .b" << sz << " _";
1262 }
1263 }
1264
1265 if (FirstVAArg)
1266 O << (first ? "" : ",") << " .param .align "
1267 << STI.getMaxRequiredAlignment() << " .b8 _[]";
1268 O << ")";
1269 if (shouldEmitPTXNoReturn(&CB, *nvTM))
1270 O << " .noreturn";
1271 O << ";";
1272
1273 return Prototype;
1274 }
1275
getFunctionArgumentAlignment(const Function * F,Type * Ty,unsigned Idx,const DataLayout & DL) const1276 Align NVPTXTargetLowering::getFunctionArgumentAlignment(
1277 const Function *F, Type *Ty, unsigned Idx, const DataLayout &DL) const {
1278 return getAlign(*F, Idx).value_or(getFunctionParamOptimizedAlign(F, Ty, DL));
1279 }
1280
getArgumentAlignment(const CallBase * CB,Type * Ty,unsigned Idx,const DataLayout & DL) const1281 Align NVPTXTargetLowering::getArgumentAlignment(const CallBase *CB, Type *Ty,
1282 unsigned Idx,
1283 const DataLayout &DL) const {
1284 if (!CB) {
1285 // CallSite is zero, fallback to ABI type alignment
1286 return DL.getABITypeAlign(Ty);
1287 }
1288
1289 const Function *DirectCallee = CB->getCalledFunction();
1290
1291 if (!DirectCallee) {
1292 // We don't have a direct function symbol, but that may be because of
1293 // constant cast instructions in the call.
1294
1295 // With bitcast'd call targets, the instruction will be the call
1296 if (const auto *CI = dyn_cast<CallInst>(CB)) {
1297 // Check if we have call alignment metadata
1298 if (MaybeAlign StackAlign = getAlign(*CI, Idx))
1299 return StackAlign.value();
1300 }
1301 DirectCallee = getMaybeBitcastedCallee(CB);
1302 }
1303
1304 // Check for function alignment information if we found that the
1305 // ultimate target is a Function
1306 if (DirectCallee)
1307 return getFunctionArgumentAlignment(DirectCallee, Ty, Idx, DL);
1308
1309 // Call is indirect, fall back to the ABI type alignment
1310 return DL.getABITypeAlign(Ty);
1311 }
1312
adjustElementType(EVT & ElementType)1313 static bool adjustElementType(EVT &ElementType) {
1314 switch (ElementType.getSimpleVT().SimpleTy) {
1315 default:
1316 return false;
1317 case MVT::f16:
1318 case MVT::bf16:
1319 ElementType = MVT::i16;
1320 return true;
1321 case MVT::f32:
1322 case MVT::v2f16:
1323 case MVT::v2bf16:
1324 ElementType = MVT::i32;
1325 return true;
1326 case MVT::f64:
1327 ElementType = MVT::i64;
1328 return true;
1329 }
1330 }
1331
1332 // Use byte-store when the param address of the argument value is unaligned.
1333 // This may happen when the return value is a field of a packed structure.
1334 //
1335 // This is called in LowerCall() when passing the param values.
LowerUnalignedStoreParam(SelectionDAG & DAG,SDValue Chain,uint64_t Offset,EVT ElementType,SDValue StVal,SDValue & InGlue,unsigned ArgID,const SDLoc & dl)1336 static SDValue LowerUnalignedStoreParam(SelectionDAG &DAG, SDValue Chain,
1337 uint64_t Offset, EVT ElementType,
1338 SDValue StVal, SDValue &InGlue,
1339 unsigned ArgID, const SDLoc &dl) {
1340 // Bit logic only works on integer types
1341 if (adjustElementType(ElementType))
1342 StVal = DAG.getNode(ISD::BITCAST, dl, ElementType, StVal);
1343
1344 // Store each byte
1345 SDVTList StoreVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1346 for (unsigned i = 0, n = ElementType.getSizeInBits() / 8; i < n; i++) {
1347 // Shift the byte to the last byte position
1348 SDValue ShiftVal = DAG.getNode(ISD::SRL, dl, ElementType, StVal,
1349 DAG.getConstant(i * 8, dl, MVT::i32));
1350 SDValue StoreOperands[] = {Chain, DAG.getConstant(ArgID, dl, MVT::i32),
1351 DAG.getConstant(Offset + i, dl, MVT::i32),
1352 ShiftVal, InGlue};
1353 // Trunc store only the last byte by using
1354 // st.param.b8
1355 // The register type can be larger than b8.
1356 Chain = DAG.getMemIntrinsicNode(
1357 NVPTXISD::StoreParam, dl, StoreVTs, StoreOperands, MVT::i8,
1358 MachinePointerInfo(), Align(1), MachineMemOperand::MOStore);
1359 InGlue = Chain.getValue(1);
1360 }
1361 return Chain;
1362 }
1363
1364 // Use byte-load when the param adress of the returned value is unaligned.
1365 // This may happen when the returned value is a field of a packed structure.
1366 static SDValue
LowerUnalignedLoadRetParam(SelectionDAG & DAG,SDValue & Chain,uint64_t Offset,EVT ElementType,SDValue & InGlue,SmallVectorImpl<SDValue> & TempProxyRegOps,const SDLoc & dl)1367 LowerUnalignedLoadRetParam(SelectionDAG &DAG, SDValue &Chain, uint64_t Offset,
1368 EVT ElementType, SDValue &InGlue,
1369 SmallVectorImpl<SDValue> &TempProxyRegOps,
1370 const SDLoc &dl) {
1371 // Bit logic only works on integer types
1372 EVT MergedType = ElementType;
1373 adjustElementType(MergedType);
1374
1375 // Load each byte and construct the whole value. Initial value to 0
1376 SDValue RetVal = DAG.getConstant(0, dl, MergedType);
1377 // LoadParamMemI8 loads into i16 register only
1378 SDVTList LoadVTs = DAG.getVTList(MVT::i16, MVT::Other, MVT::Glue);
1379 for (unsigned i = 0, n = ElementType.getSizeInBits() / 8; i < n; i++) {
1380 SDValue LoadOperands[] = {Chain, DAG.getConstant(1, dl, MVT::i32),
1381 DAG.getConstant(Offset + i, dl, MVT::i32),
1382 InGlue};
1383 // This will be selected to LoadParamMemI8
1384 SDValue LdVal =
1385 DAG.getMemIntrinsicNode(NVPTXISD::LoadParam, dl, LoadVTs, LoadOperands,
1386 MVT::i8, MachinePointerInfo(), Align(1));
1387 SDValue TmpLdVal = LdVal.getValue(0);
1388 Chain = LdVal.getValue(1);
1389 InGlue = LdVal.getValue(2);
1390
1391 TmpLdVal = DAG.getNode(NVPTXISD::ProxyReg, dl,
1392 TmpLdVal.getSimpleValueType(), TmpLdVal);
1393 TempProxyRegOps.push_back(TmpLdVal);
1394
1395 SDValue CMask = DAG.getConstant(255, dl, MergedType);
1396 SDValue CShift = DAG.getConstant(i * 8, dl, MVT::i32);
1397 // Need to extend the i16 register to the whole width.
1398 TmpLdVal = DAG.getNode(ISD::ZERO_EXTEND, dl, MergedType, TmpLdVal);
1399 // Mask off the high bits. Leave only the lower 8bits.
1400 // Do this because we are using loadparam.b8.
1401 TmpLdVal = DAG.getNode(ISD::AND, dl, MergedType, TmpLdVal, CMask);
1402 // Shift and merge
1403 TmpLdVal = DAG.getNode(ISD::SHL, dl, MergedType, TmpLdVal, CShift);
1404 RetVal = DAG.getNode(ISD::OR, dl, MergedType, RetVal, TmpLdVal);
1405 }
1406 if (ElementType != MergedType)
1407 RetVal = DAG.getNode(ISD::BITCAST, dl, ElementType, RetVal);
1408
1409 return RetVal;
1410 }
1411
shouldConvertToIndirectCall(const CallBase * CB,const GlobalAddressSDNode * Func)1412 static bool shouldConvertToIndirectCall(const CallBase *CB,
1413 const GlobalAddressSDNode *Func) {
1414 if (!Func)
1415 return false;
1416 if (auto *CalleeFunc = dyn_cast<Function>(Func->getGlobal()))
1417 return CB->getFunctionType() != CalleeFunc->getFunctionType();
1418 return false;
1419 }
1420
refinePtrAS(SDValue & Ptr,SelectionDAG & DAG,const DataLayout & DL,const TargetLowering & TL)1421 static MachinePointerInfo refinePtrAS(SDValue &Ptr, SelectionDAG &DAG,
1422 const DataLayout &DL,
1423 const TargetLowering &TL) {
1424 if (Ptr->getOpcode() == ISD::FrameIndex) {
1425 auto Ty = TL.getPointerTy(DL, ADDRESS_SPACE_LOCAL);
1426 Ptr = DAG.getAddrSpaceCast(SDLoc(), Ty, Ptr, ADDRESS_SPACE_GENERIC,
1427 ADDRESS_SPACE_LOCAL);
1428
1429 return MachinePointerInfo(ADDRESS_SPACE_LOCAL);
1430 }
1431
1432 // Peel of an addrspacecast to generic and load directly from the specific
1433 // address space.
1434 if (Ptr->getOpcode() == ISD::ADDRSPACECAST) {
1435 const auto *ASC = cast<AddrSpaceCastSDNode>(Ptr);
1436 if (ASC->getDestAddressSpace() == ADDRESS_SPACE_GENERIC) {
1437 Ptr = ASC->getOperand(0);
1438 return MachinePointerInfo(ASC->getSrcAddressSpace());
1439 }
1440 }
1441
1442 return MachinePointerInfo();
1443 }
1444
getExtOpcode(const ISD::ArgFlagsTy & Flags)1445 static ISD::NodeType getExtOpcode(const ISD::ArgFlagsTy &Flags) {
1446 if (Flags.isSExt())
1447 return ISD::SIGN_EXTEND;
1448 if (Flags.isZExt())
1449 return ISD::ZERO_EXTEND;
1450 return ISD::ANY_EXTEND;
1451 }
1452
correctParamType(SDValue V,EVT ExpectedVT,ISD::ArgFlagsTy Flags,SelectionDAG & DAG,SDLoc dl)1453 static SDValue correctParamType(SDValue V, EVT ExpectedVT,
1454 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1455 SDLoc dl) {
1456 const EVT ActualVT = V.getValueType();
1457 assert((ActualVT == ExpectedVT ||
1458 (ExpectedVT.isInteger() && ActualVT.isInteger())) &&
1459 "Non-integer argument type size mismatch");
1460 if (ExpectedVT.bitsGT(ActualVT))
1461 return DAG.getNode(getExtOpcode(Flags), dl, ExpectedVT, V);
1462 if (ExpectedVT.bitsLT(ActualVT))
1463 return DAG.getNode(ISD::TRUNCATE, dl, ExpectedVT, V);
1464
1465 return V;
1466 }
1467
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const1468 SDValue NVPTXTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1469 SmallVectorImpl<SDValue> &InVals) const {
1470
1471 if (CLI.IsVarArg && (STI.getPTXVersion() < 60 || STI.getSmVersion() < 30))
1472 report_fatal_error(
1473 "Support for variadic functions (unsized array parameter) introduced "
1474 "in PTX ISA version 6.0 and requires target sm_30.");
1475
1476 SelectionDAG &DAG = CLI.DAG;
1477 SDLoc dl = CLI.DL;
1478 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1479 SDValue Chain = CLI.Chain;
1480 SDValue Callee = CLI.Callee;
1481 bool &isTailCall = CLI.IsTailCall;
1482 ArgListTy &Args = CLI.getArgs();
1483 Type *RetTy = CLI.RetTy;
1484 const CallBase *CB = CLI.CB;
1485 const DataLayout &DL = DAG.getDataLayout();
1486
1487 const auto GetI32 = [&](const unsigned I) {
1488 return DAG.getConstant(I, dl, MVT::i32);
1489 };
1490
1491 // Variadic arguments.
1492 //
1493 // Normally, for each argument, we declare a param scalar or a param
1494 // byte array in the .param space, and store the argument value to that
1495 // param scalar or array starting at offset 0.
1496 //
1497 // In the case of the first variadic argument, we declare a vararg byte array
1498 // with size 0. The exact size of this array isn't known at this point, so
1499 // it'll be patched later. All the variadic arguments will be stored to this
1500 // array at a certain offset (which gets tracked by 'VAOffset'). The offset is
1501 // initially set to 0, so it can be used for non-variadic arguments (which use
1502 // 0 offset) to simplify the code.
1503 //
1504 // After all vararg is processed, 'VAOffset' holds the size of the
1505 // vararg byte array.
1506
1507 SDValue VADeclareParam; // vararg byte array
1508 const unsigned FirstVAArg = CLI.NumFixedArgs; // position of first variadic
1509 unsigned VAOffset = 0; // current offset in the param array
1510
1511 const unsigned UniqueCallSite = GlobalUniqueCallSite++;
1512 SDValue TempChain = Chain;
1513 Chain = DAG.getCALLSEQ_START(Chain, UniqueCallSite, 0, dl);
1514 SDValue InGlue = Chain.getValue(1);
1515
1516 // Args.size() and Outs.size() need not match.
1517 // Outs.size() will be larger
1518 // * if there is an aggregate argument with multiple fields (each field
1519 // showing up separately in Outs)
1520 // * if there is a vector argument with more than typical vector-length
1521 // elements (generally if more than 4) where each vector element is
1522 // individually present in Outs.
1523 // So a different index should be used for indexing into Outs/OutVals.
1524 // See similar issue in LowerFormalArguments.
1525 auto AllOuts = ArrayRef(CLI.Outs);
1526 auto AllOutVals = ArrayRef(CLI.OutVals);
1527 assert(AllOuts.size() == AllOutVals.size() &&
1528 "Outs and OutVals must be the same size");
1529 // Declare the .params or .reg need to pass values
1530 // to the function
1531 for (const auto E : llvm::enumerate(Args)) {
1532 const auto ArgI = E.index();
1533 const auto Arg = E.value();
1534 const auto ArgOuts =
1535 AllOuts.take_while([&](auto O) { return O.OrigArgIndex == ArgI; });
1536 const auto ArgOutVals = AllOutVals.take_front(ArgOuts.size());
1537 AllOuts = AllOuts.drop_front(ArgOuts.size());
1538 AllOutVals = AllOutVals.drop_front(ArgOuts.size());
1539
1540 const bool IsVAArg = (ArgI >= FirstVAArg);
1541 const bool IsByVal = Arg.IsByVal;
1542
1543 const SDValue ParamSymbol =
1544 getCallParamSymbol(DAG, IsVAArg ? FirstVAArg : ArgI, MVT::i32);
1545
1546 SmallVector<EVT, 16> VTs;
1547 SmallVector<uint64_t, 16> Offsets;
1548
1549 assert((!IsByVal || Arg.IndirectType) &&
1550 "byval arg must have indirect type");
1551 Type *ETy = (IsByVal ? Arg.IndirectType : Arg.Ty);
1552 ComputePTXValueVTs(*this, DL, ETy, VTs, &Offsets, IsByVal ? 0 : VAOffset);
1553 assert(VTs.size() == Offsets.size() && "Size mismatch");
1554 assert((IsByVal || VTs.size() == ArgOuts.size()) && "Size mismatch");
1555
1556 const Align ArgAlign = [&]() {
1557 if (IsByVal) {
1558 // The ByValAlign in the Outs[OIdx].Flags is always set at this point,
1559 // so we don't need to worry whether it's naturally aligned or not.
1560 // See TargetLowering::LowerCallTo().
1561 const Align InitialAlign = ArgOuts[0].Flags.getNonZeroByValAlign();
1562 const Align ByValAlign = getFunctionByValParamAlign(
1563 CB->getCalledFunction(), ETy, InitialAlign, DL);
1564 if (IsVAArg)
1565 VAOffset = alignTo(VAOffset, ByValAlign);
1566 return ByValAlign;
1567 }
1568 return getArgumentAlignment(CB, Arg.Ty, ArgI + 1, DL);
1569 }();
1570
1571 const unsigned TypeSize = DL.getTypeAllocSize(ETy);
1572 assert((!IsByVal || TypeSize == ArgOuts[0].Flags.getByValSize()) &&
1573 "type size mismatch");
1574
1575 const std::optional<SDValue> ArgDeclare = [&]() -> std::optional<SDValue> {
1576 if (IsVAArg) {
1577 if (ArgI == FirstVAArg) {
1578 VADeclareParam = DAG.getNode(
1579 NVPTXISD::DeclareArrayParam, dl, {MVT::Other, MVT::Glue},
1580 {Chain, ParamSymbol, GetI32(STI.getMaxRequiredAlignment()),
1581 GetI32(0), InGlue});
1582 return VADeclareParam;
1583 }
1584 return std::nullopt;
1585 }
1586 if (IsByVal || shouldPassAsArray(Arg.Ty)) {
1587 // declare .param .align <align> .b8 .param<n>[<size>];
1588 return DAG.getNode(NVPTXISD::DeclareArrayParam, dl,
1589 {MVT::Other, MVT::Glue},
1590 {Chain, ParamSymbol, GetI32(ArgAlign.value()),
1591 GetI32(TypeSize), InGlue});
1592 }
1593 assert(ArgOuts.size() == 1 && "We must pass only one value as non-array");
1594 // declare .param .b<size> .param<n>;
1595
1596 // PTX ABI requires integral types to be at least 32 bits in
1597 // size. FP16 is loaded/stored using i16, so it's handled
1598 // here as well.
1599 const unsigned PromotedSize =
1600 (ArgOuts[0].VT.isInteger() || ArgOuts[0].VT.isFloatingPoint())
1601 ? promoteScalarArgumentSize(TypeSize * 8)
1602 : TypeSize * 8;
1603
1604 return DAG.getNode(NVPTXISD::DeclareScalarParam, dl,
1605 {MVT::Other, MVT::Glue},
1606 {Chain, ParamSymbol, GetI32(PromotedSize), InGlue});
1607 }();
1608 if (ArgDeclare) {
1609 Chain = ArgDeclare->getValue(0);
1610 InGlue = ArgDeclare->getValue(1);
1611 }
1612
1613 // PTX Interoperability Guide 3.3(A): [Integer] Values shorter
1614 // than 32-bits are sign extended or zero extended, depending on
1615 // whether they are signed or unsigned types. This case applies
1616 // only to scalar parameters and not to aggregate values.
1617 const bool ExtendIntegerParam =
1618 Arg.Ty->isIntegerTy() && DL.getTypeAllocSizeInBits(Arg.Ty) < 32;
1619
1620 const auto GetStoredValue = [&](const unsigned I, EVT EltVT,
1621 const Align PartAlign) {
1622 SDValue StVal;
1623 if (IsByVal) {
1624 SDValue Ptr = ArgOutVals[0];
1625 auto MPI = refinePtrAS(Ptr, DAG, DL, *this);
1626 SDValue SrcAddr =
1627 DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(Offsets[I]));
1628
1629 StVal = DAG.getLoad(EltVT, dl, TempChain, SrcAddr, MPI, PartAlign);
1630 } else {
1631 StVal = ArgOutVals[I];
1632
1633 auto PromotedVT = promoteScalarIntegerPTX(StVal.getValueType());
1634 if (PromotedVT != StVal.getValueType()) {
1635 StVal = DAG.getNode(getExtOpcode(ArgOuts[I].Flags), dl, PromotedVT,
1636 StVal);
1637 }
1638 }
1639
1640 if (ExtendIntegerParam) {
1641 assert(VTs.size() == 1 && "Scalar can't have multiple parts.");
1642 // zext/sext to i32
1643 StVal =
1644 DAG.getNode(getExtOpcode(ArgOuts[I].Flags), dl, MVT::i32, StVal);
1645 } else if (EltVT.getSizeInBits() < 16) {
1646 // Use 16-bit registers for small stores as it's the
1647 // smallest general purpose register size supported by NVPTX.
1648 StVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, StVal);
1649 }
1650 return StVal;
1651 };
1652
1653 const auto VectorInfo =
1654 VectorizePTXValueVTs(VTs, Offsets, ArgAlign, IsVAArg);
1655
1656 unsigned J = 0;
1657 for (const unsigned NumElts : VectorInfo) {
1658 const int CurOffset = Offsets[J];
1659 EVT EltVT = promoteScalarIntegerPTX(VTs[J]);
1660 const Align PartAlign = commonAlignment(ArgAlign, CurOffset);
1661
1662 // If we have a PVF_SCALAR entry, it may not be sufficiently aligned for a
1663 // scalar store. In such cases, fall back to byte stores.
1664 if (NumElts == 1 && !IsVAArg && PartAlign < DAG.getEVTAlign(EltVT)) {
1665
1666 SDValue StVal = GetStoredValue(J, EltVT, PartAlign);
1667 Chain = LowerUnalignedStoreParam(DAG, Chain,
1668 CurOffset + (IsByVal ? VAOffset : 0),
1669 EltVT, StVal, InGlue, ArgI, dl);
1670
1671 // LowerUnalignedStoreParam took care of inserting the necessary nodes
1672 // into the SDAG, so just move on to the next element.
1673 J++;
1674 continue;
1675 }
1676
1677 if (IsVAArg && !IsByVal)
1678 // Align each part of the variadic argument to their type.
1679 VAOffset = alignTo(VAOffset, DAG.getEVTAlign(EltVT));
1680
1681 assert((IsVAArg || VAOffset == 0) &&
1682 "VAOffset must be 0 for non-VA args");
1683 SmallVector<SDValue, 6> StoreOperands{
1684 Chain, GetI32(IsVAArg ? FirstVAArg : ArgI),
1685 GetI32(VAOffset + ((IsVAArg && !IsByVal) ? 0 : CurOffset))};
1686
1687 // Record the values to store.
1688 for (const unsigned K : llvm::seq(NumElts))
1689 StoreOperands.push_back(GetStoredValue(J + K, EltVT, PartAlign));
1690 StoreOperands.push_back(InGlue);
1691
1692 NVPTXISD::NodeType Op;
1693 switch (NumElts) {
1694 case 1:
1695 Op = NVPTXISD::StoreParam;
1696 break;
1697 case 2:
1698 Op = NVPTXISD::StoreParamV2;
1699 break;
1700 case 4:
1701 Op = NVPTXISD::StoreParamV4;
1702 break;
1703 default:
1704 llvm_unreachable("Invalid vector info.");
1705 }
1706 // Adjust type of the store op if we've extended the scalar
1707 // return value.
1708 EVT TheStoreType = ExtendIntegerParam ? MVT::i32 : EltVT;
1709
1710 Chain = DAG.getMemIntrinsicNode(
1711 Op, dl, DAG.getVTList(MVT::Other, MVT::Glue), StoreOperands,
1712 TheStoreType, MachinePointerInfo(), PartAlign,
1713 MachineMemOperand::MOStore);
1714 InGlue = Chain.getValue(1);
1715
1716 // TODO: We may need to support vector types that can be passed
1717 // as scalars in variadic arguments.
1718 if (IsVAArg && !IsByVal) {
1719 assert(NumElts == 1 &&
1720 "Vectorization is expected to be disabled for variadics.");
1721 VAOffset +=
1722 DL.getTypeAllocSize(TheStoreType.getTypeForEVT(*DAG.getContext()));
1723 }
1724
1725 J += NumElts;
1726 }
1727 if (IsVAArg && IsByVal)
1728 VAOffset += TypeSize;
1729 }
1730
1731 GlobalAddressSDNode *Func = dyn_cast<GlobalAddressSDNode>(Callee.getNode());
1732
1733 // Handle Result
1734 if (!Ins.empty()) {
1735 const SDValue RetDeclare = [&]() {
1736 const SDValue RetSymbol = DAG.getExternalSymbol("retval0", MVT::i32);
1737 const unsigned ResultSize = DL.getTypeAllocSizeInBits(RetTy);
1738 if (shouldPassAsArray(RetTy)) {
1739 const Align RetAlign = getArgumentAlignment(CB, RetTy, 0, DL);
1740 return DAG.getNode(NVPTXISD::DeclareArrayParam, dl,
1741 {MVT::Other, MVT::Glue},
1742 {Chain, RetSymbol, GetI32(RetAlign.value()),
1743 GetI32(ResultSize / 8), InGlue});
1744 }
1745 const auto PromotedResultSize = promoteScalarArgumentSize(ResultSize);
1746 return DAG.getNode(
1747 NVPTXISD::DeclareScalarParam, dl, {MVT::Other, MVT::Glue},
1748 {Chain, RetSymbol, GetI32(PromotedResultSize), InGlue});
1749 }();
1750 Chain = RetDeclare.getValue(0);
1751 InGlue = RetDeclare.getValue(1);
1752 }
1753
1754 const bool HasVAArgs = CLI.IsVarArg && (CLI.Args.size() > CLI.NumFixedArgs);
1755 // Set the size of the vararg param byte array if the callee is a variadic
1756 // function and the variadic part is not empty.
1757 if (HasVAArgs) {
1758 SDValue DeclareParamOps[] = {VADeclareParam.getOperand(0),
1759 VADeclareParam.getOperand(1),
1760 VADeclareParam.getOperand(2), GetI32(VAOffset),
1761 VADeclareParam.getOperand(4)};
1762 DAG.MorphNodeTo(VADeclareParam.getNode(), VADeclareParam.getOpcode(),
1763 VADeclareParam->getVTList(), DeclareParamOps);
1764 }
1765
1766 // If the type of the callsite does not match that of the function, convert
1767 // the callsite to an indirect call.
1768 const bool ConvertToIndirectCall = shouldConvertToIndirectCall(CB, Func);
1769
1770 // Both indirect calls and libcalls have nullptr Func. In order to distinguish
1771 // between them we must rely on the call site value which is valid for
1772 // indirect calls but is always null for libcalls.
1773 const bool IsIndirectCall = (!Func && CB) || ConvertToIndirectCall;
1774
1775 if (isa<ExternalSymbolSDNode>(Callee)) {
1776 Function* CalleeFunc = nullptr;
1777
1778 // Try to find the callee in the current module.
1779 Callee = DAG.getSymbolFunctionGlobalAddress(Callee, &CalleeFunc);
1780 assert(CalleeFunc != nullptr && "Libcall callee must be set.");
1781
1782 // Set the "libcall callee" attribute to indicate that the function
1783 // must always have a declaration.
1784 CalleeFunc->addFnAttr("nvptx-libcall-callee", "true");
1785 }
1786
1787 if (IsIndirectCall) {
1788 // This is indirect function call case : PTX requires a prototype of the
1789 // form
1790 // proto_0 : .callprototype(.param .b32 _) _ (.param .b32 _);
1791 // to be emitted, and the label has to used as the last arg of call
1792 // instruction.
1793 // The prototype is embedded in a string and put as the operand for a
1794 // CallPrototype SDNode which will print out to the value of the string.
1795 std::string Proto =
1796 getPrototype(DL, RetTy, Args, CLI.Outs,
1797 HasVAArgs ? std::optional(FirstVAArg) : std::nullopt, *CB,
1798 UniqueCallSite);
1799 const char *ProtoStr = nvTM->getStrPool().save(Proto).data();
1800 Chain = DAG.getNode(
1801 NVPTXISD::CallPrototype, dl, {MVT::Other, MVT::Glue},
1802 {Chain, DAG.getTargetExternalSymbol(ProtoStr, MVT::i32), InGlue});
1803 InGlue = Chain.getValue(1);
1804 }
1805
1806 if (ConvertToIndirectCall) {
1807 // Copy the function ptr to a ptx register and use the register to call the
1808 // function.
1809 const MVT DestVT = Callee.getValueType().getSimpleVT();
1810 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1811 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1812 Register DestReg = MRI.createVirtualRegister(TLI.getRegClassFor(DestVT));
1813 auto RegCopy = DAG.getCopyToReg(DAG.getEntryNode(), dl, DestReg, Callee);
1814 Callee = DAG.getCopyFromReg(RegCopy, dl, DestReg, DestVT);
1815 }
1816
1817 const unsigned Proto = IsIndirectCall ? UniqueCallSite : 0;
1818 const unsigned NumArgs =
1819 std::min<unsigned>(CLI.NumFixedArgs + 1, Args.size());
1820 /// CALL(Chain, IsConvergent, IsIndirectCall/IsUniform, NumReturns,
1821 /// NumParams, Callee, Proto, InGlue)
1822 Chain = DAG.getNode(NVPTXISD::CALL, dl, {MVT::Other, MVT::Glue},
1823 {Chain, GetI32(CLI.IsConvergent), GetI32(IsIndirectCall),
1824 GetI32(Ins.empty() ? 0 : 1), GetI32(NumArgs), Callee,
1825 GetI32(Proto), InGlue});
1826 InGlue = Chain.getValue(1);
1827
1828 SmallVector<SDValue, 16> ProxyRegOps;
1829 // An item of the vector is filled if the element does not need a ProxyReg
1830 // operation on it and should be added to InVals as is. ProxyRegOps and
1831 // ProxyRegTruncates contain empty/none items at the same index.
1832 SmallVector<SDValue, 16> RetElts;
1833 // A temporary ProxyReg operations inserted in `LowerUnalignedLoadRetParam()`
1834 // to use the values of `LoadParam`s and to be replaced later then
1835 // `CALLSEQ_END` is added.
1836 SmallVector<SDValue, 16> TempProxyRegOps;
1837
1838 // Generate loads from param memory/moves from registers for result
1839 if (!Ins.empty()) {
1840 SmallVector<EVT, 16> VTs;
1841 SmallVector<uint64_t, 16> Offsets;
1842 ComputePTXValueVTs(*this, DL, RetTy, VTs, &Offsets, 0);
1843 assert(VTs.size() == Ins.size() && "Bad value decomposition");
1844
1845 const Align RetAlign = getArgumentAlignment(CB, RetTy, 0, DL);
1846
1847 // PTX Interoperability Guide 3.3(A): [Integer] Values shorter than
1848 // 32-bits are sign extended or zero extended, depending on whether
1849 // they are signed or unsigned types.
1850 const bool ExtendIntegerRetVal =
1851 RetTy->isIntegerTy() && DL.getTypeAllocSizeInBits(RetTy) < 32;
1852
1853 const auto VectorInfo = VectorizePTXValueVTs(VTs, Offsets, RetAlign);
1854 unsigned I = 0;
1855 for (const unsigned VectorizedSize : VectorInfo) {
1856 EVT TheLoadType = promoteScalarIntegerPTX(VTs[I]);
1857 EVT EltType = Ins[I].VT;
1858 const Align EltAlign = commonAlignment(RetAlign, Offsets[I]);
1859
1860 if (TheLoadType != VTs[I])
1861 EltType = TheLoadType;
1862
1863 if (ExtendIntegerRetVal) {
1864 TheLoadType = MVT::i32;
1865 EltType = MVT::i32;
1866 } else if (TheLoadType.getSizeInBits() < 16) {
1867 EltType = MVT::i16;
1868 }
1869
1870 // If we have a PVF_SCALAR entry, it may not be sufficiently aligned for a
1871 // scalar load. In such cases, fall back to byte loads.
1872 if (VectorizedSize == 1 && RetTy->isAggregateType() &&
1873 EltAlign < DAG.getEVTAlign(TheLoadType)) {
1874 SDValue Ret = LowerUnalignedLoadRetParam(
1875 DAG, Chain, Offsets[I], TheLoadType, InGlue, TempProxyRegOps, dl);
1876 ProxyRegOps.push_back(SDValue());
1877 RetElts.resize(I);
1878 RetElts.push_back(Ret);
1879
1880 I++;
1881 continue;
1882 }
1883
1884 SmallVector<EVT, 6> LoadVTs(VectorizedSize, EltType);
1885 LoadVTs.append({MVT::Other, MVT::Glue});
1886
1887 NVPTXISD::NodeType Op;
1888 switch (VectorizedSize) {
1889 case 1:
1890 Op = NVPTXISD::LoadParam;
1891 break;
1892 case 2:
1893 Op = NVPTXISD::LoadParamV2;
1894 break;
1895 case 4:
1896 Op = NVPTXISD::LoadParamV4;
1897 break;
1898 default:
1899 llvm_unreachable("Invalid vector info.");
1900 }
1901
1902 SDValue LoadOperands[] = {Chain, GetI32(1), GetI32(Offsets[I]), InGlue};
1903 SDValue RetVal = DAG.getMemIntrinsicNode(
1904 Op, dl, DAG.getVTList(LoadVTs), LoadOperands, TheLoadType,
1905 MachinePointerInfo(), EltAlign, MachineMemOperand::MOLoad);
1906
1907 for (const unsigned J : llvm::seq(VectorizedSize)) {
1908 ProxyRegOps.push_back(RetVal.getValue(J));
1909 }
1910
1911 Chain = RetVal.getValue(VectorizedSize);
1912 InGlue = RetVal.getValue(VectorizedSize + 1);
1913
1914 I += VectorizedSize;
1915 }
1916 }
1917
1918 Chain =
1919 DAG.getCALLSEQ_END(Chain, UniqueCallSite, UniqueCallSite + 1, InGlue, dl);
1920 InGlue = Chain.getValue(1);
1921
1922 // Append ProxyReg instructions to the chain to make sure that `callseq_end`
1923 // will not get lost. Otherwise, during libcalls expansion, the nodes can become
1924 // dangling.
1925 for (const unsigned I : llvm::seq(ProxyRegOps.size())) {
1926 if (I < RetElts.size() && RetElts[I]) {
1927 InVals.push_back(RetElts[I]);
1928 continue;
1929 }
1930
1931 SDValue Ret =
1932 DAG.getNode(NVPTXISD::ProxyReg, dl, ProxyRegOps[I].getSimpleValueType(),
1933 {Chain, ProxyRegOps[I]});
1934
1935 const EVT ExpectedVT = Ins[I].VT;
1936 if (!Ret.getValueType().bitsEq(ExpectedVT)) {
1937 Ret = DAG.getNode(ISD::TRUNCATE, dl, ExpectedVT, Ret);
1938 }
1939 InVals.push_back(Ret);
1940 }
1941
1942 for (SDValue &T : TempProxyRegOps) {
1943 SDValue Repl = DAG.getNode(NVPTXISD::ProxyReg, dl, T.getSimpleValueType(),
1944 {Chain, T.getOperand(0)});
1945 DAG.ReplaceAllUsesWith(T, Repl);
1946 DAG.RemoveDeadNode(T.getNode());
1947 }
1948
1949 // set isTailCall to false for now, until we figure out how to express
1950 // tail call optimization in PTX
1951 isTailCall = false;
1952 return Chain;
1953 }
1954
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const1955 SDValue NVPTXTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
1956 SelectionDAG &DAG) const {
1957
1958 if (STI.getPTXVersion() < 73 || STI.getSmVersion() < 52) {
1959 const Function &Fn = DAG.getMachineFunction().getFunction();
1960
1961 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
1962 Fn,
1963 "Support for dynamic alloca introduced in PTX ISA version 7.3 and "
1964 "requires target sm_52.",
1965 SDLoc(Op).getDebugLoc()));
1966 auto Ops = {DAG.getConstant(0, SDLoc(), Op.getValueType()),
1967 Op.getOperand(0)};
1968 return DAG.getMergeValues(Ops, SDLoc());
1969 }
1970
1971 SDLoc DL(Op.getNode());
1972 SDValue Chain = Op.getOperand(0);
1973 SDValue Size = Op.getOperand(1);
1974 uint64_t Align = Op.getConstantOperandVal(2);
1975
1976 // The alignment on a ISD::DYNAMIC_STACKALLOC node may be 0 to indicate that
1977 // the default stack alignment should be used.
1978 if (Align == 0)
1979 Align = DAG.getSubtarget().getFrameLowering()->getStackAlign().value();
1980
1981 // The size for ptx alloca instruction is 64-bit for m64 and 32-bit for m32.
1982 const MVT LocalVT = getPointerTy(DAG.getDataLayout(), ADDRESS_SPACE_LOCAL);
1983
1984 SDValue Alloc =
1985 DAG.getNode(NVPTXISD::DYNAMIC_STACKALLOC, DL, {LocalVT, MVT::Other},
1986 {Chain, DAG.getZExtOrTrunc(Size, DL, LocalVT),
1987 DAG.getTargetConstant(Align, DL, MVT::i32)});
1988
1989 SDValue ASC = DAG.getAddrSpaceCast(
1990 DL, Op.getValueType(), Alloc, ADDRESS_SPACE_LOCAL, ADDRESS_SPACE_GENERIC);
1991
1992 return DAG.getMergeValues({ASC, SDValue(Alloc.getNode(), 1)}, DL);
1993 }
1994
LowerSTACKRESTORE(SDValue Op,SelectionDAG & DAG) const1995 SDValue NVPTXTargetLowering::LowerSTACKRESTORE(SDValue Op,
1996 SelectionDAG &DAG) const {
1997 SDLoc DL(Op.getNode());
1998 if (STI.getPTXVersion() < 73 || STI.getSmVersion() < 52) {
1999 const Function &Fn = DAG.getMachineFunction().getFunction();
2000
2001 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
2002 Fn,
2003 "Support for stackrestore requires PTX ISA version >= 7.3 and target "
2004 ">= sm_52.",
2005 DL.getDebugLoc()));
2006 return Op.getOperand(0);
2007 }
2008
2009 const MVT LocalVT = getPointerTy(DAG.getDataLayout(), ADDRESS_SPACE_LOCAL);
2010 SDValue Chain = Op.getOperand(0);
2011 SDValue Ptr = Op.getOperand(1);
2012 SDValue ASC = DAG.getAddrSpaceCast(DL, LocalVT, Ptr, ADDRESS_SPACE_GENERIC,
2013 ADDRESS_SPACE_LOCAL);
2014 return DAG.getNode(NVPTXISD::STACKRESTORE, DL, MVT::Other, {Chain, ASC});
2015 }
2016
LowerSTACKSAVE(SDValue Op,SelectionDAG & DAG) const2017 SDValue NVPTXTargetLowering::LowerSTACKSAVE(SDValue Op,
2018 SelectionDAG &DAG) const {
2019 SDLoc DL(Op.getNode());
2020 if (STI.getPTXVersion() < 73 || STI.getSmVersion() < 52) {
2021 const Function &Fn = DAG.getMachineFunction().getFunction();
2022
2023 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
2024 Fn,
2025 "Support for stacksave requires PTX ISA version >= 7.3 and target >= "
2026 "sm_52.",
2027 DL.getDebugLoc()));
2028 auto Ops = {DAG.getConstant(0, DL, Op.getValueType()), Op.getOperand(0)};
2029 return DAG.getMergeValues(Ops, DL);
2030 }
2031
2032 const MVT LocalVT = getPointerTy(DAG.getDataLayout(), ADDRESS_SPACE_LOCAL);
2033 SDValue Chain = Op.getOperand(0);
2034 SDValue SS =
2035 DAG.getNode(NVPTXISD::STACKSAVE, DL, {LocalVT, MVT::Other}, Chain);
2036 SDValue ASC = DAG.getAddrSpaceCast(
2037 DL, Op.getValueType(), SS, ADDRESS_SPACE_LOCAL, ADDRESS_SPACE_GENERIC);
2038 return DAG.getMergeValues({ASC, SDValue(SS.getNode(), 1)}, DL);
2039 }
2040
2041 // By default CONCAT_VECTORS is lowered by ExpandVectorBuildThroughStack()
2042 // (see LegalizeDAG.cpp). This is slow and uses local memory.
2043 // We use extract/insert/build vector just as what LegalizeOp() does in llvm 2.5
2044 SDValue
LowerCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG) const2045 NVPTXTargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
2046 SDNode *Node = Op.getNode();
2047 SDLoc dl(Node);
2048 SmallVector<SDValue, 8> Ops;
2049 unsigned NumOperands = Node->getNumOperands();
2050 for (unsigned i = 0; i < NumOperands; ++i) {
2051 SDValue SubOp = Node->getOperand(i);
2052 EVT VVT = SubOp.getNode()->getValueType(0);
2053 EVT EltVT = VVT.getVectorElementType();
2054 unsigned NumSubElem = VVT.getVectorNumElements();
2055 for (unsigned j = 0; j < NumSubElem; ++j) {
2056 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, SubOp,
2057 DAG.getIntPtrConstant(j, dl)));
2058 }
2059 }
2060 return DAG.getBuildVector(Node->getValueType(0), dl, Ops);
2061 }
2062
LowerBITCAST(SDValue Op,SelectionDAG & DAG) const2063 SDValue NVPTXTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
2064 // Handle bitcasting from v2i8 without hitting the default promotion
2065 // strategy which goes through stack memory.
2066 EVT FromVT = Op->getOperand(0)->getValueType(0);
2067 if (FromVT != MVT::v2i8) {
2068 return Op;
2069 }
2070
2071 // Pack vector elements into i16 and bitcast to final type
2072 SDLoc DL(Op);
2073 SDValue Vec0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i8,
2074 Op->getOperand(0), DAG.getIntPtrConstant(0, DL));
2075 SDValue Vec1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i8,
2076 Op->getOperand(0), DAG.getIntPtrConstant(1, DL));
2077 SDValue Extend0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i16, Vec0);
2078 SDValue Extend1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i16, Vec1);
2079 SDValue Const8 = DAG.getConstant(8, DL, MVT::i16);
2080 SDValue AsInt = DAG.getNode(
2081 ISD::OR, DL, MVT::i16,
2082 {Extend0, DAG.getNode(ISD::SHL, DL, MVT::i16, {Extend1, Const8})});
2083 EVT ToVT = Op->getValueType(0);
2084 return DAG.getBitcast(ToVT, AsInt);
2085 }
2086
2087 // We can init constant f16x2/v2i16/v4i8 with a single .b32 move. Normally it
2088 // would get lowered as two constant loads and vector-packing move.
2089 // Instead we want just a constant move:
2090 // mov.b32 %r2, 0x40003C00
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG) const2091 SDValue NVPTXTargetLowering::LowerBUILD_VECTOR(SDValue Op,
2092 SelectionDAG &DAG) const {
2093 EVT VT = Op->getValueType(0);
2094 if (!(NVPTX::isPackedVectorTy(VT) && VT.is32BitVector()))
2095 return Op;
2096 SDLoc DL(Op);
2097
2098 if (!llvm::all_of(Op->ops(), [](SDValue Operand) {
2099 return Operand->isUndef() || isa<ConstantSDNode>(Operand) ||
2100 isa<ConstantFPSDNode>(Operand);
2101 })) {
2102 if (VT != MVT::v4i8)
2103 return Op;
2104 // Lower non-const v4i8 vector as byte-wise constructed i32, which allows us
2105 // to optimize calculation of constant parts.
2106 auto GetPRMT = [&](const SDValue Left, const SDValue Right, bool Cast,
2107 uint64_t SelectionValue) -> SDValue {
2108 SDValue L = Left;
2109 SDValue R = Right;
2110 if (Cast) {
2111 L = DAG.getAnyExtOrTrunc(L, DL, MVT::i32);
2112 R = DAG.getAnyExtOrTrunc(R, DL, MVT::i32);
2113 }
2114 return DAG.getNode(
2115 NVPTXISD::PRMT, DL, MVT::v4i8,
2116 {L, R, DAG.getConstant(SelectionValue, DL, MVT::i32),
2117 DAG.getConstant(NVPTX::PTXPrmtMode::NONE, DL, MVT::i32)});
2118 };
2119 auto PRMT__10 = GetPRMT(Op->getOperand(0), Op->getOperand(1), true, 0x3340);
2120 auto PRMT__32 = GetPRMT(Op->getOperand(2), Op->getOperand(3), true, 0x3340);
2121 auto PRMT3210 = GetPRMT(PRMT__10, PRMT__32, false, 0x5410);
2122 return DAG.getNode(ISD::BITCAST, DL, VT, PRMT3210);
2123 }
2124
2125 // Get value or the Nth operand as an APInt(32). Undef values treated as 0.
2126 auto GetOperand = [](SDValue Op, int N) -> APInt {
2127 const SDValue &Operand = Op->getOperand(N);
2128 EVT VT = Op->getValueType(0);
2129 if (Operand->isUndef())
2130 return APInt(32, 0);
2131 APInt Value;
2132 if (VT == MVT::v2f16 || VT == MVT::v2bf16)
2133 Value = cast<ConstantFPSDNode>(Operand)->getValueAPF().bitcastToAPInt();
2134 else if (VT == MVT::v2i16 || VT == MVT::v4i8)
2135 Value = Operand->getAsAPIntVal();
2136 else
2137 llvm_unreachable("Unsupported type");
2138 // i8 values are carried around as i16, so we need to zero out upper bits,
2139 // so they do not get in the way of combining individual byte values
2140 if (VT == MVT::v4i8)
2141 Value = Value.trunc(8);
2142 return Value.zext(32);
2143 };
2144
2145 // Construct a 32-bit constant by shifting into place smaller values
2146 // (elements of the vector type VT).
2147 // For example, if VT has 2 elements, then N == 2:
2148 // ShiftAmount = 32 / N = 16
2149 // Value |= Op0 (b16) << 0
2150 // Value |= Op1 (b16) << 16
2151 // If N == 4:
2152 // ShiftAmount = 32 / N = 8
2153 // Value |= Op0 (b8) << 0
2154 // Value |= Op1 (b8) << 8
2155 // Value |= Op2 (b8) << 16
2156 // Value |= Op3 (b8) << 24
2157 // ...etc
2158 APInt Value(32, 0);
2159 const unsigned NumElements = VT.getVectorNumElements();
2160 assert(32 % NumElements == 0 && "must evenly divide bit length");
2161 const unsigned ShiftAmount = 32 / NumElements;
2162 for (unsigned ElementNo : seq(NumElements))
2163 Value |= GetOperand(Op, ElementNo).shl(ElementNo * ShiftAmount);
2164 SDValue Const = DAG.getConstant(Value, DL, MVT::i32);
2165 return DAG.getNode(ISD::BITCAST, DL, Op->getValueType(0), Const);
2166 }
2167
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const2168 SDValue NVPTXTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
2169 SelectionDAG &DAG) const {
2170 SDValue Index = Op->getOperand(1);
2171 SDValue Vector = Op->getOperand(0);
2172 SDLoc DL(Op);
2173 EVT VectorVT = Vector.getValueType();
2174
2175 if (VectorVT == MVT::v4i8) {
2176 SDValue Selector = DAG.getNode(ISD::OR, DL, MVT::i32,
2177 DAG.getZExtOrTrunc(Index, DL, MVT::i32),
2178 DAG.getConstant(0x7770, DL, MVT::i32));
2179 SDValue PRMT = DAG.getNode(
2180 NVPTXISD::PRMT, DL, MVT::i32,
2181 {DAG.getBitcast(MVT::i32, Vector), DAG.getConstant(0, DL, MVT::i32),
2182 Selector, DAG.getConstant(NVPTX::PTXPrmtMode::NONE, DL, MVT::i32)});
2183 return DAG.getAnyExtOrTrunc(PRMT, DL, Op->getValueType(0));
2184 }
2185
2186 // Constant index will be matched by tablegen.
2187 if (isa<ConstantSDNode>(Index.getNode()))
2188 return Op;
2189
2190 // Extract individual elements and select one of them.
2191 assert(NVPTX::isPackedVectorTy(VectorVT) &&
2192 VectorVT.getVectorNumElements() == 2 && "Unexpected vector type.");
2193 EVT EltVT = VectorVT.getVectorElementType();
2194
2195 SDLoc dl(Op.getNode());
2196 SDValue E0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Vector,
2197 DAG.getIntPtrConstant(0, dl));
2198 SDValue E1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Vector,
2199 DAG.getIntPtrConstant(1, dl));
2200 return DAG.getSelectCC(dl, Index, DAG.getIntPtrConstant(0, dl), E0, E1,
2201 ISD::CondCode::SETEQ);
2202 }
2203
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const2204 SDValue NVPTXTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
2205 SelectionDAG &DAG) const {
2206 SDValue Vector = Op->getOperand(0);
2207 EVT VectorVT = Vector.getValueType();
2208
2209 if (VectorVT != MVT::v4i8)
2210 return Op;
2211 SDLoc DL(Op);
2212 SDValue Value = Op->getOperand(1);
2213 if (Value->isUndef())
2214 return Vector;
2215
2216 SDValue Index = Op->getOperand(2);
2217
2218 SDValue BFI =
2219 DAG.getNode(NVPTXISD::BFI, DL, MVT::i32,
2220 {DAG.getZExtOrTrunc(Value, DL, MVT::i32), Vector,
2221 DAG.getNode(ISD::MUL, DL, MVT::i32,
2222 DAG.getZExtOrTrunc(Index, DL, MVT::i32),
2223 DAG.getConstant(8, DL, MVT::i32)),
2224 DAG.getConstant(8, DL, MVT::i32)});
2225 return DAG.getNode(ISD::BITCAST, DL, Op->getValueType(0), BFI);
2226 }
2227
LowerVECTOR_SHUFFLE(SDValue Op,SelectionDAG & DAG) const2228 SDValue NVPTXTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
2229 SelectionDAG &DAG) const {
2230 SDValue V1 = Op.getOperand(0);
2231 EVT VectorVT = V1.getValueType();
2232 if (VectorVT != MVT::v4i8 || Op.getValueType() != MVT::v4i8)
2233 return Op;
2234
2235 // Lower shuffle to PRMT instruction.
2236 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2237 SDValue V2 = Op.getOperand(1);
2238 uint32_t Selector = 0;
2239 for (auto I : llvm::enumerate(SVN->getMask())) {
2240 if (I.value() != -1) // -1 is a placeholder for undef.
2241 Selector |= (I.value() << (I.index() * 4));
2242 }
2243
2244 SDLoc DL(Op);
2245 return DAG.getNode(NVPTXISD::PRMT, DL, MVT::v4i8, V1, V2,
2246 DAG.getConstant(Selector, DL, MVT::i32),
2247 DAG.getConstant(NVPTX::PTXPrmtMode::NONE, DL, MVT::i32));
2248 }
2249 /// LowerShiftRightParts - Lower SRL_PARTS, SRA_PARTS, which
2250 /// 1) returns two i32 values and take a 2 x i32 value to shift plus a shift
2251 /// amount, or
2252 /// 2) returns two i64 values and take a 2 x i64 value to shift plus a shift
2253 /// amount.
LowerShiftRightParts(SDValue Op,SelectionDAG & DAG) const2254 SDValue NVPTXTargetLowering::LowerShiftRightParts(SDValue Op,
2255 SelectionDAG &DAG) const {
2256 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
2257 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
2258
2259 EVT VT = Op.getValueType();
2260 unsigned VTBits = VT.getSizeInBits();
2261 SDLoc dl(Op);
2262 SDValue ShOpLo = Op.getOperand(0);
2263 SDValue ShOpHi = Op.getOperand(1);
2264 SDValue ShAmt = Op.getOperand(2);
2265 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
2266
2267 if (VTBits == 32 && STI.getSmVersion() >= 35) {
2268 // For 32bit and sm35, we can use the funnel shift 'shf' instruction.
2269 // {dHi, dLo} = {aHi, aLo} >> Amt
2270 // dHi = aHi >> Amt
2271 // dLo = shf.r.clamp aLo, aHi, Amt
2272
2273 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
2274 SDValue Lo =
2275 DAG.getNode(NVPTXISD::FSHR_CLAMP, dl, VT, ShOpHi, ShOpLo, ShAmt);
2276
2277 SDValue Ops[2] = { Lo, Hi };
2278 return DAG.getMergeValues(Ops, dl);
2279 }
2280 else {
2281 // {dHi, dLo} = {aHi, aLo} >> Amt
2282 // - if (Amt>=size) then
2283 // dLo = aHi >> (Amt-size)
2284 // dHi = aHi >> Amt (this is either all 0 or all 1)
2285 // else
2286 // dLo = (aLo >>logic Amt) | (aHi << (size-Amt))
2287 // dHi = aHi >> Amt
2288
2289 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
2290 DAG.getConstant(VTBits, dl, MVT::i32),
2291 ShAmt);
2292 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
2293 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
2294 DAG.getConstant(VTBits, dl, MVT::i32));
2295 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
2296 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2297 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
2298
2299 SDValue Cmp = DAG.getSetCC(dl, MVT::i1, ShAmt,
2300 DAG.getConstant(VTBits, dl, MVT::i32),
2301 ISD::SETGE);
2302 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
2303 SDValue Lo = DAG.getNode(ISD::SELECT, dl, VT, Cmp, TrueVal, FalseVal);
2304
2305 SDValue Ops[2] = { Lo, Hi };
2306 return DAG.getMergeValues(Ops, dl);
2307 }
2308 }
2309
2310 /// LowerShiftLeftParts - Lower SHL_PARTS, which
2311 /// 1) returns two i32 values and take a 2 x i32 value to shift plus a shift
2312 /// amount, or
2313 /// 2) returns two i64 values and take a 2 x i64 value to shift plus a shift
2314 /// amount.
LowerShiftLeftParts(SDValue Op,SelectionDAG & DAG) const2315 SDValue NVPTXTargetLowering::LowerShiftLeftParts(SDValue Op,
2316 SelectionDAG &DAG) const {
2317 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
2318 assert(Op.getOpcode() == ISD::SHL_PARTS);
2319
2320 EVT VT = Op.getValueType();
2321 unsigned VTBits = VT.getSizeInBits();
2322 SDLoc dl(Op);
2323 SDValue ShOpLo = Op.getOperand(0);
2324 SDValue ShOpHi = Op.getOperand(1);
2325 SDValue ShAmt = Op.getOperand(2);
2326
2327 if (VTBits == 32 && STI.getSmVersion() >= 35) {
2328 // For 32bit and sm35, we can use the funnel shift 'shf' instruction.
2329 // {dHi, dLo} = {aHi, aLo} << Amt
2330 // dHi = shf.l.clamp aLo, aHi, Amt
2331 // dLo = aLo << Amt
2332
2333 SDValue Hi =
2334 DAG.getNode(NVPTXISD::FSHL_CLAMP, dl, VT, ShOpHi, ShOpLo, ShAmt);
2335 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
2336
2337 SDValue Ops[2] = { Lo, Hi };
2338 return DAG.getMergeValues(Ops, dl);
2339 }
2340 else {
2341 // {dHi, dLo} = {aHi, aLo} << Amt
2342 // - if (Amt>=size) then
2343 // dLo = aLo << Amt (all 0)
2344 // dLo = aLo << (Amt-size)
2345 // else
2346 // dLo = aLo << Amt
2347 // dHi = (aHi << Amt) | (aLo >> (size-Amt))
2348
2349 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
2350 DAG.getConstant(VTBits, dl, MVT::i32),
2351 ShAmt);
2352 SDValue Tmp1 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
2353 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
2354 DAG.getConstant(VTBits, dl, MVT::i32));
2355 SDValue Tmp2 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
2356 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2357 SDValue TrueVal = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
2358
2359 SDValue Cmp = DAG.getSetCC(dl, MVT::i1, ShAmt,
2360 DAG.getConstant(VTBits, dl, MVT::i32),
2361 ISD::SETGE);
2362 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
2363 SDValue Hi = DAG.getNode(ISD::SELECT, dl, VT, Cmp, TrueVal, FalseVal);
2364
2365 SDValue Ops[2] = { Lo, Hi };
2366 return DAG.getMergeValues(Ops, dl);
2367 }
2368 }
2369
2370 /// If the types match, convert the generic copysign to the NVPTXISD version,
2371 /// otherwise bail ensuring that mismatched cases are properly expaned.
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG) const2372 SDValue NVPTXTargetLowering::LowerFCOPYSIGN(SDValue Op,
2373 SelectionDAG &DAG) const {
2374 EVT VT = Op.getValueType();
2375 SDLoc DL(Op);
2376
2377 SDValue In1 = Op.getOperand(0);
2378 SDValue In2 = Op.getOperand(1);
2379 EVT SrcVT = In2.getValueType();
2380
2381 if (!SrcVT.bitsEq(VT))
2382 return SDValue();
2383
2384 return DAG.getNode(NVPTXISD::FCOPYSIGN, DL, VT, In1, In2);
2385 }
2386
LowerFROUND(SDValue Op,SelectionDAG & DAG) const2387 SDValue NVPTXTargetLowering::LowerFROUND(SDValue Op, SelectionDAG &DAG) const {
2388 EVT VT = Op.getValueType();
2389
2390 if (VT == MVT::f32)
2391 return LowerFROUND32(Op, DAG);
2392
2393 if (VT == MVT::f64)
2394 return LowerFROUND64(Op, DAG);
2395
2396 llvm_unreachable("unhandled type");
2397 }
2398
2399 // This is the the rounding method used in CUDA libdevice in C like code:
2400 // float roundf(float A)
2401 // {
2402 // float RoundedA = (float) (int) ( A > 0 ? (A + 0.5f) : (A - 0.5f));
2403 // RoundedA = abs(A) > 0x1.0p23 ? A : RoundedA;
2404 // return abs(A) < 0.5 ? (float)(int)A : RoundedA;
2405 // }
LowerFROUND32(SDValue Op,SelectionDAG & DAG) const2406 SDValue NVPTXTargetLowering::LowerFROUND32(SDValue Op,
2407 SelectionDAG &DAG) const {
2408 SDLoc SL(Op);
2409 SDValue A = Op.getOperand(0);
2410 EVT VT = Op.getValueType();
2411
2412 SDValue AbsA = DAG.getNode(ISD::FABS, SL, VT, A);
2413
2414 // RoundedA = (float) (int) ( A > 0 ? (A + 0.5f) : (A - 0.5f))
2415 SDValue Bitcast = DAG.getNode(ISD::BITCAST, SL, MVT::i32, A);
2416 const unsigned SignBitMask = 0x80000000;
2417 SDValue Sign = DAG.getNode(ISD::AND, SL, MVT::i32, Bitcast,
2418 DAG.getConstant(SignBitMask, SL, MVT::i32));
2419 const unsigned PointFiveInBits = 0x3F000000;
2420 SDValue PointFiveWithSignRaw =
2421 DAG.getNode(ISD::OR, SL, MVT::i32, Sign,
2422 DAG.getConstant(PointFiveInBits, SL, MVT::i32));
2423 SDValue PointFiveWithSign =
2424 DAG.getNode(ISD::BITCAST, SL, VT, PointFiveWithSignRaw);
2425 SDValue AdjustedA = DAG.getNode(ISD::FADD, SL, VT, A, PointFiveWithSign);
2426 SDValue RoundedA = DAG.getNode(ISD::FTRUNC, SL, VT, AdjustedA);
2427
2428 // RoundedA = abs(A) > 0x1.0p23 ? A : RoundedA;
2429 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2430 SDValue IsLarge =
2431 DAG.getSetCC(SL, SetCCVT, AbsA, DAG.getConstantFP(pow(2.0, 23.0), SL, VT),
2432 ISD::SETOGT);
2433 RoundedA = DAG.getNode(ISD::SELECT, SL, VT, IsLarge, A, RoundedA);
2434
2435 // return abs(A) < 0.5 ? (float)(int)A : RoundedA;
2436 SDValue IsSmall =DAG.getSetCC(SL, SetCCVT, AbsA,
2437 DAG.getConstantFP(0.5, SL, VT), ISD::SETOLT);
2438 SDValue RoundedAForSmallA = DAG.getNode(ISD::FTRUNC, SL, VT, A);
2439 return DAG.getNode(ISD::SELECT, SL, VT, IsSmall, RoundedAForSmallA, RoundedA);
2440 }
2441
2442 // The implementation of round(double) is similar to that of round(float) in
2443 // that they both separate the value range into three regions and use a method
2444 // specific to the region to round the values. However, round(double) first
2445 // calculates the round of the absolute value and then adds the sign back while
2446 // round(float) directly rounds the value with sign.
LowerFROUND64(SDValue Op,SelectionDAG & DAG) const2447 SDValue NVPTXTargetLowering::LowerFROUND64(SDValue Op,
2448 SelectionDAG &DAG) const {
2449 SDLoc SL(Op);
2450 SDValue A = Op.getOperand(0);
2451 EVT VT = Op.getValueType();
2452
2453 SDValue AbsA = DAG.getNode(ISD::FABS, SL, VT, A);
2454
2455 // double RoundedA = (double) (int) (abs(A) + 0.5f);
2456 SDValue AdjustedA = DAG.getNode(ISD::FADD, SL, VT, AbsA,
2457 DAG.getConstantFP(0.5, SL, VT));
2458 SDValue RoundedA = DAG.getNode(ISD::FTRUNC, SL, VT, AdjustedA);
2459
2460 // RoundedA = abs(A) < 0.5 ? (double)0 : RoundedA;
2461 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2462 SDValue IsSmall =DAG.getSetCC(SL, SetCCVT, AbsA,
2463 DAG.getConstantFP(0.5, SL, VT), ISD::SETOLT);
2464 RoundedA = DAG.getNode(ISD::SELECT, SL, VT, IsSmall,
2465 DAG.getConstantFP(0, SL, VT),
2466 RoundedA);
2467
2468 // Add sign to rounded_A
2469 RoundedA = DAG.getNode(ISD::FCOPYSIGN, SL, VT, RoundedA, A);
2470 DAG.getNode(ISD::FTRUNC, SL, VT, A);
2471
2472 // RoundedA = abs(A) > 0x1.0p52 ? A : RoundedA;
2473 SDValue IsLarge =
2474 DAG.getSetCC(SL, SetCCVT, AbsA, DAG.getConstantFP(pow(2.0, 52.0), SL, VT),
2475 ISD::SETOGT);
2476 return DAG.getNode(ISD::SELECT, SL, VT, IsLarge, A, RoundedA);
2477 }
2478
PromoteBinOpToF32(SDNode * N,SelectionDAG & DAG)2479 static SDValue PromoteBinOpToF32(SDNode *N, SelectionDAG &DAG) {
2480 EVT VT = N->getValueType(0);
2481 EVT NVT = MVT::f32;
2482 if (VT.isVector()) {
2483 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
2484 }
2485 SDLoc DL(N);
2486 SDValue Tmp0 = DAG.getFPExtendOrRound(N->getOperand(0), DL, NVT);
2487 SDValue Tmp1 = DAG.getFPExtendOrRound(N->getOperand(1), DL, NVT);
2488 SDValue Res = DAG.getNode(N->getOpcode(), DL, NVT, Tmp0, Tmp1, N->getFlags());
2489 return DAG.getFPExtendOrRound(Res, DL, VT);
2490 }
2491
PromoteBinOpIfF32FTZ(SDValue Op,SelectionDAG & DAG) const2492 SDValue NVPTXTargetLowering::PromoteBinOpIfF32FTZ(SDValue Op,
2493 SelectionDAG &DAG) const {
2494 if (useF32FTZ(DAG.getMachineFunction())) {
2495 return PromoteBinOpToF32(Op.getNode(), DAG);
2496 }
2497 return Op;
2498 }
2499
LowerINT_TO_FP(SDValue Op,SelectionDAG & DAG) const2500 SDValue NVPTXTargetLowering::LowerINT_TO_FP(SDValue Op,
2501 SelectionDAG &DAG) const {
2502 assert(STI.getSmVersion() < 90 || STI.getPTXVersion() < 78);
2503
2504 if (Op.getValueType() == MVT::bf16) {
2505 SDLoc Loc(Op);
2506 return DAG.getNode(
2507 ISD::FP_ROUND, Loc, MVT::bf16,
2508 DAG.getNode(Op.getOpcode(), Loc, MVT::f32, Op.getOperand(0)),
2509 DAG.getIntPtrConstant(0, Loc, /*isTarget=*/true));
2510 }
2511
2512 // Everything else is considered legal.
2513 return Op;
2514 }
2515
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG) const2516 SDValue NVPTXTargetLowering::LowerFP_TO_INT(SDValue Op,
2517 SelectionDAG &DAG) const {
2518 assert(STI.getSmVersion() < 90 || STI.getPTXVersion() < 78);
2519
2520 if (Op.getOperand(0).getValueType() == MVT::bf16) {
2521 SDLoc Loc(Op);
2522 return DAG.getNode(
2523 Op.getOpcode(), Loc, Op.getValueType(),
2524 DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, Op.getOperand(0)));
2525 }
2526
2527 // Everything else is considered legal.
2528 return Op;
2529 }
2530
LowerFP_ROUND(SDValue Op,SelectionDAG & DAG) const2531 SDValue NVPTXTargetLowering::LowerFP_ROUND(SDValue Op,
2532 SelectionDAG &DAG) const {
2533 EVT NarrowVT = Op.getValueType();
2534 SDValue Wide = Op.getOperand(0);
2535 EVT WideVT = Wide.getValueType();
2536 if (NarrowVT.getScalarType() == MVT::bf16) {
2537 const TargetLowering *TLI = STI.getTargetLowering();
2538 if (STI.getSmVersion() < 80 || STI.getPTXVersion() < 70) {
2539 return TLI->expandFP_ROUND(Op.getNode(), DAG);
2540 }
2541 if (STI.getSmVersion() < 90 || STI.getPTXVersion() < 78) {
2542 // This combination was the first to support f32 -> bf16.
2543 if (STI.getSmVersion() >= 80 && STI.getPTXVersion() >= 70) {
2544 if (WideVT.getScalarType() == MVT::f32) {
2545 return Op;
2546 }
2547 if (WideVT.getScalarType() == MVT::f64) {
2548 SDLoc Loc(Op);
2549 // Round-inexact-to-odd f64 to f32, then do the final rounding using
2550 // the hardware f32 -> bf16 instruction.
2551 SDValue rod = TLI->expandRoundInexactToOdd(
2552 WideVT.isVector() ? WideVT.changeVectorElementType(MVT::f32)
2553 : MVT::f32,
2554 Wide, Loc, DAG);
2555 return DAG.getFPExtendOrRound(rod, Loc, NarrowVT);
2556 }
2557 }
2558 return TLI->expandFP_ROUND(Op.getNode(), DAG);
2559 }
2560 }
2561
2562 // Everything else is considered legal.
2563 return Op;
2564 }
2565
LowerFP_EXTEND(SDValue Op,SelectionDAG & DAG) const2566 SDValue NVPTXTargetLowering::LowerFP_EXTEND(SDValue Op,
2567 SelectionDAG &DAG) const {
2568 SDValue Narrow = Op.getOperand(0);
2569 EVT NarrowVT = Narrow.getValueType();
2570 EVT WideVT = Op.getValueType();
2571 if (NarrowVT.getScalarType() == MVT::bf16) {
2572 if (WideVT.getScalarType() == MVT::f32 &&
2573 (STI.getSmVersion() < 80 || STI.getPTXVersion() < 71)) {
2574 SDLoc Loc(Op);
2575 return DAG.getNode(ISD::BF16_TO_FP, Loc, WideVT, Narrow);
2576 }
2577 if (WideVT.getScalarType() == MVT::f64 &&
2578 (STI.getSmVersion() < 90 || STI.getPTXVersion() < 78)) {
2579 EVT F32 = NarrowVT.isVector() ? NarrowVT.changeVectorElementType(MVT::f32)
2580 : MVT::f32;
2581 SDLoc Loc(Op);
2582 if (STI.getSmVersion() >= 80 && STI.getPTXVersion() >= 71) {
2583 Op = DAG.getNode(ISD::FP_EXTEND, Loc, F32, Narrow);
2584 } else {
2585 Op = DAG.getNode(ISD::BF16_TO_FP, Loc, F32, Narrow);
2586 }
2587 return DAG.getNode(ISD::FP_EXTEND, Loc, WideVT, Op);
2588 }
2589 }
2590
2591 // Everything else is considered legal.
2592 return Op;
2593 }
2594
LowerVectorArith(SDValue Op,SelectionDAG & DAG)2595 static SDValue LowerVectorArith(SDValue Op, SelectionDAG &DAG) {
2596 SDLoc DL(Op);
2597 if (Op.getValueType() != MVT::v2i16)
2598 return Op;
2599 EVT EltVT = Op.getValueType().getVectorElementType();
2600 SmallVector<SDValue> VecElements;
2601 for (int I = 0, E = Op.getValueType().getVectorNumElements(); I < E; I++) {
2602 SmallVector<SDValue> ScalarArgs;
2603 llvm::transform(Op->ops(), std::back_inserter(ScalarArgs),
2604 [&](const SDUse &O) {
2605 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
2606 O.get(), DAG.getIntPtrConstant(I, DL));
2607 });
2608 VecElements.push_back(DAG.getNode(Op.getOpcode(), DL, EltVT, ScalarArgs));
2609 }
2610 SDValue V =
2611 DAG.getNode(ISD::BUILD_VECTOR, DL, Op.getValueType(), VecElements);
2612 return V;
2613 }
2614
LowerTcgen05St(SDValue Op,SelectionDAG & DAG)2615 static SDValue LowerTcgen05St(SDValue Op, SelectionDAG &DAG) {
2616 SDNode *N = Op.getNode();
2617 SDLoc DL(N);
2618 SmallVector<SDValue, 32> Ops;
2619
2620 // split the vector argument
2621 for (size_t I = 0; I < N->getNumOperands(); I++) {
2622 SDValue Val = N->getOperand(I);
2623 EVT ValVT = Val.getValueType();
2624 if (ValVT.isVector()) {
2625 EVT EltVT = ValVT.getVectorElementType();
2626 for (unsigned J = 0, NElts = ValVT.getVectorNumElements(); J < NElts; J++)
2627 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Val,
2628 DAG.getIntPtrConstant(J, DL)));
2629 } else
2630 Ops.push_back(Val);
2631 }
2632
2633 MemIntrinsicSDNode *MemSD = cast<MemIntrinsicSDNode>(N);
2634 SDValue Tcgen05StNode =
2635 DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, N->getVTList(), Ops,
2636 MemSD->getMemoryVT(), MemSD->getMemOperand());
2637
2638 return Tcgen05StNode;
2639 }
2640
LowerIntrinsicVoid(SDValue Op,SelectionDAG & DAG)2641 static SDValue LowerIntrinsicVoid(SDValue Op, SelectionDAG &DAG) {
2642 SDNode *N = Op.getNode();
2643 SDValue Intrin = N->getOperand(1);
2644
2645 // Get the intrinsic ID
2646 unsigned IntrinNo = cast<ConstantSDNode>(Intrin.getNode())->getZExtValue();
2647 switch (IntrinNo) {
2648 default:
2649 break;
2650 case Intrinsic::nvvm_tcgen05_st_16x64b_x1:
2651 case Intrinsic::nvvm_tcgen05_st_16x64b_x2:
2652 case Intrinsic::nvvm_tcgen05_st_16x64b_x4:
2653 case Intrinsic::nvvm_tcgen05_st_16x64b_x8:
2654 case Intrinsic::nvvm_tcgen05_st_16x64b_x16:
2655 case Intrinsic::nvvm_tcgen05_st_16x64b_x32:
2656 case Intrinsic::nvvm_tcgen05_st_16x64b_x128:
2657 case Intrinsic::nvvm_tcgen05_st_16x128b_x1:
2658 case Intrinsic::nvvm_tcgen05_st_16x128b_x2:
2659 case Intrinsic::nvvm_tcgen05_st_16x128b_x4:
2660 case Intrinsic::nvvm_tcgen05_st_16x128b_x8:
2661 case Intrinsic::nvvm_tcgen05_st_16x128b_x16:
2662 case Intrinsic::nvvm_tcgen05_st_16x128b_x32:
2663 case Intrinsic::nvvm_tcgen05_st_16x128b_x64:
2664 case Intrinsic::nvvm_tcgen05_st_16x256b_x1:
2665 case Intrinsic::nvvm_tcgen05_st_16x256b_x2:
2666 case Intrinsic::nvvm_tcgen05_st_16x256b_x4:
2667 case Intrinsic::nvvm_tcgen05_st_16x256b_x8:
2668 case Intrinsic::nvvm_tcgen05_st_16x256b_x16:
2669 case Intrinsic::nvvm_tcgen05_st_16x256b_x32:
2670 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x1:
2671 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x2:
2672 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x4:
2673 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x8:
2674 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x16:
2675 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x32:
2676 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x64:
2677 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x128:
2678 case Intrinsic::nvvm_tcgen05_st_32x32b_x1:
2679 case Intrinsic::nvvm_tcgen05_st_32x32b_x2:
2680 case Intrinsic::nvvm_tcgen05_st_32x32b_x4:
2681 case Intrinsic::nvvm_tcgen05_st_32x32b_x8:
2682 case Intrinsic::nvvm_tcgen05_st_32x32b_x16:
2683 case Intrinsic::nvvm_tcgen05_st_32x32b_x32:
2684 case Intrinsic::nvvm_tcgen05_st_16x64b_x64:
2685 case Intrinsic::nvvm_tcgen05_st_32x32b_x64:
2686 case Intrinsic::nvvm_tcgen05_st_32x32b_x128:
2687 return LowerTcgen05St(Op, DAG);
2688 }
2689 return Op;
2690 }
2691
LowerClusterLaunchControlQueryCancel(SDValue Op,SelectionDAG & DAG)2692 static SDValue LowerClusterLaunchControlQueryCancel(SDValue Op,
2693 SelectionDAG &DAG) {
2694
2695 SDNode *N = Op.getNode();
2696 if (N->getOperand(1).getValueType() != MVT::i128) {
2697 // return, if the operand is already lowered
2698 return SDValue();
2699 }
2700
2701 unsigned IID =
2702 cast<ConstantSDNode>(N->getOperand(0).getNode())->getZExtValue();
2703 auto Opcode = [&]() {
2704 switch (IID) {
2705 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_is_canceled:
2706 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_IS_CANCELED;
2707 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_x:
2708 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_X;
2709 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_y:
2710 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_Y;
2711 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_z:
2712 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_Z;
2713 default:
2714 llvm_unreachable("unsupported/unhandled intrinsic");
2715 }
2716 }();
2717
2718 SDLoc DL(N);
2719 SDValue TryCancelResponse = N->getOperand(1);
2720 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TryCancelResponse);
2721 SDValue TryCancelResponse0 =
2722 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, Cast,
2723 DAG.getIntPtrConstant(0, DL));
2724 SDValue TryCancelResponse1 =
2725 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, Cast,
2726 DAG.getIntPtrConstant(1, DL));
2727
2728 return DAG.getNode(Opcode, DL, N->getVTList(),
2729 {TryCancelResponse0, TryCancelResponse1});
2730 }
2731
lowerIntrinsicWOChain(SDValue Op,SelectionDAG & DAG)2732 static SDValue lowerIntrinsicWOChain(SDValue Op, SelectionDAG &DAG) {
2733 switch (Op->getConstantOperandVal(0)) {
2734 default:
2735 return Op;
2736 case Intrinsic::nvvm_internal_addrspace_wrap:
2737 return Op.getOperand(1);
2738 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_is_canceled:
2739 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_x:
2740 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_y:
2741 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_z:
2742 return LowerClusterLaunchControlQueryCancel(Op, DAG);
2743 }
2744 }
2745
2746 // In PTX 64-bit CTLZ and CTPOP are supported, but they return a 32-bit value.
2747 // Lower these into a node returning the correct type which is zero-extended
2748 // back to the correct size.
lowerCTLZCTPOP(SDValue Op,SelectionDAG & DAG)2749 static SDValue lowerCTLZCTPOP(SDValue Op, SelectionDAG &DAG) {
2750 SDValue V = Op->getOperand(0);
2751 assert(V.getValueType() == MVT::i64 &&
2752 "Unexpected CTLZ/CTPOP type to legalize");
2753
2754 SDLoc DL(Op);
2755 SDValue CT = DAG.getNode(Op->getOpcode(), DL, MVT::i32, V);
2756 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, CT, SDNodeFlags::NonNeg);
2757 }
2758
expandFSH64(SDValue A,SDValue B,SDValue ShiftAmount,SDLoc DL,unsigned Opcode,SelectionDAG & DAG)2759 static SDValue expandFSH64(SDValue A, SDValue B, SDValue ShiftAmount, SDLoc DL,
2760 unsigned Opcode, SelectionDAG &DAG) {
2761 assert(A.getValueType() == MVT::i64 && B.getValueType() == MVT::i64);
2762
2763 const auto *AmtConst = dyn_cast<ConstantSDNode>(ShiftAmount);
2764 if (!AmtConst)
2765 return SDValue();
2766 const auto Amt = AmtConst->getZExtValue() & 63;
2767
2768 SDValue UnpackA =
2769 DAG.getNode(NVPTXISD::UNPACK_VECTOR, DL, {MVT::i32, MVT::i32}, A);
2770 SDValue UnpackB =
2771 DAG.getNode(NVPTXISD::UNPACK_VECTOR, DL, {MVT::i32, MVT::i32}, B);
2772
2773 // Arch is Little endiain: 0 = low bits, 1 = high bits
2774 SDValue ALo = UnpackA.getValue(0);
2775 SDValue AHi = UnpackA.getValue(1);
2776 SDValue BLo = UnpackB.getValue(0);
2777 SDValue BHi = UnpackB.getValue(1);
2778
2779 // The bitfeild consists of { AHi : ALo : BHi : BLo }
2780 //
2781 // * FSHL, Amt < 32 - The window will contain { AHi : ALo : BHi }
2782 // * FSHL, Amt >= 32 - The window will contain { ALo : BHi : BLo }
2783 // * FSHR, Amt < 32 - The window will contain { ALo : BHi : BLo }
2784 // * FSHR, Amt >= 32 - The window will contain { AHi : ALo : BHi }
2785 //
2786 // Note that Amt = 0 and Amt = 32 are special cases where 32-bit funnel shifts
2787 // are not needed at all. Amt = 0 is a no-op producing either A or B depending
2788 // on the direction. Amt = 32 can be implemented by a packing and unpacking
2789 // move to select and arrange the 32bit values. For simplicity, these cases
2790 // are not handled here explicitly and instead we rely on DAGCombiner to
2791 // remove the no-op funnel shifts we insert.
2792 auto [High, Mid, Low] = ((Opcode == ISD::FSHL) == (Amt < 32))
2793 ? std::make_tuple(AHi, ALo, BHi)
2794 : std::make_tuple(ALo, BHi, BLo);
2795
2796 SDValue NewAmt = DAG.getConstant(Amt & 31, DL, MVT::i32);
2797 SDValue RHi = DAG.getNode(Opcode, DL, MVT::i32, {High, Mid, NewAmt});
2798 SDValue RLo = DAG.getNode(Opcode, DL, MVT::i32, {Mid, Low, NewAmt});
2799
2800 return DAG.getNode(NVPTXISD::BUILD_VECTOR, DL, MVT::i64, {RLo, RHi});
2801 }
2802
lowerFSH(SDValue Op,SelectionDAG & DAG)2803 static SDValue lowerFSH(SDValue Op, SelectionDAG &DAG) {
2804 return expandFSH64(Op->getOperand(0), Op->getOperand(1), Op->getOperand(2),
2805 SDLoc(Op), Op->getOpcode(), DAG);
2806 }
2807
lowerROT(SDValue Op,SelectionDAG & DAG)2808 static SDValue lowerROT(SDValue Op, SelectionDAG &DAG) {
2809 unsigned Opcode = Op->getOpcode() == ISD::ROTL ? ISD::FSHL : ISD::FSHR;
2810 return expandFSH64(Op->getOperand(0), Op->getOperand(0), Op->getOperand(1),
2811 SDLoc(Op), Opcode, DAG);
2812 }
2813
lowerFREM(SDValue Op,SelectionDAG & DAG,bool AllowUnsafeFPMath)2814 static SDValue lowerFREM(SDValue Op, SelectionDAG &DAG,
2815 bool AllowUnsafeFPMath) {
2816 // Lower (frem x, y) into (sub x, (mul (ftrunc (div x, y)) y)),
2817 // i.e. "poor man's fmod()". When y is infinite, x is returned. This matches
2818 // the semantics of LLVM's frem.
2819 SDLoc DL(Op);
2820 SDValue X = Op->getOperand(0);
2821 SDValue Y = Op->getOperand(1);
2822 EVT Ty = Op.getValueType();
2823 SDNodeFlags Flags = Op->getFlags();
2824
2825 SDValue Div = DAG.getNode(ISD::FDIV, DL, Ty, X, Y, Flags);
2826 SDValue Trunc = DAG.getNode(ISD::FTRUNC, DL, Ty, Div, Flags);
2827 SDValue Mul = DAG.getNode(ISD::FMUL, DL, Ty, Trunc, Y,
2828 Flags | SDNodeFlags::AllowContract);
2829 SDValue Sub = DAG.getNode(ISD::FSUB, DL, Ty, X, Mul,
2830 Flags | SDNodeFlags::AllowContract);
2831
2832 if (AllowUnsafeFPMath || Flags.hasNoInfs())
2833 return Sub;
2834
2835 // If Y is infinite, return X
2836 SDValue AbsY = DAG.getNode(ISD::FABS, DL, Ty, Y);
2837 SDValue Inf =
2838 DAG.getConstantFP(APFloat::getInf(Ty.getFltSemantics()), DL, Ty);
2839 SDValue IsInf = DAG.getSetCC(DL, MVT::i1, AbsY, Inf, ISD::SETEQ);
2840 return DAG.getSelect(DL, Ty, IsInf, X, Sub);
2841 }
2842
lowerSELECT(SDValue Op,SelectionDAG & DAG)2843 static SDValue lowerSELECT(SDValue Op, SelectionDAG &DAG) {
2844 assert(Op.getValueType() == MVT::i1 && "Custom lowering enabled only for i1");
2845
2846 SDValue Cond = Op->getOperand(0);
2847 SDValue TrueVal = Op->getOperand(1);
2848 SDValue FalseVal = Op->getOperand(2);
2849 SDLoc DL(Op);
2850
2851 // If both operands are truncated, we push the select through the truncates.
2852 if (TrueVal.getOpcode() == ISD::TRUNCATE &&
2853 FalseVal.getOpcode() == ISD::TRUNCATE) {
2854 TrueVal = TrueVal.getOperand(0);
2855 FalseVal = FalseVal.getOperand(0);
2856
2857 EVT VT = TrueVal.getSimpleValueType().bitsLE(FalseVal.getSimpleValueType())
2858 ? TrueVal.getValueType()
2859 : FalseVal.getValueType();
2860 TrueVal = DAG.getAnyExtOrTrunc(TrueVal, DL, VT);
2861 FalseVal = DAG.getAnyExtOrTrunc(FalseVal, DL, VT);
2862 SDValue Select = DAG.getSelect(DL, VT, Cond, TrueVal, FalseVal);
2863 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Select);
2864 }
2865
2866 // Otherwise, expand the select into a series of logical operations. These
2867 // often can be folded into other operations either by us or ptxas.
2868 TrueVal = DAG.getFreeze(TrueVal);
2869 FalseVal = DAG.getFreeze(FalseVal);
2870 SDValue And1 = DAG.getNode(ISD::AND, DL, MVT::i1, Cond, TrueVal);
2871 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
2872 SDValue And2 = DAG.getNode(ISD::AND, DL, MVT::i1, NotCond, FalseVal);
2873 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i1, And1, And2);
2874 return Or;
2875 }
2876
2877 SDValue
LowerOperation(SDValue Op,SelectionDAG & DAG) const2878 NVPTXTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2879 switch (Op.getOpcode()) {
2880 case ISD::RETURNADDR:
2881 return SDValue();
2882 case ISD::FRAMEADDR:
2883 return SDValue();
2884 case ISD::ADDRSPACECAST:
2885 return LowerADDRSPACECAST(Op, DAG);
2886 case ISD::INTRINSIC_W_CHAIN:
2887 return Op;
2888 case ISD::INTRINSIC_WO_CHAIN:
2889 return lowerIntrinsicWOChain(Op, DAG);
2890 case ISD::INTRINSIC_VOID:
2891 return LowerIntrinsicVoid(Op, DAG);
2892 case ISD::BUILD_VECTOR:
2893 return LowerBUILD_VECTOR(Op, DAG);
2894 case ISD::BITCAST:
2895 return LowerBITCAST(Op, DAG);
2896 case ISD::EXTRACT_SUBVECTOR:
2897 return Op;
2898 case ISD::EXTRACT_VECTOR_ELT:
2899 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2900 case ISD::INSERT_VECTOR_ELT:
2901 return LowerINSERT_VECTOR_ELT(Op, DAG);
2902 case ISD::VECTOR_SHUFFLE:
2903 return LowerVECTOR_SHUFFLE(Op, DAG);
2904 case ISD::CONCAT_VECTORS:
2905 return LowerCONCAT_VECTORS(Op, DAG);
2906 case ISD::STORE:
2907 return LowerSTORE(Op, DAG);
2908 case ISD::LOAD:
2909 return LowerLOAD(Op, DAG);
2910 case ISD::SHL_PARTS:
2911 return LowerShiftLeftParts(Op, DAG);
2912 case ISD::SRA_PARTS:
2913 case ISD::SRL_PARTS:
2914 return LowerShiftRightParts(Op, DAG);
2915 case ISD::SELECT:
2916 return lowerSELECT(Op, DAG);
2917 case ISD::FROUND:
2918 return LowerFROUND(Op, DAG);
2919 case ISD::FCOPYSIGN:
2920 return LowerFCOPYSIGN(Op, DAG);
2921 case ISD::SINT_TO_FP:
2922 case ISD::UINT_TO_FP:
2923 return LowerINT_TO_FP(Op, DAG);
2924 case ISD::FP_TO_SINT:
2925 case ISD::FP_TO_UINT:
2926 return LowerFP_TO_INT(Op, DAG);
2927 case ISD::FP_ROUND:
2928 return LowerFP_ROUND(Op, DAG);
2929 case ISD::FP_EXTEND:
2930 return LowerFP_EXTEND(Op, DAG);
2931 case ISD::BR_JT:
2932 return LowerBR_JT(Op, DAG);
2933 case ISD::VAARG:
2934 return LowerVAARG(Op, DAG);
2935 case ISD::VASTART:
2936 return LowerVASTART(Op, DAG);
2937 case ISD::FSHL:
2938 case ISD::FSHR:
2939 return lowerFSH(Op, DAG);
2940 case ISD::ROTL:
2941 case ISD::ROTR:
2942 return lowerROT(Op, DAG);
2943 case ISD::ABS:
2944 case ISD::SMIN:
2945 case ISD::SMAX:
2946 case ISD::UMIN:
2947 case ISD::UMAX:
2948 case ISD::ADD:
2949 case ISD::SUB:
2950 case ISD::MUL:
2951 case ISD::SHL:
2952 case ISD::SREM:
2953 case ISD::UREM:
2954 return LowerVectorArith(Op, DAG);
2955 case ISD::DYNAMIC_STACKALLOC:
2956 return LowerDYNAMIC_STACKALLOC(Op, DAG);
2957 case ISD::STACKRESTORE:
2958 return LowerSTACKRESTORE(Op, DAG);
2959 case ISD::STACKSAVE:
2960 return LowerSTACKSAVE(Op, DAG);
2961 case ISD::CopyToReg:
2962 return LowerCopyToReg_128(Op, DAG);
2963 case ISD::FADD:
2964 case ISD::FSUB:
2965 case ISD::FMUL:
2966 // Used only for bf16 on SM80, where we select fma for non-ftz operation
2967 return PromoteBinOpIfF32FTZ(Op, DAG);
2968 case ISD::CTPOP:
2969 case ISD::CTLZ:
2970 return lowerCTLZCTPOP(Op, DAG);
2971 case ISD::FREM:
2972 return lowerFREM(Op, DAG, allowUnsafeFPMath(DAG.getMachineFunction()));
2973
2974 default:
2975 llvm_unreachable("Custom lowering not defined for operation");
2976 }
2977 }
2978
LowerBR_JT(SDValue Op,SelectionDAG & DAG) const2979 SDValue NVPTXTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
2980 SDLoc DL(Op);
2981 SDValue Chain = Op.getOperand(0);
2982 const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
2983 SDValue Index = Op.getOperand(2);
2984
2985 unsigned JId = JT->getIndex();
2986 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
2987 ArrayRef<MachineBasicBlock *> MBBs = MJTI->getJumpTables()[JId].MBBs;
2988
2989 SDValue IdV = DAG.getConstant(JId, DL, MVT::i32);
2990
2991 // Generate BrxStart node
2992 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2993 Chain = DAG.getNode(NVPTXISD::BrxStart, DL, VTs, Chain, IdV);
2994
2995 // Generate BrxItem nodes
2996 assert(!MBBs.empty());
2997 for (MachineBasicBlock *MBB : MBBs.drop_back())
2998 Chain = DAG.getNode(NVPTXISD::BrxItem, DL, VTs, Chain.getValue(0),
2999 DAG.getBasicBlock(MBB), Chain.getValue(1));
3000
3001 // Generate BrxEnd nodes
3002 SDValue EndOps[] = {Chain.getValue(0), DAG.getBasicBlock(MBBs.back()), Index,
3003 IdV, Chain.getValue(1)};
3004 SDValue BrxEnd = DAG.getNode(NVPTXISD::BrxEnd, DL, VTs, EndOps);
3005
3006 return BrxEnd;
3007 }
3008
3009 // This will prevent AsmPrinter from trying to print the jump tables itself.
getJumpTableEncoding() const3010 unsigned NVPTXTargetLowering::getJumpTableEncoding() const {
3011 return MachineJumpTableInfo::EK_Inline;
3012 }
3013
LowerADDRSPACECAST(SDValue Op,SelectionDAG & DAG) const3014 SDValue NVPTXTargetLowering::LowerADDRSPACECAST(SDValue Op,
3015 SelectionDAG &DAG) const {
3016 AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Op.getNode());
3017 unsigned SrcAS = N->getSrcAddressSpace();
3018 unsigned DestAS = N->getDestAddressSpace();
3019 if (SrcAS != llvm::ADDRESS_SPACE_GENERIC &&
3020 DestAS != llvm::ADDRESS_SPACE_GENERIC) {
3021 // Shared and SharedCluster can be converted to each other through generic
3022 // space
3023 if ((SrcAS == llvm::ADDRESS_SPACE_SHARED &&
3024 DestAS == llvm::ADDRESS_SPACE_SHARED_CLUSTER) ||
3025 (SrcAS == llvm::ADDRESS_SPACE_SHARED_CLUSTER &&
3026 DestAS == llvm::ADDRESS_SPACE_SHARED)) {
3027 SDLoc DL(Op.getNode());
3028 const MVT GenerictVT =
3029 getPointerTy(DAG.getDataLayout(), ADDRESS_SPACE_GENERIC);
3030 SDValue GenericConversion = DAG.getAddrSpaceCast(
3031 DL, GenerictVT, Op.getOperand(0), SrcAS, ADDRESS_SPACE_GENERIC);
3032 SDValue SharedClusterConversion =
3033 DAG.getAddrSpaceCast(DL, Op.getValueType(), GenericConversion,
3034 ADDRESS_SPACE_GENERIC, DestAS);
3035 return SharedClusterConversion;
3036 }
3037
3038 return DAG.getUNDEF(Op.getValueType());
3039 }
3040
3041 return Op;
3042 }
3043
3044 // This function is almost a copy of SelectionDAG::expandVAArg().
3045 // The only diff is that this one produces loads from local address space.
LowerVAARG(SDValue Op,SelectionDAG & DAG) const3046 SDValue NVPTXTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3047 const TargetLowering *TLI = STI.getTargetLowering();
3048 SDLoc DL(Op);
3049
3050 SDNode *Node = Op.getNode();
3051 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3052 EVT VT = Node->getValueType(0);
3053 auto *Ty = VT.getTypeForEVT(*DAG.getContext());
3054 SDValue Tmp1 = Node->getOperand(0);
3055 SDValue Tmp2 = Node->getOperand(1);
3056 const MaybeAlign MA(Node->getConstantOperandVal(3));
3057
3058 SDValue VAListLoad = DAG.getLoad(TLI->getPointerTy(DAG.getDataLayout()), DL,
3059 Tmp1, Tmp2, MachinePointerInfo(V));
3060 SDValue VAList = VAListLoad;
3061
3062 if (MA && *MA > TLI->getMinStackArgumentAlignment()) {
3063 VAList = DAG.getNode(
3064 ISD::ADD, DL, VAList.getValueType(), VAList,
3065 DAG.getConstant(MA->value() - 1, DL, VAList.getValueType()));
3066
3067 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
3068 DAG.getSignedConstant(-(int64_t)MA->value(), DL,
3069 VAList.getValueType()));
3070 }
3071
3072 // Increment the pointer, VAList, to the next vaarg
3073 Tmp1 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
3074 DAG.getConstant(DAG.getDataLayout().getTypeAllocSize(Ty),
3075 DL, VAList.getValueType()));
3076
3077 // Store the incremented VAList to the legalized pointer
3078 Tmp1 = DAG.getStore(VAListLoad.getValue(1), DL, Tmp1, Tmp2,
3079 MachinePointerInfo(V));
3080
3081 const Value *SrcV = Constant::getNullValue(
3082 PointerType::get(*DAG.getContext(), ADDRESS_SPACE_LOCAL));
3083
3084 // Load the actual argument out of the pointer VAList
3085 return DAG.getLoad(VT, DL, Tmp1, VAList, MachinePointerInfo(SrcV));
3086 }
3087
LowerVASTART(SDValue Op,SelectionDAG & DAG) const3088 SDValue NVPTXTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3089 const TargetLowering *TLI = STI.getTargetLowering();
3090 SDLoc DL(Op);
3091 EVT PtrVT = TLI->getPointerTy(DAG.getDataLayout());
3092
3093 // Store the address of unsized array <function>_vararg[] in the ap object.
3094 SDValue VAReg = getParamSymbol(DAG, /* vararg */ -1, PtrVT);
3095
3096 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3097 return DAG.getStore(Op.getOperand(0), DL, VAReg, Op.getOperand(1),
3098 MachinePointerInfo(SV));
3099 }
3100
3101 static void replaceLoadVector(SDNode *N, SelectionDAG &DAG,
3102 SmallVectorImpl<SDValue> &Results,
3103 const NVPTXSubtarget &STI);
3104
LowerLOAD(SDValue Op,SelectionDAG & DAG) const3105 SDValue NVPTXTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3106 if (Op.getValueType() == MVT::i1)
3107 return LowerLOADi1(Op, DAG);
3108
3109 EVT VT = Op.getValueType();
3110
3111 if (NVPTX::isPackedVectorTy(VT)) {
3112 // v2f32/v2f16/v2bf16/v2i16/v4i8 are legal, so we can't rely on legalizer to
3113 // handle unaligned loads and have to handle it here.
3114 LoadSDNode *Load = cast<LoadSDNode>(Op);
3115 EVT MemVT = Load->getMemoryVT();
3116 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3117 MemVT, *Load->getMemOperand())) {
3118 SDValue Ops[2];
3119 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
3120 return DAG.getMergeValues(Ops, SDLoc(Op));
3121 }
3122 }
3123
3124 return SDValue();
3125 }
3126
3127 // v = ld i1* addr
3128 // =>
3129 // v1 = ld i8* addr (-> i16)
3130 // v = trunc i16 to i1
LowerLOADi1(SDValue Op,SelectionDAG & DAG) const3131 SDValue NVPTXTargetLowering::LowerLOADi1(SDValue Op, SelectionDAG &DAG) const {
3132 SDNode *Node = Op.getNode();
3133 LoadSDNode *LD = cast<LoadSDNode>(Node);
3134 SDLoc dl(Node);
3135 assert(LD->getExtensionType() == ISD::NON_EXTLOAD);
3136 assert(Node->getValueType(0) == MVT::i1 &&
3137 "Custom lowering for i1 load only");
3138 SDValue newLD = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i16, LD->getChain(),
3139 LD->getBasePtr(), LD->getPointerInfo(),
3140 MVT::i8, LD->getAlign(),
3141 LD->getMemOperand()->getFlags());
3142 SDValue result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, newLD);
3143 // The legalizer (the caller) is expecting two values from the legalized
3144 // load, so we build a MergeValues node for it. See ExpandUnalignedLoad()
3145 // in LegalizeDAG.cpp which also uses MergeValues.
3146 SDValue Ops[] = { result, LD->getChain() };
3147 return DAG.getMergeValues(Ops, dl);
3148 }
3149
LowerSTORE(SDValue Op,SelectionDAG & DAG) const3150 SDValue NVPTXTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3151 StoreSDNode *Store = cast<StoreSDNode>(Op);
3152 EVT VT = Store->getMemoryVT();
3153
3154 if (VT == MVT::i1)
3155 return LowerSTOREi1(Op, DAG);
3156
3157 // v2f32/v2f16/v2bf16/v2i16/v4i8 are legal, so we can't rely on legalizer to
3158 // handle unaligned stores and have to handle it here.
3159 if (NVPTX::isPackedVectorTy(VT) &&
3160 !allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3161 VT, *Store->getMemOperand()))
3162 return expandUnalignedStore(Store, DAG);
3163
3164 // v2f16/v2bf16/v2i16 don't need special handling.
3165 if (NVPTX::isPackedVectorTy(VT) && VT.is32BitVector())
3166 return SDValue();
3167
3168 // Lower store of any other vector type, including v2f32 as we want to break
3169 // it apart since this is not a widely-supported type.
3170 return LowerSTOREVector(Op, DAG);
3171 }
3172
3173 SDValue
LowerSTOREVector(SDValue Op,SelectionDAG & DAG) const3174 NVPTXTargetLowering::LowerSTOREVector(SDValue Op, SelectionDAG &DAG) const {
3175 MemSDNode *N = cast<MemSDNode>(Op.getNode());
3176 SDValue Val = N->getOperand(1);
3177 SDLoc DL(N);
3178 const EVT ValVT = Val.getValueType();
3179 const EVT MemVT = N->getMemoryVT();
3180
3181 // If we're truncating as part of the store, avoid lowering to a StoreV node.
3182 // TODO: consider relaxing this restriction.
3183 if (ValVT != MemVT)
3184 return SDValue();
3185
3186 const auto NumEltsAndEltVT = getVectorLoweringShape(
3187 ValVT, STI.has256BitVectorLoadStore(N->getAddressSpace()));
3188 if (!NumEltsAndEltVT)
3189 return SDValue();
3190 const auto [NumElts, EltVT] = NumEltsAndEltVT.value();
3191
3192 const DataLayout &TD = DAG.getDataLayout();
3193
3194 Align Alignment = N->getAlign();
3195 Align PrefAlign = TD.getPrefTypeAlign(ValVT.getTypeForEVT(*DAG.getContext()));
3196 if (Alignment < PrefAlign) {
3197 // This store is not sufficiently aligned, so bail out and let this vector
3198 // store be scalarized. Note that we may still be able to emit smaller
3199 // vector stores. For example, if we are storing a <4 x float> with an
3200 // alignment of 8, this check will fail but the legalizer will try again
3201 // with 2 x <2 x float>, which will succeed with an alignment of 8.
3202 return SDValue();
3203 }
3204
3205 unsigned Opcode;
3206 switch (NumElts) {
3207 default:
3208 return SDValue();
3209 case 2:
3210 Opcode = NVPTXISD::StoreV2;
3211 break;
3212 case 4:
3213 Opcode = NVPTXISD::StoreV4;
3214 break;
3215 case 8:
3216 Opcode = NVPTXISD::StoreV8;
3217 break;
3218 }
3219
3220 SmallVector<SDValue, 8> Ops;
3221
3222 // First is the chain
3223 Ops.push_back(N->getOperand(0));
3224
3225 // Then the split values
3226 if (EltVT.isVector()) {
3227 assert(EVT(EltVT.getVectorElementType()) == ValVT.getVectorElementType());
3228 assert(NumElts * EltVT.getVectorNumElements() ==
3229 ValVT.getVectorNumElements());
3230 // Combine individual elements into v2[i,f,bf]16/v4i8 subvectors to be
3231 // stored as b32s
3232 const unsigned NumEltsPerSubVector = EltVT.getVectorNumElements();
3233 for (const unsigned I : llvm::seq(NumElts)) {
3234 SmallVector<SDValue, 4> SubVectorElts;
3235 DAG.ExtractVectorElements(Val, SubVectorElts, I * NumEltsPerSubVector,
3236 NumEltsPerSubVector);
3237 Ops.push_back(DAG.getBuildVector(EltVT, DL, SubVectorElts));
3238 }
3239 } else {
3240 SDValue V = DAG.getBitcast(MVT::getVectorVT(EltVT, NumElts), Val);
3241 for (const unsigned I : llvm::seq(NumElts)) {
3242 SDValue ExtVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, V,
3243 DAG.getIntPtrConstant(I, DL));
3244
3245 // Since StoreV2 is a target node, we cannot rely on DAG type
3246 // legalization. Therefore, we must ensure the type is legal. For i1 and
3247 // i8, we set the stored type to i16 and propagate the "real" type as the
3248 // memory type.
3249 if (EltVT.getSizeInBits() < 16)
3250 ExtVal = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i16, ExtVal);
3251 Ops.push_back(ExtVal);
3252 }
3253 }
3254
3255 // Then any remaining arguments
3256 Ops.append(N->op_begin() + 2, N->op_end());
3257
3258 SDValue NewSt =
3259 DAG.getMemIntrinsicNode(Opcode, DL, DAG.getVTList(MVT::Other), Ops,
3260 N->getMemoryVT(), N->getMemOperand());
3261
3262 // return DCI.CombineTo(N, NewSt, true);
3263 return NewSt;
3264 }
3265
3266 // st i1 v, addr
3267 // =>
3268 // v1 = zxt v to i16
3269 // st.u8 i16, addr
LowerSTOREi1(SDValue Op,SelectionDAG & DAG) const3270 SDValue NVPTXTargetLowering::LowerSTOREi1(SDValue Op, SelectionDAG &DAG) const {
3271 SDNode *Node = Op.getNode();
3272 SDLoc dl(Node);
3273 StoreSDNode *ST = cast<StoreSDNode>(Node);
3274 SDValue Tmp1 = ST->getChain();
3275 SDValue Tmp2 = ST->getBasePtr();
3276 SDValue Tmp3 = ST->getValue();
3277 assert(Tmp3.getValueType() == MVT::i1 && "Custom lowering for i1 store only");
3278 Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Tmp3);
3279 SDValue Result =
3280 DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(), MVT::i8,
3281 ST->getAlign(), ST->getMemOperand()->getFlags());
3282 return Result;
3283 }
3284
LowerCopyToReg_128(SDValue Op,SelectionDAG & DAG) const3285 SDValue NVPTXTargetLowering::LowerCopyToReg_128(SDValue Op,
3286 SelectionDAG &DAG) const {
3287 // Change the CopyToReg to take in two 64-bit operands instead of a 128-bit
3288 // operand so that it can pass the legalization.
3289
3290 assert(Op.getOperand(1).getValueType() == MVT::i128 &&
3291 "Custom lowering for 128-bit CopyToReg only");
3292
3293 SDNode *Node = Op.getNode();
3294 SDLoc DL(Node);
3295
3296 SDValue Cast = DAG.getBitcast(MVT::v2i64, Op->getOperand(2));
3297 SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, Cast,
3298 DAG.getIntPtrConstant(0, DL));
3299 SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, Cast,
3300 DAG.getIntPtrConstant(1, DL));
3301
3302 SmallVector<SDValue, 5> NewOps(Op->getNumOperands() + 1);
3303 SmallVector<EVT, 3> ResultsType(Node->values());
3304
3305 NewOps[0] = Op->getOperand(0); // Chain
3306 NewOps[1] = Op->getOperand(1); // Dst Reg
3307 NewOps[2] = Lo; // Lower 64-bit
3308 NewOps[3] = Hi; // Higher 64-bit
3309 if (Op.getNumOperands() == 4)
3310 NewOps[4] = Op->getOperand(3); // Glue if exists
3311
3312 return DAG.getNode(ISD::CopyToReg, DL, ResultsType, NewOps);
3313 }
3314
getNumRegisters(LLVMContext & Context,EVT VT,std::optional<MVT> RegisterVT=std::nullopt) const3315 unsigned NVPTXTargetLowering::getNumRegisters(
3316 LLVMContext &Context, EVT VT,
3317 std::optional<MVT> RegisterVT = std::nullopt) const {
3318 if (VT == MVT::i128 && RegisterVT == MVT::i128)
3319 return 1;
3320 return TargetLoweringBase::getNumRegisters(Context, VT, RegisterVT);
3321 }
3322
splitValueIntoRegisterParts(SelectionDAG & DAG,const SDLoc & DL,SDValue Val,SDValue * Parts,unsigned NumParts,MVT PartVT,std::optional<CallingConv::ID> CC) const3323 bool NVPTXTargetLowering::splitValueIntoRegisterParts(
3324 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
3325 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
3326 if (Val.getValueType() == MVT::i128 && NumParts == 1) {
3327 Parts[0] = Val;
3328 return true;
3329 }
3330 return false;
3331 }
3332
3333 // This creates target external symbol for a function parameter.
3334 // Name of the symbol is composed from its index and the function name.
3335 // Negative index corresponds to special parameter (unsized array) used for
3336 // passing variable arguments.
getParamSymbol(SelectionDAG & DAG,int I,EVT T) const3337 SDValue NVPTXTargetLowering::getParamSymbol(SelectionDAG &DAG, int I,
3338 EVT T) const {
3339 StringRef SavedStr = nvTM->getStrPool().save(
3340 getParamName(&DAG.getMachineFunction().getFunction(), I));
3341 return DAG.getExternalSymbol(SavedStr.data(), T);
3342 }
3343
getCallParamSymbol(SelectionDAG & DAG,int I,EVT T) const3344 SDValue NVPTXTargetLowering::getCallParamSymbol(SelectionDAG &DAG, int I,
3345 EVT T) const {
3346 const StringRef SavedStr = nvTM->getStrPool().save("param" + Twine(I));
3347 return DAG.getExternalSymbol(SavedStr.data(), T);
3348 }
3349
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const3350 SDValue NVPTXTargetLowering::LowerFormalArguments(
3351 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3352 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3353 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3354 MachineFunction &MF = DAG.getMachineFunction();
3355 const DataLayout &DL = DAG.getDataLayout();
3356 auto PtrVT = getPointerTy(DAG.getDataLayout());
3357
3358 const Function *F = &MF.getFunction();
3359
3360 SDValue Root = DAG.getRoot();
3361 SmallVector<SDValue, 16> OutChains;
3362
3363 // argTypes.size() (or theArgs.size()) and Ins.size() need not match.
3364 // Ins.size() will be larger
3365 // * if there is an aggregate argument with multiple fields (each field
3366 // showing up separately in Ins)
3367 // * if there is a vector argument with more than typical vector-length
3368 // elements (generally if more than 4) where each vector element is
3369 // individually present in Ins.
3370 // So a different index should be used for indexing into Ins.
3371 // See similar issue in LowerCall.
3372
3373 auto AllIns = ArrayRef(Ins);
3374 for (const auto &Arg : F->args()) {
3375 const auto ArgIns = AllIns.take_while(
3376 [&](auto I) { return I.OrigArgIndex == Arg.getArgNo(); });
3377 AllIns = AllIns.drop_front(ArgIns.size());
3378
3379 Type *Ty = Arg.getType();
3380
3381 if (ArgIns.empty())
3382 report_fatal_error("Empty parameter types are not supported");
3383
3384 if (Arg.use_empty()) {
3385 // argument is dead
3386 for (const auto &In : ArgIns) {
3387 assert(!In.Used && "Arg.use_empty() is true but Arg is used?");
3388 InVals.push_back(DAG.getUNDEF(In.VT));
3389 }
3390 continue;
3391 }
3392
3393 SDValue ArgSymbol = getParamSymbol(DAG, Arg.getArgNo(), PtrVT);
3394
3395 // In the following cases, assign a node order of "i+1"
3396 // to newly created nodes. The SDNodes for params have to
3397 // appear in the same order as their order of appearance
3398 // in the original function. "i+1" holds that order.
3399 if (Arg.hasByValAttr()) {
3400 // Param has ByVal attribute
3401 // Return MoveParam(param symbol).
3402 // Ideally, the param symbol can be returned directly,
3403 // but when SDNode builder decides to use it in a CopyToReg(),
3404 // machine instruction fails because TargetExternalSymbol
3405 // (not lowered) is target dependent, and CopyToReg assumes
3406 // the source is lowered.
3407 assert(ArgIns.size() == 1 && "ByVal argument must be a pointer");
3408 const auto &ByvalIn = ArgIns[0];
3409 assert(getValueType(DL, Ty) == ByvalIn.VT &&
3410 "Ins type did not match function type");
3411 assert(ByvalIn.VT == PtrVT && "ByVal argument must be a pointer");
3412
3413 SDValue P;
3414 if (isKernelFunction(*F)) {
3415 P = ArgSymbol;
3416 P.getNode()->setIROrder(Arg.getArgNo() + 1);
3417 } else {
3418 P = DAG.getNode(NVPTXISD::MoveParam, dl, ByvalIn.VT, ArgSymbol);
3419 P.getNode()->setIROrder(Arg.getArgNo() + 1);
3420 P = DAG.getAddrSpaceCast(dl, ByvalIn.VT, P, ADDRESS_SPACE_LOCAL,
3421 ADDRESS_SPACE_GENERIC);
3422 }
3423 InVals.push_back(P);
3424 } else {
3425 SmallVector<EVT, 16> VTs;
3426 SmallVector<uint64_t, 16> Offsets;
3427 ComputePTXValueVTs(*this, DL, Ty, VTs, &Offsets, 0);
3428 assert(VTs.size() == ArgIns.size() && "Size mismatch");
3429 assert(VTs.size() == Offsets.size() && "Size mismatch");
3430
3431 const Align ArgAlign = getFunctionArgumentAlignment(
3432 F, Ty, Arg.getArgNo() + AttributeList::FirstArgIndex, DL);
3433
3434 const auto VectorInfo = VectorizePTXValueVTs(VTs, Offsets, ArgAlign);
3435 unsigned I = 0;
3436 for (const unsigned NumElts : VectorInfo) {
3437 // i1 is loaded/stored as i8
3438 const EVT LoadVT = VTs[I] == MVT::i1 ? MVT::i8 : VTs[I];
3439 // If the element is a packed type (ex. v2f16, v4i8, etc) holding
3440 // multiple elements.
3441 const unsigned PackingAmt =
3442 LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
3443
3444 const EVT VecVT =
3445 NumElts == 1
3446 ? LoadVT
3447 : EVT::getVectorVT(F->getContext(), LoadVT.getScalarType(),
3448 NumElts * PackingAmt);
3449
3450 SDValue VecAddr = DAG.getObjectPtrOffset(
3451 dl, ArgSymbol, TypeSize::getFixed(Offsets[I]));
3452
3453 const MaybeAlign PartAlign = commonAlignment(ArgAlign, Offsets[I]);
3454 SDValue P =
3455 DAG.getLoad(VecVT, dl, Root, VecAddr,
3456 MachinePointerInfo(ADDRESS_SPACE_PARAM), PartAlign,
3457 MachineMemOperand::MODereferenceable |
3458 MachineMemOperand::MOInvariant);
3459 if (P.getNode())
3460 P.getNode()->setIROrder(Arg.getArgNo() + 1);
3461 for (const unsigned J : llvm::seq(NumElts)) {
3462 SDValue Elt =
3463 NumElts == 1
3464 ? P
3465 : DAG.getNode(LoadVT.isVector() ? ISD::EXTRACT_SUBVECTOR
3466 : ISD::EXTRACT_VECTOR_ELT,
3467 dl, LoadVT, P,
3468 DAG.getVectorIdxConstant(J * PackingAmt, dl));
3469
3470 Elt = correctParamType(Elt, ArgIns[I + J].VT, ArgIns[I + J].Flags,
3471 DAG, dl);
3472 InVals.push_back(Elt);
3473 }
3474 I += NumElts;
3475 }
3476 }
3477 }
3478
3479 if (!OutChains.empty())
3480 DAG.setRoot(DAG.getTokenFactor(dl, OutChains));
3481
3482 return Chain;
3483 }
3484
3485 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & dl,SelectionDAG & DAG) const3486 NVPTXTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3487 bool isVarArg,
3488 const SmallVectorImpl<ISD::OutputArg> &Outs,
3489 const SmallVectorImpl<SDValue> &OutVals,
3490 const SDLoc &dl, SelectionDAG &DAG) const {
3491 const MachineFunction &MF = DAG.getMachineFunction();
3492 const Function &F = MF.getFunction();
3493 Type *RetTy = MF.getFunction().getReturnType();
3494
3495 if (RetTy->isVoidTy()) {
3496 assert(OutVals.empty() && Outs.empty() && "Return value expected for void");
3497 return DAG.getNode(NVPTXISD::RET_GLUE, dl, MVT::Other, Chain);
3498 }
3499
3500 const DataLayout &DL = DAG.getDataLayout();
3501 SmallVector<EVT, 16> VTs;
3502 SmallVector<uint64_t, 16> Offsets;
3503 ComputePTXValueVTs(*this, DL, RetTy, VTs, &Offsets);
3504 assert(VTs.size() == OutVals.size() && "Bad return value decomposition");
3505
3506 // PTX Interoperability Guide 3.3(A): [Integer] Values shorter than
3507 // 32-bits are sign extended or zero extended, depending on whether
3508 // they are signed or unsigned types.
3509 const bool ExtendIntegerRetVal =
3510 RetTy->isIntegerTy() && DL.getTypeAllocSizeInBits(RetTy) < 32;
3511
3512 const auto GetRetVal = [&](unsigned I) -> SDValue {
3513 SDValue RetVal = OutVals[I];
3514 assert(promoteScalarIntegerPTX(RetVal.getValueType()) ==
3515 RetVal.getValueType() &&
3516 "OutVal type should always be legal");
3517
3518 const EVT VTI = promoteScalarIntegerPTX(VTs[I]);
3519 const EVT StoreVT =
3520 ExtendIntegerRetVal ? MVT::i32 : (VTI == MVT::i1 ? MVT::i8 : VTI);
3521 return correctParamType(RetVal, StoreVT, Outs[I].Flags, DAG, dl);
3522 };
3523
3524 const auto RetAlign = getFunctionParamOptimizedAlign(&F, RetTy, DL);
3525 const auto VectorInfo = VectorizePTXValueVTs(VTs, Offsets, RetAlign);
3526 unsigned I = 0;
3527 for (const unsigned NumElts : VectorInfo) {
3528 const MaybeAlign CurrentAlign = ExtendIntegerRetVal
3529 ? MaybeAlign(std::nullopt)
3530 : commonAlignment(RetAlign, Offsets[I]);
3531
3532 SDValue Val;
3533 if (NumElts == 1) {
3534 Val = GetRetVal(I);
3535 } else {
3536 SmallVector<SDValue, 4> StoreVals;
3537 for (const unsigned J : llvm::seq(NumElts)) {
3538 SDValue ValJ = GetRetVal(I + J);
3539 if (ValJ.getValueType().isVector())
3540 DAG.ExtractVectorElements(ValJ, StoreVals);
3541 else
3542 StoreVals.push_back(ValJ);
3543 }
3544
3545 EVT VT = EVT::getVectorVT(F.getContext(), StoreVals[0].getValueType(),
3546 StoreVals.size());
3547 Val = DAG.getBuildVector(VT, dl, StoreVals);
3548 }
3549
3550 const SDValue RetSymbol = DAG.getExternalSymbol("func_retval0", MVT::i32);
3551 SDValue Ptr =
3552 DAG.getObjectPtrOffset(dl, RetSymbol, TypeSize::getFixed(Offsets[I]));
3553
3554 Chain = DAG.getStore(Chain, dl, Val, Ptr,
3555 MachinePointerInfo(ADDRESS_SPACE_PARAM), CurrentAlign);
3556
3557 I += NumElts;
3558 }
3559
3560 return DAG.getNode(NVPTXISD::RET_GLUE, dl, MVT::Other, Chain);
3561 }
3562
LowerAsmOperandForConstraint(SDValue Op,StringRef Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const3563 void NVPTXTargetLowering::LowerAsmOperandForConstraint(
3564 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
3565 SelectionDAG &DAG) const {
3566 if (Constraint.size() > 1)
3567 return;
3568 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3569 }
3570
3571 // llvm.ptx.memcpy.const and llvm.ptx.memmove.const need to be modeled as
3572 // TgtMemIntrinsic
3573 // because we need the information that is only available in the "Value" type
3574 // of destination
3575 // pointer. In particular, the address space information.
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,MachineFunction & MF,unsigned Intrinsic) const3576 bool NVPTXTargetLowering::getTgtMemIntrinsic(
3577 IntrinsicInfo &Info, const CallInst &I,
3578 MachineFunction &MF, unsigned Intrinsic) const {
3579 switch (Intrinsic) {
3580 default:
3581 return false;
3582 case Intrinsic::nvvm_match_all_sync_i32p:
3583 case Intrinsic::nvvm_match_all_sync_i64p:
3584 Info.opc = ISD::INTRINSIC_W_CHAIN;
3585 // memVT is bogus. These intrinsics have IntrInaccessibleMemOnly attribute
3586 // in order to model data exchange with other threads, but perform no real
3587 // memory accesses.
3588 Info.memVT = MVT::i1;
3589
3590 // Our result depends on both our and other thread's arguments.
3591 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3592 return true;
3593 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_col:
3594 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_row:
3595 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_col_stride:
3596 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_row_stride:
3597 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_col:
3598 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_row:
3599 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_col_stride:
3600 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_row_stride:
3601 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_col:
3602 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_row:
3603 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_col_stride:
3604 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_row_stride:
3605 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_col:
3606 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_row:
3607 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_col_stride:
3608 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_row_stride:
3609 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_col:
3610 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_row:
3611 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_col_stride:
3612 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_row_stride:
3613 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_col:
3614 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_row:
3615 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_col_stride:
3616 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_row_stride: {
3617 Info.opc = ISD::INTRINSIC_W_CHAIN;
3618 Info.memVT = MVT::v8f16;
3619 Info.ptrVal = I.getArgOperand(0);
3620 Info.offset = 0;
3621 Info.flags = MachineMemOperand::MOLoad;
3622 Info.align = Align(16);
3623 return true;
3624 }
3625 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_col:
3626 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_col_stride:
3627 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_col_stride:
3628 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_col:
3629 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_row:
3630 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_row_stride:
3631 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_row_stride:
3632 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_row:
3633 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_col:
3634 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_col_stride:
3635 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_row:
3636 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_row_stride:
3637 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_col:
3638 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_col_stride:
3639 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_col_stride:
3640 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_col:
3641 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_row:
3642 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_row_stride:
3643 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_row_stride:
3644 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_row:
3645 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_col:
3646 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_col_stride:
3647 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_row:
3648 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_row_stride: {
3649 Info.opc = ISD::INTRINSIC_W_CHAIN;
3650 Info.memVT = MVT::v2i32;
3651 Info.ptrVal = I.getArgOperand(0);
3652 Info.offset = 0;
3653 Info.flags = MachineMemOperand::MOLoad;
3654 Info.align = Align(8);
3655 return true;
3656 }
3657
3658 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_col:
3659 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_col_stride:
3660 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_col_stride:
3661 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_col:
3662 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_row:
3663 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_row_stride:
3664 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_row_stride:
3665 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_row:
3666 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_col:
3667 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_col_stride:
3668 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_row:
3669 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_row_stride:
3670 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_col:
3671 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_col_stride:
3672 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_row:
3673 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_row_stride:
3674
3675 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_col:
3676 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_col_stride:
3677 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_col_stride:
3678 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_col:
3679 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_row:
3680 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_row_stride:
3681 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_row_stride:
3682 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_row:
3683 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_col:
3684 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_col_stride:
3685 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_row:
3686 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_row_stride:
3687 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_col:
3688 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_col_stride:
3689 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_row:
3690 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_row_stride:
3691 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x4_b16:
3692 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x4_trans_b16:
3693 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x2_trans_b8:
3694 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x2_trans_b8x16_b4x16_p64:
3695 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x2_trans_b8x16_b6x16_p32:
3696 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x4_b8x16_b4x16_p64:
3697 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x4_b8x16_b6x16_p32: {
3698 Info.opc = ISD::INTRINSIC_W_CHAIN;
3699 Info.memVT = MVT::v4i32;
3700 Info.ptrVal = I.getArgOperand(0);
3701 Info.offset = 0;
3702 Info.flags = MachineMemOperand::MOLoad;
3703 Info.align = Align(16);
3704 return true;
3705 }
3706
3707 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_col:
3708 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_col_stride:
3709 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_col_stride:
3710 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_col:
3711 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_row:
3712 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_row_stride:
3713 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_row_stride:
3714 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_row:
3715
3716 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_col:
3717 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_col_stride:
3718 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_col_stride:
3719 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_col:
3720 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_row:
3721 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_row_stride:
3722 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_row_stride:
3723 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_row:
3724 case Intrinsic::nvvm_wmma_m8n8k128_load_a_b1_row:
3725 case Intrinsic::nvvm_wmma_m8n8k128_load_a_b1_row_stride:
3726 case Intrinsic::nvvm_wmma_m8n8k128_load_b_b1_col:
3727 case Intrinsic::nvvm_wmma_m8n8k128_load_b_b1_col_stride:
3728 case Intrinsic::nvvm_wmma_m8n8k32_load_a_s4_row:
3729 case Intrinsic::nvvm_wmma_m8n8k32_load_a_s4_row_stride:
3730 case Intrinsic::nvvm_wmma_m8n8k32_load_a_u4_row_stride:
3731 case Intrinsic::nvvm_wmma_m8n8k32_load_a_u4_row:
3732 case Intrinsic::nvvm_wmma_m8n8k32_load_b_s4_col:
3733 case Intrinsic::nvvm_wmma_m8n8k32_load_b_s4_col_stride:
3734 case Intrinsic::nvvm_wmma_m8n8k32_load_b_u4_col_stride:
3735 case Intrinsic::nvvm_wmma_m8n8k32_load_b_u4_col:
3736 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x1_b16:
3737 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x1_trans_b16:
3738 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x1_b8x16_b4x16_p64:
3739 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x1_b8x16_b6x16_p32: {
3740 Info.opc = ISD::INTRINSIC_W_CHAIN;
3741 Info.memVT = MVT::i32;
3742 Info.ptrVal = I.getArgOperand(0);
3743 Info.offset = 0;
3744 Info.flags = MachineMemOperand::MOLoad;
3745 Info.align = Align(4);
3746 return true;
3747 }
3748
3749 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_col:
3750 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_row:
3751 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_col_stride:
3752 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_row_stride:
3753 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_col:
3754 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_row:
3755 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_col_stride:
3756 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_row_stride:
3757 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_col:
3758 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_row:
3759 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_col_stride:
3760 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_row_stride: {
3761 Info.opc = ISD::INTRINSIC_W_CHAIN;
3762 Info.memVT = MVT::v4f16;
3763 Info.ptrVal = I.getArgOperand(0);
3764 Info.offset = 0;
3765 Info.flags = MachineMemOperand::MOLoad;
3766 Info.align = Align(16);
3767 return true;
3768 }
3769
3770 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_col:
3771 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_row:
3772 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_col_stride:
3773 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_row_stride:
3774 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_col:
3775 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_row:
3776 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_col_stride:
3777 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_row_stride:
3778 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_col:
3779 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_row:
3780 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_col_stride:
3781 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_row_stride:
3782 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_col:
3783 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_row:
3784 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_col_stride:
3785 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_row_stride: {
3786 Info.opc = ISD::INTRINSIC_W_CHAIN;
3787 Info.memVT = MVT::v8f32;
3788 Info.ptrVal = I.getArgOperand(0);
3789 Info.offset = 0;
3790 Info.flags = MachineMemOperand::MOLoad;
3791 Info.align = Align(16);
3792 return true;
3793 }
3794
3795 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_col:
3796 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_col_stride:
3797 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_row:
3798 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_row_stride:
3799
3800 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_col:
3801 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_col_stride:
3802 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_row:
3803 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_row_stride:
3804
3805 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_col:
3806 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_col_stride:
3807 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_row:
3808 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_row_stride:
3809 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_col:
3810 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_col_stride:
3811 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_row:
3812 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_row_stride:
3813 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_col:
3814 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_col_stride:
3815 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_row:
3816 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_row_stride: {
3817 Info.opc = ISD::INTRINSIC_W_CHAIN;
3818 Info.memVT = MVT::v8i32;
3819 Info.ptrVal = I.getArgOperand(0);
3820 Info.offset = 0;
3821 Info.flags = MachineMemOperand::MOLoad;
3822 Info.align = Align(16);
3823 return true;
3824 }
3825
3826 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_col:
3827 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_col_stride:
3828 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_row:
3829 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_row_stride:
3830 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_col:
3831 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_col_stride:
3832 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_row:
3833 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_row_stride:
3834 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x2_b16:
3835 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x2_trans_b16:
3836 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x1_trans_b8:
3837 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x1_trans_b8x16_b4x16_p64:
3838 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x1_trans_b8x16_b6x16_p32:
3839 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x2_b8x16_b4x16_p64:
3840 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x2_b8x16_b6x16_p32: {
3841 Info.opc = ISD::INTRINSIC_W_CHAIN;
3842 Info.memVT = MVT::v2i32;
3843 Info.ptrVal = I.getArgOperand(0);
3844 Info.offset = 0;
3845 Info.flags = MachineMemOperand::MOLoad;
3846 Info.align = Align(8);
3847 return true;
3848 }
3849
3850 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_col:
3851 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_col_stride:
3852 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_row:
3853 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_row_stride:
3854
3855 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_col:
3856 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_col_stride:
3857 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_row:
3858 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_row_stride: {
3859 Info.opc = ISD::INTRINSIC_W_CHAIN;
3860 Info.memVT = MVT::f64;
3861 Info.ptrVal = I.getArgOperand(0);
3862 Info.offset = 0;
3863 Info.flags = MachineMemOperand::MOLoad;
3864 Info.align = Align(8);
3865 return true;
3866 }
3867
3868 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_col:
3869 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_col_stride:
3870 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_row:
3871 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_row_stride: {
3872 Info.opc = ISD::INTRINSIC_W_CHAIN;
3873 Info.memVT = MVT::v2f64;
3874 Info.ptrVal = I.getArgOperand(0);
3875 Info.offset = 0;
3876 Info.flags = MachineMemOperand::MOLoad;
3877 Info.align = Align(16);
3878 return true;
3879 }
3880
3881 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_col:
3882 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_row:
3883 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_col_stride:
3884 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_row_stride:
3885 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_col:
3886 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_row:
3887 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_col_stride:
3888 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_row_stride:
3889 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_col:
3890 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_row:
3891 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_col_stride:
3892 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_row_stride: {
3893 Info.opc = ISD::INTRINSIC_VOID;
3894 Info.memVT = MVT::v4f16;
3895 Info.ptrVal = I.getArgOperand(0);
3896 Info.offset = 0;
3897 Info.flags = MachineMemOperand::MOStore;
3898 Info.align = Align(16);
3899 return true;
3900 }
3901
3902 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_col:
3903 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_row:
3904 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_col_stride:
3905 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_row_stride:
3906 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_col:
3907 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_row:
3908 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_col_stride:
3909 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_row_stride:
3910 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_col:
3911 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_row:
3912 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_col_stride:
3913 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_row_stride:
3914 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_col:
3915 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_row:
3916 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_col_stride:
3917 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_row_stride: {
3918 Info.opc = ISD::INTRINSIC_VOID;
3919 Info.memVT = MVT::v8f32;
3920 Info.ptrVal = I.getArgOperand(0);
3921 Info.offset = 0;
3922 Info.flags = MachineMemOperand::MOStore;
3923 Info.align = Align(16);
3924 return true;
3925 }
3926
3927 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_col:
3928 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_col_stride:
3929 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_row:
3930 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_row_stride:
3931 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_col:
3932 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_col_stride:
3933 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_row:
3934 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_row_stride:
3935 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_col:
3936 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_col_stride:
3937 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_row:
3938 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_row_stride: {
3939 Info.opc = ISD::INTRINSIC_VOID;
3940 Info.memVT = MVT::v8i32;
3941 Info.ptrVal = I.getArgOperand(0);
3942 Info.offset = 0;
3943 Info.flags = MachineMemOperand::MOStore;
3944 Info.align = Align(16);
3945 return true;
3946 }
3947
3948 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_col:
3949 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_col_stride:
3950 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_row:
3951 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_row_stride:
3952 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_col:
3953 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_col_stride:
3954 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_row:
3955 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_row_stride: {
3956 Info.opc = ISD::INTRINSIC_VOID;
3957 Info.memVT = MVT::v2i32;
3958 Info.ptrVal = I.getArgOperand(0);
3959 Info.offset = 0;
3960 Info.flags = MachineMemOperand::MOStore;
3961 Info.align = Align(8);
3962 return true;
3963 }
3964
3965 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_col:
3966 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_col_stride:
3967 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_row:
3968 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_row_stride: {
3969 Info.opc = ISD::INTRINSIC_VOID;
3970 Info.memVT = MVT::v2f64;
3971 Info.ptrVal = I.getArgOperand(0);
3972 Info.offset = 0;
3973 Info.flags = MachineMemOperand::MOStore;
3974 Info.align = Align(16);
3975 return true;
3976 }
3977
3978 case Intrinsic::nvvm_atomic_add_gen_f_cta:
3979 case Intrinsic::nvvm_atomic_add_gen_f_sys:
3980 case Intrinsic::nvvm_atomic_add_gen_i_cta:
3981 case Intrinsic::nvvm_atomic_add_gen_i_sys:
3982 case Intrinsic::nvvm_atomic_and_gen_i_cta:
3983 case Intrinsic::nvvm_atomic_and_gen_i_sys:
3984 case Intrinsic::nvvm_atomic_cas_gen_i_cta:
3985 case Intrinsic::nvvm_atomic_cas_gen_i_sys:
3986 case Intrinsic::nvvm_atomic_dec_gen_i_cta:
3987 case Intrinsic::nvvm_atomic_dec_gen_i_sys:
3988 case Intrinsic::nvvm_atomic_inc_gen_i_cta:
3989 case Intrinsic::nvvm_atomic_inc_gen_i_sys:
3990 case Intrinsic::nvvm_atomic_max_gen_i_cta:
3991 case Intrinsic::nvvm_atomic_max_gen_i_sys:
3992 case Intrinsic::nvvm_atomic_min_gen_i_cta:
3993 case Intrinsic::nvvm_atomic_min_gen_i_sys:
3994 case Intrinsic::nvvm_atomic_or_gen_i_cta:
3995 case Intrinsic::nvvm_atomic_or_gen_i_sys:
3996 case Intrinsic::nvvm_atomic_exch_gen_i_cta:
3997 case Intrinsic::nvvm_atomic_exch_gen_i_sys:
3998 case Intrinsic::nvvm_atomic_xor_gen_i_cta:
3999 case Intrinsic::nvvm_atomic_xor_gen_i_sys: {
4000 auto &DL = I.getDataLayout();
4001 Info.opc = ISD::INTRINSIC_W_CHAIN;
4002 Info.memVT = getValueType(DL, I.getType());
4003 Info.ptrVal = I.getArgOperand(0);
4004 Info.offset = 0;
4005 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4006 Info.align.reset();
4007 return true;
4008 }
4009
4010 case Intrinsic::nvvm_ldu_global_i:
4011 case Intrinsic::nvvm_ldu_global_f:
4012 case Intrinsic::nvvm_ldu_global_p: {
4013 auto &DL = I.getDataLayout();
4014 Info.opc = ISD::INTRINSIC_W_CHAIN;
4015 if (Intrinsic == Intrinsic::nvvm_ldu_global_i)
4016 Info.memVT = getValueType(DL, I.getType());
4017 else if(Intrinsic == Intrinsic::nvvm_ldu_global_p)
4018 Info.memVT = getPointerTy(DL);
4019 else
4020 Info.memVT = getValueType(DL, I.getType());
4021 Info.ptrVal = I.getArgOperand(0);
4022 Info.offset = 0;
4023 Info.flags = MachineMemOperand::MOLoad;
4024 Info.align = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4025
4026 return true;
4027 }
4028 case Intrinsic::nvvm_tex_1d_v4f32_s32:
4029 case Intrinsic::nvvm_tex_1d_v4f32_f32:
4030 case Intrinsic::nvvm_tex_1d_level_v4f32_f32:
4031 case Intrinsic::nvvm_tex_1d_grad_v4f32_f32:
4032 case Intrinsic::nvvm_tex_1d_array_v4f32_s32:
4033 case Intrinsic::nvvm_tex_1d_array_v4f32_f32:
4034 case Intrinsic::nvvm_tex_1d_array_level_v4f32_f32:
4035 case Intrinsic::nvvm_tex_1d_array_grad_v4f32_f32:
4036 case Intrinsic::nvvm_tex_2d_v4f32_s32:
4037 case Intrinsic::nvvm_tex_2d_v4f32_f32:
4038 case Intrinsic::nvvm_tex_2d_level_v4f32_f32:
4039 case Intrinsic::nvvm_tex_2d_grad_v4f32_f32:
4040 case Intrinsic::nvvm_tex_2d_array_v4f32_s32:
4041 case Intrinsic::nvvm_tex_2d_array_v4f32_f32:
4042 case Intrinsic::nvvm_tex_2d_array_level_v4f32_f32:
4043 case Intrinsic::nvvm_tex_2d_array_grad_v4f32_f32:
4044 case Intrinsic::nvvm_tex_3d_v4f32_s32:
4045 case Intrinsic::nvvm_tex_3d_v4f32_f32:
4046 case Intrinsic::nvvm_tex_3d_level_v4f32_f32:
4047 case Intrinsic::nvvm_tex_3d_grad_v4f32_f32:
4048 case Intrinsic::nvvm_tex_cube_v4f32_f32:
4049 case Intrinsic::nvvm_tex_cube_level_v4f32_f32:
4050 case Intrinsic::nvvm_tex_cube_array_v4f32_f32:
4051 case Intrinsic::nvvm_tex_cube_array_level_v4f32_f32:
4052 case Intrinsic::nvvm_tld4_r_2d_v4f32_f32:
4053 case Intrinsic::nvvm_tld4_g_2d_v4f32_f32:
4054 case Intrinsic::nvvm_tld4_b_2d_v4f32_f32:
4055 case Intrinsic::nvvm_tld4_a_2d_v4f32_f32:
4056 case Intrinsic::nvvm_tex_unified_1d_v4f32_s32:
4057 case Intrinsic::nvvm_tex_unified_1d_v4f32_f32:
4058 case Intrinsic::nvvm_tex_unified_1d_level_v4f32_f32:
4059 case Intrinsic::nvvm_tex_unified_1d_grad_v4f32_f32:
4060 case Intrinsic::nvvm_tex_unified_1d_array_v4f32_s32:
4061 case Intrinsic::nvvm_tex_unified_1d_array_v4f32_f32:
4062 case Intrinsic::nvvm_tex_unified_1d_array_level_v4f32_f32:
4063 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4f32_f32:
4064 case Intrinsic::nvvm_tex_unified_2d_v4f32_s32:
4065 case Intrinsic::nvvm_tex_unified_2d_v4f32_f32:
4066 case Intrinsic::nvvm_tex_unified_2d_level_v4f32_f32:
4067 case Intrinsic::nvvm_tex_unified_2d_grad_v4f32_f32:
4068 case Intrinsic::nvvm_tex_unified_2d_array_v4f32_s32:
4069 case Intrinsic::nvvm_tex_unified_2d_array_v4f32_f32:
4070 case Intrinsic::nvvm_tex_unified_2d_array_level_v4f32_f32:
4071 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4f32_f32:
4072 case Intrinsic::nvvm_tex_unified_3d_v4f32_s32:
4073 case Intrinsic::nvvm_tex_unified_3d_v4f32_f32:
4074 case Intrinsic::nvvm_tex_unified_3d_level_v4f32_f32:
4075 case Intrinsic::nvvm_tex_unified_3d_grad_v4f32_f32:
4076 case Intrinsic::nvvm_tex_unified_cube_v4f32_f32:
4077 case Intrinsic::nvvm_tex_unified_cube_level_v4f32_f32:
4078 case Intrinsic::nvvm_tex_unified_cube_array_v4f32_f32:
4079 case Intrinsic::nvvm_tex_unified_cube_array_level_v4f32_f32:
4080 case Intrinsic::nvvm_tex_unified_cube_grad_v4f32_f32:
4081 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4f32_f32:
4082 case Intrinsic::nvvm_tld4_unified_r_2d_v4f32_f32:
4083 case Intrinsic::nvvm_tld4_unified_g_2d_v4f32_f32:
4084 case Intrinsic::nvvm_tld4_unified_b_2d_v4f32_f32:
4085 case Intrinsic::nvvm_tld4_unified_a_2d_v4f32_f32:
4086 Info.opc = ISD::INTRINSIC_W_CHAIN;
4087 Info.memVT = MVT::v4f32;
4088 Info.ptrVal = nullptr;
4089 Info.offset = 0;
4090 Info.flags = MachineMemOperand::MOLoad;
4091 Info.align = Align(16);
4092 return true;
4093
4094 case Intrinsic::nvvm_tex_1d_v4s32_s32:
4095 case Intrinsic::nvvm_tex_1d_v4s32_f32:
4096 case Intrinsic::nvvm_tex_1d_level_v4s32_f32:
4097 case Intrinsic::nvvm_tex_1d_grad_v4s32_f32:
4098 case Intrinsic::nvvm_tex_1d_array_v4s32_s32:
4099 case Intrinsic::nvvm_tex_1d_array_v4s32_f32:
4100 case Intrinsic::nvvm_tex_1d_array_level_v4s32_f32:
4101 case Intrinsic::nvvm_tex_1d_array_grad_v4s32_f32:
4102 case Intrinsic::nvvm_tex_2d_v4s32_s32:
4103 case Intrinsic::nvvm_tex_2d_v4s32_f32:
4104 case Intrinsic::nvvm_tex_2d_level_v4s32_f32:
4105 case Intrinsic::nvvm_tex_2d_grad_v4s32_f32:
4106 case Intrinsic::nvvm_tex_2d_array_v4s32_s32:
4107 case Intrinsic::nvvm_tex_2d_array_v4s32_f32:
4108 case Intrinsic::nvvm_tex_2d_array_level_v4s32_f32:
4109 case Intrinsic::nvvm_tex_2d_array_grad_v4s32_f32:
4110 case Intrinsic::nvvm_tex_3d_v4s32_s32:
4111 case Intrinsic::nvvm_tex_3d_v4s32_f32:
4112 case Intrinsic::nvvm_tex_3d_level_v4s32_f32:
4113 case Intrinsic::nvvm_tex_3d_grad_v4s32_f32:
4114 case Intrinsic::nvvm_tex_cube_v4s32_f32:
4115 case Intrinsic::nvvm_tex_cube_level_v4s32_f32:
4116 case Intrinsic::nvvm_tex_cube_array_v4s32_f32:
4117 case Intrinsic::nvvm_tex_cube_array_level_v4s32_f32:
4118 case Intrinsic::nvvm_tex_cube_v4u32_f32:
4119 case Intrinsic::nvvm_tex_cube_level_v4u32_f32:
4120 case Intrinsic::nvvm_tex_cube_array_v4u32_f32:
4121 case Intrinsic::nvvm_tex_cube_array_level_v4u32_f32:
4122 case Intrinsic::nvvm_tex_1d_v4u32_s32:
4123 case Intrinsic::nvvm_tex_1d_v4u32_f32:
4124 case Intrinsic::nvvm_tex_1d_level_v4u32_f32:
4125 case Intrinsic::nvvm_tex_1d_grad_v4u32_f32:
4126 case Intrinsic::nvvm_tex_1d_array_v4u32_s32:
4127 case Intrinsic::nvvm_tex_1d_array_v4u32_f32:
4128 case Intrinsic::nvvm_tex_1d_array_level_v4u32_f32:
4129 case Intrinsic::nvvm_tex_1d_array_grad_v4u32_f32:
4130 case Intrinsic::nvvm_tex_2d_v4u32_s32:
4131 case Intrinsic::nvvm_tex_2d_v4u32_f32:
4132 case Intrinsic::nvvm_tex_2d_level_v4u32_f32:
4133 case Intrinsic::nvvm_tex_2d_grad_v4u32_f32:
4134 case Intrinsic::nvvm_tex_2d_array_v4u32_s32:
4135 case Intrinsic::nvvm_tex_2d_array_v4u32_f32:
4136 case Intrinsic::nvvm_tex_2d_array_level_v4u32_f32:
4137 case Intrinsic::nvvm_tex_2d_array_grad_v4u32_f32:
4138 case Intrinsic::nvvm_tex_3d_v4u32_s32:
4139 case Intrinsic::nvvm_tex_3d_v4u32_f32:
4140 case Intrinsic::nvvm_tex_3d_level_v4u32_f32:
4141 case Intrinsic::nvvm_tex_3d_grad_v4u32_f32:
4142 case Intrinsic::nvvm_tld4_r_2d_v4s32_f32:
4143 case Intrinsic::nvvm_tld4_g_2d_v4s32_f32:
4144 case Intrinsic::nvvm_tld4_b_2d_v4s32_f32:
4145 case Intrinsic::nvvm_tld4_a_2d_v4s32_f32:
4146 case Intrinsic::nvvm_tld4_r_2d_v4u32_f32:
4147 case Intrinsic::nvvm_tld4_g_2d_v4u32_f32:
4148 case Intrinsic::nvvm_tld4_b_2d_v4u32_f32:
4149 case Intrinsic::nvvm_tld4_a_2d_v4u32_f32:
4150 case Intrinsic::nvvm_tex_unified_1d_v4s32_s32:
4151 case Intrinsic::nvvm_tex_unified_1d_v4s32_f32:
4152 case Intrinsic::nvvm_tex_unified_1d_level_v4s32_f32:
4153 case Intrinsic::nvvm_tex_unified_1d_grad_v4s32_f32:
4154 case Intrinsic::nvvm_tex_unified_1d_array_v4s32_s32:
4155 case Intrinsic::nvvm_tex_unified_1d_array_v4s32_f32:
4156 case Intrinsic::nvvm_tex_unified_1d_array_level_v4s32_f32:
4157 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4s32_f32:
4158 case Intrinsic::nvvm_tex_unified_2d_v4s32_s32:
4159 case Intrinsic::nvvm_tex_unified_2d_v4s32_f32:
4160 case Intrinsic::nvvm_tex_unified_2d_level_v4s32_f32:
4161 case Intrinsic::nvvm_tex_unified_2d_grad_v4s32_f32:
4162 case Intrinsic::nvvm_tex_unified_2d_array_v4s32_s32:
4163 case Intrinsic::nvvm_tex_unified_2d_array_v4s32_f32:
4164 case Intrinsic::nvvm_tex_unified_2d_array_level_v4s32_f32:
4165 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4s32_f32:
4166 case Intrinsic::nvvm_tex_unified_3d_v4s32_s32:
4167 case Intrinsic::nvvm_tex_unified_3d_v4s32_f32:
4168 case Intrinsic::nvvm_tex_unified_3d_level_v4s32_f32:
4169 case Intrinsic::nvvm_tex_unified_3d_grad_v4s32_f32:
4170 case Intrinsic::nvvm_tex_unified_1d_v4u32_s32:
4171 case Intrinsic::nvvm_tex_unified_1d_v4u32_f32:
4172 case Intrinsic::nvvm_tex_unified_1d_level_v4u32_f32:
4173 case Intrinsic::nvvm_tex_unified_1d_grad_v4u32_f32:
4174 case Intrinsic::nvvm_tex_unified_1d_array_v4u32_s32:
4175 case Intrinsic::nvvm_tex_unified_1d_array_v4u32_f32:
4176 case Intrinsic::nvvm_tex_unified_1d_array_level_v4u32_f32:
4177 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4u32_f32:
4178 case Intrinsic::nvvm_tex_unified_2d_v4u32_s32:
4179 case Intrinsic::nvvm_tex_unified_2d_v4u32_f32:
4180 case Intrinsic::nvvm_tex_unified_2d_level_v4u32_f32:
4181 case Intrinsic::nvvm_tex_unified_2d_grad_v4u32_f32:
4182 case Intrinsic::nvvm_tex_unified_2d_array_v4u32_s32:
4183 case Intrinsic::nvvm_tex_unified_2d_array_v4u32_f32:
4184 case Intrinsic::nvvm_tex_unified_2d_array_level_v4u32_f32:
4185 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4u32_f32:
4186 case Intrinsic::nvvm_tex_unified_3d_v4u32_s32:
4187 case Intrinsic::nvvm_tex_unified_3d_v4u32_f32:
4188 case Intrinsic::nvvm_tex_unified_3d_level_v4u32_f32:
4189 case Intrinsic::nvvm_tex_unified_3d_grad_v4u32_f32:
4190 case Intrinsic::nvvm_tex_unified_cube_v4s32_f32:
4191 case Intrinsic::nvvm_tex_unified_cube_level_v4s32_f32:
4192 case Intrinsic::nvvm_tex_unified_cube_array_v4s32_f32:
4193 case Intrinsic::nvvm_tex_unified_cube_array_level_v4s32_f32:
4194 case Intrinsic::nvvm_tex_unified_cube_v4u32_f32:
4195 case Intrinsic::nvvm_tex_unified_cube_level_v4u32_f32:
4196 case Intrinsic::nvvm_tex_unified_cube_array_v4u32_f32:
4197 case Intrinsic::nvvm_tex_unified_cube_array_level_v4u32_f32:
4198 case Intrinsic::nvvm_tex_unified_cube_grad_v4s32_f32:
4199 case Intrinsic::nvvm_tex_unified_cube_grad_v4u32_f32:
4200 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4s32_f32:
4201 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4u32_f32:
4202 case Intrinsic::nvvm_tld4_unified_r_2d_v4s32_f32:
4203 case Intrinsic::nvvm_tld4_unified_g_2d_v4s32_f32:
4204 case Intrinsic::nvvm_tld4_unified_b_2d_v4s32_f32:
4205 case Intrinsic::nvvm_tld4_unified_a_2d_v4s32_f32:
4206 case Intrinsic::nvvm_tld4_unified_r_2d_v4u32_f32:
4207 case Intrinsic::nvvm_tld4_unified_g_2d_v4u32_f32:
4208 case Intrinsic::nvvm_tld4_unified_b_2d_v4u32_f32:
4209 case Intrinsic::nvvm_tld4_unified_a_2d_v4u32_f32:
4210 Info.opc = ISD::INTRINSIC_W_CHAIN;
4211 Info.memVT = MVT::v4i32;
4212 Info.ptrVal = nullptr;
4213 Info.offset = 0;
4214 Info.flags = MachineMemOperand::MOLoad;
4215 Info.align = Align(16);
4216 return true;
4217
4218 case Intrinsic::nvvm_suld_1d_i8_clamp:
4219 case Intrinsic::nvvm_suld_1d_v2i8_clamp:
4220 case Intrinsic::nvvm_suld_1d_v4i8_clamp:
4221 case Intrinsic::nvvm_suld_1d_array_i8_clamp:
4222 case Intrinsic::nvvm_suld_1d_array_v2i8_clamp:
4223 case Intrinsic::nvvm_suld_1d_array_v4i8_clamp:
4224 case Intrinsic::nvvm_suld_2d_i8_clamp:
4225 case Intrinsic::nvvm_suld_2d_v2i8_clamp:
4226 case Intrinsic::nvvm_suld_2d_v4i8_clamp:
4227 case Intrinsic::nvvm_suld_2d_array_i8_clamp:
4228 case Intrinsic::nvvm_suld_2d_array_v2i8_clamp:
4229 case Intrinsic::nvvm_suld_2d_array_v4i8_clamp:
4230 case Intrinsic::nvvm_suld_3d_i8_clamp:
4231 case Intrinsic::nvvm_suld_3d_v2i8_clamp:
4232 case Intrinsic::nvvm_suld_3d_v4i8_clamp:
4233 case Intrinsic::nvvm_suld_1d_i8_trap:
4234 case Intrinsic::nvvm_suld_1d_v2i8_trap:
4235 case Intrinsic::nvvm_suld_1d_v4i8_trap:
4236 case Intrinsic::nvvm_suld_1d_array_i8_trap:
4237 case Intrinsic::nvvm_suld_1d_array_v2i8_trap:
4238 case Intrinsic::nvvm_suld_1d_array_v4i8_trap:
4239 case Intrinsic::nvvm_suld_2d_i8_trap:
4240 case Intrinsic::nvvm_suld_2d_v2i8_trap:
4241 case Intrinsic::nvvm_suld_2d_v4i8_trap:
4242 case Intrinsic::nvvm_suld_2d_array_i8_trap:
4243 case Intrinsic::nvvm_suld_2d_array_v2i8_trap:
4244 case Intrinsic::nvvm_suld_2d_array_v4i8_trap:
4245 case Intrinsic::nvvm_suld_3d_i8_trap:
4246 case Intrinsic::nvvm_suld_3d_v2i8_trap:
4247 case Intrinsic::nvvm_suld_3d_v4i8_trap:
4248 case Intrinsic::nvvm_suld_1d_i8_zero:
4249 case Intrinsic::nvvm_suld_1d_v2i8_zero:
4250 case Intrinsic::nvvm_suld_1d_v4i8_zero:
4251 case Intrinsic::nvvm_suld_1d_array_i8_zero:
4252 case Intrinsic::nvvm_suld_1d_array_v2i8_zero:
4253 case Intrinsic::nvvm_suld_1d_array_v4i8_zero:
4254 case Intrinsic::nvvm_suld_2d_i8_zero:
4255 case Intrinsic::nvvm_suld_2d_v2i8_zero:
4256 case Intrinsic::nvvm_suld_2d_v4i8_zero:
4257 case Intrinsic::nvvm_suld_2d_array_i8_zero:
4258 case Intrinsic::nvvm_suld_2d_array_v2i8_zero:
4259 case Intrinsic::nvvm_suld_2d_array_v4i8_zero:
4260 case Intrinsic::nvvm_suld_3d_i8_zero:
4261 case Intrinsic::nvvm_suld_3d_v2i8_zero:
4262 case Intrinsic::nvvm_suld_3d_v4i8_zero:
4263 Info.opc = ISD::INTRINSIC_W_CHAIN;
4264 Info.memVT = MVT::i8;
4265 Info.ptrVal = nullptr;
4266 Info.offset = 0;
4267 Info.flags = MachineMemOperand::MOLoad;
4268 Info.align = Align(16);
4269 return true;
4270
4271 case Intrinsic::nvvm_suld_1d_i16_clamp:
4272 case Intrinsic::nvvm_suld_1d_v2i16_clamp:
4273 case Intrinsic::nvvm_suld_1d_v4i16_clamp:
4274 case Intrinsic::nvvm_suld_1d_array_i16_clamp:
4275 case Intrinsic::nvvm_suld_1d_array_v2i16_clamp:
4276 case Intrinsic::nvvm_suld_1d_array_v4i16_clamp:
4277 case Intrinsic::nvvm_suld_2d_i16_clamp:
4278 case Intrinsic::nvvm_suld_2d_v2i16_clamp:
4279 case Intrinsic::nvvm_suld_2d_v4i16_clamp:
4280 case Intrinsic::nvvm_suld_2d_array_i16_clamp:
4281 case Intrinsic::nvvm_suld_2d_array_v2i16_clamp:
4282 case Intrinsic::nvvm_suld_2d_array_v4i16_clamp:
4283 case Intrinsic::nvvm_suld_3d_i16_clamp:
4284 case Intrinsic::nvvm_suld_3d_v2i16_clamp:
4285 case Intrinsic::nvvm_suld_3d_v4i16_clamp:
4286 case Intrinsic::nvvm_suld_1d_i16_trap:
4287 case Intrinsic::nvvm_suld_1d_v2i16_trap:
4288 case Intrinsic::nvvm_suld_1d_v4i16_trap:
4289 case Intrinsic::nvvm_suld_1d_array_i16_trap:
4290 case Intrinsic::nvvm_suld_1d_array_v2i16_trap:
4291 case Intrinsic::nvvm_suld_1d_array_v4i16_trap:
4292 case Intrinsic::nvvm_suld_2d_i16_trap:
4293 case Intrinsic::nvvm_suld_2d_v2i16_trap:
4294 case Intrinsic::nvvm_suld_2d_v4i16_trap:
4295 case Intrinsic::nvvm_suld_2d_array_i16_trap:
4296 case Intrinsic::nvvm_suld_2d_array_v2i16_trap:
4297 case Intrinsic::nvvm_suld_2d_array_v4i16_trap:
4298 case Intrinsic::nvvm_suld_3d_i16_trap:
4299 case Intrinsic::nvvm_suld_3d_v2i16_trap:
4300 case Intrinsic::nvvm_suld_3d_v4i16_trap:
4301 case Intrinsic::nvvm_suld_1d_i16_zero:
4302 case Intrinsic::nvvm_suld_1d_v2i16_zero:
4303 case Intrinsic::nvvm_suld_1d_v4i16_zero:
4304 case Intrinsic::nvvm_suld_1d_array_i16_zero:
4305 case Intrinsic::nvvm_suld_1d_array_v2i16_zero:
4306 case Intrinsic::nvvm_suld_1d_array_v4i16_zero:
4307 case Intrinsic::nvvm_suld_2d_i16_zero:
4308 case Intrinsic::nvvm_suld_2d_v2i16_zero:
4309 case Intrinsic::nvvm_suld_2d_v4i16_zero:
4310 case Intrinsic::nvvm_suld_2d_array_i16_zero:
4311 case Intrinsic::nvvm_suld_2d_array_v2i16_zero:
4312 case Intrinsic::nvvm_suld_2d_array_v4i16_zero:
4313 case Intrinsic::nvvm_suld_3d_i16_zero:
4314 case Intrinsic::nvvm_suld_3d_v2i16_zero:
4315 case Intrinsic::nvvm_suld_3d_v4i16_zero:
4316 Info.opc = ISD::INTRINSIC_W_CHAIN;
4317 Info.memVT = MVT::i16;
4318 Info.ptrVal = nullptr;
4319 Info.offset = 0;
4320 Info.flags = MachineMemOperand::MOLoad;
4321 Info.align = Align(16);
4322 return true;
4323
4324 case Intrinsic::nvvm_suld_1d_i32_clamp:
4325 case Intrinsic::nvvm_suld_1d_v2i32_clamp:
4326 case Intrinsic::nvvm_suld_1d_v4i32_clamp:
4327 case Intrinsic::nvvm_suld_1d_array_i32_clamp:
4328 case Intrinsic::nvvm_suld_1d_array_v2i32_clamp:
4329 case Intrinsic::nvvm_suld_1d_array_v4i32_clamp:
4330 case Intrinsic::nvvm_suld_2d_i32_clamp:
4331 case Intrinsic::nvvm_suld_2d_v2i32_clamp:
4332 case Intrinsic::nvvm_suld_2d_v4i32_clamp:
4333 case Intrinsic::nvvm_suld_2d_array_i32_clamp:
4334 case Intrinsic::nvvm_suld_2d_array_v2i32_clamp:
4335 case Intrinsic::nvvm_suld_2d_array_v4i32_clamp:
4336 case Intrinsic::nvvm_suld_3d_i32_clamp:
4337 case Intrinsic::nvvm_suld_3d_v2i32_clamp:
4338 case Intrinsic::nvvm_suld_3d_v4i32_clamp:
4339 case Intrinsic::nvvm_suld_1d_i32_trap:
4340 case Intrinsic::nvvm_suld_1d_v2i32_trap:
4341 case Intrinsic::nvvm_suld_1d_v4i32_trap:
4342 case Intrinsic::nvvm_suld_1d_array_i32_trap:
4343 case Intrinsic::nvvm_suld_1d_array_v2i32_trap:
4344 case Intrinsic::nvvm_suld_1d_array_v4i32_trap:
4345 case Intrinsic::nvvm_suld_2d_i32_trap:
4346 case Intrinsic::nvvm_suld_2d_v2i32_trap:
4347 case Intrinsic::nvvm_suld_2d_v4i32_trap:
4348 case Intrinsic::nvvm_suld_2d_array_i32_trap:
4349 case Intrinsic::nvvm_suld_2d_array_v2i32_trap:
4350 case Intrinsic::nvvm_suld_2d_array_v4i32_trap:
4351 case Intrinsic::nvvm_suld_3d_i32_trap:
4352 case Intrinsic::nvvm_suld_3d_v2i32_trap:
4353 case Intrinsic::nvvm_suld_3d_v4i32_trap:
4354 case Intrinsic::nvvm_suld_1d_i32_zero:
4355 case Intrinsic::nvvm_suld_1d_v2i32_zero:
4356 case Intrinsic::nvvm_suld_1d_v4i32_zero:
4357 case Intrinsic::nvvm_suld_1d_array_i32_zero:
4358 case Intrinsic::nvvm_suld_1d_array_v2i32_zero:
4359 case Intrinsic::nvvm_suld_1d_array_v4i32_zero:
4360 case Intrinsic::nvvm_suld_2d_i32_zero:
4361 case Intrinsic::nvvm_suld_2d_v2i32_zero:
4362 case Intrinsic::nvvm_suld_2d_v4i32_zero:
4363 case Intrinsic::nvvm_suld_2d_array_i32_zero:
4364 case Intrinsic::nvvm_suld_2d_array_v2i32_zero:
4365 case Intrinsic::nvvm_suld_2d_array_v4i32_zero:
4366 case Intrinsic::nvvm_suld_3d_i32_zero:
4367 case Intrinsic::nvvm_suld_3d_v2i32_zero:
4368 case Intrinsic::nvvm_suld_3d_v4i32_zero:
4369 Info.opc = ISD::INTRINSIC_W_CHAIN;
4370 Info.memVT = MVT::i32;
4371 Info.ptrVal = nullptr;
4372 Info.offset = 0;
4373 Info.flags = MachineMemOperand::MOLoad;
4374 Info.align = Align(16);
4375 return true;
4376
4377 case Intrinsic::nvvm_suld_1d_i64_clamp:
4378 case Intrinsic::nvvm_suld_1d_v2i64_clamp:
4379 case Intrinsic::nvvm_suld_1d_array_i64_clamp:
4380 case Intrinsic::nvvm_suld_1d_array_v2i64_clamp:
4381 case Intrinsic::nvvm_suld_2d_i64_clamp:
4382 case Intrinsic::nvvm_suld_2d_v2i64_clamp:
4383 case Intrinsic::nvvm_suld_2d_array_i64_clamp:
4384 case Intrinsic::nvvm_suld_2d_array_v2i64_clamp:
4385 case Intrinsic::nvvm_suld_3d_i64_clamp:
4386 case Intrinsic::nvvm_suld_3d_v2i64_clamp:
4387 case Intrinsic::nvvm_suld_1d_i64_trap:
4388 case Intrinsic::nvvm_suld_1d_v2i64_trap:
4389 case Intrinsic::nvvm_suld_1d_array_i64_trap:
4390 case Intrinsic::nvvm_suld_1d_array_v2i64_trap:
4391 case Intrinsic::nvvm_suld_2d_i64_trap:
4392 case Intrinsic::nvvm_suld_2d_v2i64_trap:
4393 case Intrinsic::nvvm_suld_2d_array_i64_trap:
4394 case Intrinsic::nvvm_suld_2d_array_v2i64_trap:
4395 case Intrinsic::nvvm_suld_3d_i64_trap:
4396 case Intrinsic::nvvm_suld_3d_v2i64_trap:
4397 case Intrinsic::nvvm_suld_1d_i64_zero:
4398 case Intrinsic::nvvm_suld_1d_v2i64_zero:
4399 case Intrinsic::nvvm_suld_1d_array_i64_zero:
4400 case Intrinsic::nvvm_suld_1d_array_v2i64_zero:
4401 case Intrinsic::nvvm_suld_2d_i64_zero:
4402 case Intrinsic::nvvm_suld_2d_v2i64_zero:
4403 case Intrinsic::nvvm_suld_2d_array_i64_zero:
4404 case Intrinsic::nvvm_suld_2d_array_v2i64_zero:
4405 case Intrinsic::nvvm_suld_3d_i64_zero:
4406 case Intrinsic::nvvm_suld_3d_v2i64_zero:
4407 Info.opc = ISD::INTRINSIC_W_CHAIN;
4408 Info.memVT = MVT::i64;
4409 Info.ptrVal = nullptr;
4410 Info.offset = 0;
4411 Info.flags = MachineMemOperand::MOLoad;
4412 Info.align = Align(16);
4413 return true;
4414
4415 case Intrinsic::nvvm_tcgen05_ld_16x64b_x1:
4416 case Intrinsic::nvvm_tcgen05_ld_32x32b_x1:
4417 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x1: {
4418 Info.opc = ISD::INTRINSIC_W_CHAIN;
4419 Info.memVT = MVT::v1i32;
4420 Info.ptrVal = I.getArgOperand(0);
4421 Info.offset = 0;
4422 Info.flags = MachineMemOperand::MOLoad;
4423 Info.align.reset();
4424 return true;
4425 }
4426
4427 case Intrinsic::nvvm_tcgen05_ld_16x64b_x2:
4428 case Intrinsic::nvvm_tcgen05_ld_16x128b_x1:
4429 case Intrinsic::nvvm_tcgen05_ld_32x32b_x2:
4430 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x2: {
4431 Info.opc = ISD::INTRINSIC_W_CHAIN;
4432 Info.memVT = MVT::v2i32;
4433 Info.ptrVal = I.getArgOperand(0);
4434 Info.offset = 0;
4435 Info.flags = MachineMemOperand::MOLoad;
4436 Info.align.reset();
4437 return true;
4438 }
4439
4440 case Intrinsic::nvvm_tcgen05_ld_16x64b_x4:
4441 case Intrinsic::nvvm_tcgen05_ld_16x128b_x2:
4442 case Intrinsic::nvvm_tcgen05_ld_32x32b_x4:
4443 case Intrinsic::nvvm_tcgen05_ld_16x256b_x1:
4444 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x4: {
4445 Info.opc = ISD::INTRINSIC_W_CHAIN;
4446 Info.memVT = MVT::v4i32;
4447 Info.ptrVal = I.getArgOperand(0);
4448 Info.offset = 0;
4449 Info.flags = MachineMemOperand::MOLoad;
4450 Info.align.reset();
4451 return true;
4452 }
4453
4454 case Intrinsic::nvvm_tcgen05_ld_16x64b_x8:
4455 case Intrinsic::nvvm_tcgen05_ld_16x128b_x4:
4456 case Intrinsic::nvvm_tcgen05_ld_16x256b_x2:
4457 case Intrinsic::nvvm_tcgen05_ld_32x32b_x8:
4458 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x8: {
4459 Info.opc = ISD::INTRINSIC_W_CHAIN;
4460 Info.memVT = MVT::v8i32;
4461 Info.ptrVal = I.getArgOperand(0);
4462 Info.offset = 0;
4463 Info.flags = MachineMemOperand::MOLoad;
4464 Info.align.reset();
4465 return true;
4466 }
4467
4468 case Intrinsic::nvvm_tcgen05_ld_16x64b_x16:
4469 case Intrinsic::nvvm_tcgen05_ld_16x128b_x8:
4470 case Intrinsic::nvvm_tcgen05_ld_16x256b_x4:
4471 case Intrinsic::nvvm_tcgen05_ld_32x32b_x16:
4472 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x16: {
4473 Info.opc = ISD::INTRINSIC_W_CHAIN;
4474 Info.memVT = MVT::v16i32;
4475 Info.ptrVal = I.getArgOperand(0);
4476 Info.offset = 0;
4477 Info.flags = MachineMemOperand::MOLoad;
4478 Info.align.reset();
4479 return true;
4480 }
4481
4482 case Intrinsic::nvvm_tcgen05_ld_16x64b_x32:
4483 case Intrinsic::nvvm_tcgen05_ld_16x128b_x16:
4484 case Intrinsic::nvvm_tcgen05_ld_16x256b_x8:
4485 case Intrinsic::nvvm_tcgen05_ld_32x32b_x32:
4486 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x32: {
4487 Info.opc = ISD::INTRINSIC_W_CHAIN;
4488 Info.memVT = MVT::v32i32;
4489 Info.ptrVal = I.getArgOperand(0);
4490 Info.offset = 0;
4491 Info.flags = MachineMemOperand::MOLoad;
4492 Info.align.reset();
4493 return true;
4494 }
4495
4496 case Intrinsic::nvvm_tcgen05_ld_16x64b_x64:
4497 case Intrinsic::nvvm_tcgen05_ld_16x128b_x32:
4498 case Intrinsic::nvvm_tcgen05_ld_16x256b_x16:
4499 case Intrinsic::nvvm_tcgen05_ld_32x32b_x64:
4500 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x64: {
4501 Info.opc = ISD::INTRINSIC_W_CHAIN;
4502 Info.memVT = MVT::v64i32;
4503 Info.ptrVal = I.getArgOperand(0);
4504 Info.offset = 0;
4505 Info.flags = MachineMemOperand::MOLoad;
4506 Info.align.reset();
4507 return true;
4508 }
4509
4510 case Intrinsic::nvvm_tcgen05_ld_16x64b_x128:
4511 case Intrinsic::nvvm_tcgen05_ld_16x128b_x64:
4512 case Intrinsic::nvvm_tcgen05_ld_16x256b_x32:
4513 case Intrinsic::nvvm_tcgen05_ld_32x32b_x128:
4514 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x128: {
4515 Info.opc = ISD::INTRINSIC_W_CHAIN;
4516 Info.memVT = MVT::v128i32;
4517 Info.ptrVal = I.getArgOperand(0);
4518 Info.offset = 0;
4519 Info.flags = MachineMemOperand::MOLoad;
4520 Info.align.reset();
4521 return true;
4522 }
4523
4524 case Intrinsic::nvvm_tcgen05_st_16x64b_x1:
4525 case Intrinsic::nvvm_tcgen05_st_32x32b_x1:
4526 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x1: {
4527 Info.opc = ISD::INTRINSIC_VOID;
4528 Info.memVT = MVT::i32;
4529 Info.ptrVal = I.getArgOperand(0);
4530 Info.offset = 0;
4531 Info.flags = MachineMemOperand::MOStore;
4532 Info.align.reset();
4533 return true;
4534 }
4535
4536 case Intrinsic::nvvm_tcgen05_st_16x64b_x2:
4537 case Intrinsic::nvvm_tcgen05_st_16x128b_x1:
4538 case Intrinsic::nvvm_tcgen05_st_32x32b_x2:
4539 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x2: {
4540 Info.opc = ISD::INTRINSIC_VOID;
4541 Info.memVT = MVT::v2i32;
4542 Info.ptrVal = I.getArgOperand(0);
4543 Info.offset = 0;
4544 Info.flags = MachineMemOperand::MOStore;
4545 Info.align.reset();
4546 return true;
4547 }
4548
4549 case Intrinsic::nvvm_tcgen05_st_16x64b_x4:
4550 case Intrinsic::nvvm_tcgen05_st_16x128b_x2:
4551 case Intrinsic::nvvm_tcgen05_st_16x256b_x1:
4552 case Intrinsic::nvvm_tcgen05_st_32x32b_x4:
4553 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x4: {
4554 Info.opc = ISD::INTRINSIC_VOID;
4555 Info.memVT = MVT::v4i32;
4556 Info.ptrVal = I.getArgOperand(0);
4557 Info.offset = 0;
4558 Info.flags = MachineMemOperand::MOStore;
4559 Info.align.reset();
4560 return true;
4561 }
4562
4563 case Intrinsic::nvvm_tcgen05_st_16x64b_x8:
4564 case Intrinsic::nvvm_tcgen05_st_16x128b_x4:
4565 case Intrinsic::nvvm_tcgen05_st_16x256b_x2:
4566 case Intrinsic::nvvm_tcgen05_st_32x32b_x8:
4567 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x8: {
4568 Info.opc = ISD::INTRINSIC_VOID;
4569 Info.memVT = MVT::v8i32;
4570 Info.ptrVal = I.getArgOperand(0);
4571 Info.offset = 0;
4572 Info.flags = MachineMemOperand::MOStore;
4573 Info.align.reset();
4574 return true;
4575 }
4576
4577 case Intrinsic::nvvm_tcgen05_st_16x64b_x16:
4578 case Intrinsic::nvvm_tcgen05_st_16x128b_x8:
4579 case Intrinsic::nvvm_tcgen05_st_16x256b_x4:
4580 case Intrinsic::nvvm_tcgen05_st_32x32b_x16:
4581 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x16: {
4582 Info.opc = ISD::INTRINSIC_VOID;
4583 Info.memVT = MVT::v16i32;
4584 Info.ptrVal = I.getArgOperand(0);
4585 Info.offset = 0;
4586 Info.flags = MachineMemOperand::MOStore;
4587 Info.align.reset();
4588 return true;
4589 }
4590
4591 case Intrinsic::nvvm_tcgen05_st_16x64b_x32:
4592 case Intrinsic::nvvm_tcgen05_st_16x128b_x16:
4593 case Intrinsic::nvvm_tcgen05_st_16x256b_x8:
4594 case Intrinsic::nvvm_tcgen05_st_32x32b_x32:
4595 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x32: {
4596 Info.opc = ISD::INTRINSIC_VOID;
4597 Info.memVT = MVT::v32i32;
4598 Info.ptrVal = I.getArgOperand(0);
4599 Info.offset = 0;
4600 Info.flags = MachineMemOperand::MOStore;
4601 Info.align.reset();
4602 return true;
4603 }
4604
4605 case Intrinsic::nvvm_tcgen05_st_16x64b_x64:
4606 case Intrinsic::nvvm_tcgen05_st_16x128b_x32:
4607 case Intrinsic::nvvm_tcgen05_st_16x256b_x16:
4608 case Intrinsic::nvvm_tcgen05_st_32x32b_x64:
4609 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x64: {
4610 Info.opc = ISD::INTRINSIC_VOID;
4611 Info.memVT = MVT::v64i32;
4612 Info.ptrVal = I.getArgOperand(0);
4613 Info.offset = 0;
4614 Info.flags = MachineMemOperand::MOStore;
4615 Info.align.reset();
4616 return true;
4617 }
4618
4619 case Intrinsic::nvvm_tcgen05_st_16x64b_x128:
4620 case Intrinsic::nvvm_tcgen05_st_16x128b_x64:
4621 case Intrinsic::nvvm_tcgen05_st_16x256b_x32:
4622 case Intrinsic::nvvm_tcgen05_st_32x32b_x128:
4623 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x128: {
4624 Info.opc = ISD::INTRINSIC_VOID;
4625 Info.memVT = MVT::v128i32;
4626 Info.ptrVal = I.getArgOperand(0);
4627 Info.offset = 0;
4628 Info.flags = MachineMemOperand::MOStore;
4629 Info.align.reset();
4630 return true;
4631 }
4632 }
4633 return false;
4634 }
4635
4636 /// getFunctionParamOptimizedAlign - since function arguments are passed via
4637 /// .param space, we may want to increase their alignment in a way that
4638 /// ensures that we can effectively vectorize their loads & stores. We can
4639 /// increase alignment only if the function has internal or has private
4640 /// linkage as for other linkage types callers may already rely on default
4641 /// alignment. To allow using 128-bit vectorized loads/stores, this function
4642 /// ensures that alignment is 16 or greater.
getFunctionParamOptimizedAlign(const Function * F,Type * ArgTy,const DataLayout & DL) const4643 Align NVPTXTargetLowering::getFunctionParamOptimizedAlign(
4644 const Function *F, Type *ArgTy, const DataLayout &DL) const {
4645 // Capping the alignment to 128 bytes as that is the maximum alignment
4646 // supported by PTX.
4647 const Align ABITypeAlign = std::min(Align(128), DL.getABITypeAlign(ArgTy));
4648
4649 // If a function has linkage different from internal or private, we
4650 // must use default ABI alignment as external users rely on it. Same
4651 // for a function that may be called from a function pointer.
4652 if (!F || !F->hasLocalLinkage() ||
4653 F->hasAddressTaken(/*Users=*/nullptr,
4654 /*IgnoreCallbackUses=*/false,
4655 /*IgnoreAssumeLikeCalls=*/true,
4656 /*IgnoreLLVMUsed=*/true))
4657 return ABITypeAlign;
4658
4659 assert(!isKernelFunction(*F) && "Expect kernels to have non-local linkage");
4660 return std::max(Align(16), ABITypeAlign);
4661 }
4662
4663 /// Helper for computing alignment of a device function byval parameter.
getFunctionByValParamAlign(const Function * F,Type * ArgTy,Align InitialAlign,const DataLayout & DL) const4664 Align NVPTXTargetLowering::getFunctionByValParamAlign(
4665 const Function *F, Type *ArgTy, Align InitialAlign,
4666 const DataLayout &DL) const {
4667 Align ArgAlign = InitialAlign;
4668 // Try to increase alignment to enhance vectorization options.
4669 if (F)
4670 ArgAlign = std::max(ArgAlign, getFunctionParamOptimizedAlign(F, ArgTy, DL));
4671
4672 // Old ptx versions have a bug. When PTX code takes address of
4673 // byval parameter with alignment < 4, ptxas generates code to
4674 // spill argument into memory. Alas on sm_50+ ptxas generates
4675 // SASS code that fails with misaligned access. To work around
4676 // the problem, make sure that we align byval parameters by at
4677 // least 4. This bug seems to be fixed at least starting from
4678 // ptxas > 9.0.
4679 // TODO: remove this after verifying the bug is not reproduced
4680 // on non-deprecated ptxas versions.
4681 if (ForceMinByValParamAlign)
4682 ArgAlign = std::max(ArgAlign, Align(4));
4683
4684 return ArgAlign;
4685 }
4686
4687 // Helper for getting a function parameter name. Name is composed from
4688 // its index and the function name. Negative index corresponds to special
4689 // parameter (unsized array) used for passing variable arguments.
getParamName(const Function * F,int Idx) const4690 std::string NVPTXTargetLowering::getParamName(const Function *F,
4691 int Idx) const {
4692 std::string ParamName;
4693 raw_string_ostream ParamStr(ParamName);
4694
4695 ParamStr << getTargetMachine().getSymbol(F)->getName();
4696 if (Idx < 0)
4697 ParamStr << "_vararg";
4698 else
4699 ParamStr << "_param_" << Idx;
4700
4701 return ParamName;
4702 }
4703
4704 /// isLegalAddressingMode - Return true if the addressing mode represented
4705 /// by AM is legal for this target, for a load/store of the specified type.
4706 /// Used to guide target specific optimizations, like loop strength reduction
4707 /// (LoopStrengthReduce.cpp) and memory optimization for address mode
4708 /// (CodeGenPrepare.cpp)
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const4709 bool NVPTXTargetLowering::isLegalAddressingMode(const DataLayout &DL,
4710 const AddrMode &AM, Type *Ty,
4711 unsigned AS, Instruction *I) const {
4712 // AddrMode - This represents an addressing mode of:
4713 // BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
4714 //
4715 // The legal address modes are
4716 // - [avar]
4717 // - [areg]
4718 // - [areg+immoff]
4719 // - [immAddr]
4720
4721 // immoff must fit in a signed 32-bit int
4722 if (!APInt(64, AM.BaseOffs).isSignedIntN(32))
4723 return false;
4724
4725 if (AM.BaseGV)
4726 return !AM.BaseOffs && !AM.HasBaseReg && !AM.Scale;
4727
4728 switch (AM.Scale) {
4729 case 0: // "r", "r+i" or "i" is allowed
4730 break;
4731 case 1:
4732 if (AM.HasBaseReg) // "r+r+i" or "r+r" is not allowed.
4733 return false;
4734 // Otherwise we have r+i.
4735 break;
4736 default:
4737 // No scale > 1 is allowed
4738 return false;
4739 }
4740 return true;
4741 }
4742
4743 //===----------------------------------------------------------------------===//
4744 // NVPTX Inline Assembly Support
4745 //===----------------------------------------------------------------------===//
4746
4747 /// getConstraintType - Given a constraint letter, return the type of
4748 /// constraint it is for this target.
4749 NVPTXTargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const4750 NVPTXTargetLowering::getConstraintType(StringRef Constraint) const {
4751 if (Constraint.size() == 1) {
4752 switch (Constraint[0]) {
4753 default:
4754 break;
4755 case 'b':
4756 case 'r':
4757 case 'h':
4758 case 'c':
4759 case 'l':
4760 case 'f':
4761 case 'd':
4762 case 'q':
4763 case '0':
4764 case 'N':
4765 return C_RegisterClass;
4766 }
4767 }
4768 return TargetLowering::getConstraintType(Constraint);
4769 }
4770
4771 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const4772 NVPTXTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4773 StringRef Constraint,
4774 MVT VT) const {
4775 if (Constraint.size() == 1) {
4776 switch (Constraint[0]) {
4777 case 'b':
4778 return std::make_pair(0U, &NVPTX::B1RegClass);
4779 case 'c':
4780 case 'h':
4781 return std::make_pair(0U, &NVPTX::B16RegClass);
4782 case 'r':
4783 case 'f':
4784 return std::make_pair(0U, &NVPTX::B32RegClass);
4785 case 'l':
4786 case 'N':
4787 case 'd':
4788 return std::make_pair(0U, &NVPTX::B64RegClass);
4789 case 'q': {
4790 if (STI.getSmVersion() < 70)
4791 report_fatal_error("Inline asm with 128 bit operands is only "
4792 "supported for sm_70 and higher!");
4793 return std::make_pair(0U, &NVPTX::B128RegClass);
4794 }
4795 }
4796 }
4797 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4798 }
4799
4800 //===----------------------------------------------------------------------===//
4801 // NVPTX DAG Combining
4802 //===----------------------------------------------------------------------===//
4803
allowFMA(MachineFunction & MF,CodeGenOptLevel OptLevel) const4804 bool NVPTXTargetLowering::allowFMA(MachineFunction &MF,
4805 CodeGenOptLevel OptLevel) const {
4806 // Always honor command-line argument
4807 if (FMAContractLevelOpt.getNumOccurrences() > 0)
4808 return FMAContractLevelOpt > 0;
4809
4810 // Do not contract if we're not optimizing the code.
4811 if (OptLevel == CodeGenOptLevel::None)
4812 return false;
4813
4814 // Honor TargetOptions flags that explicitly say fusion is okay.
4815 if (MF.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast)
4816 return true;
4817
4818 return allowUnsafeFPMath(MF);
4819 }
4820
allowUnsafeFPMath(const MachineFunction & MF) const4821 bool NVPTXTargetLowering::allowUnsafeFPMath(const MachineFunction &MF) const {
4822 // Honor TargetOptions flags that explicitly say unsafe math is okay.
4823 if (MF.getTarget().Options.UnsafeFPMath)
4824 return true;
4825
4826 // Allow unsafe math if unsafe-fp-math attribute explicitly says so.
4827 const Function &F = MF.getFunction();
4828 return F.getFnAttribute("unsafe-fp-math").getValueAsBool();
4829 }
4830
isConstZero(const SDValue & Operand)4831 static bool isConstZero(const SDValue &Operand) {
4832 const auto *Const = dyn_cast<ConstantSDNode>(Operand);
4833 return Const && Const->getZExtValue() == 0;
4834 }
4835
4836 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
4837 /// operands N0 and N1. This is a helper for PerformADDCombine that is
4838 /// called with the default operands, and if that fails, with commuted
4839 /// operands.
4840 static SDValue
PerformADDCombineWithOperands(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI)4841 PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
4842 TargetLowering::DAGCombinerInfo &DCI) {
4843 EVT VT = N0.getValueType();
4844
4845 // Since integer multiply-add costs the same as integer multiply
4846 // but is more costly than integer add, do the fusion only when
4847 // the mul is only used in the add.
4848 // TODO: this may not be true for later architectures, consider relaxing this
4849 if (!N0.getNode()->hasOneUse())
4850 return SDValue();
4851
4852 // fold (add (select cond, 0, (mul a, b)), c)
4853 // -> (select cond, c, (add (mul a, b), c))
4854 //
4855 if (N0.getOpcode() == ISD::SELECT) {
4856 unsigned ZeroOpNum;
4857 if (isConstZero(N0->getOperand(1)))
4858 ZeroOpNum = 1;
4859 else if (isConstZero(N0->getOperand(2)))
4860 ZeroOpNum = 2;
4861 else
4862 return SDValue();
4863
4864 SDValue M = N0->getOperand((ZeroOpNum == 1) ? 2 : 1);
4865 if (M->getOpcode() != ISD::MUL || !M.getNode()->hasOneUse())
4866 return SDValue();
4867
4868 SDLoc DL(N);
4869 SDValue Mul =
4870 DCI.DAG.getNode(ISD::MUL, DL, VT, M->getOperand(0), M->getOperand(1));
4871 SDValue MAD = DCI.DAG.getNode(ISD::ADD, DL, VT, Mul, N1);
4872 return DCI.DAG.getSelect(SDLoc(N), VT, N0->getOperand(0),
4873 ((ZeroOpNum == 1) ? N1 : MAD),
4874 ((ZeroOpNum == 1) ? MAD : N1));
4875 }
4876
4877 return SDValue();
4878 }
4879
4880 static SDValue
PerformFADDCombineWithOperands(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,CodeGenOptLevel OptLevel)4881 PerformFADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
4882 TargetLowering::DAGCombinerInfo &DCI,
4883 CodeGenOptLevel OptLevel) {
4884 EVT VT = N0.getValueType();
4885 if (N0.getOpcode() == ISD::FMUL) {
4886 const auto *TLI = static_cast<const NVPTXTargetLowering *>(
4887 &DCI.DAG.getTargetLoweringInfo());
4888 if (!(TLI->allowFMA(DCI.DAG.getMachineFunction(), OptLevel) ||
4889 (N->getFlags().hasAllowContract() &&
4890 N0->getFlags().hasAllowContract())))
4891 return SDValue();
4892
4893 // For floating point:
4894 // Do the fusion only when the mul has less than 5 uses and all
4895 // are add.
4896 // The heuristic is that if a use is not an add, then that use
4897 // cannot be fused into fma, therefore mul is still needed anyway.
4898 // If there are more than 4 uses, even if they are all add, fusing
4899 // them will increase register pressue.
4900 //
4901 int numUses = 0;
4902 int nonAddCount = 0;
4903 for (const SDNode *User : N0.getNode()->users()) {
4904 numUses++;
4905 if (User->getOpcode() != ISD::FADD)
4906 ++nonAddCount;
4907 if (numUses >= 5)
4908 return SDValue();
4909 }
4910 if (nonAddCount) {
4911 int orderNo = N->getIROrder();
4912 int orderNo2 = N0.getNode()->getIROrder();
4913 // simple heuristics here for considering potential register
4914 // pressure, the logics here is that the differnce are used
4915 // to measure the distance between def and use, the longer distance
4916 // more likely cause register pressure.
4917 if (orderNo - orderNo2 < 500)
4918 return SDValue();
4919
4920 // Now, check if at least one of the FMUL's operands is live beyond the
4921 // node N, which guarantees that the FMA will not increase register
4922 // pressure at node N.
4923 bool opIsLive = false;
4924 const SDNode *left = N0.getOperand(0).getNode();
4925 const SDNode *right = N0.getOperand(1).getNode();
4926
4927 if (isa<ConstantSDNode>(left) || isa<ConstantSDNode>(right))
4928 opIsLive = true;
4929
4930 if (!opIsLive)
4931 for (const SDNode *User : left->users()) {
4932 int orderNo3 = User->getIROrder();
4933 if (orderNo3 > orderNo) {
4934 opIsLive = true;
4935 break;
4936 }
4937 }
4938
4939 if (!opIsLive)
4940 for (const SDNode *User : right->users()) {
4941 int orderNo3 = User->getIROrder();
4942 if (orderNo3 > orderNo) {
4943 opIsLive = true;
4944 break;
4945 }
4946 }
4947
4948 if (!opIsLive)
4949 return SDValue();
4950 }
4951
4952 return DCI.DAG.getNode(ISD::FMA, SDLoc(N), VT, N0.getOperand(0),
4953 N0.getOperand(1), N1);
4954 }
4955
4956 return SDValue();
4957 }
4958
4959 /// Fold unpacking movs into a load by increasing the number of return values.
4960 ///
4961 /// ex:
4962 /// L: v2f16,ch = load <p>
4963 /// a: f16 = extractelt L:0, 0
4964 /// b: f16 = extractelt L:0, 1
4965 /// use(a, b)
4966 ///
4967 /// ...is turned into...
4968 ///
4969 /// L: f16,f16,ch = LoadV2 <p>
4970 /// use(L:0, L:1)
4971 static SDValue
combineUnpackingMovIntoLoad(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)4972 combineUnpackingMovIntoLoad(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
4973 // Don't run this optimization before the legalizer
4974 if (!DCI.isAfterLegalizeDAG())
4975 return SDValue();
4976
4977 EVT ElementVT = N->getValueType(0);
4978 // Avoid non-packed types and v4i8
4979 if (!NVPTX::isPackedVectorTy(ElementVT) || ElementVT == MVT::v4i8)
4980 return SDValue();
4981
4982 SmallVector<SDNode *> DeadCopyToRegs;
4983
4984 // Check whether all outputs are either used by an extractelt or are
4985 // glue/chain nodes
4986 if (!all_of(N->uses(), [&](SDUse &U) {
4987 // Skip glue, chain nodes
4988 if (U.getValueType() == MVT::Glue || U.getValueType() == MVT::Other)
4989 return true;
4990 if (U.getUser()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4991 if (N->getOpcode() != ISD::LOAD)
4992 return true;
4993 // Since this is an ISD::LOAD, check all extractelts are used. If
4994 // any are not used, we don't want to defeat another optimization that
4995 // will narrow the load.
4996 //
4997 // For example:
4998 //
4999 // L: v2f16,ch = load <p>
5000 // e0: f16 = extractelt L:0, 0
5001 // e1: f16 = extractelt L:0, 1 <-- unused
5002 // store e0
5003 //
5004 // Can be optimized by DAGCombiner to:
5005 //
5006 // L: f16,ch = load <p>
5007 // store L:0
5008 return !U.getUser()->use_empty();
5009 }
5010
5011 // Otherwise, this use prevents us from splitting a value.
5012 return false;
5013 }))
5014 return SDValue();
5015
5016 auto *LD = cast<MemSDNode>(N);
5017 EVT MemVT = LD->getMemoryVT();
5018 SDLoc DL(LD);
5019
5020 // the new opcode after we double the number of operands
5021 NVPTXISD::NodeType Opcode;
5022 SmallVector<SDValue> Operands(LD->ops());
5023 unsigned OldNumOutputs; // non-glue, non-chain outputs
5024 switch (LD->getOpcode()) {
5025 case ISD::LOAD:
5026 OldNumOutputs = 1;
5027 // Any packed type is legal, so the legalizer will not have lowered
5028 // ISD::LOAD -> NVPTXISD::Load (unless it's under-aligned). We have to do it
5029 // here.
5030 Opcode = NVPTXISD::LoadV2;
5031 Operands.push_back(DCI.DAG.getIntPtrConstant(
5032 cast<LoadSDNode>(LD)->getExtensionType(), DL));
5033 break;
5034 case NVPTXISD::LoadParamV2:
5035 OldNumOutputs = 2;
5036 Opcode = NVPTXISD::LoadParamV4;
5037 break;
5038 case NVPTXISD::LoadV2:
5039 OldNumOutputs = 2;
5040 Opcode = NVPTXISD::LoadV4;
5041 break;
5042 case NVPTXISD::LoadV4:
5043 // V8 is only supported for f32. Don't forget, we're not changing the load
5044 // size here. This is already a 256-bit load.
5045 if (ElementVT != MVT::v2f32)
5046 return SDValue();
5047 OldNumOutputs = 4;
5048 Opcode = NVPTXISD::LoadV8;
5049 break;
5050 case NVPTXISD::LoadV8:
5051 // PTX doesn't support the next doubling of outputs
5052 return SDValue();
5053 }
5054
5055 // the non-glue, non-chain outputs in the new load
5056 const unsigned NewNumOutputs = OldNumOutputs * 2;
5057 SmallVector<EVT> NewVTs(NewNumOutputs, ElementVT.getVectorElementType());
5058 // add remaining chain and glue values
5059 NewVTs.append(LD->value_begin() + OldNumOutputs, LD->value_end());
5060
5061 // Create the new load
5062 SDValue NewLoad =
5063 DCI.DAG.getMemIntrinsicNode(Opcode, DL, DCI.DAG.getVTList(NewVTs),
5064 Operands, MemVT, LD->getMemOperand());
5065
5066 // Now we use a combination of BUILD_VECTORs and a MERGE_VALUES node to keep
5067 // the outputs the same. These nodes will be optimized away in later
5068 // DAGCombiner iterations.
5069 SmallVector<SDValue> Results;
5070 for (unsigned I : seq(OldNumOutputs))
5071 Results.push_back(DCI.DAG.getBuildVector(
5072 ElementVT, DL, {NewLoad.getValue(I * 2), NewLoad.getValue(I * 2 + 1)}));
5073 // Add remaining chain and glue nodes
5074 for (unsigned I : seq(NewLoad->getNumValues() - NewNumOutputs))
5075 Results.push_back(NewLoad.getValue(NewNumOutputs + I));
5076
5077 return DCI.DAG.getMergeValues(Results, DL);
5078 }
5079
5080 /// Fold packing movs into a store.
5081 ///
5082 /// ex:
5083 /// v1: v2f16 = BUILD_VECTOR a:f16, b:f16
5084 /// v2: v2f16 = BUILD_VECTOR c:f16, d:f16
5085 /// StoreV2 v1, v2
5086 ///
5087 /// ...is turned into...
5088 ///
5089 /// StoreV4 a, b, c, d
combinePackingMovIntoStore(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,unsigned Front,unsigned Back)5090 static SDValue combinePackingMovIntoStore(SDNode *N,
5091 TargetLowering::DAGCombinerInfo &DCI,
5092 unsigned Front, unsigned Back) {
5093 // We want to run this as late as possible since other optimizations may
5094 // eliminate the BUILD_VECTORs.
5095 if (!DCI.isAfterLegalizeDAG())
5096 return SDValue();
5097
5098 // Get the type of the operands being stored.
5099 EVT ElementVT = N->getOperand(Front).getValueType();
5100
5101 // Avoid non-packed types and v4i8
5102 if (!NVPTX::isPackedVectorTy(ElementVT) || ElementVT == MVT::v4i8)
5103 return SDValue();
5104
5105 auto *ST = cast<MemSDNode>(N);
5106 EVT MemVT = ElementVT.getVectorElementType();
5107
5108 // The new opcode after we double the number of operands.
5109 NVPTXISD::NodeType Opcode;
5110 switch (N->getOpcode()) {
5111 case ISD::STORE:
5112 // Any packed type is legal, so the legalizer will not have lowered
5113 // ISD::STORE -> NVPTXISD::Store (unless it's under-aligned). We have to do
5114 // it here.
5115 MemVT = ST->getMemoryVT();
5116 Opcode = NVPTXISD::StoreV2;
5117 break;
5118 case NVPTXISD::StoreParam:
5119 Opcode = NVPTXISD::StoreParamV2;
5120 break;
5121 case NVPTXISD::StoreParamV2:
5122 Opcode = NVPTXISD::StoreParamV4;
5123 break;
5124 case NVPTXISD::StoreV2:
5125 MemVT = ST->getMemoryVT();
5126 Opcode = NVPTXISD::StoreV4;
5127 break;
5128 case NVPTXISD::StoreV4:
5129 // V8 is only supported for f32. Don't forget, we're not changing the store
5130 // size here. This is already a 256-bit store.
5131 if (ElementVT != MVT::v2f32)
5132 return SDValue();
5133 Opcode = NVPTXISD::StoreV8;
5134 break;
5135 case NVPTXISD::StoreParamV4:
5136 case NVPTXISD::StoreV8:
5137 // PTX doesn't support the next doubling of operands
5138 return SDValue();
5139 default:
5140 llvm_unreachable("Unhandled store opcode");
5141 }
5142
5143 // Scan the operands and if they're all BUILD_VECTORs, we'll have gathered
5144 // their elements.
5145 SmallVector<SDValue, 4> Operands(N->ops().take_front(Front));
5146 for (SDValue BV : N->ops().drop_front(Front).drop_back(Back)) {
5147 if (BV.getOpcode() != ISD::BUILD_VECTOR)
5148 return SDValue();
5149
5150 // If the operand has multiple uses, this optimization can increase register
5151 // pressure.
5152 if (!BV.hasOneUse())
5153 return SDValue();
5154
5155 // DAGCombiner visits nodes bottom-up. Check the BUILD_VECTOR operands for
5156 // any signs they may be folded by some other pattern or rule.
5157 for (SDValue Op : BV->ops()) {
5158 // Peek through bitcasts
5159 if (Op.getOpcode() == ISD::BITCAST)
5160 Op = Op.getOperand(0);
5161
5162 // This may be folded into a PRMT.
5163 if (Op.getValueType() == MVT::i16 && Op.getOpcode() == ISD::TRUNCATE &&
5164 Op->getOperand(0).getValueType() == MVT::i32)
5165 return SDValue();
5166
5167 // This may be folded into cvt.bf16x2
5168 if (Op.getOpcode() == ISD::FP_ROUND)
5169 return SDValue();
5170 }
5171 Operands.append({BV.getOperand(0), BV.getOperand(1)});
5172 }
5173 Operands.append(N->op_end() - Back, N->op_end());
5174
5175 // Now we replace the store
5176 return DCI.DAG.getMemIntrinsicNode(Opcode, SDLoc(N), N->getVTList(), Operands,
5177 MemVT, ST->getMemOperand());
5178 }
5179
PerformStoreCombineHelper(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,unsigned Front,unsigned Back)5180 static SDValue PerformStoreCombineHelper(SDNode *N,
5181 TargetLowering::DAGCombinerInfo &DCI,
5182 unsigned Front, unsigned Back) {
5183 if (all_of(N->ops().drop_front(Front).drop_back(Back),
5184 [](const SDUse &U) { return U.get()->isUndef(); }))
5185 // Operand 0 is the previous value in the chain. Cannot return EntryToken
5186 // as the previous value will become unused and eliminated later.
5187 return N->getOperand(0);
5188
5189 return combinePackingMovIntoStore(N, DCI, Front, Back);
5190 }
5191
PerformStoreCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)5192 static SDValue PerformStoreCombine(SDNode *N,
5193 TargetLowering::DAGCombinerInfo &DCI) {
5194 return combinePackingMovIntoStore(N, DCI, 1, 2);
5195 }
5196
PerformStoreParamCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)5197 static SDValue PerformStoreParamCombine(SDNode *N,
5198 TargetLowering::DAGCombinerInfo &DCI) {
5199 // Operands from the 3rd to the 2nd last one are the values to be stored.
5200 // {Chain, ArgID, Offset, Val, Glue}
5201 return PerformStoreCombineHelper(N, DCI, 3, 1);
5202 }
5203
5204 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
5205 ///
PerformADDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,CodeGenOptLevel OptLevel)5206 static SDValue PerformADDCombine(SDNode *N,
5207 TargetLowering::DAGCombinerInfo &DCI,
5208 CodeGenOptLevel OptLevel) {
5209 if (OptLevel == CodeGenOptLevel::None)
5210 return SDValue();
5211
5212 SDValue N0 = N->getOperand(0);
5213 SDValue N1 = N->getOperand(1);
5214
5215 // Skip non-integer, non-scalar case
5216 EVT VT = N0.getValueType();
5217 if (VT.isVector() || VT != MVT::i32)
5218 return SDValue();
5219
5220 // First try with the default operand order.
5221 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI))
5222 return Result;
5223
5224 // If that didn't work, try again with the operands commuted.
5225 return PerformADDCombineWithOperands(N, N1, N0, DCI);
5226 }
5227
5228 /// PerformFADDCombine - Target-specific dag combine xforms for ISD::FADD.
5229 ///
PerformFADDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,CodeGenOptLevel OptLevel)5230 static SDValue PerformFADDCombine(SDNode *N,
5231 TargetLowering::DAGCombinerInfo &DCI,
5232 CodeGenOptLevel OptLevel) {
5233 SDValue N0 = N->getOperand(0);
5234 SDValue N1 = N->getOperand(1);
5235
5236 EVT VT = N0.getValueType();
5237 if (VT.isVector() || !(VT == MVT::f32 || VT == MVT::f64))
5238 return SDValue();
5239
5240 // First try with the default operand order.
5241 if (SDValue Result = PerformFADDCombineWithOperands(N, N0, N1, DCI, OptLevel))
5242 return Result;
5243
5244 // If that didn't work, try again with the operands commuted.
5245 return PerformFADDCombineWithOperands(N, N1, N0, DCI, OptLevel);
5246 }
5247
PerformANDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)5248 static SDValue PerformANDCombine(SDNode *N,
5249 TargetLowering::DAGCombinerInfo &DCI) {
5250 // The type legalizer turns a vector load of i8 values into a zextload to i16
5251 // registers, optionally ANY_EXTENDs it (if target type is integer),
5252 // and ANDs off the high 8 bits. Since we turn this load into a
5253 // target-specific DAG node, the DAG combiner fails to eliminate these AND
5254 // nodes. Do that here.
5255 SDValue Val = N->getOperand(0);
5256 SDValue Mask = N->getOperand(1);
5257
5258 if (isa<ConstantSDNode>(Val)) {
5259 std::swap(Val, Mask);
5260 }
5261
5262 SDValue AExt;
5263
5264 // Generally, we will see zextload -> IMOV16rr -> ANY_EXTEND -> and
5265 if (Val.getOpcode() == ISD::ANY_EXTEND) {
5266 AExt = Val;
5267 Val = Val->getOperand(0);
5268 }
5269
5270 if (Val->getOpcode() == NVPTXISD::LoadV2 ||
5271 Val->getOpcode() == NVPTXISD::LoadV4) {
5272 ConstantSDNode *MaskCnst = dyn_cast<ConstantSDNode>(Mask);
5273 if (!MaskCnst) {
5274 // Not an AND with a constant
5275 return SDValue();
5276 }
5277
5278 uint64_t MaskVal = MaskCnst->getZExtValue();
5279 if (MaskVal != 0xff) {
5280 // Not an AND that chops off top 8 bits
5281 return SDValue();
5282 }
5283
5284 MemSDNode *Mem = dyn_cast<MemSDNode>(Val);
5285 if (!Mem) {
5286 // Not a MemSDNode?!?
5287 return SDValue();
5288 }
5289
5290 EVT MemVT = Mem->getMemoryVT();
5291 if (MemVT != MVT::v2i8 && MemVT != MVT::v4i8) {
5292 // We only handle the i8 case
5293 return SDValue();
5294 }
5295
5296 unsigned ExtType = Val->getConstantOperandVal(Val->getNumOperands() - 1);
5297 if (ExtType == ISD::SEXTLOAD) {
5298 // If for some reason the load is a sextload, the and is needed to zero
5299 // out the high 8 bits
5300 return SDValue();
5301 }
5302
5303 bool AddTo = false;
5304 if (AExt.getNode() != nullptr) {
5305 // Re-insert the ext as a zext.
5306 Val = DCI.DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
5307 AExt.getValueType(), Val);
5308 AddTo = true;
5309 }
5310
5311 // If we get here, the AND is unnecessary. Just replace it with the load
5312 DCI.CombineTo(N, Val, AddTo);
5313 }
5314
5315 return SDValue();
5316 }
5317
PerformREMCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,CodeGenOptLevel OptLevel)5318 static SDValue PerformREMCombine(SDNode *N,
5319 TargetLowering::DAGCombinerInfo &DCI,
5320 CodeGenOptLevel OptLevel) {
5321 assert(N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM);
5322
5323 // Don't do anything at less than -O2.
5324 if (OptLevel < CodeGenOptLevel::Default)
5325 return SDValue();
5326
5327 SelectionDAG &DAG = DCI.DAG;
5328 SDLoc DL(N);
5329 EVT VT = N->getValueType(0);
5330 bool IsSigned = N->getOpcode() == ISD::SREM;
5331 unsigned DivOpc = IsSigned ? ISD::SDIV : ISD::UDIV;
5332
5333 const SDValue &Num = N->getOperand(0);
5334 const SDValue &Den = N->getOperand(1);
5335
5336 for (const SDNode *U : Num->users()) {
5337 if (U->getOpcode() == DivOpc && U->getOperand(0) == Num &&
5338 U->getOperand(1) == Den) {
5339 // Num % Den -> Num - (Num / Den) * Den
5340 return DAG.getNode(ISD::SUB, DL, VT, Num,
5341 DAG.getNode(ISD::MUL, DL, VT,
5342 DAG.getNode(DivOpc, DL, VT, Num, Den),
5343 Den));
5344 }
5345 }
5346 return SDValue();
5347 }
5348
5349 enum OperandSignedness {
5350 Signed = 0,
5351 Unsigned,
5352 Unknown
5353 };
5354
5355 /// IsMulWideOperandDemotable - Checks if the provided DAG node is an operand
5356 /// that can be demoted to \p OptSize bits without loss of information. The
5357 /// signedness of the operand, if determinable, is placed in \p S.
IsMulWideOperandDemotable(SDValue Op,unsigned OptSize,OperandSignedness & S)5358 static bool IsMulWideOperandDemotable(SDValue Op,
5359 unsigned OptSize,
5360 OperandSignedness &S) {
5361 S = Unknown;
5362
5363 if (Op.getOpcode() == ISD::SIGN_EXTEND ||
5364 Op.getOpcode() == ISD::SIGN_EXTEND_INREG) {
5365 EVT OrigVT = Op.getOperand(0).getValueType();
5366 if (OrigVT.getFixedSizeInBits() <= OptSize) {
5367 S = Signed;
5368 return true;
5369 }
5370 } else if (Op.getOpcode() == ISD::ZERO_EXTEND) {
5371 EVT OrigVT = Op.getOperand(0).getValueType();
5372 if (OrigVT.getFixedSizeInBits() <= OptSize) {
5373 S = Unsigned;
5374 return true;
5375 }
5376 }
5377
5378 return false;
5379 }
5380
5381 /// AreMulWideOperandsDemotable - Checks if the given LHS and RHS operands can
5382 /// be demoted to \p OptSize bits without loss of information. If the operands
5383 /// contain a constant, it should appear as the RHS operand. The signedness of
5384 /// the operands is placed in \p IsSigned.
AreMulWideOperandsDemotable(SDValue LHS,SDValue RHS,unsigned OptSize,bool & IsSigned)5385 static bool AreMulWideOperandsDemotable(SDValue LHS, SDValue RHS,
5386 unsigned OptSize,
5387 bool &IsSigned) {
5388 OperandSignedness LHSSign;
5389
5390 // The LHS operand must be a demotable op
5391 if (!IsMulWideOperandDemotable(LHS, OptSize, LHSSign))
5392 return false;
5393
5394 // We should have been able to determine the signedness from the LHS
5395 if (LHSSign == Unknown)
5396 return false;
5397
5398 IsSigned = (LHSSign == Signed);
5399
5400 // The RHS can be a demotable op or a constant
5401 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(RHS)) {
5402 const APInt &Val = CI->getAPIntValue();
5403 if (LHSSign == Unsigned) {
5404 return Val.isIntN(OptSize);
5405 } else {
5406 return Val.isSignedIntN(OptSize);
5407 }
5408 } else {
5409 OperandSignedness RHSSign;
5410 if (!IsMulWideOperandDemotable(RHS, OptSize, RHSSign))
5411 return false;
5412
5413 return LHSSign == RHSSign;
5414 }
5415 }
5416
5417 /// TryMULWIDECombine - Attempt to replace a multiply of M bits with a multiply
5418 /// of M/2 bits that produces an M-bit result (i.e. mul.wide). This transform
5419 /// works on both multiply DAG nodes and SHL DAG nodes with a constant shift
5420 /// amount.
TryMULWIDECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)5421 static SDValue TryMULWIDECombine(SDNode *N,
5422 TargetLowering::DAGCombinerInfo &DCI) {
5423 EVT MulType = N->getValueType(0);
5424 if (MulType != MVT::i32 && MulType != MVT::i64) {
5425 return SDValue();
5426 }
5427
5428 SDLoc DL(N);
5429 unsigned OptSize = MulType.getSizeInBits() >> 1;
5430 SDValue LHS = N->getOperand(0);
5431 SDValue RHS = N->getOperand(1);
5432
5433 // Canonicalize the multiply so the constant (if any) is on the right
5434 if (N->getOpcode() == ISD::MUL) {
5435 if (isa<ConstantSDNode>(LHS)) {
5436 std::swap(LHS, RHS);
5437 }
5438 }
5439
5440 // If we have a SHL, determine the actual multiply amount
5441 if (N->getOpcode() == ISD::SHL) {
5442 ConstantSDNode *ShlRHS = dyn_cast<ConstantSDNode>(RHS);
5443 if (!ShlRHS) {
5444 return SDValue();
5445 }
5446
5447 APInt ShiftAmt = ShlRHS->getAPIntValue();
5448 unsigned BitWidth = MulType.getSizeInBits();
5449 if (ShiftAmt.sge(0) && ShiftAmt.slt(BitWidth)) {
5450 APInt MulVal = APInt(BitWidth, 1) << ShiftAmt;
5451 RHS = DCI.DAG.getConstant(MulVal, DL, MulType);
5452 } else {
5453 return SDValue();
5454 }
5455 }
5456
5457 bool Signed;
5458 // Verify that our operands are demotable
5459 if (!AreMulWideOperandsDemotable(LHS, RHS, OptSize, Signed)) {
5460 return SDValue();
5461 }
5462
5463 EVT DemotedVT;
5464 if (MulType == MVT::i32) {
5465 DemotedVT = MVT::i16;
5466 } else {
5467 DemotedVT = MVT::i32;
5468 }
5469
5470 // Truncate the operands to the correct size. Note that these are just for
5471 // type consistency and will (likely) be eliminated in later phases.
5472 SDValue TruncLHS =
5473 DCI.DAG.getNode(ISD::TRUNCATE, DL, DemotedVT, LHS);
5474 SDValue TruncRHS =
5475 DCI.DAG.getNode(ISD::TRUNCATE, DL, DemotedVT, RHS);
5476
5477 unsigned Opc;
5478 if (Signed) {
5479 Opc = NVPTXISD::MUL_WIDE_SIGNED;
5480 } else {
5481 Opc = NVPTXISD::MUL_WIDE_UNSIGNED;
5482 }
5483
5484 return DCI.DAG.getNode(Opc, DL, MulType, TruncLHS, TruncRHS);
5485 }
5486
isConstOne(const SDValue & Operand)5487 static bool isConstOne(const SDValue &Operand) {
5488 const auto *Const = dyn_cast<ConstantSDNode>(Operand);
5489 return Const && Const->getZExtValue() == 1;
5490 }
5491
matchMADConstOnePattern(SDValue Add)5492 static SDValue matchMADConstOnePattern(SDValue Add) {
5493 if (Add->getOpcode() != ISD::ADD)
5494 return SDValue();
5495
5496 if (isConstOne(Add->getOperand(0)))
5497 return Add->getOperand(1);
5498
5499 if (isConstOne(Add->getOperand(1)))
5500 return Add->getOperand(0);
5501
5502 return SDValue();
5503 }
5504
combineMADConstOne(SDValue X,SDValue Add,EVT VT,SDLoc DL,TargetLowering::DAGCombinerInfo & DCI)5505 static SDValue combineMADConstOne(SDValue X, SDValue Add, EVT VT, SDLoc DL,
5506 TargetLowering::DAGCombinerInfo &DCI) {
5507
5508 if (SDValue Y = matchMADConstOnePattern(Add)) {
5509 SDValue Mul = DCI.DAG.getNode(ISD::MUL, DL, VT, X, Y);
5510 return DCI.DAG.getNode(ISD::ADD, DL, VT, Mul, X);
5511 }
5512
5513 return SDValue();
5514 }
5515
combineMulSelectConstOne(SDValue X,SDValue Select,EVT VT,SDLoc DL,TargetLowering::DAGCombinerInfo & DCI)5516 static SDValue combineMulSelectConstOne(SDValue X, SDValue Select, EVT VT,
5517 SDLoc DL,
5518 TargetLowering::DAGCombinerInfo &DCI) {
5519 if (Select->getOpcode() != ISD::SELECT)
5520 return SDValue();
5521
5522 SDValue Cond = Select->getOperand(0);
5523
5524 unsigned ConstOpNo;
5525 if (isConstOne(Select->getOperand(1)))
5526 ConstOpNo = 1;
5527 else if (isConstOne(Select->getOperand(2)))
5528 ConstOpNo = 2;
5529 else
5530 return SDValue();
5531
5532 SDValue Y = Select->getOperand((ConstOpNo == 1) ? 2 : 1);
5533
5534 // Do not combine if the resulting sequence is not obviously profitable.
5535 if (!matchMADConstOnePattern(Y))
5536 return SDValue();
5537
5538 SDValue NewMul = DCI.DAG.getNode(ISD::MUL, DL, VT, X, Y);
5539
5540 return DCI.DAG.getNode(ISD::SELECT, DL, VT, Cond,
5541 (ConstOpNo == 1) ? X : NewMul,
5542 (ConstOpNo == 1) ? NewMul : X);
5543 }
5544
5545 static SDValue
PerformMULCombineWithOperands(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI)5546 PerformMULCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
5547 TargetLowering::DAGCombinerInfo &DCI) {
5548
5549 EVT VT = N0.getValueType();
5550 if (VT.isVector())
5551 return SDValue();
5552
5553 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
5554 return SDValue();
5555
5556 SDLoc DL(N);
5557
5558 // (mul x, (add y, 1)) -> (add (mul x, y), x)
5559 if (SDValue Res = combineMADConstOne(N0, N1, VT, DL, DCI))
5560 return Res;
5561 if (SDValue Res = combineMADConstOne(N1, N0, VT, DL, DCI))
5562 return Res;
5563
5564 // (mul x, (select y, 1)) -> (select (mul x, y), x)
5565 if (SDValue Res = combineMulSelectConstOne(N0, N1, VT, DL, DCI))
5566 return Res;
5567 if (SDValue Res = combineMulSelectConstOne(N1, N0, VT, DL, DCI))
5568 return Res;
5569
5570 return SDValue();
5571 }
5572
5573 /// PerformMULCombine - Runs PTX-specific DAG combine patterns on MUL nodes.
PerformMULCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,CodeGenOptLevel OptLevel)5574 static SDValue PerformMULCombine(SDNode *N,
5575 TargetLowering::DAGCombinerInfo &DCI,
5576 CodeGenOptLevel OptLevel) {
5577 if (OptLevel == CodeGenOptLevel::None)
5578 return SDValue();
5579
5580 if (SDValue Ret = TryMULWIDECombine(N, DCI))
5581 return Ret;
5582
5583 SDValue N0 = N->getOperand(0);
5584 SDValue N1 = N->getOperand(1);
5585 return PerformMULCombineWithOperands(N, N0, N1, DCI);
5586 }
5587
5588 /// PerformSHLCombine - Runs PTX-specific DAG combine patterns on SHL nodes.
PerformSHLCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,CodeGenOptLevel OptLevel)5589 static SDValue PerformSHLCombine(SDNode *N,
5590 TargetLowering::DAGCombinerInfo &DCI,
5591 CodeGenOptLevel OptLevel) {
5592 if (OptLevel > CodeGenOptLevel::None) {
5593 // Try mul.wide combining at OptLevel > 0
5594 if (SDValue Ret = TryMULWIDECombine(N, DCI))
5595 return Ret;
5596 }
5597
5598 return SDValue();
5599 }
5600
PerformSETCCCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,unsigned int SmVersion)5601 static SDValue PerformSETCCCombine(SDNode *N,
5602 TargetLowering::DAGCombinerInfo &DCI,
5603 unsigned int SmVersion) {
5604 EVT CCType = N->getValueType(0);
5605 SDValue A = N->getOperand(0);
5606 SDValue B = N->getOperand(1);
5607
5608 EVT AType = A.getValueType();
5609 if (!(CCType == MVT::v2i1 && (AType == MVT::v2f16 || AType == MVT::v2bf16)))
5610 return SDValue();
5611
5612 if (A.getValueType() == MVT::v2bf16 && SmVersion < 90)
5613 return SDValue();
5614
5615 SDLoc DL(N);
5616 // setp.f16x2 returns two scalar predicates, which we need to
5617 // convert back to v2i1. The returned result will be scalarized by
5618 // the legalizer, but the comparison will remain a single vector
5619 // instruction.
5620 SDValue CCNode = DCI.DAG.getNode(
5621 A.getValueType() == MVT::v2f16 ? NVPTXISD::SETP_F16X2
5622 : NVPTXISD::SETP_BF16X2,
5623 DL, DCI.DAG.getVTList(MVT::i1, MVT::i1), {A, B, N->getOperand(2)});
5624 return DCI.DAG.getNode(ISD::BUILD_VECTOR, DL, CCType, CCNode.getValue(0),
5625 CCNode.getValue(1));
5626 }
5627
PerformEXTRACTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)5628 static SDValue PerformEXTRACTCombine(SDNode *N,
5629 TargetLowering::DAGCombinerInfo &DCI) {
5630 SDValue Vector = N->getOperand(0);
5631 if (Vector->getOpcode() == ISD::FREEZE)
5632 Vector = Vector->getOperand(0);
5633 SDLoc DL(N);
5634 EVT VectorVT = Vector.getValueType();
5635 if (Vector->getOpcode() == ISD::LOAD && VectorVT.isSimple() &&
5636 IsPTXVectorType(VectorVT.getSimpleVT()))
5637 return SDValue(); // Native vector loads already combine nicely w/
5638 // extract_vector_elt.
5639 // Don't mess with singletons or packed types (v2f32, v2*16, v4i8 and v8i8),
5640 // we already handle them OK.
5641 if (VectorVT.getVectorNumElements() == 1 ||
5642 NVPTX::isPackedVectorTy(VectorVT) || VectorVT == MVT::v8i8)
5643 return SDValue();
5644
5645 // Don't mess with undef values as sra may be simplified to 0, not undef.
5646 if (Vector->isUndef() || ISD::allOperandsUndef(Vector.getNode()))
5647 return SDValue();
5648
5649 uint64_t VectorBits = VectorVT.getSizeInBits();
5650 // We only handle the types we can extract in-register.
5651 if (!(VectorBits == 16 || VectorBits == 32 || VectorBits == 64))
5652 return SDValue();
5653
5654 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(N->getOperand(1));
5655 // Index == 0 is handled by generic DAG combiner.
5656 if (!Index || Index->getZExtValue() == 0)
5657 return SDValue();
5658
5659 MVT IVT = MVT::getIntegerVT(VectorBits);
5660 EVT EltVT = VectorVT.getVectorElementType();
5661 EVT EltIVT = EltVT.changeTypeToInteger();
5662 uint64_t EltBits = EltVT.getScalarSizeInBits();
5663
5664 SDValue Result = DCI.DAG.getNode(
5665 ISD::TRUNCATE, DL, EltIVT,
5666 DCI.DAG.getNode(
5667 ISD::SRA, DL, IVT, DCI.DAG.getNode(ISD::BITCAST, DL, IVT, Vector),
5668 DCI.DAG.getConstant(Index->getZExtValue() * EltBits, DL, IVT)));
5669
5670 // If element has non-integer type, bitcast it back to the expected type.
5671 if (EltVT != EltIVT)
5672 Result = DCI.DAG.getNode(ISD::BITCAST, DL, EltVT, Result);
5673 // Past legalizer, we may need to extent i8 -> i16 to match the register type.
5674 if (EltVT != N->getValueType(0))
5675 Result = DCI.DAG.getNode(ISD::ANY_EXTEND, DL, N->getValueType(0), Result);
5676
5677 return Result;
5678 }
5679
PerformVSELECTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)5680 static SDValue PerformVSELECTCombine(SDNode *N,
5681 TargetLowering::DAGCombinerInfo &DCI) {
5682 SDValue VA = N->getOperand(1);
5683 EVT VectorVT = VA.getValueType();
5684 if (VectorVT != MVT::v4i8)
5685 return SDValue();
5686
5687 // We need to split vselect into individual per-element operations Because we
5688 // use BFE/BFI instruction for byte extraction/insertion, we do end up with
5689 // 32-bit values, so we may as well do comparison as i32 to avoid conversions
5690 // to/from i16 normally used for i8 values.
5691 SmallVector<SDValue, 4> E;
5692 SDLoc DL(N);
5693 SDValue VCond = N->getOperand(0);
5694 SDValue VB = N->getOperand(2);
5695 for (int I = 0; I < 4; ++I) {
5696 SDValue C = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i1, VCond,
5697 DCI.DAG.getConstant(I, DL, MVT::i32));
5698 SDValue EA = DCI.DAG.getAnyExtOrTrunc(
5699 DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i8, VA,
5700 DCI.DAG.getConstant(I, DL, MVT::i32)),
5701 DL, MVT::i32);
5702 SDValue EB = DCI.DAG.getAnyExtOrTrunc(
5703 DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i8, VB,
5704 DCI.DAG.getConstant(I, DL, MVT::i32)),
5705 DL, MVT::i32);
5706 E.push_back(DCI.DAG.getAnyExtOrTrunc(
5707 DCI.DAG.getNode(ISD::SELECT, DL, MVT::i32, C, EA, EB), DL, MVT::i8));
5708 }
5709 return DCI.DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i8, E);
5710 }
5711
5712 static SDValue
PerformBUILD_VECTORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)5713 PerformBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
5714 auto VT = N->getValueType(0);
5715 if (!DCI.isAfterLegalizeDAG() ||
5716 // only process v2*16 types
5717 !(NVPTX::isPackedVectorTy(VT) && VT.is32BitVector() &&
5718 VT.getVectorNumElements() == 2))
5719 return SDValue();
5720
5721 auto Op0 = N->getOperand(0);
5722 auto Op1 = N->getOperand(1);
5723
5724 // Start out by assuming we want to take the lower 2 bytes of each i32
5725 // operand.
5726 uint64_t Op0Bytes = 0x10;
5727 uint64_t Op1Bytes = 0x54;
5728
5729 std::pair<SDValue *, uint64_t *> OpData[2] = {{&Op0, &Op0Bytes},
5730 {&Op1, &Op1Bytes}};
5731
5732 // Check that each operand is an i16, truncated from an i32 operand. We'll
5733 // select individual bytes from those original operands. Optionally, fold in a
5734 // shift right of that original operand.
5735 for (auto &[Op, OpBytes] : OpData) {
5736 // Eat up any bitcast
5737 if (Op->getOpcode() == ISD::BITCAST)
5738 *Op = Op->getOperand(0);
5739
5740 if (!(Op->getValueType() == MVT::i16 && Op->getOpcode() == ISD::TRUNCATE &&
5741 Op->getOperand(0).getValueType() == MVT::i32))
5742 return SDValue();
5743
5744 // If the truncate has multiple uses, this optimization can increase
5745 // register pressure
5746 if (!Op->hasOneUse())
5747 return SDValue();
5748
5749 *Op = Op->getOperand(0);
5750
5751 // Optionally, fold in a shift-right of the original operand and let permute
5752 // pick the two higher bytes of the original value directly.
5753 if (Op->getOpcode() == ISD::SRL && isa<ConstantSDNode>(Op->getOperand(1))) {
5754 if (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue() == 16) {
5755 // Shift the PRMT byte selector to pick upper bytes from each respective
5756 // value, instead of the lower ones: 0x10 -> 0x32, 0x54 -> 0x76
5757 assert((*OpBytes == 0x10 || *OpBytes == 0x54) &&
5758 "PRMT selector values out of range");
5759 *OpBytes += 0x22;
5760 *Op = Op->getOperand(0);
5761 }
5762 }
5763 }
5764
5765 SDLoc DL(N);
5766 auto &DAG = DCI.DAG;
5767
5768 auto PRMT = DAG.getNode(
5769 NVPTXISD::PRMT, DL, MVT::v4i8,
5770 {Op0, Op1, DAG.getConstant((Op1Bytes << 8) | Op0Bytes, DL, MVT::i32),
5771 DAG.getConstant(NVPTX::PTXPrmtMode::NONE, DL, MVT::i32)});
5772 return DAG.getNode(ISD::BITCAST, DL, VT, PRMT);
5773 }
5774
combineADDRSPACECAST(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)5775 static SDValue combineADDRSPACECAST(SDNode *N,
5776 TargetLowering::DAGCombinerInfo &DCI) {
5777 auto *ASCN1 = cast<AddrSpaceCastSDNode>(N);
5778
5779 if (auto *ASCN2 = dyn_cast<AddrSpaceCastSDNode>(ASCN1->getOperand(0))) {
5780 assert(ASCN2->getDestAddressSpace() == ASCN1->getSrcAddressSpace());
5781
5782 // Fold asc[B -> A](asc[A -> B](x)) -> x
5783 if (ASCN1->getDestAddressSpace() == ASCN2->getSrcAddressSpace())
5784 return ASCN2->getOperand(0);
5785 }
5786
5787 return SDValue();
5788 }
5789
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const5790 SDValue NVPTXTargetLowering::PerformDAGCombine(SDNode *N,
5791 DAGCombinerInfo &DCI) const {
5792 CodeGenOptLevel OptLevel = getTargetMachine().getOptLevel();
5793 switch (N->getOpcode()) {
5794 default: break;
5795 case ISD::ADD:
5796 return PerformADDCombine(N, DCI, OptLevel);
5797 case ISD::FADD:
5798 return PerformFADDCombine(N, DCI, OptLevel);
5799 case ISD::MUL:
5800 return PerformMULCombine(N, DCI, OptLevel);
5801 case ISD::SHL:
5802 return PerformSHLCombine(N, DCI, OptLevel);
5803 case ISD::AND:
5804 return PerformANDCombine(N, DCI);
5805 case ISD::UREM:
5806 case ISD::SREM:
5807 return PerformREMCombine(N, DCI, OptLevel);
5808 case ISD::SETCC:
5809 return PerformSETCCCombine(N, DCI, STI.getSmVersion());
5810 case ISD::LOAD:
5811 case NVPTXISD::LoadParamV2:
5812 case NVPTXISD::LoadV2:
5813 case NVPTXISD::LoadV4:
5814 return combineUnpackingMovIntoLoad(N, DCI);
5815 case NVPTXISD::StoreParam:
5816 case NVPTXISD::StoreParamV2:
5817 case NVPTXISD::StoreParamV4:
5818 return PerformStoreParamCombine(N, DCI);
5819 case ISD::STORE:
5820 case NVPTXISD::StoreV2:
5821 case NVPTXISD::StoreV4:
5822 return PerformStoreCombine(N, DCI);
5823 case ISD::EXTRACT_VECTOR_ELT:
5824 return PerformEXTRACTCombine(N, DCI);
5825 case ISD::VSELECT:
5826 return PerformVSELECTCombine(N, DCI);
5827 case ISD::BUILD_VECTOR:
5828 return PerformBUILD_VECTORCombine(N, DCI);
5829 case ISD::ADDRSPACECAST:
5830 return combineADDRSPACECAST(N, DCI);
5831 }
5832 return SDValue();
5833 }
5834
ReplaceBITCAST(SDNode * Node,SelectionDAG & DAG,SmallVectorImpl<SDValue> & Results)5835 static void ReplaceBITCAST(SDNode *Node, SelectionDAG &DAG,
5836 SmallVectorImpl<SDValue> &Results) {
5837 // Handle bitcasting to v2i8 without hitting the default promotion
5838 // strategy which goes through stack memory.
5839 SDValue Op(Node, 0);
5840 EVT ToVT = Op->getValueType(0);
5841 if (ToVT != MVT::v2i8) {
5842 return;
5843 }
5844
5845 // Bitcast to i16 and unpack elements into a vector
5846 SDLoc DL(Node);
5847 SDValue AsInt = DAG.getBitcast(MVT::i16, Op->getOperand(0));
5848 SDValue Vec0 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, AsInt);
5849 SDValue Const8 = DAG.getConstant(8, DL, MVT::i16);
5850 SDValue Vec1 =
5851 DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
5852 DAG.getNode(ISD::SRL, DL, MVT::i16, {AsInt, Const8}));
5853 Results.push_back(
5854 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i8, {Vec0, Vec1}));
5855 }
5856
5857 /// ReplaceVectorLoad - Convert vector loads into multi-output scalar loads.
replaceLoadVector(SDNode * N,SelectionDAG & DAG,SmallVectorImpl<SDValue> & Results,const NVPTXSubtarget & STI)5858 static void replaceLoadVector(SDNode *N, SelectionDAG &DAG,
5859 SmallVectorImpl<SDValue> &Results,
5860 const NVPTXSubtarget &STI) {
5861 LoadSDNode *LD = cast<LoadSDNode>(N);
5862 const EVT ResVT = LD->getValueType(0);
5863 const EVT MemVT = LD->getMemoryVT();
5864
5865 // If we're doing sign/zero extension as part of the load, avoid lowering to
5866 // a LoadV node. TODO: consider relaxing this restriction.
5867 if (ResVT != MemVT)
5868 return;
5869
5870 const auto NumEltsAndEltVT = getVectorLoweringShape(
5871 ResVT, STI.has256BitVectorLoadStore(LD->getAddressSpace()));
5872 if (!NumEltsAndEltVT)
5873 return;
5874 const auto [NumElts, EltVT] = NumEltsAndEltVT.value();
5875
5876 Align Alignment = LD->getAlign();
5877 const auto &TD = DAG.getDataLayout();
5878 Align PrefAlign = TD.getPrefTypeAlign(MemVT.getTypeForEVT(*DAG.getContext()));
5879 if (Alignment < PrefAlign) {
5880 // This load is not sufficiently aligned, so bail out and let this vector
5881 // load be scalarized. Note that we may still be able to emit smaller
5882 // vector loads. For example, if we are loading a <4 x float> with an
5883 // alignment of 8, this check will fail but the legalizer will try again
5884 // with 2 x <2 x float>, which will succeed with an alignment of 8.
5885 return;
5886 }
5887
5888 // Since LoadV2 is a target node, we cannot rely on DAG type legalization.
5889 // Therefore, we must ensure the type is legal. For i1 and i8, we set the
5890 // loaded type to i16 and propagate the "real" type as the memory type.
5891 const MVT LoadEltVT = (EltVT.getSizeInBits() < 16) ? MVT::i16 : EltVT;
5892
5893 unsigned Opcode;
5894 switch (NumElts) {
5895 default:
5896 return;
5897 case 2:
5898 Opcode = NVPTXISD::LoadV2;
5899 break;
5900 case 4:
5901 Opcode = NVPTXISD::LoadV4;
5902 break;
5903 case 8:
5904 Opcode = NVPTXISD::LoadV8;
5905 break;
5906 }
5907 auto ListVTs = SmallVector<EVT, 9>(NumElts, LoadEltVT);
5908 ListVTs.push_back(MVT::Other);
5909 SDVTList LdResVTs = DAG.getVTList(ListVTs);
5910
5911 SDLoc DL(LD);
5912
5913 // Copy regular operands
5914 SmallVector<SDValue, 8> OtherOps(LD->ops());
5915
5916 // The select routine does not have access to the LoadSDNode instance, so
5917 // pass along the extension information
5918 OtherOps.push_back(DAG.getIntPtrConstant(LD->getExtensionType(), DL));
5919
5920 SDValue NewLD = DAG.getMemIntrinsicNode(Opcode, DL, LdResVTs, OtherOps,
5921 LD->getMemoryVT(),
5922 LD->getMemOperand());
5923
5924 SmallVector<SDValue> ScalarRes;
5925 if (EltVT.isVector()) {
5926 assert(EVT(EltVT.getVectorElementType()) == ResVT.getVectorElementType());
5927 assert(NumElts * EltVT.getVectorNumElements() ==
5928 ResVT.getVectorNumElements());
5929 // Generate EXTRACT_VECTOR_ELTs to split v2[i,f,bf]16/v4i8 subvectors back
5930 // into individual elements.
5931 for (const unsigned I : llvm::seq(NumElts)) {
5932 SDValue SubVector = NewLD.getValue(I);
5933 DAG.ExtractVectorElements(SubVector, ScalarRes);
5934 }
5935 } else {
5936 for (const unsigned I : llvm::seq(NumElts)) {
5937 SDValue Res = NewLD.getValue(I);
5938 if (LoadEltVT != EltVT)
5939 Res = DAG.getNode(ISD::TRUNCATE, DL, EltVT, Res);
5940 ScalarRes.push_back(Res);
5941 }
5942 }
5943
5944 SDValue LoadChain = NewLD.getValue(NumElts);
5945
5946 const MVT BuildVecVT =
5947 MVT::getVectorVT(EltVT.getScalarType(), ScalarRes.size());
5948 SDValue BuildVec = DAG.getBuildVector(BuildVecVT, DL, ScalarRes);
5949 SDValue LoadValue = DAG.getBitcast(ResVT, BuildVec);
5950
5951 Results.append({LoadValue, LoadChain});
5952 }
5953
5954 // Lower vector return type of tcgen05.ld intrinsics
ReplaceTcgen05Ld(SDNode * N,SelectionDAG & DAG,SmallVectorImpl<SDValue> & Results,bool hasOffset=false)5955 static void ReplaceTcgen05Ld(SDNode *N, SelectionDAG &DAG,
5956 SmallVectorImpl<SDValue> &Results,
5957 bool hasOffset = false) {
5958 SDLoc DL(N);
5959 EVT ResVT = N->getValueType(0);
5960 if (!ResVT.isVector())
5961 return; // already legalized.
5962
5963 const unsigned NumElts = ResVT.getVectorNumElements();
5964
5965 // Create the return type of the instructions
5966 SmallVector<EVT, 5> ListVTs;
5967 for (unsigned i = 0; i < NumElts; ++i)
5968 ListVTs.push_back(MVT::i32);
5969
5970 ListVTs.push_back(N->getValueType(1)); // Chain
5971
5972 SDVTList ResVTs = DAG.getVTList(ListVTs);
5973
5974 SmallVector<SDValue, 8> Ops{N->getOperand(0), N->getOperand(1),
5975 N->getOperand(2)};
5976
5977 if (hasOffset) {
5978 Ops.push_back(N->getOperand(3)); // offset
5979 Ops.push_back(N->getOperand(4)); // Pack flag
5980 } else
5981 Ops.push_back(N->getOperand(3)); // Pack flag
5982
5983 MemIntrinsicSDNode *MemSD = cast<MemIntrinsicSDNode>(N);
5984 SDValue NewNode =
5985 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, ResVTs, Ops,
5986 MemSD->getMemoryVT(), MemSD->getMemOperand());
5987
5988 // split the vector result
5989 SmallVector<SDValue, 4> ScalarRes;
5990 for (unsigned i = 0; i < NumElts; ++i) {
5991 SDValue Res = NewNode.getValue(i);
5992 ScalarRes.push_back(Res);
5993 }
5994
5995 SDValue Chain = NewNode.getValue(NumElts);
5996 SDValue BuildVector = DAG.getNode(ISD::BUILD_VECTOR, DL, ResVT, ScalarRes);
5997 Results.push_back(BuildVector); // Build Vector
5998 Results.push_back(Chain); // Chain
5999 }
6000
ReplaceINTRINSIC_W_CHAIN(SDNode * N,SelectionDAG & DAG,SmallVectorImpl<SDValue> & Results)6001 static void ReplaceINTRINSIC_W_CHAIN(SDNode *N, SelectionDAG &DAG,
6002 SmallVectorImpl<SDValue> &Results) {
6003 SDValue Chain = N->getOperand(0);
6004 SDValue Intrin = N->getOperand(1);
6005 SDLoc DL(N);
6006
6007 // Get the intrinsic ID
6008 unsigned IntrinNo = Intrin.getNode()->getAsZExtVal();
6009 switch (IntrinNo) {
6010 default:
6011 return;
6012 case Intrinsic::nvvm_ldu_global_i:
6013 case Intrinsic::nvvm_ldu_global_f:
6014 case Intrinsic::nvvm_ldu_global_p: {
6015 EVT ResVT = N->getValueType(0);
6016
6017 if (ResVT.isVector()) {
6018 // Vector LDG/LDU
6019
6020 unsigned NumElts = ResVT.getVectorNumElements();
6021 EVT EltVT = ResVT.getVectorElementType();
6022
6023 // Since LDU/LDG are target nodes, we cannot rely on DAG type
6024 // legalization.
6025 // Therefore, we must ensure the type is legal. For i1 and i8, we set the
6026 // loaded type to i16 and propagate the "real" type as the memory type.
6027 bool NeedTrunc = false;
6028 if (EltVT.getSizeInBits() < 16) {
6029 EltVT = MVT::i16;
6030 NeedTrunc = true;
6031 }
6032
6033 unsigned Opcode = 0;
6034 SDVTList LdResVTs;
6035
6036 switch (NumElts) {
6037 default:
6038 return;
6039 case 2:
6040 Opcode = NVPTXISD::LDUV2;
6041 LdResVTs = DAG.getVTList(EltVT, EltVT, MVT::Other);
6042 break;
6043 case 4: {
6044 Opcode = NVPTXISD::LDUV4;
6045 EVT ListVTs[] = { EltVT, EltVT, EltVT, EltVT, MVT::Other };
6046 LdResVTs = DAG.getVTList(ListVTs);
6047 break;
6048 }
6049 }
6050
6051 SmallVector<SDValue, 8> OtherOps;
6052
6053 // Copy regular operands
6054
6055 OtherOps.push_back(Chain); // Chain
6056 // Skip operand 1 (intrinsic ID)
6057 // Others
6058 OtherOps.append(N->op_begin() + 2, N->op_end());
6059
6060 MemIntrinsicSDNode *MemSD = cast<MemIntrinsicSDNode>(N);
6061
6062 SDValue NewLD = DAG.getMemIntrinsicNode(Opcode, DL, LdResVTs, OtherOps,
6063 MemSD->getMemoryVT(),
6064 MemSD->getMemOperand());
6065
6066 SmallVector<SDValue, 4> ScalarRes;
6067
6068 for (unsigned i = 0; i < NumElts; ++i) {
6069 SDValue Res = NewLD.getValue(i);
6070 if (NeedTrunc)
6071 Res =
6072 DAG.getNode(ISD::TRUNCATE, DL, ResVT.getVectorElementType(), Res);
6073 ScalarRes.push_back(Res);
6074 }
6075
6076 SDValue LoadChain = NewLD.getValue(NumElts);
6077
6078 SDValue BuildVec =
6079 DAG.getBuildVector(ResVT, DL, ScalarRes);
6080
6081 Results.push_back(BuildVec);
6082 Results.push_back(LoadChain);
6083 } else {
6084 // i8 LDG/LDU
6085 assert(ResVT.isSimple() && ResVT.getSimpleVT().SimpleTy == MVT::i8 &&
6086 "Custom handling of non-i8 ldu/ldg?");
6087
6088 // Just copy all operands as-is
6089 SmallVector<SDValue, 4> Ops(N->ops());
6090
6091 // Force output to i16
6092 SDVTList LdResVTs = DAG.getVTList(MVT::i16, MVT::Other);
6093
6094 MemIntrinsicSDNode *MemSD = cast<MemIntrinsicSDNode>(N);
6095
6096 // We make sure the memory type is i8, which will be used during isel
6097 // to select the proper instruction.
6098 SDValue NewLD =
6099 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, LdResVTs, Ops,
6100 MVT::i8, MemSD->getMemOperand());
6101
6102 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
6103 NewLD.getValue(0)));
6104 Results.push_back(NewLD.getValue(1));
6105 }
6106 return;
6107 }
6108
6109 case Intrinsic::nvvm_tcgen05_ld_16x64b_x2:
6110 case Intrinsic::nvvm_tcgen05_ld_16x64b_x4:
6111 case Intrinsic::nvvm_tcgen05_ld_16x64b_x8:
6112 case Intrinsic::nvvm_tcgen05_ld_16x64b_x16:
6113 case Intrinsic::nvvm_tcgen05_ld_16x64b_x32:
6114 case Intrinsic::nvvm_tcgen05_ld_16x64b_x64:
6115 case Intrinsic::nvvm_tcgen05_ld_16x64b_x128:
6116 case Intrinsic::nvvm_tcgen05_ld_32x32b_x2:
6117 case Intrinsic::nvvm_tcgen05_ld_32x32b_x4:
6118 case Intrinsic::nvvm_tcgen05_ld_32x32b_x8:
6119 case Intrinsic::nvvm_tcgen05_ld_32x32b_x16:
6120 case Intrinsic::nvvm_tcgen05_ld_32x32b_x32:
6121 case Intrinsic::nvvm_tcgen05_ld_32x32b_x64:
6122 case Intrinsic::nvvm_tcgen05_ld_32x32b_x128:
6123 case Intrinsic::nvvm_tcgen05_ld_16x128b_x1:
6124 case Intrinsic::nvvm_tcgen05_ld_16x128b_x2:
6125 case Intrinsic::nvvm_tcgen05_ld_16x128b_x4:
6126 case Intrinsic::nvvm_tcgen05_ld_16x128b_x8:
6127 case Intrinsic::nvvm_tcgen05_ld_16x128b_x16:
6128 case Intrinsic::nvvm_tcgen05_ld_16x128b_x32:
6129 case Intrinsic::nvvm_tcgen05_ld_16x128b_x64:
6130 case Intrinsic::nvvm_tcgen05_ld_16x256b_x1:
6131 case Intrinsic::nvvm_tcgen05_ld_16x256b_x2:
6132 case Intrinsic::nvvm_tcgen05_ld_16x256b_x4:
6133 case Intrinsic::nvvm_tcgen05_ld_16x256b_x8:
6134 case Intrinsic::nvvm_tcgen05_ld_16x256b_x16:
6135 case Intrinsic::nvvm_tcgen05_ld_16x256b_x32:
6136 return ReplaceTcgen05Ld(N, DAG, Results);
6137
6138 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x2:
6139 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x4:
6140 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x8:
6141 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x16:
6142 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x32:
6143 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x64:
6144 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x128:
6145 return ReplaceTcgen05Ld(N, DAG, Results, /* Offset */ true);
6146 }
6147 }
6148
ReplaceCopyFromReg_128(SDNode * N,SelectionDAG & DAG,SmallVectorImpl<SDValue> & Results)6149 static void ReplaceCopyFromReg_128(SDNode *N, SelectionDAG &DAG,
6150 SmallVectorImpl<SDValue> &Results) {
6151 // Change the CopyFromReg to output 2 64-bit results instead of a 128-bit
6152 // result so that it can pass the legalization
6153 SDLoc DL(N);
6154 SDValue Chain = N->getOperand(0);
6155 SDValue Reg = N->getOperand(1);
6156 SDValue Glue = N->getOperand(2);
6157
6158 assert(Reg.getValueType() == MVT::i128 &&
6159 "Custom lowering for CopyFromReg with 128-bit reg only");
6160 SmallVector<EVT, 4> ResultsType = {MVT::i64, MVT::i64, N->getValueType(1),
6161 N->getValueType(2)};
6162 SmallVector<SDValue, 3> NewOps = {Chain, Reg, Glue};
6163
6164 SDValue NewValue = DAG.getNode(ISD::CopyFromReg, DL, ResultsType, NewOps);
6165 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128,
6166 {NewValue.getValue(0), NewValue.getValue(1)});
6167
6168 Results.push_back(Pair);
6169 Results.push_back(NewValue.getValue(2));
6170 Results.push_back(NewValue.getValue(3));
6171 }
6172
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const6173 void NVPTXTargetLowering::ReplaceNodeResults(
6174 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
6175 switch (N->getOpcode()) {
6176 default:
6177 report_fatal_error("Unhandled custom legalization");
6178 case ISD::BITCAST:
6179 ReplaceBITCAST(N, DAG, Results);
6180 return;
6181 case ISD::LOAD:
6182 replaceLoadVector(N, DAG, Results, STI);
6183 return;
6184 case ISD::INTRINSIC_W_CHAIN:
6185 ReplaceINTRINSIC_W_CHAIN(N, DAG, Results);
6186 return;
6187 case ISD::CopyFromReg:
6188 ReplaceCopyFromReg_128(N, DAG, Results);
6189 return;
6190 }
6191 }
6192
6193 NVPTXTargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const6194 NVPTXTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
6195 Type *Ty = AI->getValOperand()->getType();
6196
6197 if (AI->isFloatingPointOperation()) {
6198 if (AI->getOperation() == AtomicRMWInst::BinOp::FAdd) {
6199 if (Ty->isHalfTy() && STI.getSmVersion() >= 70 &&
6200 STI.getPTXVersion() >= 63)
6201 return AtomicExpansionKind::None;
6202 if (Ty->isBFloatTy() && STI.getSmVersion() >= 90 &&
6203 STI.getPTXVersion() >= 78)
6204 return AtomicExpansionKind::None;
6205 if (Ty->isFloatTy())
6206 return AtomicExpansionKind::None;
6207 if (Ty->isDoubleTy() && STI.hasAtomAddF64())
6208 return AtomicExpansionKind::None;
6209 }
6210 return AtomicExpansionKind::CmpXChg;
6211 }
6212
6213 assert(Ty->isIntegerTy() && "Ty should be integer at this point");
6214 auto ITy = cast<llvm::IntegerType>(Ty);
6215
6216 switch (AI->getOperation()) {
6217 default:
6218 return AtomicExpansionKind::CmpXChg;
6219 case AtomicRMWInst::BinOp::And:
6220 case AtomicRMWInst::BinOp::Or:
6221 case AtomicRMWInst::BinOp::Xor:
6222 case AtomicRMWInst::BinOp::Xchg:
6223 switch (ITy->getBitWidth()) {
6224 case 8:
6225 case 16:
6226 return AtomicExpansionKind::CmpXChg;
6227 case 32:
6228 return AtomicExpansionKind::None;
6229 case 64:
6230 if (STI.hasAtomBitwise64())
6231 return AtomicExpansionKind::None;
6232 return AtomicExpansionKind::CmpXChg;
6233 default:
6234 llvm_unreachable("unsupported width encountered");
6235 }
6236 case AtomicRMWInst::BinOp::Add:
6237 case AtomicRMWInst::BinOp::Sub:
6238 case AtomicRMWInst::BinOp::Max:
6239 case AtomicRMWInst::BinOp::Min:
6240 case AtomicRMWInst::BinOp::UMax:
6241 case AtomicRMWInst::BinOp::UMin:
6242 switch (ITy->getBitWidth()) {
6243 case 8:
6244 case 16:
6245 return AtomicExpansionKind::CmpXChg;
6246 case 32:
6247 return AtomicExpansionKind::None;
6248 case 64:
6249 if (STI.hasAtomMinMax64())
6250 return AtomicExpansionKind::None;
6251 return AtomicExpansionKind::CmpXChg;
6252 default:
6253 llvm_unreachable("unsupported width encountered");
6254 }
6255 case AtomicRMWInst::BinOp::UIncWrap:
6256 case AtomicRMWInst::BinOp::UDecWrap:
6257 switch (ITy->getBitWidth()) {
6258 case 32:
6259 return AtomicExpansionKind::None;
6260 case 8:
6261 case 16:
6262 case 64:
6263 return AtomicExpansionKind::CmpXChg;
6264 default:
6265 llvm_unreachable("unsupported width encountered");
6266 }
6267 }
6268
6269 return AtomicExpansionKind::CmpXChg;
6270 }
6271
shouldInsertFencesForAtomic(const Instruction * I) const6272 bool NVPTXTargetLowering::shouldInsertFencesForAtomic(
6273 const Instruction *I) const {
6274 auto *CI = dyn_cast<AtomicCmpXchgInst>(I);
6275 // When CAS bitwidth is not supported on the hardware, the CAS is emulated
6276 // using a retry loop that uses a higher-bitwidth monotonic CAS. We enforce
6277 // the memory order using explicit fences around the retry loop.
6278 // The memory order of natively supported CAS operations can be enforced
6279 // by lowering to an atom.cas with the right memory synchronizing effect.
6280 // However, atom.cas only supports relaxed, acquire, release and acq_rel.
6281 // So we also use explicit fences for enforcing memory order for
6282 // seq_cast CAS with natively-supported bitwidths.
6283 return CI &&
6284 (cast<IntegerType>(CI->getCompareOperand()->getType())->getBitWidth() <
6285 STI.getMinCmpXchgSizeInBits() ||
6286 CI->getMergedOrdering() == AtomicOrdering::SequentiallyConsistent);
6287 }
6288
atomicOperationOrderAfterFenceSplit(const Instruction * I) const6289 AtomicOrdering NVPTXTargetLowering::atomicOperationOrderAfterFenceSplit(
6290 const Instruction *I) const {
6291 auto *CI = dyn_cast<AtomicCmpXchgInst>(I);
6292 bool BitwidthSupportedAndIsSeqCst =
6293 CI && CI->getMergedOrdering() == AtomicOrdering::SequentiallyConsistent &&
6294 cast<IntegerType>(CI->getCompareOperand()->getType())->getBitWidth() >=
6295 STI.getMinCmpXchgSizeInBits();
6296 return BitwidthSupportedAndIsSeqCst ? AtomicOrdering::Acquire
6297 : AtomicOrdering::Monotonic;
6298 }
6299
emitLeadingFence(IRBuilderBase & Builder,Instruction * Inst,AtomicOrdering Ord) const6300 Instruction *NVPTXTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
6301 Instruction *Inst,
6302 AtomicOrdering Ord) const {
6303 if (!isa<AtomicCmpXchgInst>(Inst))
6304 return TargetLoweringBase::emitLeadingFence(Builder, Inst, Ord);
6305
6306 // Specialize for cmpxchg
6307 // Emit a fence.sc leading fence for cmpxchg seq_cst which are not emulated
6308 if (isReleaseOrStronger(Ord))
6309 return Ord == AtomicOrdering::SequentiallyConsistent
6310 ? Builder.CreateFence(AtomicOrdering::SequentiallyConsistent)
6311 : Builder.CreateFence(AtomicOrdering::Release);
6312
6313 return nullptr;
6314 }
6315
emitTrailingFence(IRBuilderBase & Builder,Instruction * Inst,AtomicOrdering Ord) const6316 Instruction *NVPTXTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
6317 Instruction *Inst,
6318 AtomicOrdering Ord) const {
6319 // Specialize for cmpxchg
6320 if (!isa<AtomicCmpXchgInst>(Inst))
6321 return TargetLoweringBase::emitTrailingFence(Builder, Inst, Ord);
6322
6323 auto CASWidth =
6324 cast<IntegerType>(
6325 dyn_cast<AtomicCmpXchgInst>(Inst)->getCompareOperand()->getType())
6326 ->getBitWidth();
6327 // Do not emit a trailing fence for cmpxchg seq_cst which are not emulated
6328 if (isAcquireOrStronger(Ord) &&
6329 (Ord != AtomicOrdering::SequentiallyConsistent ||
6330 CASWidth < STI.getMinCmpXchgSizeInBits()))
6331 return Builder.CreateFence(AtomicOrdering::Acquire);
6332
6333 return nullptr;
6334 }
6335
6336 // Rather than default to SINT when both UINT and SINT are custom, we only
6337 // change the opcode when UINT is not legal and SINT is. UINT is preferred when
6338 // both are custom since unsigned CVT instructions can lead to slightly better
6339 // SASS code with fewer instructions.
getPreferredFPToIntOpcode(unsigned Op,EVT FromVT,EVT ToVT) const6340 unsigned NVPTXTargetLowering::getPreferredFPToIntOpcode(unsigned Op, EVT FromVT,
6341 EVT ToVT) const {
6342 if (isOperationLegal(Op, ToVT))
6343 return Op;
6344 switch (Op) {
6345 case ISD::FP_TO_UINT:
6346 if (isOperationLegal(ISD::FP_TO_SINT, ToVT))
6347 return ISD::FP_TO_SINT;
6348 break;
6349 case ISD::STRICT_FP_TO_UINT:
6350 if (isOperationLegal(ISD::STRICT_FP_TO_SINT, ToVT))
6351 return ISD::STRICT_FP_TO_SINT;
6352 break;
6353 case ISD::VP_FP_TO_UINT:
6354 if (isOperationLegal(ISD::VP_FP_TO_SINT, ToVT))
6355 return ISD::VP_FP_TO_SINT;
6356 break;
6357 default:
6358 break;
6359 }
6360 return Op;
6361 }
6362
6363 // Pin NVPTXTargetObjectFile's vtables to this file.
6364 NVPTXTargetObjectFile::~NVPTXTargetObjectFile() = default;
6365
SelectSectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const6366 MCSection *NVPTXTargetObjectFile::SelectSectionForGlobal(
6367 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
6368 return getDataSection();
6369 }
6370
computeKnownBitsForPRMT(const SDValue Op,KnownBits & Known,const SelectionDAG & DAG,unsigned Depth)6371 static void computeKnownBitsForPRMT(const SDValue Op, KnownBits &Known,
6372 const SelectionDAG &DAG, unsigned Depth) {
6373 SDValue A = Op.getOperand(0);
6374 SDValue B = Op.getOperand(1);
6375 ConstantSDNode *Selector = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6376 unsigned Mode = Op.getConstantOperandVal(3);
6377
6378 if (Mode != NVPTX::PTXPrmtMode::NONE || !Selector)
6379 return;
6380
6381 KnownBits AKnown = DAG.computeKnownBits(A, Depth);
6382 KnownBits BKnown = DAG.computeKnownBits(B, Depth);
6383
6384 // {b, a} = {{b7, b6, b5, b4}, {b3, b2, b1, b0}}
6385 KnownBits BitField = BKnown.concat(AKnown);
6386
6387 APInt SelectorVal = Selector->getAPIntValue();
6388 for (unsigned I : llvm::seq(std::min(4U, Known.getBitWidth() / 8))) {
6389 APInt Sel = SelectorVal.extractBits(4, I * 4);
6390 unsigned Idx = Sel.getLoBits(3).getZExtValue();
6391 unsigned Sign = Sel.getHiBits(1).getZExtValue();
6392 KnownBits Byte = BitField.extractBits(8, Idx * 8);
6393 if (Sign)
6394 Byte = KnownBits::ashr(Byte, 8);
6395 Known.insertBits(Byte, I * 8);
6396 }
6397 }
6398
computeKnownBitsForTargetNode(const SDValue Op,KnownBits & Known,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const6399 void NVPTXTargetLowering::computeKnownBitsForTargetNode(
6400 const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
6401 const SelectionDAG &DAG, unsigned Depth) const {
6402 Known.resetAll();
6403
6404 switch (Op.getOpcode()) {
6405 case NVPTXISD::PRMT:
6406 computeKnownBitsForPRMT(Op, Known, DAG, Depth);
6407 break;
6408 default:
6409 break;
6410 }
6411 }
6412