LLVM 22.0.0git
AMDGPULegalizerInfo.cpp
Go to the documentation of this file.
1//===- AMDGPULegalizerInfo.cpp -----------------------------------*- C++ -*-==//
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/// \file
9/// This file implements the targeting of the Machinelegalizer class for
10/// AMDGPU.
11/// \todo This should be generated by TableGen.
12//===----------------------------------------------------------------------===//
13
14#include "AMDGPULegalizerInfo.h"
15
16#include "AMDGPU.h"
18#include "AMDGPUInstrInfo.h"
19#include "AMDGPUMemoryUtils.h"
20#include "AMDGPUTargetMachine.h"
22#include "SIInstrInfo.h"
24#include "SIRegisterInfo.h"
26#include "llvm/ADT/ScopeExit.h"
36#include "llvm/IR/IntrinsicsAMDGPU.h"
37#include "llvm/IR/IntrinsicsR600.h"
38
39#define DEBUG_TYPE "amdgpu-legalinfo"
40
41using namespace llvm;
42using namespace LegalizeActions;
43using namespace LegalizeMutations;
44using namespace LegalityPredicates;
45using namespace MIPatternMatch;
46
47// Hack until load/store selection patterns support any tuple of legal types.
49 "amdgpu-global-isel-new-legality",
50 cl::desc("Use GlobalISel desired legality, rather than try to use"
51 "rules compatible with selection patterns"),
52 cl::init(false),
54
55static constexpr unsigned MaxRegisterSize = 1024;
56
57// Round the number of elements to the next power of two elements
59 unsigned NElts = Ty.getNumElements();
60 unsigned Pow2NElts = 1 << Log2_32_Ceil(NElts);
61 return Ty.changeElementCount(ElementCount::getFixed(Pow2NElts));
62}
63
64// Round the number of bits to the next power of two bits
66 unsigned Bits = Ty.getSizeInBits();
67 unsigned Pow2Bits = 1 << Log2_32_Ceil(Bits);
68 return LLT::scalar(Pow2Bits);
69}
70
71/// \returns true if this is an odd sized vector which should widen by adding an
72/// additional element. This is mostly to handle <3 x s16> -> <4 x s16>. This
73/// excludes s1 vectors, which should always be scalarized.
74static LegalityPredicate isSmallOddVector(unsigned TypeIdx) {
75 return [=](const LegalityQuery &Query) {
76 const LLT Ty = Query.Types[TypeIdx];
77 if (!Ty.isVector())
78 return false;
79
80 const LLT EltTy = Ty.getElementType();
81 const unsigned EltSize = EltTy.getSizeInBits();
82 return Ty.getNumElements() % 2 != 0 &&
83 EltSize > 1 && EltSize < 32 &&
84 Ty.getSizeInBits() % 32 != 0;
85 };
86}
87
88static LegalityPredicate sizeIsMultipleOf32(unsigned TypeIdx) {
89 return [=](const LegalityQuery &Query) {
90 const LLT Ty = Query.Types[TypeIdx];
91 return Ty.getSizeInBits() % 32 == 0;
92 };
93}
94
95static LegalityPredicate isWideVec16(unsigned TypeIdx) {
96 return [=](const LegalityQuery &Query) {
97 const LLT Ty = Query.Types[TypeIdx];
98 const LLT EltTy = Ty.getScalarType();
99 return EltTy.getSizeInBits() == 16 && Ty.getNumElements() > 2;
100 };
101}
102
103static LegalizeMutation oneMoreElement(unsigned TypeIdx) {
104 return [=](const LegalityQuery &Query) {
105 const LLT Ty = Query.Types[TypeIdx];
106 const LLT EltTy = Ty.getElementType();
107 return std::pair(TypeIdx,
108 LLT::fixed_vector(Ty.getNumElements() + 1, EltTy));
109 };
110}
111
113 return [=](const LegalityQuery &Query) {
114 const LLT Ty = Query.Types[TypeIdx];
115 const LLT EltTy = Ty.getElementType();
116 unsigned Size = Ty.getSizeInBits();
117 unsigned Pieces = (Size + 63) / 64;
118 unsigned NewNumElts = (Ty.getNumElements() + 1) / Pieces;
119 return std::pair(TypeIdx, LLT::scalarOrVector(
120 ElementCount::getFixed(NewNumElts), EltTy));
121 };
122}
123
124// Increase the number of vector elements to reach the next multiple of 32-bit
125// type.
126static LegalizeMutation moreEltsToNext32Bit(unsigned TypeIdx) {
127 return [=](const LegalityQuery &Query) {
128 const LLT Ty = Query.Types[TypeIdx];
129
130 const LLT EltTy = Ty.getElementType();
131 const int Size = Ty.getSizeInBits();
132 const int EltSize = EltTy.getSizeInBits();
133 const int NextMul32 = (Size + 31) / 32;
134
135 assert(EltSize < 32);
136
137 const int NewNumElts = (32 * NextMul32 + EltSize - 1) / EltSize;
138 return std::pair(TypeIdx, LLT::fixed_vector(NewNumElts, EltTy));
139 };
140}
141
142// Retrieves the scalar type that's the same size as the mem desc
144 return [=](const LegalityQuery &Query) {
145 unsigned MemSize = Query.MMODescrs[0].MemoryTy.getSizeInBits();
146 return std::make_pair(TypeIdx, LLT::scalar(MemSize));
147 };
148}
149
150// Increase the number of vector elements to reach the next legal RegClass.
152 return [=](const LegalityQuery &Query) {
153 const LLT Ty = Query.Types[TypeIdx];
154 const unsigned NumElts = Ty.getNumElements();
155 const unsigned EltSize = Ty.getElementType().getSizeInBits();
156 const unsigned MaxNumElts = MaxRegisterSize / EltSize;
157
158 assert(EltSize == 32 || EltSize == 64);
159 assert(Ty.getSizeInBits() < MaxRegisterSize);
160
161 unsigned NewNumElts;
162 // Find the nearest legal RegClass that is larger than the current type.
163 for (NewNumElts = NumElts; NewNumElts < MaxNumElts; ++NewNumElts) {
164 if (SIRegisterInfo::getSGPRClassForBitWidth(NewNumElts * EltSize))
165 break;
166 }
167 return std::pair(TypeIdx,
168 LLT::fixed_vector(NewNumElts, Ty.getElementType()));
169 };
170}
171
173 if (!Ty.isVector())
174 return LLT::scalar(128);
175 const ElementCount NumElems = Ty.getElementCount();
176 return LLT::vector(NumElems, LLT::scalar(128));
177}
178
180 if (!Ty.isVector())
181 return LLT::fixed_vector(4, LLT::scalar(32));
182 const unsigned NumElems = Ty.getElementCount().getFixedValue();
183 return LLT::fixed_vector(NumElems * 4, LLT::scalar(32));
184}
185
187 const unsigned Size = Ty.getSizeInBits();
188
189 if (Size <= 32) {
190 // <2 x s8> -> s16
191 // <4 x s8> -> s32
192 return LLT::scalar(Size);
193 }
194
196}
197
198static LegalizeMutation bitcastToRegisterType(unsigned TypeIdx) {
199 return [=](const LegalityQuery &Query) {
200 const LLT Ty = Query.Types[TypeIdx];
201 return std::pair(TypeIdx, getBitcastRegisterType(Ty));
202 };
203}
204
206 return [=](const LegalityQuery &Query) {
207 const LLT Ty = Query.Types[TypeIdx];
208 unsigned Size = Ty.getSizeInBits();
209 assert(Size % 32 == 0);
210 return std::pair(
212 };
213}
214
215static LegalityPredicate vectorSmallerThan(unsigned TypeIdx, unsigned Size) {
216 return [=](const LegalityQuery &Query) {
217 const LLT QueryTy = Query.Types[TypeIdx];
218 return QueryTy.isVector() && QueryTy.getSizeInBits() < Size;
219 };
220}
221
222static LegalityPredicate vectorWiderThan(unsigned TypeIdx, unsigned Size) {
223 return [=](const LegalityQuery &Query) {
224 const LLT QueryTy = Query.Types[TypeIdx];
225 return QueryTy.isVector() && QueryTy.getSizeInBits() > Size;
226 };
227}
228
229static LegalityPredicate numElementsNotEven(unsigned TypeIdx) {
230 return [=](const LegalityQuery &Query) {
231 const LLT QueryTy = Query.Types[TypeIdx];
232 return QueryTy.isVector() && QueryTy.getNumElements() % 2 != 0;
233 };
234}
235
236static bool isRegisterSize(const GCNSubtarget &ST, unsigned Size) {
237 return ((ST.useRealTrue16Insts() && Size == 16) || Size % 32 == 0) &&
239}
240
242 const int EltSize = EltTy.getSizeInBits();
243 return EltSize == 16 || EltSize % 32 == 0;
244}
245
246static bool isRegisterVectorType(LLT Ty) {
247 const int EltSize = Ty.getElementType().getSizeInBits();
248 return EltSize == 32 || EltSize == 64 ||
249 (EltSize == 16 && Ty.getNumElements() % 2 == 0) ||
250 EltSize == 128 || EltSize == 256;
251}
252
253// TODO: replace all uses of isRegisterType with isRegisterClassType
254static bool isRegisterType(const GCNSubtarget &ST, LLT Ty) {
255 if (!isRegisterSize(ST, Ty.getSizeInBits()))
256 return false;
257
258 if (Ty.isVector())
259 return isRegisterVectorType(Ty);
260
261 return true;
262}
263
264// Any combination of 32 or 64-bit elements up the maximum register size, and
265// multiples of v2s16.
267 unsigned TypeIdx) {
268 return [=, &ST](const LegalityQuery &Query) {
269 return isRegisterType(ST, Query.Types[TypeIdx]);
270 };
271}
272
273// RegisterType that doesn't have a corresponding RegClass.
274// TODO: Once `isRegisterType` is replaced with `isRegisterClassType` this
275// should be removed.
277 unsigned TypeIdx) {
278 return [=, &ST](const LegalityQuery &Query) {
279 LLT Ty = Query.Types[TypeIdx];
280 return isRegisterType(ST, Ty) &&
281 !SIRegisterInfo::getSGPRClassForBitWidth(Ty.getSizeInBits());
282 };
283}
284
285static LegalityPredicate elementTypeIsLegal(unsigned TypeIdx) {
286 return [=](const LegalityQuery &Query) {
287 const LLT QueryTy = Query.Types[TypeIdx];
288 if (!QueryTy.isVector())
289 return false;
290 const LLT EltTy = QueryTy.getElementType();
291 return EltTy == LLT::scalar(16) || EltTy.getSizeInBits() >= 32;
292 };
293}
294
295constexpr LLT S1 = LLT::scalar(1);
296constexpr LLT S8 = LLT::scalar(8);
297constexpr LLT S16 = LLT::scalar(16);
298constexpr LLT S32 = LLT::scalar(32);
299constexpr LLT F32 = LLT::float32();
300constexpr LLT S64 = LLT::scalar(64);
301constexpr LLT F64 = LLT::float64();
302constexpr LLT S96 = LLT::scalar(96);
303constexpr LLT S128 = LLT::scalar(128);
304constexpr LLT S160 = LLT::scalar(160);
305constexpr LLT S192 = LLT::scalar(192);
306constexpr LLT S224 = LLT::scalar(224);
307constexpr LLT S256 = LLT::scalar(256);
308constexpr LLT S512 = LLT::scalar(512);
309constexpr LLT S1024 = LLT::scalar(1024);
311
312constexpr LLT V2S8 = LLT::fixed_vector(2, 8);
313constexpr LLT V2S16 = LLT::fixed_vector(2, 16);
314constexpr LLT V4S16 = LLT::fixed_vector(4, 16);
315constexpr LLT V6S16 = LLT::fixed_vector(6, 16);
316constexpr LLT V8S16 = LLT::fixed_vector(8, 16);
317constexpr LLT V10S16 = LLT::fixed_vector(10, 16);
318constexpr LLT V12S16 = LLT::fixed_vector(12, 16);
319constexpr LLT V16S16 = LLT::fixed_vector(16, 16);
320
322constexpr LLT V2BF16 = V2F16; // FIXME
323
324constexpr LLT V2S32 = LLT::fixed_vector(2, 32);
325constexpr LLT V3S32 = LLT::fixed_vector(3, 32);
326constexpr LLT V4S32 = LLT::fixed_vector(4, 32);
327constexpr LLT V5S32 = LLT::fixed_vector(5, 32);
328constexpr LLT V6S32 = LLT::fixed_vector(6, 32);
329constexpr LLT V7S32 = LLT::fixed_vector(7, 32);
330constexpr LLT V8S32 = LLT::fixed_vector(8, 32);
331constexpr LLT V9S32 = LLT::fixed_vector(9, 32);
332constexpr LLT V10S32 = LLT::fixed_vector(10, 32);
333constexpr LLT V11S32 = LLT::fixed_vector(11, 32);
334constexpr LLT V12S32 = LLT::fixed_vector(12, 32);
335constexpr LLT V16S32 = LLT::fixed_vector(16, 32);
336constexpr LLT V32S32 = LLT::fixed_vector(32, 32);
337
338constexpr LLT V2S64 = LLT::fixed_vector(2, 64);
339constexpr LLT V3S64 = LLT::fixed_vector(3, 64);
340constexpr LLT V4S64 = LLT::fixed_vector(4, 64);
341constexpr LLT V5S64 = LLT::fixed_vector(5, 64);
342constexpr LLT V6S64 = LLT::fixed_vector(6, 64);
343constexpr LLT V7S64 = LLT::fixed_vector(7, 64);
344constexpr LLT V8S64 = LLT::fixed_vector(8, 64);
345constexpr LLT V16S64 = LLT::fixed_vector(16, 64);
346
347constexpr LLT V2S128 = LLT::fixed_vector(2, 128);
348constexpr LLT V4S128 = LLT::fixed_vector(4, 128);
349
350constexpr std::initializer_list<LLT> AllScalarTypes = {
352
353constexpr std::initializer_list<LLT> AllS16Vectors{
355
356constexpr std::initializer_list<LLT> AllS32Vectors = {
359
360constexpr std::initializer_list<LLT> AllS64Vectors = {
362
368
369// Checks whether a type is in the list of legal register types.
370static bool isRegisterClassType(const GCNSubtarget &ST, LLT Ty) {
371 if (Ty.isPointerOrPointerVector())
372 Ty = Ty.changeElementType(LLT::scalar(Ty.getScalarSizeInBits()));
373
376 (ST.useRealTrue16Insts() && Ty == S16) ||
378}
379
381 unsigned TypeIdx) {
382 return [&ST, TypeIdx](const LegalityQuery &Query) {
383 return isRegisterClassType(ST, Query.Types[TypeIdx]);
384 };
385}
386
387// If we have a truncating store or an extending load with a data size larger
388// than 32-bits, we need to reduce to a 32-bit type.
390 return [=](const LegalityQuery &Query) {
391 const LLT Ty = Query.Types[TypeIdx];
392 return !Ty.isVector() && Ty.getSizeInBits() > 32 &&
393 Query.MMODescrs[0].MemoryTy.getSizeInBits() < Ty.getSizeInBits();
394 };
395}
396
397// If we have a truncating store or an extending load with a data size larger
398// than 32-bits and mem location is a power of 2
400 return [=](const LegalityQuery &Query) {
401 unsigned MemSize = Query.MMODescrs[0].MemoryTy.getSizeInBits();
402 return isWideScalarExtLoadTruncStore(TypeIdx)(Query) &&
403 isPowerOf2_64(MemSize);
404 };
405}
406
407// TODO: Should load to s16 be legal? Most loads extend to 32-bits, but we
408// handle some operations by just promoting the register during
409// selection. There are also d16 loads on GFX9+ which preserve the high bits.
410static unsigned maxSizeForAddrSpace(const GCNSubtarget &ST, unsigned AS,
411 bool IsLoad, bool IsAtomic) {
412 switch (AS) {
414 // FIXME: Private element size.
415 return ST.enableFlatScratch() ? 128 : 32;
417 return ST.useDS128() ? 128 : 64;
422 // Treat constant and global as identical. SMRD loads are sometimes usable for
423 // global loads (ideally constant address space should be eliminated)
424 // depending on the context. Legality cannot be context dependent, but
425 // RegBankSelect can split the load as necessary depending on the pointer
426 // register bank/uniformity and if the memory is invariant or not written in a
427 // kernel.
428 return IsLoad ? 512 : 128;
429 default:
430 // FIXME: Flat addresses may contextually need to be split to 32-bit parts
431 // if they may alias scratch depending on the subtarget. This needs to be
432 // moved to custom handling to use addressMayBeAccessedAsPrivate
433 return ST.hasMultiDwordFlatScratchAddressing() || IsAtomic ? 128 : 32;
434 }
435}
436
437static bool isLoadStoreSizeLegal(const GCNSubtarget &ST,
438 const LegalityQuery &Query) {
439 const LLT Ty = Query.Types[0];
440
441 // Handle G_LOAD, G_ZEXTLOAD, G_SEXTLOAD
442 const bool IsLoad = Query.Opcode != AMDGPU::G_STORE;
443
444 unsigned RegSize = Ty.getSizeInBits();
445 uint64_t MemSize = Query.MMODescrs[0].MemoryTy.getSizeInBits();
446 uint64_t AlignBits = Query.MMODescrs[0].AlignInBits;
447 unsigned AS = Query.Types[1].getAddressSpace();
448
449 // All of these need to be custom lowered to cast the pointer operand.
451 return false;
452
453 // Do not handle extending vector loads.
454 if (Ty.isVector() && MemSize != RegSize)
455 return false;
456
457 // TODO: We should be able to widen loads if the alignment is high enough, but
458 // we also need to modify the memory access size.
459#if 0
460 // Accept widening loads based on alignment.
461 if (IsLoad && MemSize < Size)
462 MemSize = std::max(MemSize, Align);
463#endif
464
465 // Only 1-byte and 2-byte to 32-bit extloads are valid.
466 if (MemSize != RegSize && RegSize != 32)
467 return false;
468
469 if (MemSize > maxSizeForAddrSpace(ST, AS, IsLoad,
470 Query.MMODescrs[0].Ordering !=
472 return false;
473
474 switch (MemSize) {
475 case 8:
476 case 16:
477 case 32:
478 case 64:
479 case 128:
480 break;
481 case 96:
482 if (!ST.hasDwordx3LoadStores())
483 return false;
484 break;
485 case 256:
486 case 512:
487 // These may contextually need to be broken down.
488 break;
489 default:
490 return false;
491 }
492
493 assert(RegSize >= MemSize);
494
495 if (AlignBits < MemSize) {
496 const SITargetLowering *TLI = ST.getTargetLowering();
497 if (!TLI->allowsMisalignedMemoryAccessesImpl(MemSize, AS,
498 Align(AlignBits / 8)))
499 return false;
500 }
501
502 return true;
503}
504
505// The newer buffer intrinsic forms take their resource arguments as
506// pointers in address space 8, aka s128 values. However, in order to not break
507// SelectionDAG, the underlying operations have to continue to take v4i32
508// arguments. Therefore, we convert resource pointers - or vectors of them
509// to integer values here.
510static bool hasBufferRsrcWorkaround(const LLT Ty) {
511 if (Ty.isPointer() && Ty.getAddressSpace() == AMDGPUAS::BUFFER_RESOURCE)
512 return true;
513 if (Ty.isVector()) {
514 const LLT ElemTy = Ty.getElementType();
515 return hasBufferRsrcWorkaround(ElemTy);
516 }
517 return false;
518}
519
520// The current selector can't handle <6 x s16>, <8 x s16>, s96, s128 etc, so
521// workaround this. Eventually it should ignore the type for loads and only care
522// about the size. Return true in cases where we will workaround this for now by
523// bitcasting.
524static bool loadStoreBitcastWorkaround(const LLT Ty) {
526 return false;
527
528 const unsigned Size = Ty.getSizeInBits();
529 if (Ty.isPointerVector())
530 return true;
531 if (Size <= 64)
532 return false;
533 // Address space 8 pointers get their own workaround.
535 return false;
536 if (!Ty.isVector())
537 return true;
538
539 unsigned EltSize = Ty.getScalarSizeInBits();
540 return EltSize != 32 && EltSize != 64;
541}
542
543static bool isLoadStoreLegal(const GCNSubtarget &ST, const LegalityQuery &Query) {
544 const LLT Ty = Query.Types[0];
545 return isRegisterType(ST, Ty) && isLoadStoreSizeLegal(ST, Query) &&
547}
548
549/// Return true if a load or store of the type should be lowered with a bitcast
550/// to a different type.
551static bool shouldBitcastLoadStoreType(const GCNSubtarget &ST, const LLT Ty,
552 const LLT MemTy) {
553 const unsigned MemSizeInBits = MemTy.getSizeInBits();
554 const unsigned Size = Ty.getSizeInBits();
555 if (Size != MemSizeInBits)
556 return Size <= 32 && Ty.isVector();
557
559 return true;
560
561 // Don't try to handle bitcasting vector ext loads for now.
562 return Ty.isVector() && (!MemTy.isVector() || MemTy == Ty) &&
563 (Size <= 32 || isRegisterSize(ST, Size)) &&
564 !isRegisterVectorElementType(Ty.getElementType());
565}
566
567/// Return true if we should legalize a load by widening an odd sized memory
568/// access up to the alignment. Note this case when the memory access itself
569/// changes, not the size of the result register.
570static bool shouldWidenLoad(const GCNSubtarget &ST, LLT MemoryTy,
571 uint64_t AlignInBits, unsigned AddrSpace,
572 unsigned Opcode) {
573 unsigned SizeInBits = MemoryTy.getSizeInBits();
574 // We don't want to widen cases that are naturally legal.
575 if (isPowerOf2_32(SizeInBits))
576 return false;
577
578 // If we have 96-bit memory operations, we shouldn't touch them. Note we may
579 // end up widening these for a scalar load during RegBankSelect, if we don't
580 // have 96-bit scalar loads.
581 if (SizeInBits == 96 && ST.hasDwordx3LoadStores())
582 return false;
583
584 if (SizeInBits >= maxSizeForAddrSpace(ST, AddrSpace, Opcode, false))
585 return false;
586
587 // A load is known dereferenceable up to the alignment, so it's legal to widen
588 // to it.
589 //
590 // TODO: Could check dereferenceable for less aligned cases.
591 unsigned RoundedSize = NextPowerOf2(SizeInBits);
592 if (AlignInBits < RoundedSize)
593 return false;
594
595 // Do not widen if it would introduce a slow unaligned load.
596 const SITargetLowering *TLI = ST.getTargetLowering();
597 unsigned Fast = 0;
599 RoundedSize, AddrSpace, Align(AlignInBits / 8),
601 Fast;
602}
603
604static bool shouldWidenLoad(const GCNSubtarget &ST, const LegalityQuery &Query,
605 unsigned Opcode) {
606 if (Query.MMODescrs[0].Ordering != AtomicOrdering::NotAtomic)
607 return false;
608
609 return shouldWidenLoad(ST, Query.MMODescrs[0].MemoryTy,
610 Query.MMODescrs[0].AlignInBits,
611 Query.Types[1].getAddressSpace(), Opcode);
612}
613
614/// Mutates IR (typicaly a load instruction) to use a <4 x s32> as the initial
615/// type of the operand `idx` and then to transform it to a `p8` via bitcasts
616/// and inttoptr. In addition, handle vectors of p8. Returns the new type.
618 MachineRegisterInfo &MRI, unsigned Idx) {
619 MachineOperand &MO = MI.getOperand(Idx);
620
621 const LLT PointerTy = MRI.getType(MO.getReg());
622
623 // Paranoidly prevent us from doing this multiple times.
625 return PointerTy;
626
627 const LLT ScalarTy = getBufferRsrcScalarType(PointerTy);
628 const LLT VectorTy = getBufferRsrcRegisterType(PointerTy);
629 if (!PointerTy.isVector()) {
630 // Happy path: (4 x s32) -> (s32, s32, s32, s32) -> (p8)
631 const unsigned NumParts = PointerTy.getSizeInBits() / 32;
632 const LLT S32 = LLT::scalar(32);
633
634 Register VectorReg = MRI.createGenericVirtualRegister(VectorTy);
635 std::array<Register, 4> VectorElems;
636 B.setInsertPt(B.getMBB(), ++B.getInsertPt());
637 for (unsigned I = 0; I < NumParts; ++I)
638 VectorElems[I] =
639 B.buildExtractVectorElementConstant(S32, VectorReg, I).getReg(0);
640 B.buildMergeValues(MO, VectorElems);
641 MO.setReg(VectorReg);
642 return VectorTy;
643 }
644 Register BitcastReg = MRI.createGenericVirtualRegister(VectorTy);
645 B.setInsertPt(B.getMBB(), ++B.getInsertPt());
646 auto Scalar = B.buildBitcast(ScalarTy, BitcastReg);
647 B.buildIntToPtr(MO, Scalar);
648 MO.setReg(BitcastReg);
649
650 return VectorTy;
651}
652
653/// Cast a buffer resource (an address space 8 pointer) into a 4xi32, which is
654/// the form in which the value must be in order to be passed to the low-level
655/// representations used for MUBUF/MTBUF intrinsics. This is a hack, which is
656/// needed in order to account for the fact that we can't define a register
657/// class for s128 without breaking SelectionDAG.
659 MachineRegisterInfo &MRI = *B.getMRI();
660 const LLT PointerTy = MRI.getType(Pointer);
661 const LLT ScalarTy = getBufferRsrcScalarType(PointerTy);
662 const LLT VectorTy = getBufferRsrcRegisterType(PointerTy);
663
664 if (!PointerTy.isVector()) {
665 // Special case: p8 -> (s32, s32, s32, s32) -> (4xs32)
666 SmallVector<Register, 4> PointerParts;
667 const unsigned NumParts = PointerTy.getSizeInBits() / 32;
668 auto Unmerged = B.buildUnmerge(LLT::scalar(32), Pointer);
669 for (unsigned I = 0; I < NumParts; ++I)
670 PointerParts.push_back(Unmerged.getReg(I));
671 return B.buildBuildVector(VectorTy, PointerParts).getReg(0);
672 }
673 Register Scalar = B.buildPtrToInt(ScalarTy, Pointer).getReg(0);
674 return B.buildBitcast(VectorTy, Scalar).getReg(0);
675}
676
678 unsigned Idx) {
679 MachineOperand &MO = MI.getOperand(Idx);
680
681 const LLT PointerTy = B.getMRI()->getType(MO.getReg());
682 // Paranoidly prevent us from doing this multiple times.
684 return;
686}
687
689 const GCNTargetMachine &TM)
690 : ST(ST_) {
691 using namespace TargetOpcode;
692
693 auto GetAddrSpacePtr = [&TM](unsigned AS) {
694 return LLT::pointer(AS, TM.getPointerSizeInBits(AS));
695 };
696
697 const LLT GlobalPtr = GetAddrSpacePtr(AMDGPUAS::GLOBAL_ADDRESS);
698 const LLT ConstantPtr = GetAddrSpacePtr(AMDGPUAS::CONSTANT_ADDRESS);
699 const LLT Constant32Ptr = GetAddrSpacePtr(AMDGPUAS::CONSTANT_ADDRESS_32BIT);
700 const LLT LocalPtr = GetAddrSpacePtr(AMDGPUAS::LOCAL_ADDRESS);
701 const LLT RegionPtr = GetAddrSpacePtr(AMDGPUAS::REGION_ADDRESS);
702 const LLT FlatPtr = GetAddrSpacePtr(AMDGPUAS::FLAT_ADDRESS);
703 const LLT PrivatePtr = GetAddrSpacePtr(AMDGPUAS::PRIVATE_ADDRESS);
704 const LLT BufferFatPtr = GetAddrSpacePtr(AMDGPUAS::BUFFER_FAT_POINTER);
705 const LLT RsrcPtr = GetAddrSpacePtr(AMDGPUAS::BUFFER_RESOURCE);
706 const LLT BufferStridedPtr =
707 GetAddrSpacePtr(AMDGPUAS::BUFFER_STRIDED_POINTER);
708
709 const LLT CodePtr = FlatPtr;
710
711 const std::initializer_list<LLT> AddrSpaces64 = {
712 GlobalPtr, ConstantPtr, FlatPtr
713 };
714
715 const std::initializer_list<LLT> AddrSpaces32 = {
716 LocalPtr, PrivatePtr, Constant32Ptr, RegionPtr
717 };
718
719 const std::initializer_list<LLT> AddrSpaces128 = {RsrcPtr};
720
721 const std::initializer_list<LLT> FPTypesBase = {
722 S32, S64
723 };
724
725 const std::initializer_list<LLT> FPTypes16 = {
726 S32, S64, S16
727 };
728
729 const std::initializer_list<LLT> FPTypesPK16 = {
730 S32, S64, S16, V2S16
731 };
732
733 const LLT MinScalarFPTy = ST.has16BitInsts() ? S16 : S32;
734
735 // s1 for VCC branches, s32 for SCC branches.
737
738 // TODO: All multiples of 32, vectors of pointers, all v2s16 pairs, more
739 // elements for v3s16
742 .legalFor(AllS32Vectors)
744 .legalFor(AddrSpaces64)
745 .legalFor(AddrSpaces32)
746 .legalFor(AddrSpaces128)
747 .legalIf(isPointer(0))
748 .clampScalar(0, S16, S256)
750 .clampMaxNumElements(0, S32, 16)
752 .scalarize(0);
753
754 if (ST.hasVOP3PInsts() && ST.hasAddNoCarry() && ST.hasIntClamp()) {
755 // Full set of gfx9 features.
756 if (ST.hasScalarAddSub64()) {
757 getActionDefinitionsBuilder({G_ADD, G_SUB})
758 .legalFor({S64, S32, S16, V2S16})
759 .clampMaxNumElementsStrict(0, S16, 2)
760 .scalarize(0)
761 .minScalar(0, S16)
763 .maxScalar(0, S32);
764 } else {
765 getActionDefinitionsBuilder({G_ADD, G_SUB})
766 .legalFor({S32, S16, V2S16})
767 .clampMaxNumElementsStrict(0, S16, 2)
768 .scalarize(0)
769 .minScalar(0, S16)
771 .maxScalar(0, S32);
772 }
773
774 if (ST.hasScalarSMulU64()) {
776 .legalFor({S64, S32, S16, V2S16})
777 .clampMaxNumElementsStrict(0, S16, 2)
778 .scalarize(0)
779 .minScalar(0, S16)
781 .custom();
782 } else {
784 .legalFor({S32, S16, V2S16})
785 .clampMaxNumElementsStrict(0, S16, 2)
786 .scalarize(0)
787 .minScalar(0, S16)
789 .custom();
790 }
791 assert(ST.hasMad64_32());
792
793 getActionDefinitionsBuilder({G_UADDSAT, G_USUBSAT, G_SADDSAT, G_SSUBSAT})
794 .legalFor({S32, S16, V2S16}) // Clamp modifier
795 .minScalarOrElt(0, S16)
797 .scalarize(0)
799 .lower();
800 } else if (ST.has16BitInsts()) {
801 getActionDefinitionsBuilder({G_ADD, G_SUB})
802 .legalFor({S32, S16})
803 .minScalar(0, S16)
805 .maxScalar(0, S32)
806 .scalarize(0);
807
809 .legalFor({S32, S16})
810 .scalarize(0)
811 .minScalar(0, S16)
813 .custom();
814 assert(ST.hasMad64_32());
815
816 // Technically the saturating operations require clamp bit support, but this
817 // was introduced at the same time as 16-bit operations.
818 getActionDefinitionsBuilder({G_UADDSAT, G_USUBSAT})
819 .legalFor({S32, S16}) // Clamp modifier
820 .minScalar(0, S16)
821 .scalarize(0)
823 .lower();
824
825 // We're just lowering this, but it helps get a better result to try to
826 // coerce to the desired type first.
827 getActionDefinitionsBuilder({G_SADDSAT, G_SSUBSAT})
828 .minScalar(0, S16)
829 .scalarize(0)
830 .lower();
831 } else {
832 getActionDefinitionsBuilder({G_ADD, G_SUB})
833 .legalFor({S32})
834 .widenScalarToNextMultipleOf(0, 32)
835 .clampScalar(0, S32, S32)
836 .scalarize(0);
837
838 auto &Mul = getActionDefinitionsBuilder(G_MUL)
839 .legalFor({S32})
840 .scalarize(0)
841 .minScalar(0, S32)
843
844 if (ST.hasMad64_32())
845 Mul.custom();
846 else
847 Mul.maxScalar(0, S32);
848
849 if (ST.hasIntClamp()) {
850 getActionDefinitionsBuilder({G_UADDSAT, G_USUBSAT})
851 .legalFor({S32}) // Clamp modifier.
852 .scalarize(0)
854 .lower();
855 } else {
856 // Clamp bit support was added in VI, along with 16-bit operations.
857 getActionDefinitionsBuilder({G_UADDSAT, G_USUBSAT})
858 .minScalar(0, S32)
859 .scalarize(0)
860 .lower();
861 }
862
863 // FIXME: DAG expansion gets better results. The widening uses the smaller
864 // range values and goes for the min/max lowering directly.
865 getActionDefinitionsBuilder({G_SADDSAT, G_SSUBSAT})
866 .minScalar(0, S32)
867 .scalarize(0)
868 .lower();
869 }
870
872 {G_SDIV, G_UDIV, G_SREM, G_UREM, G_SDIVREM, G_UDIVREM})
873 .customFor({S32, S64})
874 .clampScalar(0, S32, S64)
876 .scalarize(0);
877
878 auto &Mulh = getActionDefinitionsBuilder({G_UMULH, G_SMULH})
879 .legalFor({S32})
880 .maxScalar(0, S32);
881
882 if (ST.hasVOP3PInsts()) {
883 Mulh
884 .clampMaxNumElements(0, S8, 2)
885 .lowerFor({V2S8});
886 }
887
888 Mulh
889 .scalarize(0)
890 .lower();
891
892 // Report legal for any types we can handle anywhere. For the cases only legal
893 // on the SALU, RegBankSelect will be able to re-legalize.
894 getActionDefinitionsBuilder({G_AND, G_OR, G_XOR})
895 .legalFor({S32, S1, S64, V2S32, S16, V2S16, V4S16})
896 .clampScalar(0, S32, S64)
902 .scalarize(0);
903
905 {G_UADDO, G_USUBO, G_UADDE, G_SADDE, G_USUBE, G_SSUBE})
906 .legalFor({{S32, S1}, {S32, S32}})
907 .clampScalar(0, S32, S32)
908 .scalarize(0);
909
911 // Don't worry about the size constraint.
913 .lower();
914
916 .legalFor({S1, S32, S64, S16, GlobalPtr,
917 LocalPtr, ConstantPtr, PrivatePtr, FlatPtr })
918 .legalIf(isPointer(0))
919 .clampScalar(0, S32, S64)
921
922 getActionDefinitionsBuilder(G_FCONSTANT)
923 .legalFor({S32, S64, S16})
924 .clampScalar(0, S16, S64);
925
926 getActionDefinitionsBuilder({G_IMPLICIT_DEF, G_FREEZE})
927 .legalIf(isRegisterClassType(ST, 0))
928 // s1 and s16 are special cases because they have legal operations on
929 // them, but don't really occupy registers in the normal way.
930 .legalFor({S1, S16})
931 .clampNumElements(0, V16S32, V32S32)
935 .clampMaxNumElements(0, S32, 16);
936
937 getActionDefinitionsBuilder(G_FRAME_INDEX).legalFor({PrivatePtr});
938
939 // If the amount is divergent, we have to do a wave reduction to get the
940 // maximum value, so this is expanded during RegBankSelect.
941 getActionDefinitionsBuilder(G_DYN_STACKALLOC)
942 .legalFor({{PrivatePtr, S32}});
943
944 getActionDefinitionsBuilder(G_STACKSAVE)
945 .customFor({PrivatePtr});
946 getActionDefinitionsBuilder(G_STACKRESTORE)
947 .legalFor({PrivatePtr});
948
949 getActionDefinitionsBuilder({G_GET_FPENV, G_SET_FPENV}).customFor({S64});
950
951 getActionDefinitionsBuilder(G_GLOBAL_VALUE)
952 .customIf(typeIsNot(0, PrivatePtr));
953
954 getActionDefinitionsBuilder(G_BLOCK_ADDR).legalFor({CodePtr});
955
956 auto &FPOpActions = getActionDefinitionsBuilder(
957 { G_FADD, G_FMUL, G_FMA, G_FCANONICALIZE,
958 G_STRICT_FADD, G_STRICT_FMUL, G_STRICT_FMA})
959 .legalFor({S32, S64});
960 auto &TrigActions = getActionDefinitionsBuilder({G_FSIN, G_FCOS})
961 .customFor({S32, S64});
962 auto &FDIVActions = getActionDefinitionsBuilder(G_FDIV)
963 .customFor({S32, S64});
964
965 if (ST.has16BitInsts()) {
966 if (ST.hasVOP3PInsts())
967 FPOpActions.legalFor({S16, V2S16});
968 else
969 FPOpActions.legalFor({S16});
970
971 TrigActions.customFor({S16});
972 FDIVActions.customFor({S16});
973 }
974
975 if (ST.hasPackedFP32Ops()) {
976 FPOpActions.legalFor({V2S32});
977 FPOpActions.clampMaxNumElementsStrict(0, S32, 2);
978 }
979
980 auto &MinNumMaxNumIeee =
981 getActionDefinitionsBuilder({G_FMINNUM_IEEE, G_FMAXNUM_IEEE});
982
983 if (ST.hasVOP3PInsts()) {
984 MinNumMaxNumIeee.legalFor(FPTypesPK16)
985 .moreElementsIf(isSmallOddVector(0), oneMoreElement(0))
986 .clampMaxNumElements(0, S16, 2)
987 .clampScalar(0, S16, S64)
988 .scalarize(0);
989 } else if (ST.has16BitInsts()) {
990 MinNumMaxNumIeee.legalFor(FPTypes16).clampScalar(0, S16, S64).scalarize(0);
991 } else {
992 MinNumMaxNumIeee.legalFor(FPTypesBase)
993 .clampScalar(0, S32, S64)
994 .scalarize(0);
995 }
996
997 auto &MinNumMaxNum = getActionDefinitionsBuilder(
998 {G_FMINNUM, G_FMAXNUM, G_FMINIMUMNUM, G_FMAXIMUMNUM});
999
1000 if (ST.hasVOP3PInsts()) {
1001 MinNumMaxNum.customFor(FPTypesPK16)
1002 .moreElementsIf(isSmallOddVector(0), oneMoreElement(0))
1003 .clampMaxNumElements(0, S16, 2)
1004 .clampScalar(0, S16, S64)
1005 .scalarize(0);
1006 } else if (ST.has16BitInsts()) {
1007 MinNumMaxNum.customFor(FPTypes16)
1008 .clampScalar(0, S16, S64)
1009 .scalarize(0);
1010 } else {
1011 MinNumMaxNum.customFor(FPTypesBase)
1012 .clampScalar(0, S32, S64)
1013 .scalarize(0);
1014 }
1015
1016 if (ST.hasVOP3PInsts())
1017 FPOpActions.clampMaxNumElementsStrict(0, S16, 2);
1018
1019 FPOpActions
1020 .scalarize(0)
1021 .clampScalar(0, ST.has16BitInsts() ? S16 : S32, S64);
1022
1023 TrigActions
1024 .scalarize(0)
1025 .clampScalar(0, ST.has16BitInsts() ? S16 : S32, S64);
1026
1027 FDIVActions
1028 .scalarize(0)
1029 .clampScalar(0, ST.has16BitInsts() ? S16 : S32, S64);
1030
1031 getActionDefinitionsBuilder({G_FNEG, G_FABS})
1032 .legalFor(FPTypesPK16)
1034 .scalarize(0)
1035 .clampScalar(0, S16, S64);
1036
1037 if (ST.has16BitInsts()) {
1039 .legalFor({S16})
1040 .customFor({S32, S64})
1041 .scalarize(0)
1042 .unsupported();
1044 .legalFor({S32, S64, S16})
1045 .scalarize(0)
1046 .clampScalar(0, S16, S64);
1047
1048 getActionDefinitionsBuilder({G_FLDEXP, G_STRICT_FLDEXP})
1049 .legalFor({{S32, S32}, {S64, S32}, {S16, S16}})
1050 .scalarize(0)
1051 .maxScalarIf(typeIs(0, S16), 1, S16)
1052 .clampScalar(1, S32, S32)
1053 .lower();
1054
1056 .customFor({{S32, S32}, {S64, S32}, {S16, S16}, {S16, S32}})
1057 .scalarize(0)
1058 .lower();
1059 } else {
1061 .customFor({S32, S64, S16})
1062 .scalarize(0)
1063 .unsupported();
1064
1065
1066 if (ST.hasFractBug()) {
1068 .customFor({S64})
1069 .legalFor({S32, S64})
1070 .scalarize(0)
1071 .clampScalar(0, S32, S64);
1072 } else {
1074 .legalFor({S32, S64})
1075 .scalarize(0)
1076 .clampScalar(0, S32, S64);
1077 }
1078
1079 getActionDefinitionsBuilder({G_FLDEXP, G_STRICT_FLDEXP})
1080 .legalFor({{S32, S32}, {S64, S32}})
1081 .scalarize(0)
1082 .clampScalar(0, S32, S64)
1083 .clampScalar(1, S32, S32)
1084 .lower();
1085
1087 .customFor({{S32, S32}, {S64, S32}})
1088 .scalarize(0)
1089 .minScalar(0, S32)
1090 .clampScalar(1, S32, S32)
1091 .lower();
1092 }
1093
1094 auto &FPTruncActions = getActionDefinitionsBuilder(G_FPTRUNC);
1095 if (ST.hasCvtPkF16F32Inst()) {
1096 FPTruncActions.legalFor({{S32, S64}, {S16, S32}, {V2S16, V2S32}})
1097 .clampMaxNumElements(0, S16, 2);
1098 } else {
1099 FPTruncActions.legalFor({{S32, S64}, {S16, S32}});
1100 }
1101 FPTruncActions.scalarize(0).lower();
1102
1104 .legalFor({{S64, S32}, {S32, S16}})
1105 .narrowScalarFor({{S64, S16}}, changeTo(0, S32))
1106 .scalarize(0);
1107
1108 auto &FSubActions = getActionDefinitionsBuilder({G_FSUB, G_STRICT_FSUB});
1109 if (ST.has16BitInsts()) {
1110 FSubActions
1111 // Use actual fsub instruction
1112 .legalFor({S32, S16})
1113 // Must use fadd + fneg
1114 .lowerFor({S64, V2S16});
1115 } else {
1116 FSubActions
1117 // Use actual fsub instruction
1118 .legalFor({S32})
1119 // Must use fadd + fneg
1120 .lowerFor({S64, S16, V2S16});
1121 }
1122
1123 FSubActions
1124 .scalarize(0)
1125 .clampScalar(0, S32, S64);
1126
1127 // Whether this is legal depends on the floating point mode for the function.
1128 auto &FMad = getActionDefinitionsBuilder(G_FMAD);
1129 if (ST.hasMadF16() && ST.hasMadMacF32Insts())
1130 FMad.customFor({S32, S16});
1131 else if (ST.hasMadMacF32Insts())
1132 FMad.customFor({S32});
1133 else if (ST.hasMadF16())
1134 FMad.customFor({S16});
1135 FMad.scalarize(0)
1136 .lower();
1137
1138 auto &FRem = getActionDefinitionsBuilder(G_FREM);
1139 if (ST.has16BitInsts()) {
1140 FRem.customFor({S16, S32, S64});
1141 } else {
1142 FRem.minScalar(0, S32)
1143 .customFor({S32, S64});
1144 }
1145 FRem.scalarize(0);
1146
1147 // TODO: Do we need to clamp maximum bitwidth?
1149 .legalIf(isScalar(0))
1150 .legalFor({{V2S16, V2S32}})
1151 .clampMaxNumElements(0, S16, 2)
1152 // Avoid scalarizing in cases that should be truly illegal. In unresolvable
1153 // situations (like an invalid implicit use), we don't want to infinite loop
1154 // in the legalizer.
1156 .alwaysLegal();
1157
1158 getActionDefinitionsBuilder({G_SEXT, G_ZEXT, G_ANYEXT})
1159 .legalFor({{S64, S32}, {S32, S16}, {S64, S16},
1160 {S32, S1}, {S64, S1}, {S16, S1}})
1161 .scalarize(0)
1162 .clampScalar(0, S32, S64)
1163 .widenScalarToNextPow2(1, 32);
1164
1165 // TODO: Split s1->s64 during regbankselect for VALU.
1166 auto &IToFP = getActionDefinitionsBuilder({G_SITOFP, G_UITOFP})
1167 .legalFor({{S32, S32}, {S64, S32}, {S16, S32}})
1168 .lowerIf(typeIs(1, S1))
1169 .customFor({{S32, S64}, {S64, S64}});
1170 if (ST.has16BitInsts())
1171 IToFP.legalFor({{S16, S16}});
1172 IToFP.clampScalar(1, S32, S64)
1173 .minScalar(0, S32)
1174 .scalarize(0)
1176
1177 auto &FPToI = getActionDefinitionsBuilder({G_FPTOSI, G_FPTOUI})
1178 .legalFor({{S32, S32}, {S32, S64}, {S32, S16}})
1179 .customFor({{S64, S32}, {S64, S64}})
1180 .narrowScalarFor({{S64, S16}}, changeTo(0, S32));
1181 if (ST.has16BitInsts())
1182 FPToI.legalFor({{S16, S16}});
1183 else
1184 FPToI.minScalar(1, S32);
1185
1186 FPToI.minScalar(0, S32)
1187 .widenScalarToNextPow2(0, 32)
1188 .scalarize(0)
1189 .lower();
1190
1191 getActionDefinitionsBuilder({G_LROUND, G_LLROUND})
1192 .clampScalar(0, S16, S64)
1193 .scalarize(0)
1194 .lower();
1195
1196 getActionDefinitionsBuilder(G_INTRINSIC_FPTRUNC_ROUND)
1197 .legalFor({S16, S32})
1198 .scalarize(0)
1199 .lower();
1200
1201 // Lower G_FNEARBYINT and G_FRINT into G_INTRINSIC_ROUNDEVEN
1202 getActionDefinitionsBuilder({G_INTRINSIC_ROUND, G_FRINT, G_FNEARBYINT})
1203 .scalarize(0)
1204 .lower();
1205
1206 getActionDefinitionsBuilder({G_INTRINSIC_LRINT, G_INTRINSIC_LLRINT})
1207 .clampScalar(0, S16, S64)
1208 .scalarize(0)
1209 .lower();
1210
1211 if (ST.has16BitInsts()) {
1213 {G_INTRINSIC_TRUNC, G_FCEIL, G_INTRINSIC_ROUNDEVEN})
1214 .legalFor({S16, S32, S64})
1215 .clampScalar(0, S16, S64)
1216 .scalarize(0);
1217 } else if (ST.getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
1219 {G_INTRINSIC_TRUNC, G_FCEIL, G_INTRINSIC_ROUNDEVEN})
1220 .legalFor({S32, S64})
1221 .clampScalar(0, S32, S64)
1222 .scalarize(0);
1223 } else {
1225 {G_INTRINSIC_TRUNC, G_FCEIL, G_INTRINSIC_ROUNDEVEN})
1226 .legalFor({S32})
1227 .customFor({S64})
1228 .clampScalar(0, S32, S64)
1229 .scalarize(0);
1230 }
1231
1233 .unsupportedFor({BufferFatPtr, BufferStridedPtr, RsrcPtr})
1234 .legalIf(all(isPointer(0), sameSize(0, 1)))
1235 .scalarize(0)
1236 .scalarSameSizeAs(1, 0);
1237
1239 .legalIf(all(sameSize(0, 1), typeInSet(1, {S64, S32})))
1240 .scalarSameSizeAs(1, 0)
1241 .scalarize(0);
1242
1243 auto &CmpBuilder =
1245 // The compare output type differs based on the register bank of the output,
1246 // so make both s1 and s32 legal.
1247 //
1248 // Scalar compares producing output in scc will be promoted to s32, as that
1249 // is the allocatable register type that will be needed for the copy from
1250 // scc. This will be promoted during RegBankSelect, and we assume something
1251 // before that won't try to use s32 result types.
1252 //
1253 // Vector compares producing an output in vcc/SGPR will use s1 in VCC reg
1254 // bank.
1256 {S1}, {S32, S64, GlobalPtr, LocalPtr, ConstantPtr, PrivatePtr, FlatPtr})
1257 .legalForCartesianProduct(
1258 {S32}, {S32, S64, GlobalPtr, LocalPtr, ConstantPtr, PrivatePtr, FlatPtr});
1259 if (ST.has16BitInsts()) {
1260 CmpBuilder.legalFor({{S1, S16}});
1261 }
1262
1263 CmpBuilder
1265 .clampScalar(1, S32, S64)
1266 .scalarize(0)
1267 .legalIf(all(typeInSet(0, {S1, S32}), isPointer(1)));
1268
1269 auto &FCmpBuilder =
1271 {S1}, ST.has16BitInsts() ? FPTypes16 : FPTypesBase);
1272
1273 if (ST.hasSALUFloatInsts())
1274 FCmpBuilder.legalForCartesianProduct({S32}, {S16, S32});
1275
1276 FCmpBuilder
1278 .clampScalar(1, S32, S64)
1279 .scalarize(0);
1280
1281 // FIXME: fpow has a selection pattern that should move to custom lowering.
1282 auto &ExpOps = getActionDefinitionsBuilder(G_FPOW);
1283 if (ST.has16BitInsts())
1284 ExpOps.customFor({{S32}, {S16}});
1285 else
1286 ExpOps.customFor({S32});
1287 ExpOps.clampScalar(0, MinScalarFPTy, S32)
1288 .scalarize(0);
1289
1291 .clampScalar(0, MinScalarFPTy, S32)
1292 .lower();
1293
1294 auto &Log2Ops = getActionDefinitionsBuilder({G_FLOG2, G_FEXP2});
1295 Log2Ops.customFor({S32});
1296 if (ST.has16BitInsts())
1297 Log2Ops.legalFor({S16});
1298 else
1299 Log2Ops.customFor({S16});
1300 Log2Ops.scalarize(0)
1301 .lower();
1302
1303 auto &LogOps =
1304 getActionDefinitionsBuilder({G_FLOG, G_FLOG10, G_FEXP, G_FEXP10});
1305 LogOps.customFor({S32, S16});
1306 LogOps.clampScalar(0, MinScalarFPTy, S32)
1307 .scalarize(0);
1308
1309 // The 64-bit versions produce 32-bit results, but only on the SALU.
1311 .legalFor({{S32, S32}, {S32, S64}})
1312 .clampScalar(0, S32, S32)
1313 .widenScalarToNextPow2(1, 32)
1314 .clampScalar(1, S32, S64)
1315 .scalarize(0)
1316 .widenScalarToNextPow2(0, 32);
1317
1318 // If no 16 bit instr is available, lower into different instructions.
1319 if (ST.has16BitInsts())
1320 getActionDefinitionsBuilder(G_IS_FPCLASS)
1321 .legalForCartesianProduct({S1}, FPTypes16)
1322 .widenScalarToNextPow2(1)
1323 .scalarize(0)
1324 .lower();
1325 else
1326 getActionDefinitionsBuilder(G_IS_FPCLASS)
1327 .legalForCartesianProduct({S1}, FPTypesBase)
1328 .lowerFor({S1, S16})
1329 .widenScalarToNextPow2(1)
1330 .scalarize(0)
1331 .lower();
1332
1333 // The hardware instructions return a different result on 0 than the generic
1334 // instructions expect. The hardware produces -1, but these produce the
1335 // bitwidth.
1336 getActionDefinitionsBuilder({G_CTLZ, G_CTTZ})
1337 .scalarize(0)
1338 .clampScalar(0, S32, S32)
1339 .clampScalar(1, S32, S64)
1340 .widenScalarToNextPow2(0, 32)
1341 .widenScalarToNextPow2(1, 32)
1342 .custom();
1343
1344 // The 64-bit versions produce 32-bit results, but only on the SALU.
1345 getActionDefinitionsBuilder(G_CTLZ_ZERO_UNDEF)
1346 .legalFor({{S32, S32}, {S32, S64}})
1347 .customIf(scalarNarrowerThan(1, 32))
1348 .clampScalar(0, S32, S32)
1349 .clampScalar(1, S32, S64)
1350 .scalarize(0)
1351 .widenScalarToNextPow2(0, 32)
1352 .widenScalarToNextPow2(1, 32);
1353
1354 getActionDefinitionsBuilder(G_CTTZ_ZERO_UNDEF)
1355 .legalFor({{S32, S32}, {S32, S64}})
1356 .clampScalar(0, S32, S32)
1357 .clampScalar(1, S32, S64)
1358 .scalarize(0)
1359 .widenScalarToNextPow2(0, 32)
1360 .widenScalarToNextPow2(1, 32);
1361
1362 // S64 is only legal on SALU, and needs to be broken into 32-bit elements in
1363 // RegBankSelect.
1364 getActionDefinitionsBuilder(G_BITREVERSE)
1365 .legalFor({S32, S64})
1366 .clampScalar(0, S32, S64)
1367 .scalarize(0)
1369
1370 if (ST.has16BitInsts()) {
1372 .legalFor({S16, S32, V2S16})
1373 .clampMaxNumElementsStrict(0, S16, 2)
1374 // FIXME: Fixing non-power-of-2 before clamp is workaround for
1375 // narrowScalar limitation.
1377 .clampScalar(0, S16, S32)
1378 .scalarize(0);
1379
1380 if (ST.hasVOP3PInsts()) {
1382 .legalFor({S32, S16, V2S16})
1383 .clampMaxNumElements(0, S16, 2)
1384 .minScalar(0, S16)
1386 .scalarize(0)
1387 .lower();
1388 if (ST.hasIntMinMax64()) {
1389 getActionDefinitionsBuilder({G_SMIN, G_SMAX, G_UMIN, G_UMAX})
1390 .legalFor({S32, S16, S64, V2S16})
1391 .clampMaxNumElements(0, S16, 2)
1392 .minScalar(0, S16)
1394 .scalarize(0)
1395 .lower();
1396 } else {
1397 getActionDefinitionsBuilder({G_SMIN, G_SMAX, G_UMIN, G_UMAX})
1398 .legalFor({S32, S16, V2S16})
1399 .clampMaxNumElements(0, S16, 2)
1400 .minScalar(0, S16)
1402 .scalarize(0)
1403 .lower();
1404 }
1405 } else {
1406 getActionDefinitionsBuilder({G_SMIN, G_SMAX, G_UMIN, G_UMAX, G_ABS})
1407 .legalFor({S32, S16})
1408 .widenScalarToNextPow2(0)
1409 .minScalar(0, S16)
1410 .scalarize(0)
1411 .lower();
1412 }
1413 } else {
1414 // TODO: Should have same legality without v_perm_b32
1416 .legalFor({S32})
1417 .lowerIf(scalarNarrowerThan(0, 32))
1418 // FIXME: Fixing non-power-of-2 before clamp is workaround for
1419 // narrowScalar limitation.
1421 .maxScalar(0, S32)
1422 .scalarize(0)
1423 .lower();
1424
1425 getActionDefinitionsBuilder({G_SMIN, G_SMAX, G_UMIN, G_UMAX, G_ABS})
1426 .legalFor({S32})
1427 .minScalar(0, S32)
1429 .scalarize(0)
1430 .lower();
1431 }
1432
1433 getActionDefinitionsBuilder(G_INTTOPTR)
1434 // List the common cases
1435 .legalForCartesianProduct(AddrSpaces64, {S64})
1436 .legalForCartesianProduct(AddrSpaces32, {S32})
1437 .scalarize(0)
1438 // Accept any address space as long as the size matches
1439 .legalIf(sameSize(0, 1))
1441 [](const LegalityQuery &Query) {
1442 return std::pair(
1443 1, LLT::scalar(Query.Types[0].getSizeInBits()));
1444 })
1445 .narrowScalarIf(largerThan(1, 0), [](const LegalityQuery &Query) {
1446 return std::pair(1, LLT::scalar(Query.Types[0].getSizeInBits()));
1447 });
1448
1449 getActionDefinitionsBuilder(G_PTRTOINT)
1450 // List the common cases
1451 .legalForCartesianProduct(AddrSpaces64, {S64})
1452 .legalForCartesianProduct(AddrSpaces32, {S32})
1453 .scalarize(0)
1454 // Accept any address space as long as the size matches
1455 .legalIf(sameSize(0, 1))
1457 [](const LegalityQuery &Query) {
1458 return std::pair(
1459 0, LLT::scalar(Query.Types[1].getSizeInBits()));
1460 })
1461 .narrowScalarIf(largerThan(0, 1), [](const LegalityQuery &Query) {
1462 return std::pair(0, LLT::scalar(Query.Types[1].getSizeInBits()));
1463 });
1464
1465 getActionDefinitionsBuilder(G_ADDRSPACE_CAST)
1466 .scalarize(0)
1467 .custom();
1468
1469 const auto needToSplitMemOp = [=](const LegalityQuery &Query,
1470 bool IsLoad) -> bool {
1471 const LLT DstTy = Query.Types[0];
1472
1473 // Split vector extloads.
1474 unsigned MemSize = Query.MMODescrs[0].MemoryTy.getSizeInBits();
1475
1476 if (DstTy.isVector() && DstTy.getSizeInBits() > MemSize)
1477 return true;
1478
1479 const LLT PtrTy = Query.Types[1];
1480 unsigned AS = PtrTy.getAddressSpace();
1481 if (MemSize > maxSizeForAddrSpace(ST, AS, IsLoad,
1482 Query.MMODescrs[0].Ordering !=
1484 return true;
1485
1486 // Catch weird sized loads that don't evenly divide into the access sizes
1487 // TODO: May be able to widen depending on alignment etc.
1488 unsigned NumRegs = (MemSize + 31) / 32;
1489 if (NumRegs == 3) {
1490 if (!ST.hasDwordx3LoadStores())
1491 return true;
1492 } else {
1493 // If the alignment allows, these should have been widened.
1494 if (!isPowerOf2_32(NumRegs))
1495 return true;
1496 }
1497
1498 return false;
1499 };
1500
1501 unsigned GlobalAlign32 = ST.hasUnalignedBufferAccessEnabled() ? 0 : 32;
1502 unsigned GlobalAlign16 = ST.hasUnalignedBufferAccessEnabled() ? 0 : 16;
1503 unsigned GlobalAlign8 = ST.hasUnalignedBufferAccessEnabled() ? 0 : 8;
1504
1505 // TODO: Refine based on subtargets which support unaligned access or 128-bit
1506 // LDS
1507 // TODO: Unsupported flat for SI.
1508
1509 for (unsigned Op : {G_LOAD, G_STORE}) {
1510 const bool IsStore = Op == G_STORE;
1511
1512 auto &Actions = getActionDefinitionsBuilder(Op);
1513 // Explicitly list some common cases.
1514 // TODO: Does this help compile time at all?
1515 Actions.legalForTypesWithMemDesc({{S32, GlobalPtr, S32, GlobalAlign32},
1516 {V2S32, GlobalPtr, V2S32, GlobalAlign32},
1517 {V4S32, GlobalPtr, V4S32, GlobalAlign32},
1518 {S64, GlobalPtr, S64, GlobalAlign32},
1519 {V2S64, GlobalPtr, V2S64, GlobalAlign32},
1520 {V2S16, GlobalPtr, V2S16, GlobalAlign32},
1521 {S32, GlobalPtr, S8, GlobalAlign8},
1522 {S32, GlobalPtr, S16, GlobalAlign16},
1523
1524 {S32, LocalPtr, S32, 32},
1525 {S64, LocalPtr, S64, 32},
1526 {V2S32, LocalPtr, V2S32, 32},
1527 {S32, LocalPtr, S8, 8},
1528 {S32, LocalPtr, S16, 16},
1529 {V2S16, LocalPtr, S32, 32},
1530
1531 {S32, PrivatePtr, S32, 32},
1532 {S32, PrivatePtr, S8, 8},
1533 {S32, PrivatePtr, S16, 16},
1534 {V2S16, PrivatePtr, S32, 32},
1535
1536 {S32, ConstantPtr, S32, GlobalAlign32},
1537 {V2S32, ConstantPtr, V2S32, GlobalAlign32},
1538 {V4S32, ConstantPtr, V4S32, GlobalAlign32},
1539 {S64, ConstantPtr, S64, GlobalAlign32},
1540 {V2S32, ConstantPtr, V2S32, GlobalAlign32}});
1541 Actions.legalIf(
1542 [=](const LegalityQuery &Query) -> bool {
1543 return isLoadStoreLegal(ST, Query);
1544 });
1545
1546 // The custom pointers (fat pointers, buffer resources) don't work with load
1547 // and store at this level. Fat pointers should have been lowered to
1548 // intrinsics before the translation to MIR.
1549 Actions.unsupportedIf(
1550 typeInSet(1, {BufferFatPtr, BufferStridedPtr, RsrcPtr}));
1551
1552 // Address space 8 pointers are handled by a 4xs32 load, bitcast, and
1553 // ptrtoint. This is needed to account for the fact that we can't have i128
1554 // as a register class for SelectionDAG reasons.
1555 Actions.customIf([=](const LegalityQuery &Query) -> bool {
1556 return hasBufferRsrcWorkaround(Query.Types[0]);
1557 });
1558
1559 // Constant 32-bit is handled by addrspacecasting the 32-bit pointer to
1560 // 64-bits.
1561 //
1562 // TODO: Should generalize bitcast action into coerce, which will also cover
1563 // inserting addrspacecasts.
1564 Actions.customIf(typeIs(1, Constant32Ptr));
1565
1566 // Turn any illegal element vectors into something easier to deal
1567 // with. These will ultimately produce 32-bit scalar shifts to extract the
1568 // parts anyway.
1569 //
1570 // For odd 16-bit element vectors, prefer to split those into pieces with
1571 // 16-bit vector parts.
1572 Actions.bitcastIf(
1573 [=](const LegalityQuery &Query) -> bool {
1574 return shouldBitcastLoadStoreType(ST, Query.Types[0],
1575 Query.MMODescrs[0].MemoryTy);
1576 }, bitcastToRegisterType(0));
1577
1578 if (!IsStore) {
1579 // Widen suitably aligned loads by loading extra bytes. The standard
1580 // legalization actions can't properly express widening memory operands.
1581 Actions.customIf([=](const LegalityQuery &Query) -> bool {
1582 return shouldWidenLoad(ST, Query, G_LOAD);
1583 });
1584 }
1585
1586 // FIXME: load/store narrowing should be moved to lower action
1587 Actions
1588 .narrowScalarIf(
1589 [=](const LegalityQuery &Query) -> bool {
1590 return !Query.Types[0].isVector() &&
1591 needToSplitMemOp(Query, Op == G_LOAD);
1592 },
1593 [=](const LegalityQuery &Query) -> std::pair<unsigned, LLT> {
1594 const LLT DstTy = Query.Types[0];
1595 const LLT PtrTy = Query.Types[1];
1596
1597 const unsigned DstSize = DstTy.getSizeInBits();
1598 unsigned MemSize = Query.MMODescrs[0].MemoryTy.getSizeInBits();
1599
1600 // Split extloads.
1601 if (DstSize > MemSize)
1602 return std::pair(0, LLT::scalar(MemSize));
1603
1604 unsigned MaxSize = maxSizeForAddrSpace(
1605 ST, PtrTy.getAddressSpace(), Op == G_LOAD,
1606 Query.MMODescrs[0].Ordering != AtomicOrdering::NotAtomic);
1607 if (MemSize > MaxSize)
1608 return std::pair(0, LLT::scalar(MaxSize));
1609
1610 uint64_t Align = Query.MMODescrs[0].AlignInBits;
1611 return std::pair(0, LLT::scalar(Align));
1612 })
1613 .fewerElementsIf(
1614 [=](const LegalityQuery &Query) -> bool {
1615 return Query.Types[0].isVector() &&
1616 needToSplitMemOp(Query, Op == G_LOAD);
1617 },
1618 [=](const LegalityQuery &Query) -> std::pair<unsigned, LLT> {
1619 const LLT DstTy = Query.Types[0];
1620 const LLT PtrTy = Query.Types[1];
1621
1622 LLT EltTy = DstTy.getElementType();
1623 unsigned MaxSize = maxSizeForAddrSpace(
1624 ST, PtrTy.getAddressSpace(), Op == G_LOAD,
1625 Query.MMODescrs[0].Ordering != AtomicOrdering::NotAtomic);
1626
1627 // FIXME: Handle widened to power of 2 results better. This ends
1628 // up scalarizing.
1629 // FIXME: 3 element stores scalarized on SI
1630
1631 // Split if it's too large for the address space.
1632 unsigned MemSize = Query.MMODescrs[0].MemoryTy.getSizeInBits();
1633 if (MemSize > MaxSize) {
1634 unsigned NumElts = DstTy.getNumElements();
1635 unsigned EltSize = EltTy.getSizeInBits();
1636
1637 if (MaxSize % EltSize == 0) {
1638 return std::pair(
1640 ElementCount::getFixed(MaxSize / EltSize), EltTy));
1641 }
1642
1643 unsigned NumPieces = MemSize / MaxSize;
1644
1645 // FIXME: Refine when odd breakdowns handled
1646 // The scalars will need to be re-legalized.
1647 if (NumPieces == 1 || NumPieces >= NumElts ||
1648 NumElts % NumPieces != 0)
1649 return std::pair(0, EltTy);
1650
1651 return std::pair(0,
1652 LLT::fixed_vector(NumElts / NumPieces, EltTy));
1653 }
1654
1655 // FIXME: We could probably handle weird extending loads better.
1656 if (DstTy.getSizeInBits() > MemSize)
1657 return std::pair(0, EltTy);
1658
1659 unsigned EltSize = EltTy.getSizeInBits();
1660 unsigned DstSize = DstTy.getSizeInBits();
1661 if (!isPowerOf2_32(DstSize)) {
1662 // We're probably decomposing an odd sized store. Try to split
1663 // to the widest type. TODO: Account for alignment. As-is it
1664 // should be OK, since the new parts will be further legalized.
1665 unsigned FloorSize = llvm::bit_floor(DstSize);
1666 return std::pair(
1668 ElementCount::getFixed(FloorSize / EltSize), EltTy));
1669 }
1670
1671 // May need relegalization for the scalars.
1672 return std::pair(0, EltTy);
1673 })
1674 .minScalar(0, S32)
1675 .narrowScalarIf(isTruncStoreToSizePowerOf2(0),
1677 .widenScalarToNextPow2(0)
1678 .moreElementsIf(vectorSmallerThan(0, 32), moreEltsToNext32Bit(0))
1679 .lower();
1680 }
1681
1682 // FIXME: Unaligned accesses not lowered.
1683 auto &ExtLoads = getActionDefinitionsBuilder({G_SEXTLOAD, G_ZEXTLOAD})
1684 .legalForTypesWithMemDesc({{S32, GlobalPtr, S8, 8},
1685 {S32, GlobalPtr, S16, 2 * 8},
1686 {S32, LocalPtr, S8, 8},
1687 {S32, LocalPtr, S16, 16},
1688 {S32, PrivatePtr, S8, 8},
1689 {S32, PrivatePtr, S16, 16},
1690 {S32, ConstantPtr, S8, 8},
1691 {S32, ConstantPtr, S16, 2 * 8}})
1692 .legalIf(
1693 [=](const LegalityQuery &Query) -> bool {
1694 return isLoadStoreLegal(ST, Query);
1695 });
1696
1697 if (ST.hasFlatAddressSpace()) {
1698 ExtLoads.legalForTypesWithMemDesc(
1699 {{S32, FlatPtr, S8, 8}, {S32, FlatPtr, S16, 16}});
1700 }
1701
1702 // Constant 32-bit is handled by addrspacecasting the 32-bit pointer to
1703 // 64-bits.
1704 //
1705 // TODO: Should generalize bitcast action into coerce, which will also cover
1706 // inserting addrspacecasts.
1707 ExtLoads.customIf(typeIs(1, Constant32Ptr));
1708
1709 ExtLoads.clampScalar(0, S32, S32)
1711 .lower();
1712
1713 auto &Atomics = getActionDefinitionsBuilder(
1714 {G_ATOMICRMW_XCHG, G_ATOMICRMW_ADD, G_ATOMICRMW_SUB,
1715 G_ATOMICRMW_AND, G_ATOMICRMW_OR, G_ATOMICRMW_XOR,
1716 G_ATOMICRMW_MAX, G_ATOMICRMW_MIN, G_ATOMICRMW_UMAX,
1717 G_ATOMICRMW_UMIN, G_ATOMICRMW_UINC_WRAP, G_ATOMICRMW_UDEC_WRAP})
1718 .legalFor({{S32, GlobalPtr}, {S32, LocalPtr},
1719 {S64, GlobalPtr}, {S64, LocalPtr},
1720 {S32, RegionPtr}, {S64, RegionPtr}});
1721 if (ST.hasFlatAddressSpace()) {
1722 Atomics.legalFor({{S32, FlatPtr}, {S64, FlatPtr}});
1723 }
1724
1725 auto &Atomics32 =
1726 getActionDefinitionsBuilder({G_ATOMICRMW_USUB_COND, G_ATOMICRMW_USUB_SAT})
1727 .legalFor({{S32, GlobalPtr}, {S32, LocalPtr}, {S32, RegionPtr}});
1728 if (ST.hasFlatAddressSpace()) {
1729 Atomics32.legalFor({{S32, FlatPtr}});
1730 }
1731
1732 // TODO: v2bf16 operations, and fat buffer pointer support.
1733 auto &Atomic = getActionDefinitionsBuilder(G_ATOMICRMW_FADD);
1734 if (ST.hasLDSFPAtomicAddF32()) {
1735 Atomic.legalFor({{S32, LocalPtr}, {S32, RegionPtr}});
1736 if (ST.hasLdsAtomicAddF64())
1737 Atomic.legalFor({{S64, LocalPtr}});
1738 if (ST.hasAtomicDsPkAdd16Insts())
1739 Atomic.legalFor({{V2F16, LocalPtr}, {V2BF16, LocalPtr}});
1740 }
1741 if (ST.hasAtomicFaddInsts())
1742 Atomic.legalFor({{S32, GlobalPtr}});
1743 if (ST.hasFlatAtomicFaddF32Inst())
1744 Atomic.legalFor({{S32, FlatPtr}});
1745
1746 if (ST.hasGFX90AInsts() || ST.hasGFX1250Insts()) {
1747 // These are legal with some caveats, and should have undergone expansion in
1748 // the IR in most situations
1749 // TODO: Move atomic expansion into legalizer
1750 Atomic.legalFor({
1751 {S32, GlobalPtr},
1752 {S64, GlobalPtr},
1753 {S64, FlatPtr}
1754 });
1755 }
1756
1757 if (ST.hasAtomicBufferGlobalPkAddF16NoRtnInsts() ||
1758 ST.hasAtomicBufferGlobalPkAddF16Insts())
1759 Atomic.legalFor({{V2F16, GlobalPtr}, {V2F16, BufferFatPtr}});
1760 if (ST.hasAtomicGlobalPkAddBF16Inst())
1761 Atomic.legalFor({{V2BF16, GlobalPtr}});
1762 if (ST.hasAtomicFlatPkAdd16Insts())
1763 Atomic.legalFor({{V2F16, FlatPtr}, {V2BF16, FlatPtr}});
1764
1765
1766 // Most of the legalization work here is done by AtomicExpand. We could
1767 // probably use a simpler legality rule that just assumes anything is OK.
1768 auto &AtomicFMinFMax =
1769 getActionDefinitionsBuilder({G_ATOMICRMW_FMIN, G_ATOMICRMW_FMAX})
1770 .legalFor({{F32, LocalPtr}, {F64, LocalPtr}});
1771
1772 if (ST.hasAtomicFMinFMaxF32GlobalInsts())
1773 AtomicFMinFMax.legalFor({{F32, GlobalPtr},{F32, BufferFatPtr}});
1774 if (ST.hasAtomicFMinFMaxF64GlobalInsts())
1775 AtomicFMinFMax.legalFor({{F64, GlobalPtr}, {F64, BufferFatPtr}});
1776 if (ST.hasAtomicFMinFMaxF32FlatInsts())
1777 AtomicFMinFMax.legalFor({F32, FlatPtr});
1778 if (ST.hasAtomicFMinFMaxF64FlatInsts())
1779 AtomicFMinFMax.legalFor({F64, FlatPtr});
1780
1781 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, and output
1782 // demarshalling
1783 getActionDefinitionsBuilder(G_ATOMIC_CMPXCHG)
1784 .customFor({{S32, GlobalPtr}, {S64, GlobalPtr},
1785 {S32, FlatPtr}, {S64, FlatPtr}})
1786 .legalFor({{S32, LocalPtr}, {S64, LocalPtr},
1787 {S32, RegionPtr}, {S64, RegionPtr}});
1788 // TODO: Pointer types, any 32-bit or 64-bit vector
1789
1790 // Condition should be s32 for scalar, s1 for vector.
1793 LocalPtr, FlatPtr, PrivatePtr,
1794 LLT::fixed_vector(2, LocalPtr),
1795 LLT::fixed_vector(2, PrivatePtr)},
1796 {S1, S32})
1797 .clampScalar(0, S16, S64)
1798 .scalarize(1)
1801 .clampMaxNumElements(0, S32, 2)
1802 .clampMaxNumElements(0, LocalPtr, 2)
1803 .clampMaxNumElements(0, PrivatePtr, 2)
1804 .scalarize(0)
1806 .legalIf(all(isPointer(0), typeInSet(1, {S1, S32})));
1807
1808 // TODO: Only the low 4/5/6 bits of the shift amount are observed, so we can
1809 // be more flexible with the shift amount type.
1810 auto &Shifts = getActionDefinitionsBuilder({G_SHL, G_LSHR, G_ASHR})
1811 .legalFor({{S32, S32}, {S64, S32}});
1812 if (ST.has16BitInsts()) {
1813 if (ST.hasVOP3PInsts()) {
1814 Shifts.legalFor({{S16, S16}, {V2S16, V2S16}})
1815 .clampMaxNumElements(0, S16, 2);
1816 } else
1817 Shifts.legalFor({{S16, S16}});
1818
1819 // TODO: Support 16-bit shift amounts for all types
1820 Shifts.widenScalarIf(
1821 [=](const LegalityQuery &Query) {
1822 // Use 16-bit shift amounts for any 16-bit shift. Otherwise we want a
1823 // 32-bit amount.
1824 const LLT ValTy = Query.Types[0];
1825 const LLT AmountTy = Query.Types[1];
1826 return ValTy.isScalar() && ValTy.getSizeInBits() <= 16 &&
1827 AmountTy.getSizeInBits() < 16;
1828 }, changeTo(1, S16));
1829 Shifts.maxScalarIf(typeIs(0, S16), 1, S16);
1830 Shifts.clampScalar(1, S32, S32);
1831 Shifts.widenScalarToNextPow2(0, 16);
1832 Shifts.clampScalar(0, S16, S64);
1833
1834 getActionDefinitionsBuilder({G_SSHLSAT, G_USHLSAT})
1835 .minScalar(0, S16)
1836 .scalarize(0)
1837 .lower();
1838 } else {
1839 // Make sure we legalize the shift amount type first, as the general
1840 // expansion for the shifted type will produce much worse code if it hasn't
1841 // been truncated already.
1842 Shifts.clampScalar(1, S32, S32);
1843 Shifts.widenScalarToNextPow2(0, 32);
1844 Shifts.clampScalar(0, S32, S64);
1845
1846 getActionDefinitionsBuilder({G_SSHLSAT, G_USHLSAT})
1847 .minScalar(0, S32)
1848 .scalarize(0)
1849 .lower();
1850 }
1851 Shifts.scalarize(0);
1852
1853 for (unsigned Op : {G_EXTRACT_VECTOR_ELT, G_INSERT_VECTOR_ELT}) {
1854 unsigned VecTypeIdx = Op == G_EXTRACT_VECTOR_ELT ? 1 : 0;
1855 unsigned EltTypeIdx = Op == G_EXTRACT_VECTOR_ELT ? 0 : 1;
1856 unsigned IdxTypeIdx = 2;
1857
1859 .customIf([=](const LegalityQuery &Query) {
1860 const LLT EltTy = Query.Types[EltTypeIdx];
1861 const LLT VecTy = Query.Types[VecTypeIdx];
1862 const LLT IdxTy = Query.Types[IdxTypeIdx];
1863 const unsigned EltSize = EltTy.getSizeInBits();
1864 const bool isLegalVecType =
1866 // Address space 8 pointers are 128-bit wide values, but the logic
1867 // below will try to bitcast them to 2N x s64, which will fail.
1868 // Therefore, as an intermediate step, wrap extracts/insertions from a
1869 // ptrtoint-ing the vector and scalar arguments (or inttoptring the
1870 // extraction result) in order to produce a vector operation that can
1871 // be handled by the logic below.
1872 if (EltTy.isPointer() && EltSize > 64)
1873 return true;
1874 return (EltSize == 32 || EltSize == 64) &&
1875 VecTy.getSizeInBits() % 32 == 0 &&
1876 VecTy.getSizeInBits() <= MaxRegisterSize &&
1877 IdxTy.getSizeInBits() == 32 &&
1878 isLegalVecType;
1879 })
1880 .bitcastIf(all(sizeIsMultipleOf32(VecTypeIdx),
1881 scalarOrEltNarrowerThan(VecTypeIdx, 32)),
1882 bitcastToVectorElement32(VecTypeIdx))
1883 //.bitcastIf(vectorSmallerThan(1, 32), bitcastToScalar(1))
1884 .bitcastIf(all(sizeIsMultipleOf32(VecTypeIdx),
1885 scalarOrEltWiderThan(VecTypeIdx, 64)),
1886 [=](const LegalityQuery &Query) {
1887 // For > 64-bit element types, try to turn this into a
1888 // 64-bit element vector since we may be able to do better
1889 // indexing if this is scalar. If not, fall back to 32.
1890 const LLT EltTy = Query.Types[EltTypeIdx];
1891 const LLT VecTy = Query.Types[VecTypeIdx];
1892 const unsigned DstEltSize = EltTy.getSizeInBits();
1893 const unsigned VecSize = VecTy.getSizeInBits();
1894
1895 const unsigned TargetEltSize =
1896 DstEltSize % 64 == 0 ? 64 : 32;
1897 return std::pair(VecTypeIdx,
1898 LLT::fixed_vector(VecSize / TargetEltSize,
1899 TargetEltSize));
1900 })
1901 .clampScalar(EltTypeIdx, S32, S64)
1902 .clampScalar(VecTypeIdx, S32, S64)
1903 .clampScalar(IdxTypeIdx, S32, S32)
1904 .clampMaxNumElements(VecTypeIdx, S32, 32)
1905 // TODO: Clamp elements for 64-bit vectors?
1906 .moreElementsIf(isIllegalRegisterType(ST, VecTypeIdx),
1908 // It should only be necessary with variable indexes.
1909 // As a last resort, lower to the stack
1910 .lower();
1911 }
1912
1913 getActionDefinitionsBuilder(G_EXTRACT_VECTOR_ELT)
1914 .unsupportedIf([=](const LegalityQuery &Query) {
1915 const LLT &EltTy = Query.Types[1].getElementType();
1916 return Query.Types[0] != EltTy;
1917 });
1918
1919 for (unsigned Op : {G_EXTRACT, G_INSERT}) {
1920 unsigned BigTyIdx = Op == G_EXTRACT ? 1 : 0;
1921 unsigned LitTyIdx = Op == G_EXTRACT ? 0 : 1;
1922
1923 // FIXME: Doesn't handle extract of illegal sizes.
1925 .lowerIf(all(typeIs(LitTyIdx, S16), sizeIs(BigTyIdx, 32)))
1926 .lowerIf([=](const LegalityQuery &Query) {
1927 // Sub-vector(or single element) insert and extract.
1928 // TODO: verify immediate offset here since lower only works with
1929 // whole elements.
1930 const LLT BigTy = Query.Types[BigTyIdx];
1931 return BigTy.isVector();
1932 })
1933 // FIXME: Multiples of 16 should not be legal.
1934 .legalIf([=](const LegalityQuery &Query) {
1935 const LLT BigTy = Query.Types[BigTyIdx];
1936 const LLT LitTy = Query.Types[LitTyIdx];
1937 return (BigTy.getSizeInBits() % 32 == 0) &&
1938 (LitTy.getSizeInBits() % 16 == 0);
1939 })
1940 .widenScalarIf(
1941 [=](const LegalityQuery &Query) {
1942 const LLT BigTy = Query.Types[BigTyIdx];
1943 return (BigTy.getScalarSizeInBits() < 16);
1944 },
1946 .widenScalarIf(
1947 [=](const LegalityQuery &Query) {
1948 const LLT LitTy = Query.Types[LitTyIdx];
1949 return (LitTy.getScalarSizeInBits() < 16);
1950 },
1952 .moreElementsIf(isSmallOddVector(BigTyIdx), oneMoreElement(BigTyIdx))
1953 .widenScalarToNextPow2(BigTyIdx, 32);
1954
1955 }
1956
1957 auto &BuildVector =
1958 getActionDefinitionsBuilder(G_BUILD_VECTOR)
1960 .legalForCartesianProduct(AllS64Vectors, {S64})
1961 .clampNumElements(0, V16S32, V32S32)
1966
1967 if (ST.hasScalarPackInsts()) {
1968 BuildVector
1969 // FIXME: Should probably widen s1 vectors straight to s32
1970 .minScalarOrElt(0, S16)
1971 .minScalar(1, S16);
1972
1973 getActionDefinitionsBuilder(G_BUILD_VECTOR_TRUNC)
1974 .legalFor({V2S16, S32})
1975 .lower();
1976 } else {
1977 BuildVector.customFor({V2S16, S16});
1978 BuildVector.minScalarOrElt(0, S32);
1979
1980 getActionDefinitionsBuilder(G_BUILD_VECTOR_TRUNC)
1981 .customFor({V2S16, S32})
1982 .lower();
1983 }
1984
1985 BuildVector.legalIf(isRegisterType(ST, 0));
1986
1987 // FIXME: Clamp maximum size
1988 getActionDefinitionsBuilder(G_CONCAT_VECTORS)
1989 .legalIf(all(isRegisterType(ST, 0), isRegisterType(ST, 1)))
1990 .clampMaxNumElements(0, S32, 32)
1991 .clampMaxNumElements(1, S16, 2) // TODO: Make 4?
1992 .clampMaxNumElements(0, S16, 64);
1993
1994 getActionDefinitionsBuilder(G_SHUFFLE_VECTOR).lower();
1995
1996 // Merge/Unmerge
1997 for (unsigned Op : {G_MERGE_VALUES, G_UNMERGE_VALUES}) {
1998 unsigned BigTyIdx = Op == G_MERGE_VALUES ? 0 : 1;
1999 unsigned LitTyIdx = Op == G_MERGE_VALUES ? 1 : 0;
2000
2001 auto notValidElt = [=](const LegalityQuery &Query, unsigned TypeIdx) {
2002 const LLT Ty = Query.Types[TypeIdx];
2003 if (Ty.isVector()) {
2004 const LLT &EltTy = Ty.getElementType();
2005 if (EltTy.getSizeInBits() < 8 || EltTy.getSizeInBits() > 512)
2006 return true;
2008 return true;
2009 }
2010 return false;
2011 };
2012
2013 auto &Builder =
2015 .legalIf(all(isRegisterType(ST, 0), isRegisterType(ST, 1)))
2016 .lowerFor({{S16, V2S16}})
2017 .lowerIf([=](const LegalityQuery &Query) {
2018 const LLT BigTy = Query.Types[BigTyIdx];
2019 return BigTy.getSizeInBits() == 32;
2020 })
2021 // Try to widen to s16 first for small types.
2022 // TODO: Only do this on targets with legal s16 shifts
2023 .minScalarOrEltIf(scalarNarrowerThan(LitTyIdx, 16), LitTyIdx, S16)
2024 .widenScalarToNextPow2(LitTyIdx, /*Min*/ 16)
2026 oneMoreElement(BigTyIdx))
2028 elementTypeIs(1, S16)),
2029 changeTo(1, V2S16))
2030 // Clamp the little scalar to s8-s256 and make it a power of 2. It's
2031 // not worth considering the multiples of 64 since 2*192 and 2*384
2032 // are not valid.
2033 .clampScalar(LitTyIdx, S32, S512)
2034 .widenScalarToNextPow2(LitTyIdx, /*Min*/ 32)
2035 // Break up vectors with weird elements into scalars
2037 [=](const LegalityQuery &Query) {
2038 return notValidElt(Query, LitTyIdx);
2039 },
2040 scalarize(0))
2041 .fewerElementsIf(
2042 [=](const LegalityQuery &Query) {
2043 return notValidElt(Query, BigTyIdx);
2044 },
2045 scalarize(1))
2046 .clampScalar(BigTyIdx, S32, MaxScalar);
2047
2048 if (Op == G_MERGE_VALUES) {
2049 Builder.widenScalarIf(
2050 // TODO: Use 16-bit shifts if legal for 8-bit values?
2051 [=](const LegalityQuery &Query) {
2052 const LLT Ty = Query.Types[LitTyIdx];
2053 return Ty.getSizeInBits() < 32;
2054 },
2055 changeTo(LitTyIdx, S32));
2056 }
2057
2058 Builder.widenScalarIf(
2059 [=](const LegalityQuery &Query) {
2060 const LLT Ty = Query.Types[BigTyIdx];
2061 return Ty.getSizeInBits() % 16 != 0;
2062 },
2063 [=](const LegalityQuery &Query) {
2064 // Pick the next power of 2, or a multiple of 64 over 128.
2065 // Whichever is smaller.
2066 const LLT &Ty = Query.Types[BigTyIdx];
2067 unsigned NewSizeInBits = 1 << Log2_32_Ceil(Ty.getSizeInBits() + 1);
2068 if (NewSizeInBits >= 256) {
2069 unsigned RoundedTo = alignTo<64>(Ty.getSizeInBits() + 1);
2070 if (RoundedTo < NewSizeInBits)
2071 NewSizeInBits = RoundedTo;
2072 }
2073 return std::pair(BigTyIdx, LLT::scalar(NewSizeInBits));
2074 })
2075 // Any vectors left are the wrong size. Scalarize them.
2076 .scalarize(0)
2077 .scalarize(1);
2078 }
2079
2080 // S64 is only legal on SALU, and needs to be broken into 32-bit elements in
2081 // RegBankSelect.
2082 auto &SextInReg = getActionDefinitionsBuilder(G_SEXT_INREG)
2083 .legalFor({{S32}, {S64}})
2084 .clampScalar(0, S32, S64);
2085
2086 if (ST.hasVOP3PInsts()) {
2087 SextInReg.lowerFor({{V2S16}})
2088 // Prefer to reduce vector widths for 16-bit vectors before lowering, to
2089 // get more vector shift opportunities, since we'll get those when
2090 // expanded.
2091 .clampMaxNumElementsStrict(0, S16, 2);
2092 } else if (ST.has16BitInsts()) {
2093 SextInReg.lowerFor({{S32}, {S64}, {S16}});
2094 } else {
2095 // Prefer to promote to s32 before lowering if we don't have 16-bit
2096 // shifts. This avoid a lot of intermediate truncate and extend operations.
2097 SextInReg.lowerFor({{S32}, {S64}});
2098 }
2099
2100 SextInReg
2101 .scalarize(0)
2102 .clampScalar(0, S32, S64)
2103 .lower();
2104
2105 getActionDefinitionsBuilder({G_ROTR, G_ROTL})
2106 .scalarize(0)
2107 .lower();
2108
2109 auto &FSHRActionDefs = getActionDefinitionsBuilder(G_FSHR);
2110 FSHRActionDefs.legalFor({{S32, S32}})
2111 .clampMaxNumElementsStrict(0, S16, 2);
2112 if (ST.hasVOP3PInsts())
2113 FSHRActionDefs.lowerFor({{V2S16, V2S16}});
2114 FSHRActionDefs.scalarize(0).lower();
2115
2116 if (ST.hasVOP3PInsts()) {
2118 .lowerFor({{V2S16, V2S16}})
2119 .clampMaxNumElementsStrict(0, S16, 2)
2120 .scalarize(0)
2121 .lower();
2122 } else {
2124 .scalarize(0)
2125 .lower();
2126 }
2127
2128 getActionDefinitionsBuilder(G_READCYCLECOUNTER)
2129 .legalFor({S64});
2130
2131 getActionDefinitionsBuilder(G_READSTEADYCOUNTER).legalFor({S64});
2132
2134 .alwaysLegal();
2135
2136 getActionDefinitionsBuilder({G_SMULO, G_UMULO})
2137 .scalarize(0)
2138 .minScalar(0, S32)
2139 .lower();
2140
2141 getActionDefinitionsBuilder({G_SBFX, G_UBFX})
2142 .legalFor({{S32, S32}, {S64, S32}})
2143 .clampScalar(1, S32, S32)
2144 .clampScalar(0, S32, S64)
2146 .scalarize(0);
2147
2149 {// TODO: Verify V_BFI_B32 is generated from expanded bit ops
2150 G_FCOPYSIGN,
2151
2152 G_ATOMIC_CMPXCHG_WITH_SUCCESS, G_ATOMICRMW_NAND, G_ATOMICRMW_FSUB,
2153 G_READ_REGISTER, G_WRITE_REGISTER,
2154
2155 G_SADDO, G_SSUBO})
2156 .lower();
2157
2158 if (ST.hasIEEEMinimumMaximumInsts()) {
2159 getActionDefinitionsBuilder({G_FMINIMUM, G_FMAXIMUM})
2160 .legalFor(FPTypesPK16)
2161 .clampMaxNumElements(0, S16, 2)
2162 .scalarize(0);
2163 } else if (ST.hasVOP3PInsts()) {
2164 getActionDefinitionsBuilder({G_FMINIMUM, G_FMAXIMUM})
2165 .lowerFor({V2S16})
2166 .clampMaxNumElementsStrict(0, S16, 2)
2167 .scalarize(0)
2168 .lower();
2169 } else {
2170 getActionDefinitionsBuilder({G_FMINIMUM, G_FMAXIMUM})
2171 .scalarize(0)
2172 .clampScalar(0, S32, S64)
2173 .lower();
2174 }
2175
2176 getActionDefinitionsBuilder({G_MEMCPY, G_MEMCPY_INLINE, G_MEMMOVE, G_MEMSET})
2177 .lower();
2178
2179 getActionDefinitionsBuilder({G_TRAP, G_DEBUGTRAP}).custom();
2180
2181 getActionDefinitionsBuilder({G_VASTART, G_VAARG, G_BRJT, G_JUMP_TABLE,
2182 G_INDEXED_LOAD, G_INDEXED_SEXTLOAD,
2183 G_INDEXED_ZEXTLOAD, G_INDEXED_STORE})
2184 .unsupported();
2185
2187
2189 {G_VECREDUCE_SMIN, G_VECREDUCE_SMAX, G_VECREDUCE_UMIN, G_VECREDUCE_UMAX,
2190 G_VECREDUCE_ADD, G_VECREDUCE_MUL, G_VECREDUCE_FMUL, G_VECREDUCE_FMIN,
2191 G_VECREDUCE_FMAX, G_VECREDUCE_FMINIMUM, G_VECREDUCE_FMAXIMUM,
2192 G_VECREDUCE_OR, G_VECREDUCE_AND, G_VECREDUCE_XOR})
2193 .legalFor(AllVectors)
2194 .scalarize(1)
2195 .lower();
2196
2198 verify(*ST.getInstrInfo());
2199}
2200
2203 LostDebugLocObserver &LocObserver) const {
2204 MachineIRBuilder &B = Helper.MIRBuilder;
2205 MachineRegisterInfo &MRI = *B.getMRI();
2206
2207 switch (MI.getOpcode()) {
2208 case TargetOpcode::G_ADDRSPACE_CAST:
2209 return legalizeAddrSpaceCast(MI, MRI, B);
2210 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
2211 return legalizeFroundeven(MI, MRI, B);
2212 case TargetOpcode::G_FCEIL:
2213 return legalizeFceil(MI, MRI, B);
2214 case TargetOpcode::G_FREM:
2215 return legalizeFrem(MI, MRI, B);
2216 case TargetOpcode::G_INTRINSIC_TRUNC:
2217 return legalizeIntrinsicTrunc(MI, MRI, B);
2218 case TargetOpcode::G_SITOFP:
2219 return legalizeITOFP(MI, MRI, B, true);
2220 case TargetOpcode::G_UITOFP:
2221 return legalizeITOFP(MI, MRI, B, false);
2222 case TargetOpcode::G_FPTOSI:
2223 return legalizeFPTOI(MI, MRI, B, true);
2224 case TargetOpcode::G_FPTOUI:
2225 return legalizeFPTOI(MI, MRI, B, false);
2226 case TargetOpcode::G_FMINNUM:
2227 case TargetOpcode::G_FMAXNUM:
2228 case TargetOpcode::G_FMINIMUMNUM:
2229 case TargetOpcode::G_FMAXIMUMNUM:
2230 return legalizeMinNumMaxNum(Helper, MI);
2231 case TargetOpcode::G_EXTRACT_VECTOR_ELT:
2232 return legalizeExtractVectorElt(MI, MRI, B);
2233 case TargetOpcode::G_INSERT_VECTOR_ELT:
2234 return legalizeInsertVectorElt(MI, MRI, B);
2235 case TargetOpcode::G_FSIN:
2236 case TargetOpcode::G_FCOS:
2237 return legalizeSinCos(MI, MRI, B);
2238 case TargetOpcode::G_GLOBAL_VALUE:
2239 return legalizeGlobalValue(MI, MRI, B);
2240 case TargetOpcode::G_LOAD:
2241 case TargetOpcode::G_SEXTLOAD:
2242 case TargetOpcode::G_ZEXTLOAD:
2243 return legalizeLoad(Helper, MI);
2244 case TargetOpcode::G_STORE:
2245 return legalizeStore(Helper, MI);
2246 case TargetOpcode::G_FMAD:
2247 return legalizeFMad(MI, MRI, B);
2248 case TargetOpcode::G_FDIV:
2249 return legalizeFDIV(MI, MRI, B);
2250 case TargetOpcode::G_FFREXP:
2251 return legalizeFFREXP(MI, MRI, B);
2252 case TargetOpcode::G_FSQRT:
2253 return legalizeFSQRT(MI, MRI, B);
2254 case TargetOpcode::G_UDIV:
2255 case TargetOpcode::G_UREM:
2256 case TargetOpcode::G_UDIVREM:
2257 return legalizeUnsignedDIV_REM(MI, MRI, B);
2258 case TargetOpcode::G_SDIV:
2259 case TargetOpcode::G_SREM:
2260 case TargetOpcode::G_SDIVREM:
2261 return legalizeSignedDIV_REM(MI, MRI, B);
2262 case TargetOpcode::G_ATOMIC_CMPXCHG:
2263 return legalizeAtomicCmpXChg(MI, MRI, B);
2264 case TargetOpcode::G_FLOG2:
2265 return legalizeFlog2(MI, B);
2266 case TargetOpcode::G_FLOG:
2267 case TargetOpcode::G_FLOG10:
2268 return legalizeFlogCommon(MI, B);
2269 case TargetOpcode::G_FEXP2:
2270 return legalizeFExp2(MI, B);
2271 case TargetOpcode::G_FEXP:
2272 case TargetOpcode::G_FEXP10:
2273 return legalizeFExp(MI, B);
2274 case TargetOpcode::G_FPOW:
2275 return legalizeFPow(MI, B);
2276 case TargetOpcode::G_FFLOOR:
2277 return legalizeFFloor(MI, MRI, B);
2278 case TargetOpcode::G_BUILD_VECTOR:
2279 case TargetOpcode::G_BUILD_VECTOR_TRUNC:
2280 return legalizeBuildVector(MI, MRI, B);
2281 case TargetOpcode::G_MUL:
2282 return legalizeMul(Helper, MI);
2283 case TargetOpcode::G_CTLZ:
2284 case TargetOpcode::G_CTTZ:
2285 return legalizeCTLZ_CTTZ(MI, MRI, B);
2286 case TargetOpcode::G_CTLZ_ZERO_UNDEF:
2287 return legalizeCTLZ_ZERO_UNDEF(MI, MRI, B);
2288 case TargetOpcode::G_STACKSAVE:
2289 return legalizeStackSave(MI, B);
2290 case TargetOpcode::G_GET_FPENV:
2291 return legalizeGetFPEnv(MI, MRI, B);
2292 case TargetOpcode::G_SET_FPENV:
2293 return legalizeSetFPEnv(MI, MRI, B);
2294 case TargetOpcode::G_TRAP:
2295 return legalizeTrap(MI, MRI, B);
2296 case TargetOpcode::G_DEBUGTRAP:
2297 return legalizeDebugTrap(MI, MRI, B);
2298 default:
2299 return false;
2300 }
2301
2302 llvm_unreachable("expected switch to return");
2303}
2304
2306 unsigned AS,
2308 MachineIRBuilder &B) const {
2309 MachineFunction &MF = B.getMF();
2310 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2311 const LLT S32 = LLT::scalar(32);
2312 const LLT S64 = LLT::scalar(64);
2313
2315
2316 if (ST.hasApertureRegs()) {
2317 // Note: this register is somewhat broken. When used as a 32-bit operand,
2318 // it only returns zeroes. The real value is in the upper 32 bits.
2319 // Thus, we must emit extract the high 32 bits.
2320 const unsigned ApertureRegNo = (AS == AMDGPUAS::LOCAL_ADDRESS)
2321 ? AMDGPU::SRC_SHARED_BASE
2322 : AMDGPU::SRC_PRIVATE_BASE;
2323 assert((ApertureRegNo != AMDGPU::SRC_PRIVATE_BASE ||
2324 !ST.hasGloballyAddressableScratch()) &&
2325 "Cannot use src_private_base with globally addressable scratch!");
2326 Register Dst = MRI.createGenericVirtualRegister(S64);
2327 MRI.setRegClass(Dst, &AMDGPU::SReg_64RegClass);
2328 B.buildCopy({Dst}, {Register(ApertureRegNo)});
2329 return B.buildUnmerge(S32, Dst).getReg(1);
2330 }
2331
2332 Register LoadAddr = MRI.createGenericVirtualRegister(
2334 // For code object version 5, private_base and shared_base are passed through
2335 // implicit kernargs.
2339
2344 ST.getTargetLowering()->getImplicitParameterOffset(B.getMF(), Param);
2345
2346 Register KernargPtrReg = MRI.createGenericVirtualRegister(
2348
2349 if (!loadInputValue(KernargPtrReg, B,
2351 return Register();
2352
2354 PtrInfo.getWithOffset(Offset),
2358
2359 // Pointer address
2360 B.buildObjectPtrOffset(LoadAddr, KernargPtrReg,
2361 B.buildConstant(LLT::scalar(64), Offset).getReg(0));
2362 // Load address
2363 return B.buildLoad(S32, LoadAddr, *MMO).getReg(0);
2364 }
2365
2366 Register QueuePtr = MRI.createGenericVirtualRegister(
2368
2370 return Register();
2371
2372 // TODO: Use custom PseudoSourceValue
2374
2375 // Offset into amd_queue_t for group_segment_aperture_base_hi /
2376 // private_segment_aperture_base_hi.
2377 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
2378
2380 PtrInfo,
2383 LLT::scalar(32), commonAlignment(Align(64), StructOffset));
2384
2385 B.buildObjectPtrOffset(
2386 LoadAddr, QueuePtr,
2387 B.buildConstant(LLT::scalar(64), StructOffset).getReg(0));
2388 return B.buildLoad(S32, LoadAddr, *MMO).getReg(0);
2389}
2390
2391/// Return true if the value is a known valid address, such that a null check is
2392/// not necessary.
2394 const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
2395 MachineInstr *Def = MRI.getVRegDef(Val);
2396 switch (Def->getOpcode()) {
2397 case AMDGPU::G_FRAME_INDEX:
2398 case AMDGPU::G_GLOBAL_VALUE:
2399 case AMDGPU::G_BLOCK_ADDR:
2400 return true;
2401 case AMDGPU::G_CONSTANT: {
2402 const ConstantInt *CI = Def->getOperand(1).getCImm();
2403 return CI->getSExtValue() != TM.getNullPointerValue(AddrSpace);
2404 }
2405 default:
2406 return false;
2407 }
2408
2409 return false;
2410}
2411
2414 MachineIRBuilder &B) const {
2415 MachineFunction &MF = B.getMF();
2416
2417 // MI can either be a G_ADDRSPACE_CAST or a
2418 // G_INTRINSIC @llvm.amdgcn.addrspacecast.nonnull
2419 assert(MI.getOpcode() == TargetOpcode::G_ADDRSPACE_CAST ||
2420 (isa<GIntrinsic>(MI) && cast<GIntrinsic>(MI).getIntrinsicID() ==
2421 Intrinsic::amdgcn_addrspacecast_nonnull));
2422
2423 const LLT S32 = LLT::scalar(32);
2424 Register Dst = MI.getOperand(0).getReg();
2425 Register Src = isa<GIntrinsic>(MI) ? MI.getOperand(2).getReg()
2426 : MI.getOperand(1).getReg();
2427 LLT DstTy = MRI.getType(Dst);
2428 LLT SrcTy = MRI.getType(Src);
2429 unsigned DestAS = DstTy.getAddressSpace();
2430 unsigned SrcAS = SrcTy.getAddressSpace();
2431
2432 // TODO: Avoid reloading from the queue ptr for each cast, or at least each
2433 // vector element.
2434 assert(!DstTy.isVector());
2435
2436 const AMDGPUTargetMachine &TM
2437 = static_cast<const AMDGPUTargetMachine &>(MF.getTarget());
2438
2439 if (TM.isNoopAddrSpaceCast(SrcAS, DestAS)) {
2440 MI.setDesc(B.getTII().get(TargetOpcode::G_BITCAST));
2441 return true;
2442 }
2443
2444 if (SrcAS == AMDGPUAS::FLAT_ADDRESS &&
2445 (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
2446 DestAS == AMDGPUAS::PRIVATE_ADDRESS)) {
2447 auto castFlatToLocalOrPrivate = [&](const DstOp &Dst) -> Register {
2448 if (DestAS == AMDGPUAS::PRIVATE_ADDRESS &&
2449 ST.hasGloballyAddressableScratch()) {
2450 // flat -> private with globally addressable scratch: subtract
2451 // src_flat_scratch_base_lo.
2452 const LLT S32 = LLT::scalar(32);
2453 Register SrcLo = B.buildExtract(S32, Src, 0).getReg(0);
2454 Register FlatScratchBaseLo =
2455 B.buildInstr(AMDGPU::S_MOV_B32, {S32},
2456 {Register(AMDGPU::SRC_FLAT_SCRATCH_BASE_LO)})
2457 .getReg(0);
2458 MRI.setRegClass(FlatScratchBaseLo, &AMDGPU::SReg_32RegClass);
2459 Register Sub = B.buildSub(S32, SrcLo, FlatScratchBaseLo).getReg(0);
2460 return B.buildIntToPtr(Dst, Sub).getReg(0);
2461 }
2462
2463 // Extract low 32-bits of the pointer.
2464 return B.buildExtract(Dst, Src, 0).getReg(0);
2465 };
2466
2467 // For llvm.amdgcn.addrspacecast.nonnull we can always assume non-null, for
2468 // G_ADDRSPACE_CAST we need to guess.
2469 if (isa<GIntrinsic>(MI) || isKnownNonNull(Src, MRI, TM, SrcAS)) {
2470 castFlatToLocalOrPrivate(Dst);
2471 MI.eraseFromParent();
2472 return true;
2473 }
2474
2475 unsigned NullVal = TM.getNullPointerValue(DestAS);
2476
2477 auto SegmentNull = B.buildConstant(DstTy, NullVal);
2478 auto FlatNull = B.buildConstant(SrcTy, 0);
2479
2480 // Extract low 32-bits of the pointer.
2481 auto PtrLo32 = castFlatToLocalOrPrivate(DstTy);
2482
2483 auto CmpRes =
2484 B.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Src, FlatNull.getReg(0));
2485 B.buildSelect(Dst, CmpRes, PtrLo32, SegmentNull.getReg(0));
2486
2487 MI.eraseFromParent();
2488 return true;
2489 }
2490
2491 if (DestAS == AMDGPUAS::FLAT_ADDRESS &&
2492 (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
2493 SrcAS == AMDGPUAS::PRIVATE_ADDRESS)) {
2494 auto castLocalOrPrivateToFlat = [&](const DstOp &Dst) -> Register {
2495 // Coerce the type of the low half of the result so we can use
2496 // merge_values.
2497 Register SrcAsInt = B.buildPtrToInt(S32, Src).getReg(0);
2498
2499 if (SrcAS == AMDGPUAS::PRIVATE_ADDRESS &&
2500 ST.hasGloballyAddressableScratch()) {
2501 // For wave32: Addr = (TID[4:0] << 52) + FLAT_SCRATCH_BASE + privateAddr
2502 // For wave64: Addr = (TID[5:0] << 51) + FLAT_SCRATCH_BASE + privateAddr
2503 Register AllOnes = B.buildConstant(S32, -1).getReg(0);
2504 Register ThreadID = B.buildConstant(S32, 0).getReg(0);
2505 ThreadID = B.buildIntrinsic(Intrinsic::amdgcn_mbcnt_lo, {S32})
2506 .addUse(AllOnes)
2507 .addUse(ThreadID)
2508 .getReg(0);
2509 if (ST.isWave64()) {
2510 ThreadID = B.buildIntrinsic(Intrinsic::amdgcn_mbcnt_hi, {S32})
2511 .addUse(AllOnes)
2512 .addUse(ThreadID)
2513 .getReg(0);
2514 }
2515 Register ShAmt =
2516 B.buildConstant(S32, 57 - 32 - ST.getWavefrontSizeLog2()).getReg(0);
2517 Register SrcHi = B.buildShl(S32, ThreadID, ShAmt).getReg(0);
2518 Register CvtPtr =
2519 B.buildMergeLikeInstr(DstTy, {SrcAsInt, SrcHi}).getReg(0);
2520 // Accessing src_flat_scratch_base_lo as a 64-bit operand gives the full
2521 // 64-bit hi:lo value.
2522 Register FlatScratchBase =
2523 B.buildInstr(AMDGPU::S_MOV_B64, {S64},
2524 {Register(AMDGPU::SRC_FLAT_SCRATCH_BASE)})
2525 .getReg(0);
2526 MRI.setRegClass(FlatScratchBase, &AMDGPU::SReg_64RegClass);
2527 return B.buildPtrAdd(Dst, CvtPtr, FlatScratchBase).getReg(0);
2528 }
2529
2530 Register ApertureReg = getSegmentAperture(SrcAS, MRI, B);
2531 if (!ApertureReg.isValid())
2532 return false;
2533
2534 // TODO: Should we allow mismatched types but matching sizes in merges to
2535 // avoid the ptrtoint?
2536 return B.buildMergeLikeInstr(Dst, {SrcAsInt, ApertureReg}).getReg(0);
2537 };
2538
2539 // For llvm.amdgcn.addrspacecast.nonnull we can always assume non-null, for
2540 // G_ADDRSPACE_CAST we need to guess.
2541 if (isa<GIntrinsic>(MI) || isKnownNonNull(Src, MRI, TM, SrcAS)) {
2542 castLocalOrPrivateToFlat(Dst);
2543 MI.eraseFromParent();
2544 return true;
2545 }
2546
2547 Register BuildPtr = castLocalOrPrivateToFlat(DstTy);
2548
2549 auto SegmentNull = B.buildConstant(SrcTy, TM.getNullPointerValue(SrcAS));
2550 auto FlatNull = B.buildConstant(DstTy, TM.getNullPointerValue(DestAS));
2551
2552 auto CmpRes = B.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Src,
2553 SegmentNull.getReg(0));
2554
2555 B.buildSelect(Dst, CmpRes, BuildPtr, FlatNull);
2556
2557 MI.eraseFromParent();
2558 return true;
2559 }
2560
2561 if (DestAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
2562 SrcTy.getSizeInBits() == 64) {
2563 // Truncate.
2564 B.buildExtract(Dst, Src, 0);
2565 MI.eraseFromParent();
2566 return true;
2567 }
2568
2569 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
2570 DstTy.getSizeInBits() == 64) {
2572 uint32_t AddrHiVal = Info->get32BitAddressHighBits();
2573 auto PtrLo = B.buildPtrToInt(S32, Src);
2574 if (AddrHiVal == 0) {
2575 auto Zext = B.buildZExt(LLT::scalar(64), PtrLo);
2576 B.buildIntToPtr(Dst, Zext);
2577 } else {
2578 auto HighAddr = B.buildConstant(S32, AddrHiVal);
2579 B.buildMergeLikeInstr(Dst, {PtrLo, HighAddr});
2580 }
2581
2582 MI.eraseFromParent();
2583 return true;
2584 }
2585
2586 // Invalid casts are poison.
2587 // TODO: Should return poison
2588 B.buildUndef(Dst);
2589 MI.eraseFromParent();
2590 return true;
2591}
2592
2595 MachineIRBuilder &B) const {
2596 Register Src = MI.getOperand(1).getReg();
2597 LLT Ty = MRI.getType(Src);
2598 assert(Ty.isScalar() && Ty.getSizeInBits() == 64);
2599
2600 APFloat C1Val(APFloat::IEEEdouble(), "0x1.0p+52");
2601 APFloat C2Val(APFloat::IEEEdouble(), "0x1.fffffffffffffp+51");
2602
2603 auto C1 = B.buildFConstant(Ty, C1Val);
2604 auto CopySign = B.buildFCopysign(Ty, C1, Src);
2605
2606 // TODO: Should this propagate fast-math-flags?
2607 auto Tmp1 = B.buildFAdd(Ty, Src, CopySign);
2608 auto Tmp2 = B.buildFSub(Ty, Tmp1, CopySign);
2609
2610 auto C2 = B.buildFConstant(Ty, C2Val);
2611 auto Fabs = B.buildFAbs(Ty, Src);
2612
2613 auto Cond = B.buildFCmp(CmpInst::FCMP_OGT, LLT::scalar(1), Fabs, C2);
2614 B.buildSelect(MI.getOperand(0).getReg(), Cond, Src, Tmp2);
2615 MI.eraseFromParent();
2616 return true;
2617}
2618
2621 MachineIRBuilder &B) const {
2622
2623 const LLT S1 = LLT::scalar(1);
2624 const LLT S64 = LLT::scalar(64);
2625
2626 Register Src = MI.getOperand(1).getReg();
2627 assert(MRI.getType(Src) == S64);
2628
2629 // result = trunc(src)
2630 // if (src > 0.0 && src != result)
2631 // result += 1.0
2632
2633 auto Trunc = B.buildIntrinsicTrunc(S64, Src);
2634
2635 const auto Zero = B.buildFConstant(S64, 0.0);
2636 const auto One = B.buildFConstant(S64, 1.0);
2637 auto Lt0 = B.buildFCmp(CmpInst::FCMP_OGT, S1, Src, Zero);
2638 auto NeTrunc = B.buildFCmp(CmpInst::FCMP_ONE, S1, Src, Trunc);
2639 auto And = B.buildAnd(S1, Lt0, NeTrunc);
2640 auto Add = B.buildSelect(S64, And, One, Zero);
2641
2642 // TODO: Should this propagate fast-math-flags?
2643 B.buildFAdd(MI.getOperand(0).getReg(), Trunc, Add);
2644 MI.eraseFromParent();
2645 return true;
2646}
2647
2650 MachineIRBuilder &B) const {
2651 Register DstReg = MI.getOperand(0).getReg();
2652 Register Src0Reg = MI.getOperand(1).getReg();
2653 Register Src1Reg = MI.getOperand(2).getReg();
2654 auto Flags = MI.getFlags();
2655 LLT Ty = MRI.getType(DstReg);
2656
2657 auto Div = B.buildFDiv(Ty, Src0Reg, Src1Reg, Flags);
2658 auto Trunc = B.buildIntrinsicTrunc(Ty, Div, Flags);
2659 auto Neg = B.buildFNeg(Ty, Trunc, Flags);
2660 B.buildFMA(DstReg, Neg, Src1Reg, Src0Reg, Flags);
2661 MI.eraseFromParent();
2662 return true;
2663}
2664
2667 const unsigned FractBits = 52;
2668 const unsigned ExpBits = 11;
2669 LLT S32 = LLT::scalar(32);
2670
2671 auto Const0 = B.buildConstant(S32, FractBits - 32);
2672 auto Const1 = B.buildConstant(S32, ExpBits);
2673
2674 auto ExpPart = B.buildIntrinsic(Intrinsic::amdgcn_ubfe, {S32})
2675 .addUse(Hi)
2676 .addUse(Const0.getReg(0))
2677 .addUse(Const1.getReg(0));
2678
2679 return B.buildSub(S32, ExpPart, B.buildConstant(S32, 1023));
2680}
2681
2684 MachineIRBuilder &B) const {
2685 const LLT S1 = LLT::scalar(1);
2686 const LLT S32 = LLT::scalar(32);
2687 const LLT S64 = LLT::scalar(64);
2688
2689 Register Src = MI.getOperand(1).getReg();
2690 assert(MRI.getType(Src) == S64);
2691
2692 // TODO: Should this use extract since the low half is unused?
2693 auto Unmerge = B.buildUnmerge({S32, S32}, Src);
2694 Register Hi = Unmerge.getReg(1);
2695
2696 // Extract the upper half, since this is where we will find the sign and
2697 // exponent.
2698 auto Exp = extractF64Exponent(Hi, B);
2699
2700 const unsigned FractBits = 52;
2701
2702 // Extract the sign bit.
2703 const auto SignBitMask = B.buildConstant(S32, UINT32_C(1) << 31);
2704 auto SignBit = B.buildAnd(S32, Hi, SignBitMask);
2705
2706 const auto FractMask = B.buildConstant(S64, (UINT64_C(1) << FractBits) - 1);
2707
2708 const auto Zero32 = B.buildConstant(S32, 0);
2709
2710 // Extend back to 64-bits.
2711 auto SignBit64 = B.buildMergeLikeInstr(S64, {Zero32, SignBit});
2712
2713 auto Shr = B.buildAShr(S64, FractMask, Exp);
2714 auto Not = B.buildNot(S64, Shr);
2715 auto Tmp0 = B.buildAnd(S64, Src, Not);
2716 auto FiftyOne = B.buildConstant(S32, FractBits - 1);
2717
2718 auto ExpLt0 = B.buildICmp(CmpInst::ICMP_SLT, S1, Exp, Zero32);
2719 auto ExpGt51 = B.buildICmp(CmpInst::ICMP_SGT, S1, Exp, FiftyOne);
2720
2721 auto Tmp1 = B.buildSelect(S64, ExpLt0, SignBit64, Tmp0);
2722 B.buildSelect(MI.getOperand(0).getReg(), ExpGt51, Src, Tmp1);
2723 MI.eraseFromParent();
2724 return true;
2725}
2726
2729 MachineIRBuilder &B, bool Signed) const {
2730
2731 Register Dst = MI.getOperand(0).getReg();
2732 Register Src = MI.getOperand(1).getReg();
2733
2734 const LLT S64 = LLT::scalar(64);
2735 const LLT S32 = LLT::scalar(32);
2736
2737 assert(MRI.getType(Src) == S64);
2738
2739 auto Unmerge = B.buildUnmerge({S32, S32}, Src);
2740 auto ThirtyTwo = B.buildConstant(S32, 32);
2741
2742 if (MRI.getType(Dst) == S64) {
2743 auto CvtHi = Signed ? B.buildSITOFP(S64, Unmerge.getReg(1))
2744 : B.buildUITOFP(S64, Unmerge.getReg(1));
2745
2746 auto CvtLo = B.buildUITOFP(S64, Unmerge.getReg(0));
2747 auto LdExp = B.buildFLdexp(S64, CvtHi, ThirtyTwo);
2748
2749 // TODO: Should this propagate fast-math-flags?
2750 B.buildFAdd(Dst, LdExp, CvtLo);
2751 MI.eraseFromParent();
2752 return true;
2753 }
2754
2755 assert(MRI.getType(Dst) == S32);
2756
2757 auto One = B.buildConstant(S32, 1);
2758
2759 MachineInstrBuilder ShAmt;
2760 if (Signed) {
2761 auto ThirtyOne = B.buildConstant(S32, 31);
2762 auto X = B.buildXor(S32, Unmerge.getReg(0), Unmerge.getReg(1));
2763 auto OppositeSign = B.buildAShr(S32, X, ThirtyOne);
2764 auto MaxShAmt = B.buildAdd(S32, ThirtyTwo, OppositeSign);
2765 auto LS = B.buildIntrinsic(Intrinsic::amdgcn_sffbh, {S32})
2766 .addUse(Unmerge.getReg(1));
2767 auto LS2 = B.buildSub(S32, LS, One);
2768 ShAmt = B.buildUMin(S32, LS2, MaxShAmt);
2769 } else
2770 ShAmt = B.buildCTLZ(S32, Unmerge.getReg(1));
2771 auto Norm = B.buildShl(S64, Src, ShAmt);
2772 auto Unmerge2 = B.buildUnmerge({S32, S32}, Norm);
2773 auto Adjust = B.buildUMin(S32, One, Unmerge2.getReg(0));
2774 auto Norm2 = B.buildOr(S32, Unmerge2.getReg(1), Adjust);
2775 auto FVal = Signed ? B.buildSITOFP(S32, Norm2) : B.buildUITOFP(S32, Norm2);
2776 auto Scale = B.buildSub(S32, ThirtyTwo, ShAmt);
2777 B.buildFLdexp(Dst, FVal, Scale);
2778 MI.eraseFromParent();
2779 return true;
2780}
2781
2782// TODO: Copied from DAG implementation. Verify logic and document how this
2783// actually works.
2787 bool Signed) const {
2788
2789 Register Dst = MI.getOperand(0).getReg();
2790 Register Src = MI.getOperand(1).getReg();
2791
2792 const LLT S64 = LLT::scalar(64);
2793 const LLT S32 = LLT::scalar(32);
2794
2795 const LLT SrcLT = MRI.getType(Src);
2796 assert((SrcLT == S32 || SrcLT == S64) && MRI.getType(Dst) == S64);
2797
2798 unsigned Flags = MI.getFlags();
2799
2800 // The basic idea of converting a floating point number into a pair of 32-bit
2801 // integers is illustrated as follows:
2802 //
2803 // tf := trunc(val);
2804 // hif := floor(tf * 2^-32);
2805 // lof := tf - hif * 2^32; // lof is always positive due to floor.
2806 // hi := fptoi(hif);
2807 // lo := fptoi(lof);
2808 //
2809 auto Trunc = B.buildIntrinsicTrunc(SrcLT, Src, Flags);
2811 if (Signed && SrcLT == S32) {
2812 // However, a 32-bit floating point number has only 23 bits mantissa and
2813 // it's not enough to hold all the significant bits of `lof` if val is
2814 // negative. To avoid the loss of precision, We need to take the absolute
2815 // value after truncating and flip the result back based on the original
2816 // signedness.
2817 Sign = B.buildAShr(S32, Src, B.buildConstant(S32, 31));
2818 Trunc = B.buildFAbs(S32, Trunc, Flags);
2819 }
2820 MachineInstrBuilder K0, K1;
2821 if (SrcLT == S64) {
2822 K0 = B.buildFConstant(
2823 S64, llvm::bit_cast<double>(UINT64_C(/*2^-32*/ 0x3df0000000000000)));
2824 K1 = B.buildFConstant(
2825 S64, llvm::bit_cast<double>(UINT64_C(/*-2^32*/ 0xc1f0000000000000)));
2826 } else {
2827 K0 = B.buildFConstant(
2828 S32, llvm::bit_cast<float>(UINT32_C(/*2^-32*/ 0x2f800000)));
2829 K1 = B.buildFConstant(
2830 S32, llvm::bit_cast<float>(UINT32_C(/*-2^32*/ 0xcf800000)));
2831 }
2832
2833 auto Mul = B.buildFMul(SrcLT, Trunc, K0, Flags);
2834 auto FloorMul = B.buildFFloor(SrcLT, Mul, Flags);
2835 auto Fma = B.buildFMA(SrcLT, FloorMul, K1, Trunc, Flags);
2836
2837 auto Hi = (Signed && SrcLT == S64) ? B.buildFPTOSI(S32, FloorMul)
2838 : B.buildFPTOUI(S32, FloorMul);
2839 auto Lo = B.buildFPTOUI(S32, Fma);
2840
2841 if (Signed && SrcLT == S32) {
2842 // Flip the result based on the signedness, which is either all 0s or 1s.
2843 Sign = B.buildMergeLikeInstr(S64, {Sign, Sign});
2844 // r := xor({lo, hi}, sign) - sign;
2845 B.buildSub(Dst, B.buildXor(S64, B.buildMergeLikeInstr(S64, {Lo, Hi}), Sign),
2846 Sign);
2847 } else
2848 B.buildMergeLikeInstr(Dst, {Lo, Hi});
2849 MI.eraseFromParent();
2850
2851 return true;
2852}
2853
2855 MachineInstr &MI) const {
2856 MachineFunction &MF = Helper.MIRBuilder.getMF();
2858
2859 // With ieee_mode disabled, the instructions have the correct behavior.
2860 if (!MFI->getMode().IEEE)
2861 return true;
2862
2864}
2865
2868 MachineIRBuilder &B) const {
2869 // TODO: Should move some of this into LegalizerHelper.
2870
2871 // TODO: Promote dynamic indexing of s16 to s32
2872
2873 Register Dst = MI.getOperand(0).getReg();
2874 Register Vec = MI.getOperand(1).getReg();
2875
2876 LLT VecTy = MRI.getType(Vec);
2877 LLT EltTy = VecTy.getElementType();
2878 assert(EltTy == MRI.getType(Dst));
2879
2880 // Other legalization maps vector<? x [type bigger than 64 bits]> via bitcasts
2881 // but we can't go directly to that logic becasue you can't bitcast a vector
2882 // of pointers to a vector of integers. Therefore, introduce an intermediate
2883 // vector of integers using ptrtoint (and inttoptr on the output) in order to
2884 // drive the legalization forward.
2885 if (EltTy.isPointer() && EltTy.getSizeInBits() > 64) {
2886 LLT IntTy = LLT::scalar(EltTy.getSizeInBits());
2887 LLT IntVecTy = VecTy.changeElementType(IntTy);
2888
2889 auto IntVec = B.buildPtrToInt(IntVecTy, Vec);
2890 auto IntElt = B.buildExtractVectorElement(IntTy, IntVec, MI.getOperand(2));
2891 B.buildIntToPtr(Dst, IntElt);
2892
2893 MI.eraseFromParent();
2894 return true;
2895 }
2896
2897 // FIXME: Artifact combiner probably should have replaced the truncated
2898 // constant before this, so we shouldn't need
2899 // getIConstantVRegValWithLookThrough.
2900 std::optional<ValueAndVReg> MaybeIdxVal =
2901 getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
2902 if (!MaybeIdxVal) // Dynamic case will be selected to register indexing.
2903 return true;
2904 const uint64_t IdxVal = MaybeIdxVal->Value.getZExtValue();
2905
2906 if (IdxVal < VecTy.getNumElements()) {
2907 auto Unmerge = B.buildUnmerge(EltTy, Vec);
2908 B.buildCopy(Dst, Unmerge.getReg(IdxVal));
2909 } else {
2910 B.buildUndef(Dst);
2911 }
2912
2913 MI.eraseFromParent();
2914 return true;
2915}
2916
2919 MachineIRBuilder &B) const {
2920 // TODO: Should move some of this into LegalizerHelper.
2921
2922 // TODO: Promote dynamic indexing of s16 to s32
2923
2924 Register Dst = MI.getOperand(0).getReg();
2925 Register Vec = MI.getOperand(1).getReg();
2926 Register Ins = MI.getOperand(2).getReg();
2927
2928 LLT VecTy = MRI.getType(Vec);
2929 LLT EltTy = VecTy.getElementType();
2930 assert(EltTy == MRI.getType(Ins));
2931
2932 // Other legalization maps vector<? x [type bigger than 64 bits]> via bitcasts
2933 // but we can't go directly to that logic becasue you can't bitcast a vector
2934 // of pointers to a vector of integers. Therefore, make the pointer vector
2935 // into an equivalent vector of integers with ptrtoint, insert the ptrtoint'd
2936 // new value, and then inttoptr the result vector back. This will then allow
2937 // the rest of legalization to take over.
2938 if (EltTy.isPointer() && EltTy.getSizeInBits() > 64) {
2939 LLT IntTy = LLT::scalar(EltTy.getSizeInBits());
2940 LLT IntVecTy = VecTy.changeElementType(IntTy);
2941
2942 auto IntVecSource = B.buildPtrToInt(IntVecTy, Vec);
2943 auto IntIns = B.buildPtrToInt(IntTy, Ins);
2944 auto IntVecDest = B.buildInsertVectorElement(IntVecTy, IntVecSource, IntIns,
2945 MI.getOperand(3));
2946 B.buildIntToPtr(Dst, IntVecDest);
2947 MI.eraseFromParent();
2948 return true;
2949 }
2950
2951 // FIXME: Artifact combiner probably should have replaced the truncated
2952 // constant before this, so we shouldn't need
2953 // getIConstantVRegValWithLookThrough.
2954 std::optional<ValueAndVReg> MaybeIdxVal =
2955 getIConstantVRegValWithLookThrough(MI.getOperand(3).getReg(), MRI);
2956 if (!MaybeIdxVal) // Dynamic case will be selected to register indexing.
2957 return true;
2958
2959 const uint64_t IdxVal = MaybeIdxVal->Value.getZExtValue();
2960
2961 unsigned NumElts = VecTy.getNumElements();
2962 if (IdxVal < NumElts) {
2964 for (unsigned i = 0; i < NumElts; ++i)
2965 SrcRegs.push_back(MRI.createGenericVirtualRegister(EltTy));
2966 B.buildUnmerge(SrcRegs, Vec);
2967
2968 SrcRegs[IdxVal] = MI.getOperand(2).getReg();
2969 B.buildMergeLikeInstr(Dst, SrcRegs);
2970 } else {
2971 B.buildUndef(Dst);
2972 }
2973
2974 MI.eraseFromParent();
2975 return true;
2976}
2977
2980 MachineIRBuilder &B) const {
2981
2982 Register DstReg = MI.getOperand(0).getReg();
2983 Register SrcReg = MI.getOperand(1).getReg();
2984 LLT Ty = MRI.getType(DstReg);
2985 unsigned Flags = MI.getFlags();
2986
2987 Register TrigVal;
2988 auto OneOver2Pi = B.buildFConstant(Ty, 0.5 * numbers::inv_pi);
2989 if (ST.hasTrigReducedRange()) {
2990 auto MulVal = B.buildFMul(Ty, SrcReg, OneOver2Pi, Flags);
2991 TrigVal = B.buildIntrinsic(Intrinsic::amdgcn_fract, {Ty})
2992 .addUse(MulVal.getReg(0))
2993 .setMIFlags(Flags)
2994 .getReg(0);
2995 } else
2996 TrigVal = B.buildFMul(Ty, SrcReg, OneOver2Pi, Flags).getReg(0);
2997
2998 Intrinsic::ID TrigIntrin = MI.getOpcode() == AMDGPU::G_FSIN ?
2999 Intrinsic::amdgcn_sin : Intrinsic::amdgcn_cos;
3000 B.buildIntrinsic(TrigIntrin, ArrayRef<Register>(DstReg))
3001 .addUse(TrigVal)
3002 .setMIFlags(Flags);
3003 MI.eraseFromParent();
3004 return true;
3005}
3006
3009 const GlobalValue *GV,
3010 int64_t Offset,
3011 unsigned GAFlags) const {
3012 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
3013 // In order to support pc-relative addressing, SI_PC_ADD_REL_OFFSET is lowered
3014 // to the following code sequence:
3015 //
3016 // For constant address space:
3017 // s_getpc_b64 s[0:1]
3018 // s_add_u32 s0, s0, $symbol
3019 // s_addc_u32 s1, s1, 0
3020 //
3021 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
3022 // a fixup or relocation is emitted to replace $symbol with a literal
3023 // constant, which is a pc-relative offset from the encoding of the $symbol
3024 // operand to the global variable.
3025 //
3026 // For global address space:
3027 // s_getpc_b64 s[0:1]
3028 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
3029 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
3030 //
3031 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
3032 // fixups or relocations are emitted to replace $symbol@*@lo and
3033 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
3034 // which is a 64-bit pc-relative offset from the encoding of the $symbol
3035 // operand to the global variable.
3036
3038
3039 Register PCReg = PtrTy.getSizeInBits() != 32 ? DstReg :
3040 B.getMRI()->createGenericVirtualRegister(ConstPtrTy);
3041
3042 if (ST.has64BitLiterals()) {
3043 assert(GAFlags != SIInstrInfo::MO_NONE);
3044
3046 B.buildInstr(AMDGPU::SI_PC_ADD_REL_OFFSET64).addDef(PCReg);
3047 MIB.addGlobalAddress(GV, Offset, GAFlags + 2);
3048 } else {
3050 B.buildInstr(AMDGPU::SI_PC_ADD_REL_OFFSET).addDef(PCReg);
3051
3052 MIB.addGlobalAddress(GV, Offset, GAFlags);
3053 if (GAFlags == SIInstrInfo::MO_NONE)
3054 MIB.addImm(0);
3055 else
3056 MIB.addGlobalAddress(GV, Offset, GAFlags + 1);
3057 }
3058
3059 if (!B.getMRI()->getRegClassOrNull(PCReg))
3060 B.getMRI()->setRegClass(PCReg, &AMDGPU::SReg_64RegClass);
3061
3062 if (PtrTy.getSizeInBits() == 32)
3063 B.buildExtract(DstReg, PCReg, 0);
3064 return true;
3065}
3066
3067// Emit a ABS32_LO / ABS32_HI relocation stub.
3069 Register DstReg, LLT PtrTy, MachineIRBuilder &B, const GlobalValue *GV,
3070 MachineRegisterInfo &MRI) const {
3071 bool RequiresHighHalf = PtrTy.getSizeInBits() != 32;
3072
3073 if (RequiresHighHalf && ST.has64BitLiterals()) {
3074 if (!MRI.getRegClassOrNull(DstReg))
3075 MRI.setRegClass(DstReg, &AMDGPU::SReg_64RegClass);
3076 B.buildInstr(AMDGPU::S_MOV_B64)
3077 .addDef(DstReg)
3078 .addGlobalAddress(GV, 0, SIInstrInfo::MO_ABS64);
3079 return;
3080 }
3081
3082 LLT S32 = LLT::scalar(32);
3083
3084 // Use the destination directly, if and only if we store the lower address
3085 // part only and we don't have a register class being set.
3086 Register AddrLo = !RequiresHighHalf && !MRI.getRegClassOrNull(DstReg)
3087 ? DstReg
3088 : MRI.createGenericVirtualRegister(S32);
3089
3090 if (!MRI.getRegClassOrNull(AddrLo))
3091 MRI.setRegClass(AddrLo, &AMDGPU::SReg_32RegClass);
3092
3093 // Write the lower half.
3094 B.buildInstr(AMDGPU::S_MOV_B32)
3095 .addDef(AddrLo)
3096 .addGlobalAddress(GV, 0, SIInstrInfo::MO_ABS32_LO);
3097
3098 // If required, write the upper half as well.
3099 if (RequiresHighHalf) {
3100 assert(PtrTy.getSizeInBits() == 64 &&
3101 "Must provide a 64-bit pointer type!");
3102
3103 Register AddrHi = MRI.createGenericVirtualRegister(S32);
3104 MRI.setRegClass(AddrHi, &AMDGPU::SReg_32RegClass);
3105
3106 B.buildInstr(AMDGPU::S_MOV_B32)
3107 .addDef(AddrHi)
3108 .addGlobalAddress(GV, 0, SIInstrInfo::MO_ABS32_HI);
3109
3110 // Use the destination directly, if and only if we don't have a register
3111 // class being set.
3112 Register AddrDst = !MRI.getRegClassOrNull(DstReg)
3113 ? DstReg
3114 : MRI.createGenericVirtualRegister(LLT::scalar(64));
3115
3116 if (!MRI.getRegClassOrNull(AddrDst))
3117 MRI.setRegClass(AddrDst, &AMDGPU::SReg_64RegClass);
3118
3119 B.buildMergeValues(AddrDst, {AddrLo, AddrHi});
3120
3121 // If we created a new register for the destination, cast the result into
3122 // the final output.
3123 if (AddrDst != DstReg)
3124 B.buildCast(DstReg, AddrDst);
3125 } else if (AddrLo != DstReg) {
3126 // If we created a new register for the destination, cast the result into
3127 // the final output.
3128 B.buildCast(DstReg, AddrLo);
3129 }
3130}
3131
3134 MachineIRBuilder &B) const {
3135 Register DstReg = MI.getOperand(0).getReg();
3136 LLT Ty = MRI.getType(DstReg);
3137 unsigned AS = Ty.getAddressSpace();
3138
3139 const GlobalValue *GV = MI.getOperand(1).getGlobal();
3140 MachineFunction &MF = B.getMF();
3142
3144 if (!MFI->isModuleEntryFunction() &&
3145 GV->getName() != "llvm.amdgcn.module.lds" &&
3147 const Function &Fn = MF.getFunction();
3149 Fn, "local memory global used by non-kernel function",
3150 MI.getDebugLoc(), DS_Warning));
3151
3152 // We currently don't have a way to correctly allocate LDS objects that
3153 // aren't directly associated with a kernel. We do force inlining of
3154 // functions that use local objects. However, if these dead functions are
3155 // not eliminated, we don't want a compile time error. Just emit a warning
3156 // and a trap, since there should be no callable path here.
3157 B.buildTrap();
3158 B.buildUndef(DstReg);
3159 MI.eraseFromParent();
3160 return true;
3161 }
3162
3163 // TODO: We could emit code to handle the initialization somewhere.
3164 // We ignore the initializer for now and legalize it to allow selection.
3165 // The initializer will anyway get errored out during assembly emission.
3166 const SITargetLowering *TLI = ST.getTargetLowering();
3167 if (!TLI->shouldUseLDSConstAddress(GV)) {
3168 MI.getOperand(1).setTargetFlags(SIInstrInfo::MO_ABS32_LO);
3169 return true; // Leave in place;
3170 }
3171
3172 if (AS == AMDGPUAS::LOCAL_ADDRESS && GV->hasExternalLinkage()) {
3173 Type *Ty = GV->getValueType();
3174 // HIP uses an unsized array `extern __shared__ T s[]` or similar
3175 // zero-sized type in other languages to declare the dynamic shared
3176 // memory which size is not known at the compile time. They will be
3177 // allocated by the runtime and placed directly after the static
3178 // allocated ones. They all share the same offset.
3179 if (B.getDataLayout().getTypeAllocSize(Ty).isZero()) {
3180 // Adjust alignment for that dynamic shared memory array.
3182 LLT S32 = LLT::scalar(32);
3183 auto Sz = B.buildIntrinsic(Intrinsic::amdgcn_groupstaticsize, {S32});
3184 B.buildIntToPtr(DstReg, Sz);
3185 MI.eraseFromParent();
3186 return true;
3187 }
3188 }
3189
3190 B.buildConstant(DstReg, MFI->allocateLDSGlobal(B.getDataLayout(),
3191 *cast<GlobalVariable>(GV)));
3192 MI.eraseFromParent();
3193 return true;
3194 }
3195
3196 if (ST.isAmdPalOS() || ST.isMesa3DOS()) {
3197 buildAbsGlobalAddress(DstReg, Ty, B, GV, MRI);
3198 MI.eraseFromParent();
3199 return true;
3200 }
3201
3202 const SITargetLowering *TLI = ST.getTargetLowering();
3203
3204 if (TLI->shouldEmitFixup(GV)) {
3205 buildPCRelGlobalAddress(DstReg, Ty, B, GV, 0);
3206 MI.eraseFromParent();
3207 return true;
3208 }
3209
3210 if (TLI->shouldEmitPCReloc(GV)) {
3211 buildPCRelGlobalAddress(DstReg, Ty, B, GV, 0, SIInstrInfo::MO_REL32);
3212 MI.eraseFromParent();
3213 return true;
3214 }
3215
3217 Register GOTAddr = MRI.createGenericVirtualRegister(PtrTy);
3218
3219 LLT LoadTy = Ty.getSizeInBits() == 32 ? PtrTy : Ty;
3224 LoadTy, Align(8));
3225
3226 buildPCRelGlobalAddress(GOTAddr, PtrTy, B, GV, 0, SIInstrInfo::MO_GOTPCREL32);
3227
3228 if (Ty.getSizeInBits() == 32) {
3229 // Truncate if this is a 32-bit constant address.
3230 auto Load = B.buildLoad(PtrTy, GOTAddr, *GOTMMO);
3231 B.buildExtract(DstReg, Load, 0);
3232 } else
3233 B.buildLoad(DstReg, GOTAddr, *GOTMMO);
3234
3235 MI.eraseFromParent();
3236 return true;
3237}
3238
3240 if (Ty.isVector())
3241 return Ty.changeElementCount(
3242 ElementCount::getFixed(PowerOf2Ceil(Ty.getNumElements())));
3243 return LLT::scalar(PowerOf2Ceil(Ty.getSizeInBits()));
3244}
3245
3247 MachineInstr &MI) const {
3248 MachineIRBuilder &B = Helper.MIRBuilder;
3249 MachineRegisterInfo &MRI = *B.getMRI();
3250 GISelChangeObserver &Observer = Helper.Observer;
3251
3252 Register PtrReg = MI.getOperand(1).getReg();
3253 LLT PtrTy = MRI.getType(PtrReg);
3254 unsigned AddrSpace = PtrTy.getAddressSpace();
3255
3256 if (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
3258 auto Cast = B.buildAddrSpaceCast(ConstPtr, PtrReg);
3259 Observer.changingInstr(MI);
3260 MI.getOperand(1).setReg(Cast.getReg(0));
3261 Observer.changedInstr(MI);
3262 return true;
3263 }
3264
3265 if (MI.getOpcode() != AMDGPU::G_LOAD)
3266 return false;
3267
3268 Register ValReg = MI.getOperand(0).getReg();
3269 LLT ValTy = MRI.getType(ValReg);
3270
3271 if (hasBufferRsrcWorkaround(ValTy)) {
3272 Observer.changingInstr(MI);
3274 Observer.changedInstr(MI);
3275 return true;
3276 }
3277
3278 MachineMemOperand *MMO = *MI.memoperands_begin();
3279 const unsigned ValSize = ValTy.getSizeInBits();
3280 const LLT MemTy = MMO->getMemoryType();
3281 const Align MemAlign = MMO->getAlign();
3282 const unsigned MemSize = MemTy.getSizeInBits();
3283 const uint64_t AlignInBits = 8 * MemAlign.value();
3284
3285 // Widen non-power-of-2 loads to the alignment if needed
3286 if (shouldWidenLoad(ST, MemTy, AlignInBits, AddrSpace, MI.getOpcode())) {
3287 const unsigned WideMemSize = PowerOf2Ceil(MemSize);
3288
3289 // This was already the correct extending load result type, so just adjust
3290 // the memory type.
3291 if (WideMemSize == ValSize) {
3292 MachineFunction &MF = B.getMF();
3293
3294 MachineMemOperand *WideMMO =
3295 MF.getMachineMemOperand(MMO, 0, WideMemSize / 8);
3296 Observer.changingInstr(MI);
3297 MI.setMemRefs(MF, {WideMMO});
3298 Observer.changedInstr(MI);
3299 return true;
3300 }
3301
3302 // Don't bother handling edge case that should probably never be produced.
3303 if (ValSize > WideMemSize)
3304 return false;
3305
3306 LLT WideTy = widenToNextPowerOf2(ValTy);
3307
3308 Register WideLoad;
3309 if (!WideTy.isVector()) {
3310 WideLoad = B.buildLoadFromOffset(WideTy, PtrReg, *MMO, 0).getReg(0);
3311 B.buildTrunc(ValReg, WideLoad).getReg(0);
3312 } else {
3313 // Extract the subvector.
3314
3315 if (isRegisterType(ST, ValTy)) {
3316 // If this a case where G_EXTRACT is legal, use it.
3317 // (e.g. <3 x s32> -> <4 x s32>)
3318 WideLoad = B.buildLoadFromOffset(WideTy, PtrReg, *MMO, 0).getReg(0);
3319 B.buildExtract(ValReg, WideLoad, 0);
3320 } else {
3321 // For cases where the widened type isn't a nice register value, unmerge
3322 // from a widened register (e.g. <3 x s16> -> <4 x s16>)
3323 WideLoad = B.buildLoadFromOffset(WideTy, PtrReg, *MMO, 0).getReg(0);
3324 B.buildDeleteTrailingVectorElements(ValReg, WideLoad);
3325 }
3326 }
3327
3328 MI.eraseFromParent();
3329 return true;
3330 }
3331
3332 return false;
3333}
3334
3336 MachineInstr &MI) const {
3337 MachineIRBuilder &B = Helper.MIRBuilder;
3338 MachineRegisterInfo &MRI = *B.getMRI();
3339 GISelChangeObserver &Observer = Helper.Observer;
3340
3341 Register DataReg = MI.getOperand(0).getReg();
3342 LLT DataTy = MRI.getType(DataReg);
3343
3344 if (hasBufferRsrcWorkaround(DataTy)) {
3345 Observer.changingInstr(MI);
3347 Observer.changedInstr(MI);
3348 return true;
3349 }
3350 return false;
3351}
3352
3355 MachineIRBuilder &B) const {
3356 LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3357 assert(Ty.isScalar());
3358
3359 MachineFunction &MF = B.getMF();
3361
3362 // TODO: Always legal with future ftz flag.
3363 // FIXME: Do we need just output?
3364 if (Ty == LLT::float32() &&
3366 return true;
3367 if (Ty == LLT::float16() &&
3369 return true;
3370
3371 MachineIRBuilder HelperBuilder(MI);
3372 GISelObserverWrapper DummyObserver;
3373 LegalizerHelper Helper(MF, DummyObserver, HelperBuilder);
3374 return Helper.lowerFMad(MI) == LegalizerHelper::Legalized;
3375}
3376
3379 Register DstReg = MI.getOperand(0).getReg();
3380 Register PtrReg = MI.getOperand(1).getReg();
3381 Register CmpVal = MI.getOperand(2).getReg();
3382 Register NewVal = MI.getOperand(3).getReg();
3383
3384 assert(AMDGPU::isFlatGlobalAddrSpace(MRI.getType(PtrReg).getAddressSpace()) &&
3385 "this should not have been custom lowered");
3386
3387 LLT ValTy = MRI.getType(CmpVal);
3388 LLT VecTy = LLT::fixed_vector(2, ValTy);
3389
3390 Register PackedVal = B.buildBuildVector(VecTy, { NewVal, CmpVal }).getReg(0);
3391
3392 B.buildInstr(AMDGPU::G_AMDGPU_ATOMIC_CMPXCHG)
3393 .addDef(DstReg)
3394 .addUse(PtrReg)
3395 .addUse(PackedVal)
3396 .setMemRefs(MI.memoperands());
3397
3398 MI.eraseFromParent();
3399 return true;
3400}
3401
3402/// Return true if it's known that \p Src can never be an f32 denormal value.
3404 Register Src) {
3405 const MachineInstr *DefMI = MRI.getVRegDef(Src);
3406 switch (DefMI->getOpcode()) {
3407 case TargetOpcode::G_INTRINSIC: {
3409 case Intrinsic::amdgcn_frexp_mant:
3410 return true;
3411 default:
3412 break;
3413 }
3414
3415 break;
3416 }
3417 case TargetOpcode::G_FFREXP: {
3418 if (DefMI->getOperand(0).getReg() == Src)
3419 return true;
3420 break;
3421 }
3422 case TargetOpcode::G_FPEXT: {
3423 return MRI.getType(DefMI->getOperand(1).getReg()) == LLT::scalar(16);
3424 }
3425 default:
3426 return false;
3427 }
3428
3429 return false;
3430}
3431
3432static bool allowApproxFunc(const MachineFunction &MF, unsigned Flags) {
3433 return Flags & MachineInstr::FmAfn;
3434}
3435
3437 unsigned Flags) {
3438 return !valueIsKnownNeverF32Denorm(MF.getRegInfo(), Src) &&
3441}
3442
3443std::pair<Register, Register>
3445 unsigned Flags) const {
3446 if (!needsDenormHandlingF32(B.getMF(), Src, Flags))
3447 return {};
3448
3449 const LLT F32 = LLT::scalar(32);
3450 auto SmallestNormal = B.buildFConstant(
3452 auto IsLtSmallestNormal =
3453 B.buildFCmp(CmpInst::FCMP_OLT, LLT::scalar(1), Src, SmallestNormal);
3454
3455 auto Scale32 = B.buildFConstant(F32, 0x1.0p+32);
3456 auto One = B.buildFConstant(F32, 1.0);
3457 auto ScaleFactor =
3458 B.buildSelect(F32, IsLtSmallestNormal, Scale32, One, Flags);
3459 auto ScaledInput = B.buildFMul(F32, Src, ScaleFactor, Flags);
3460
3461 return {ScaledInput.getReg(0), IsLtSmallestNormal.getReg(0)};
3462}
3463
3465 MachineIRBuilder &B) const {
3466 // v_log_f32 is good enough for OpenCL, except it doesn't handle denormals.
3467 // If we have to handle denormals, scale up the input and adjust the result.
3468
3469 // scaled = x * (is_denormal ? 0x1.0p+32 : 1.0)
3470 // log2 = amdgpu_log2 - (is_denormal ? 32.0 : 0.0)
3471
3472 Register Dst = MI.getOperand(0).getReg();
3473 Register Src = MI.getOperand(1).getReg();
3474 LLT Ty = B.getMRI()->getType(Dst);
3475 unsigned Flags = MI.getFlags();
3476
3477 if (Ty == LLT::scalar(16)) {
3478 const LLT F32 = LLT::scalar(32);
3479 // Nothing in half is a denormal when promoted to f32.
3480 auto Ext = B.buildFPExt(F32, Src, Flags);
3481 auto Log2 = B.buildIntrinsic(Intrinsic::amdgcn_log, {F32})
3482 .addUse(Ext.getReg(0))
3483 .setMIFlags(Flags);
3484 B.buildFPTrunc(Dst, Log2, Flags);
3485 MI.eraseFromParent();
3486 return true;
3487 }
3488
3489 assert(Ty == LLT::scalar(32));
3490
3491 auto [ScaledInput, IsLtSmallestNormal] = getScaledLogInput(B, Src, Flags);
3492 if (!ScaledInput) {
3493 B.buildIntrinsic(Intrinsic::amdgcn_log, {MI.getOperand(0)})
3494 .addUse(Src)
3495 .setMIFlags(Flags);
3496 MI.eraseFromParent();
3497 return true;
3498 }
3499
3500 auto Log2 = B.buildIntrinsic(Intrinsic::amdgcn_log, {Ty})
3501 .addUse(ScaledInput)
3502 .setMIFlags(Flags);
3503
3504 auto ThirtyTwo = B.buildFConstant(Ty, 32.0);
3505 auto Zero = B.buildFConstant(Ty, 0.0);
3506 auto ResultOffset =
3507 B.buildSelect(Ty, IsLtSmallestNormal, ThirtyTwo, Zero, Flags);
3508 B.buildFSub(Dst, Log2, ResultOffset, Flags);
3509
3510 MI.eraseFromParent();
3511 return true;
3512}
3513
3515 Register Z, unsigned Flags) {
3516 auto FMul = B.buildFMul(Ty, X, Y, Flags);
3517 return B.buildFAdd(Ty, FMul, Z, Flags).getReg(0);
3518}
3519
3521 MachineIRBuilder &B) const {
3522 const bool IsLog10 = MI.getOpcode() == TargetOpcode::G_FLOG10;
3523 assert(IsLog10 || MI.getOpcode() == TargetOpcode::G_FLOG);
3524
3525 MachineRegisterInfo &MRI = *B.getMRI();
3526 Register Dst = MI.getOperand(0).getReg();
3527 Register X = MI.getOperand(1).getReg();
3528 unsigned Flags = MI.getFlags();
3529 const LLT Ty = MRI.getType(X);
3530 MachineFunction &MF = B.getMF();
3531
3532 const LLT F32 = LLT::scalar(32);
3533 const LLT F16 = LLT::scalar(16);
3534
3535 const AMDGPUTargetMachine &TM =
3536 static_cast<const AMDGPUTargetMachine &>(MF.getTarget());
3537
3538 if (Ty == F16 || MI.getFlag(MachineInstr::FmAfn)) {
3539 if (Ty == F16 && !ST.has16BitInsts()) {
3540 Register LogVal = MRI.createGenericVirtualRegister(F32);
3541 auto PromoteSrc = B.buildFPExt(F32, X);
3542 legalizeFlogUnsafe(B, LogVal, PromoteSrc.getReg(0), IsLog10, Flags);
3543 B.buildFPTrunc(Dst, LogVal);
3544 } else {
3545 legalizeFlogUnsafe(B, Dst, X, IsLog10, Flags);
3546 }
3547
3548 MI.eraseFromParent();
3549 return true;
3550 }
3551
3552 auto [ScaledInput, IsScaled] = getScaledLogInput(B, X, Flags);
3553 if (ScaledInput)
3554 X = ScaledInput;
3555
3556 auto Y =
3557 B.buildIntrinsic(Intrinsic::amdgcn_log, {Ty}).addUse(X).setMIFlags(Flags);
3558
3559 Register R;
3560 if (ST.hasFastFMAF32()) {
3561 // c+cc are ln(2)/ln(10) to more than 49 bits
3562 const float c_log10 = 0x1.344134p-2f;
3563 const float cc_log10 = 0x1.09f79ep-26f;
3564
3565 // c + cc is ln(2) to more than 49 bits
3566 const float c_log = 0x1.62e42ep-1f;
3567 const float cc_log = 0x1.efa39ep-25f;
3568
3569 auto C = B.buildFConstant(Ty, IsLog10 ? c_log10 : c_log);
3570 auto CC = B.buildFConstant(Ty, IsLog10 ? cc_log10 : cc_log);
3571 // This adds correction terms for which contraction may lead to an increase
3572 // in the error of the approximation, so disable it.
3573 auto NewFlags = Flags & ~(MachineInstr::FmContract);
3574 R = B.buildFMul(Ty, Y, C, NewFlags).getReg(0);
3575 auto NegR = B.buildFNeg(Ty, R, NewFlags);
3576 auto FMA0 = B.buildFMA(Ty, Y, C, NegR, NewFlags);
3577 auto FMA1 = B.buildFMA(Ty, Y, CC, FMA0, NewFlags);
3578 R = B.buildFAdd(Ty, R, FMA1, NewFlags).getReg(0);
3579 } else {
3580 // ch+ct is ln(2)/ln(10) to more than 36 bits
3581 const float ch_log10 = 0x1.344000p-2f;
3582 const float ct_log10 = 0x1.3509f6p-18f;
3583
3584 // ch + ct is ln(2) to more than 36 bits
3585 const float ch_log = 0x1.62e000p-1f;
3586 const float ct_log = 0x1.0bfbe8p-15f;
3587
3588 auto CH = B.buildFConstant(Ty, IsLog10 ? ch_log10 : ch_log);
3589 auto CT = B.buildFConstant(Ty, IsLog10 ? ct_log10 : ct_log);
3590
3591 auto MaskConst = B.buildConstant(Ty, 0xfffff000);
3592 auto YH = B.buildAnd(Ty, Y, MaskConst);
3593 auto YT = B.buildFSub(Ty, Y, YH, Flags);
3594 // This adds correction terms for which contraction may lead to an increase
3595 // in the error of the approximation, so disable it.
3596 auto NewFlags = Flags & ~(MachineInstr::FmContract);
3597 auto YTCT = B.buildFMul(Ty, YT, CT, NewFlags);
3598
3599 Register Mad0 =
3600 getMad(B, Ty, YH.getReg(0), CT.getReg(0), YTCT.getReg(0), NewFlags);
3601 Register Mad1 = getMad(B, Ty, YT.getReg(0), CH.getReg(0), Mad0, NewFlags);
3602 R = getMad(B, Ty, YH.getReg(0), CH.getReg(0), Mad1, NewFlags);
3603 }
3604
3605 const bool IsFiniteOnly =
3606 (MI.getFlag(MachineInstr::FmNoNans) || TM.Options.NoNaNsFPMath) &&
3607 MI.getFlag(MachineInstr::FmNoInfs);
3608
3609 if (!IsFiniteOnly) {
3610 // Expand isfinite(x) => fabs(x) < inf
3611 auto Inf = B.buildFConstant(Ty, APFloat::getInf(APFloat::IEEEsingle()));
3612 auto Fabs = B.buildFAbs(Ty, Y);
3613 auto IsFinite =
3614 B.buildFCmp(CmpInst::FCMP_OLT, LLT::scalar(1), Fabs, Inf, Flags);
3615 R = B.buildSelect(Ty, IsFinite, R, Y, Flags).getReg(0);
3616 }
3617
3618 if (ScaledInput) {
3619 auto Zero = B.buildFConstant(Ty, 0.0);
3620 auto ShiftK =
3621 B.buildFConstant(Ty, IsLog10 ? 0x1.344136p+3f : 0x1.62e430p+4f);
3622 auto Shift = B.buildSelect(Ty, IsScaled, ShiftK, Zero, Flags);
3623 B.buildFSub(Dst, R, Shift, Flags);
3624 } else {
3625 B.buildCopy(Dst, R);
3626 }
3627
3628 MI.eraseFromParent();
3629 return true;
3630}
3631
3633 Register Src, bool IsLog10,
3634 unsigned Flags) const {
3635 const double Log2BaseInverted =
3637
3638 LLT Ty = B.getMRI()->getType(Dst);
3639
3640 if (Ty == LLT::scalar(32)) {
3641 auto [ScaledInput, IsScaled] = getScaledLogInput(B, Src, Flags);
3642 if (ScaledInput) {
3643 auto LogSrc = B.buildIntrinsic(Intrinsic::amdgcn_log, {Ty})
3644 .addUse(Src)
3645 .setMIFlags(Flags);
3646 auto ScaledResultOffset = B.buildFConstant(Ty, -32.0 * Log2BaseInverted);
3647 auto Zero = B.buildFConstant(Ty, 0.0);
3648 auto ResultOffset =
3649 B.buildSelect(Ty, IsScaled, ScaledResultOffset, Zero, Flags);
3650 auto Log2Inv = B.buildFConstant(Ty, Log2BaseInverted);
3651
3652 if (ST.hasFastFMAF32())
3653 B.buildFMA(Dst, LogSrc, Log2Inv, ResultOffset, Flags);
3654 else {
3655 auto Mul = B.buildFMul(Ty, LogSrc, Log2Inv, Flags);
3656 B.buildFAdd(Dst, Mul, ResultOffset, Flags);
3657 }
3658
3659 return true;
3660 }
3661 }
3662
3663 auto Log2Operand = Ty == LLT::scalar(16)
3664 ? B.buildFLog2(Ty, Src, Flags)
3665 : B.buildIntrinsic(Intrinsic::amdgcn_log, {Ty})
3666 .addUse(Src)
3667 .setMIFlags(Flags);
3668 auto Log2BaseInvertedOperand = B.buildFConstant(Ty, Log2BaseInverted);
3669 B.buildFMul(Dst, Log2Operand, Log2BaseInvertedOperand, Flags);
3670 return true;
3671}
3672
3674 MachineIRBuilder &B) const {
3675 // v_exp_f32 is good enough for OpenCL, except it doesn't handle denormals.
3676 // If we have to handle denormals, scale up the input and adjust the result.
3677
3678 Register Dst = MI.getOperand(0).getReg();
3679 Register Src = MI.getOperand(1).getReg();
3680 unsigned Flags = MI.getFlags();
3681 LLT Ty = B.getMRI()->getType(Dst);
3682 const LLT F16 = LLT::scalar(16);
3683 const LLT F32 = LLT::scalar(32);
3684
3685 if (Ty == F16) {
3686 // Nothing in half is a denormal when promoted to f32.
3687 auto Ext = B.buildFPExt(F32, Src, Flags);
3688 auto Log2 = B.buildIntrinsic(Intrinsic::amdgcn_exp2, {F32})
3689 .addUse(Ext.getReg(0))
3690 .setMIFlags(Flags);
3691 B.buildFPTrunc(Dst, Log2, Flags);
3692 MI.eraseFromParent();
3693 return true;
3694 }
3695
3696 assert(Ty == F32);
3697
3698 if (!needsDenormHandlingF32(B.getMF(), Src, Flags)) {
3699 B.buildIntrinsic(Intrinsic::amdgcn_exp2, ArrayRef<Register>{Dst})
3700 .addUse(Src)
3701 .setMIFlags(Flags);
3702 MI.eraseFromParent();
3703 return true;
3704 }
3705
3706 // bool needs_scaling = x < -0x1.f80000p+6f;
3707 // v_exp_f32(x + (s ? 0x1.0p+6f : 0.0f)) * (s ? 0x1.0p-64f : 1.0f);
3708
3709 // -nextafter(128.0, -1)
3710 auto RangeCheckConst = B.buildFConstant(Ty, -0x1.f80000p+6f);
3711 auto NeedsScaling = B.buildFCmp(CmpInst::FCMP_OLT, LLT::scalar(1), Src,
3712 RangeCheckConst, Flags);
3713
3714 auto SixtyFour = B.buildFConstant(Ty, 0x1.0p+6f);
3715 auto Zero = B.buildFConstant(Ty, 0.0);
3716 auto AddOffset = B.buildSelect(F32, NeedsScaling, SixtyFour, Zero, Flags);
3717 auto AddInput = B.buildFAdd(F32, Src, AddOffset, Flags);
3718
3719 auto Exp2 = B.buildIntrinsic(Intrinsic::amdgcn_exp2, {Ty})
3720 .addUse(AddInput.getReg(0))
3721 .setMIFlags(Flags);
3722
3723 auto TwoExpNeg64 = B.buildFConstant(Ty, 0x1.0p-64f);
3724 auto One = B.buildFConstant(Ty, 1.0);
3725 auto ResultScale = B.buildSelect(F32, NeedsScaling, TwoExpNeg64, One, Flags);
3726 B.buildFMul(Dst, Exp2, ResultScale, Flags);
3727 MI.eraseFromParent();
3728 return true;
3729}
3730
3732 const SrcOp &Src, unsigned Flags) {
3733 LLT Ty = Dst.getLLTTy(*B.getMRI());
3734
3735 if (Ty == LLT::scalar(32)) {
3736 return B.buildIntrinsic(Intrinsic::amdgcn_exp2, {Dst})
3737 .addUse(Src.getReg())
3738 .setMIFlags(Flags);
3739 }
3740 return B.buildFExp2(Dst, Src, Flags);
3741}
3742
3744 Register Dst, Register X,
3745 unsigned Flags,
3746 bool IsExp10) const {
3747 LLT Ty = B.getMRI()->getType(X);
3748
3749 // exp(x) -> exp2(M_LOG2E_F * x);
3750 // exp10(x) -> exp2(log2(10) * x);
3751 auto Const = B.buildFConstant(Ty, IsExp10 ? 0x1.a934f0p+1f : numbers::log2e);
3752 auto Mul = B.buildFMul(Ty, X, Const, Flags);
3753 buildExp(B, Dst, Mul, Flags);
3754 return true;
3755}
3756
3758 Register X, unsigned Flags) const {
3759 LLT Ty = B.getMRI()->getType(Dst);
3760 LLT F32 = LLT::scalar(32);
3761
3762 if (Ty != F32 || !needsDenormHandlingF32(B.getMF(), X, Flags)) {
3763 return legalizeFExpUnsafeImpl(B, Dst, X, Flags, /*IsExp10=*/false);
3764 }
3765
3766 auto Threshold = B.buildFConstant(Ty, -0x1.5d58a0p+6f);
3767 auto NeedsScaling =
3768 B.buildFCmp(CmpInst::FCMP_OLT, LLT::scalar(1), X, Threshold, Flags);
3769 auto ScaleOffset = B.buildFConstant(Ty, 0x1.0p+6f);
3770 auto ScaledX = B.buildFAdd(Ty, X, ScaleOffset, Flags);
3771 auto AdjustedX = B.buildSelect(Ty, NeedsScaling, ScaledX, X, Flags);
3772
3773 auto Log2E = B.buildFConstant(Ty, numbers::log2e);
3774 auto ExpInput = B.buildFMul(Ty, AdjustedX, Log2E, Flags);
3775
3776 auto Exp2 = B.buildIntrinsic(Intrinsic::amdgcn_exp2, {Ty})
3777 .addUse(ExpInput.getReg(0))
3778 .setMIFlags(Flags);
3779
3780 auto ResultScaleFactor = B.buildFConstant(Ty, 0x1.969d48p-93f);
3781 auto AdjustedResult = B.buildFMul(Ty, Exp2, ResultScaleFactor, Flags);
3782 B.buildSelect(Dst, NeedsScaling, AdjustedResult, Exp2, Flags);
3783 return true;
3784}
3785
3787 Register Dst, Register X,
3788 unsigned Flags) const {
3789 LLT Ty = B.getMRI()->getType(Dst);
3790 LLT F32 = LLT::scalar(32);
3791
3792 if (Ty != F32 || !needsDenormHandlingF32(B.getMF(), X, Flags)) {
3793 // exp2(x * 0x1.a92000p+1f) * exp2(x * 0x1.4f0978p-11f);
3794 auto K0 = B.buildFConstant(Ty, 0x1.a92000p+1f);
3795 auto K1 = B.buildFConstant(Ty, 0x1.4f0978p-11f);
3796
3797 auto Mul1 = B.buildFMul(Ty, X, K1, Flags);
3798 auto Exp2_1 = buildExp(B, Ty, Mul1, Flags);
3799 auto Mul0 = B.buildFMul(Ty, X, K0, Flags);
3800 auto Exp2_0 = buildExp(B, Ty, Mul0, Flags);
3801 B.buildFMul(Dst, Exp2_0, Exp2_1, Flags);
3802 return true;
3803 }
3804
3805 // bool s = x < -0x1.2f7030p+5f;
3806 // x += s ? 0x1.0p+5f : 0.0f;
3807 // exp10 = exp2(x * 0x1.a92000p+1f) *
3808 // exp2(x * 0x1.4f0978p-11f) *
3809 // (s ? 0x1.9f623ep-107f : 1.0f);
3810
3811 auto Threshold = B.buildFConstant(Ty, -0x1.2f7030p+5f);
3812 auto NeedsScaling =
3813 B.buildFCmp(CmpInst::FCMP_OLT, LLT::scalar(1), X, Threshold);
3814
3815 auto ScaleOffset = B.buildFConstant(Ty, 0x1.0p+5f);
3816 auto ScaledX = B.buildFAdd(Ty, X, ScaleOffset, Flags);
3817 auto AdjustedX = B.buildSelect(Ty, NeedsScaling, ScaledX, X);
3818
3819 auto K0 = B.buildFConstant(Ty, 0x1.a92000p+1f);
3820 auto K1 = B.buildFConstant(Ty, 0x1.4f0978p-11f);
3821
3822 auto Mul1 = B.buildFMul(Ty, AdjustedX, K1, Flags);
3823 auto Exp2_1 = buildExp(B, Ty, Mul1, Flags);
3824 auto Mul0 = B.buildFMul(Ty, AdjustedX, K0, Flags);
3825 auto Exp2_0 = buildExp(B, Ty, Mul0, Flags);
3826
3827 auto MulExps = B.buildFMul(Ty, Exp2_0, Exp2_1, Flags);
3828 auto ResultScaleFactor = B.buildFConstant(Ty, 0x1.9f623ep-107f);
3829 auto AdjustedResult = B.buildFMul(Ty, MulExps, ResultScaleFactor, Flags);
3830
3831 B.buildSelect(Dst, NeedsScaling, AdjustedResult, MulExps);
3832 return true;
3833}
3834
3836 MachineIRBuilder &B) const {
3837 Register Dst = MI.getOperand(0).getReg();
3838 Register X = MI.getOperand(1).getReg();
3839 const unsigned Flags = MI.getFlags();
3840 MachineFunction &MF = B.getMF();
3841 MachineRegisterInfo &MRI = *B.getMRI();
3842 LLT Ty = MRI.getType(Dst);
3843 const LLT F16 = LLT::scalar(16);
3844 const LLT F32 = LLT::scalar(32);
3845 const bool IsExp10 = MI.getOpcode() == TargetOpcode::G_FEXP10;
3846
3847 if (Ty == F16) {
3848 // v_exp_f16 (fmul x, log2e)
3849 if (allowApproxFunc(MF, Flags)) {
3850 // TODO: Does this really require fast?
3851 IsExp10 ? legalizeFExp10Unsafe(B, Dst, X, Flags)
3852 : legalizeFExpUnsafe(B, Dst, X, Flags);
3853 MI.eraseFromParent();
3854 return true;
3855 }
3856
3857 // Nothing in half is a denormal when promoted to f32.
3858 //
3859 // exp(f16 x) ->
3860 // fptrunc (v_exp_f32 (fmul (fpext x), log2e))
3861 //
3862 // exp10(f16 x) ->
3863 // fptrunc (v_exp_f32 (fmul (fpext x), log2(10)))
3864 auto Ext = B.buildFPExt(F32, X, Flags);
3865 Register Lowered = MRI.createGenericVirtualRegister(F32);
3866 legalizeFExpUnsafeImpl(B, Lowered, Ext.getReg(0), Flags, IsExp10);
3867 B.buildFPTrunc(Dst, Lowered, Flags);
3868 MI.eraseFromParent();
3869 return true;
3870 }
3871
3872 assert(Ty == F32);
3873
3874 // TODO: Interpret allowApproxFunc as ignoring DAZ. This is currently copying
3875 // library behavior. Also, is known-not-daz source sufficient?
3876 if (allowApproxFunc(MF, Flags)) {
3877 IsExp10 ? legalizeFExp10Unsafe(B, Dst, X, Flags)
3878 : legalizeFExpUnsafe(B, Dst, X, Flags);
3879 MI.eraseFromParent();
3880 return true;
3881 }
3882
3883 // Algorithm:
3884 //
3885 // e^x = 2^(x/ln(2)) = 2^(x*(64/ln(2))/64)
3886 //
3887 // x*(64/ln(2)) = n + f, |f| <= 0.5, n is integer
3888 // n = 64*m + j, 0 <= j < 64
3889 //
3890 // e^x = 2^((64*m + j + f)/64)
3891 // = (2^m) * (2^(j/64)) * 2^(f/64)
3892 // = (2^m) * (2^(j/64)) * e^(f*(ln(2)/64))
3893 //
3894 // f = x*(64/ln(2)) - n
3895 // r = f*(ln(2)/64) = x - n*(ln(2)/64)
3896 //
3897 // e^x = (2^m) * (2^(j/64)) * e^r
3898 //
3899 // (2^(j/64)) is precomputed
3900 //
3901 // e^r = 1 + r + (r^2)/2! + (r^3)/3! + (r^4)/4! + (r^5)/5!
3902 // e^r = 1 + q
3903 //
3904 // q = r + (r^2)/2! + (r^3)/3! + (r^4)/4! + (r^5)/5!
3905 //
3906 // e^x = (2^m) * ( (2^(j/64)) + q*(2^(j/64)) )
3907 const unsigned FlagsNoContract = Flags & ~MachineInstr::FmContract;
3908 Register PH, PL;
3909
3910 if (ST.hasFastFMAF32()) {
3911 const float c_exp = numbers::log2ef;
3912 const float cc_exp = 0x1.4ae0bep-26f; // c+cc are 49 bits
3913 const float c_exp10 = 0x1.a934f0p+1f;
3914 const float cc_exp10 = 0x1.2f346ep-24f;
3915
3916 auto C = B.buildFConstant(Ty, IsExp10 ? c_exp10 : c_exp);
3917 PH = B.buildFMul(Ty, X, C, Flags).getReg(0);
3918 auto NegPH = B.buildFNeg(Ty, PH, Flags);
3919 auto FMA0 = B.buildFMA(Ty, X, C, NegPH, Flags);
3920
3921 auto CC = B.buildFConstant(Ty, IsExp10 ? cc_exp10 : cc_exp);
3922 PL = B.buildFMA(Ty, X, CC, FMA0, Flags).getReg(0);
3923 } else {
3924 const float ch_exp = 0x1.714000p+0f;
3925 const float cl_exp = 0x1.47652ap-12f; // ch + cl are 36 bits
3926
3927 const float ch_exp10 = 0x1.a92000p+1f;
3928 const float cl_exp10 = 0x1.4f0978p-11f;
3929
3930 auto MaskConst = B.buildConstant(Ty, 0xfffff000);
3931 auto XH = B.buildAnd(Ty, X, MaskConst);
3932 auto XL = B.buildFSub(Ty, X, XH, Flags);
3933
3934 auto CH = B.buildFConstant(Ty, IsExp10 ? ch_exp10 : ch_exp);
3935 PH = B.buildFMul(Ty, XH, CH, Flags).getReg(0);
3936
3937 auto CL = B.buildFConstant(Ty, IsExp10 ? cl_exp10 : cl_exp);
3938 auto XLCL = B.buildFMul(Ty, XL, CL, Flags);
3939
3940 Register Mad0 =
3941 getMad(B, Ty, XL.getReg(0), CH.getReg(0), XLCL.getReg(0), Flags);
3942 PL = getMad(B, Ty, XH.getReg(0), CL.getReg(0), Mad0, Flags);
3943 }
3944
3945 auto E = B.buildIntrinsicRoundeven(Ty, PH, Flags);
3946
3947 // It is unsafe to contract this fsub into the PH multiply.
3948 auto PHSubE = B.buildFSub(Ty, PH, E, FlagsNoContract);
3949 auto A = B.buildFAdd(Ty, PHSubE, PL, Flags);
3950 auto IntE = B.buildFPTOSI(LLT::scalar(32), E);
3951
3952 auto Exp2 = B.buildIntrinsic(Intrinsic::amdgcn_exp2, {Ty})
3953 .addUse(A.getReg(0))
3954 .setMIFlags(Flags);
3955 auto R = B.buildFLdexp(Ty, Exp2, IntE, Flags);
3956
3957 auto UnderflowCheckConst =
3958 B.buildFConstant(Ty, IsExp10 ? -0x1.66d3e8p+5f : -0x1.9d1da0p+6f);
3959 auto Zero = B.buildFConstant(Ty, 0.0);
3960 auto Underflow =
3961 B.buildFCmp(CmpInst::FCMP_OLT, LLT::scalar(1), X, UnderflowCheckConst);
3962
3963 R = B.buildSelect(Ty, Underflow, Zero, R);
3964
3965 if (!(Flags & MachineInstr::FmNoInfs)) {
3966 auto OverflowCheckConst =
3967 B.buildFConstant(Ty, IsExp10 ? 0x1.344136p+5f : 0x1.62e430p+6f);
3968
3969 auto Overflow =
3970 B.buildFCmp(CmpInst::FCMP_OGT, LLT::scalar(1), X, OverflowCheckConst);
3971 auto Inf = B.buildFConstant(Ty, APFloat::getInf(APFloat::IEEEsingle()));
3972 R = B.buildSelect(Ty, Overflow, Inf, R, Flags);
3973 }
3974
3975 B.buildCopy(Dst, R);
3976 MI.eraseFromParent();
3977 return true;
3978}
3979
3981 MachineIRBuilder &B) const {
3982 Register Dst = MI.getOperand(0).getReg();
3983 Register Src0 = MI.getOperand(1).getReg();
3984 Register Src1 = MI.getOperand(2).getReg();
3985 unsigned Flags = MI.getFlags();
3986 LLT Ty = B.getMRI()->getType(Dst);
3987 const LLT F16 = LLT::float16();
3988 const LLT F32 = LLT::float32();
3989
3990 if (Ty == F32) {
3991 auto Log = B.buildFLog2(F32, Src0, Flags);
3992 auto Mul = B.buildIntrinsic(Intrinsic::amdgcn_fmul_legacy, {F32})
3993 .addUse(Log.getReg(0))
3994 .addUse(Src1)
3995 .setMIFlags(Flags);
3996 B.buildFExp2(Dst, Mul, Flags);
3997 } else if (Ty == F16) {
3998 // There's no f16 fmul_legacy, so we need to convert for it.
3999 auto Log = B.buildFLog2(F16, Src0, Flags);
4000 auto Ext0 = B.buildFPExt(F32, Log, Flags);
4001 auto Ext1 = B.buildFPExt(F32, Src1, Flags);
4002 auto Mul = B.buildIntrinsic(Intrinsic::amdgcn_fmul_legacy, {F32})
4003 .addUse(Ext0.getReg(0))
4004 .addUse(Ext1.getReg(0))
4005 .setMIFlags(Flags);
4006 B.buildFExp2(Dst, B.buildFPTrunc(F16, Mul), Flags);
4007 } else
4008 return false;
4009
4010 MI.eraseFromParent();
4011 return true;
4012}
4013
4014// Find a source register, ignoring any possible source modifiers.
4016 Register ModSrc = OrigSrc;
4017 if (MachineInstr *SrcFNeg = getOpcodeDef(AMDGPU::G_FNEG, ModSrc, MRI)) {
4018 ModSrc = SrcFNeg->getOperand(1).getReg();
4019 if (MachineInstr *SrcFAbs = getOpcodeDef(AMDGPU::G_FABS, ModSrc, MRI))
4020 ModSrc = SrcFAbs->getOperand(1).getReg();
4021 } else if (MachineInstr *SrcFAbs = getOpcodeDef(AMDGPU::G_FABS, ModSrc, MRI))
4022 ModSrc = SrcFAbs->getOperand(1).getReg();
4023 return ModSrc;
4024}
4025
4028 MachineIRBuilder &B) const {
4029
4030 const LLT S1 = LLT::scalar(1);
4031 const LLT F64 = LLT::float64();
4032 Register Dst = MI.getOperand(0).getReg();
4033 Register OrigSrc = MI.getOperand(1).getReg();
4034 unsigned Flags = MI.getFlags();
4035 assert(ST.hasFractBug() && MRI.getType(Dst) == F64 &&
4036 "this should not have been custom lowered");
4037
4038 // V_FRACT is buggy on SI, so the F32 version is never used and (x-floor(x))
4039 // is used instead. However, SI doesn't have V_FLOOR_F64, so the most
4040 // efficient way to implement it is using V_FRACT_F64. The workaround for the
4041 // V_FRACT bug is:
4042 // fract(x) = isnan(x) ? x : min(V_FRACT(x), 0.99999999999999999)
4043 //
4044 // Convert floor(x) to (x - fract(x))
4045
4046 auto Fract = B.buildIntrinsic(Intrinsic::amdgcn_fract, {F64})
4047 .addUse(OrigSrc)
4048 .setMIFlags(Flags);
4049
4050 // Give source modifier matching some assistance before obscuring a foldable
4051 // pattern.
4052
4053 // TODO: We can avoid the neg on the fract? The input sign to fract
4054 // shouldn't matter?
4055 Register ModSrc = stripAnySourceMods(OrigSrc, MRI);
4056
4057 auto Const =
4058 B.buildFConstant(F64, llvm::bit_cast<double>(0x3fefffffffffffff));
4059
4060 Register Min = MRI.createGenericVirtualRegister(F64);
4061
4062 // We don't need to concern ourselves with the snan handling difference, so
4063 // use the one which will directly select.
4064 const SIMachineFunctionInfo *MFI = B.getMF().getInfo<SIMachineFunctionInfo>();
4065 if (MFI->getMode().IEEE)
4066 B.buildFMinNumIEEE(Min, Fract, Const, Flags);
4067 else
4068 B.buildFMinNum(Min, Fract, Const, Flags);
4069
4070 Register CorrectedFract = Min;
4071 if (!MI.getFlag(MachineInstr::FmNoNans)) {
4072 auto IsNan = B.buildFCmp(CmpInst::FCMP_ORD, S1, ModSrc, ModSrc, Flags);
4073 CorrectedFract = B.buildSelect(F64, IsNan, ModSrc, Min, Flags).getReg(0);
4074 }
4075
4076 auto NegFract = B.buildFNeg(F64, CorrectedFract, Flags);
4077 B.buildFAdd(Dst, OrigSrc, NegFract, Flags);
4078
4079 MI.eraseFromParent();
4080 return true;
4081}
4082
4083// Turn an illegal packed v2s16 build vector into bit operations.
4084// TODO: This should probably be a bitcast action in LegalizerHelper.
4087 Register Dst = MI.getOperand(0).getReg();
4088 const LLT S32 = LLT::scalar(32);
4089 const LLT S16 = LLT::scalar(16);
4090 assert(MRI.getType(Dst) == LLT::fixed_vector(2, 16));
4091
4092 Register Src0 = MI.getOperand(1).getReg();
4093 Register Src1 = MI.getOperand(2).getReg();
4094
4095 if (MI.getOpcode() == AMDGPU::G_BUILD_VECTOR_TRUNC) {
4096 assert(MRI.getType(Src0) == S32);
4097 Src0 = B.buildTrunc(S16, MI.getOperand(1).getReg()).getReg(0);
4098 Src1 = B.buildTrunc(S16, MI.getOperand(2).getReg()).getReg(0);
4099 }
4100
4101 auto Merge = B.buildMergeLikeInstr(S32, {Src0, Src1});
4102 B.buildBitcast(Dst, Merge);
4103
4104 MI.eraseFromParent();
4105 return true;
4106}
4107
4108// Build a big integer multiply or multiply-add using MAD_64_32 instructions.
4109//
4110// Source and accumulation registers must all be 32-bits.
4111//
4112// TODO: When the multiply is uniform, we should produce a code sequence
4113// that is better suited to instruction selection on the SALU. Instead of
4114// the outer loop going over parts of the result, the outer loop should go
4115// over parts of one of the factors. This should result in instruction
4116// selection that makes full use of S_ADDC_U32 instructions.
4119 ArrayRef<Register> Src0,
4120 ArrayRef<Register> Src1,
4121 bool UsePartialMad64_32,
4122 bool SeparateOddAlignedProducts) const {
4123 // Use (possibly empty) vectors of S1 registers to represent the set of
4124 // carries from one pair of positions to the next.
4125 using Carry = SmallVector<Register, 2>;
4126
4127 MachineIRBuilder &B = Helper.MIRBuilder;
4128 GISelValueTracking &VT = *Helper.getValueTracking();
4129
4130 const LLT S1 = LLT::scalar(1);
4131 const LLT S32 = LLT::scalar(32);
4132 const LLT S64 = LLT::scalar(64);
4133
4134 Register Zero32;
4135 Register Zero64;
4136
4137 auto getZero32 = [&]() -> Register {
4138 if (!Zero32)
4139 Zero32 = B.buildConstant(S32, 0).getReg(0);
4140 return Zero32;
4141 };
4142 auto getZero64 = [&]() -> Register {
4143 if (!Zero64)
4144 Zero64 = B.buildConstant(S64, 0).getReg(0);
4145 return Zero64;
4146 };
4147
4148 SmallVector<bool, 2> Src0KnownZeros, Src1KnownZeros;
4149 for (unsigned i = 0; i < Src0.size(); ++i) {
4150 Src0KnownZeros.push_back(VT.getKnownBits(Src0[i]).isZero());
4151 Src1KnownZeros.push_back(VT.getKnownBits(Src1[i]).isZero());
4152 }
4153
4154 // Merge the given carries into the 32-bit LocalAccum, which is modified
4155 // in-place.
4156 //
4157 // Returns the carry-out, which is a single S1 register or null.
4158 auto mergeCarry =
4159 [&](Register &LocalAccum, const Carry &CarryIn) -> Register {
4160 if (CarryIn.empty())
4161 return Register();
4162
4163 bool HaveCarryOut = true;
4164 Register CarryAccum;
4165 if (CarryIn.size() == 1) {
4166 if (!LocalAccum) {
4167 LocalAccum = B.buildZExt(S32, CarryIn[0]).getReg(0);
4168 return Register();
4169 }
4170
4171 CarryAccum = getZero32();
4172 } else {
4173 CarryAccum = B.buildZExt(S32, CarryIn[0]).getReg(0);
4174 for (unsigned i = 1; i + 1 < CarryIn.size(); ++i) {
4175 CarryAccum =
4176 B.buildUAdde(S32, S1, CarryAccum, getZero32(), CarryIn[i])
4177 .getReg(0);
4178 }
4179
4180 if (!LocalAccum) {
4181 LocalAccum = getZero32();
4182 HaveCarryOut = false;
4183 }
4184 }
4185
4186 auto Add =
4187 B.buildUAdde(S32, S1, CarryAccum, LocalAccum, CarryIn.back());
4188 LocalAccum = Add.getReg(0);
4189 return HaveCarryOut ? Add.getReg(1) : Register();
4190 };
4191
4192 // Build a multiply-add chain to compute
4193 //
4194 // LocalAccum + (partial products at DstIndex)
4195 // + (opportunistic subset of CarryIn)
4196 //
4197 // LocalAccum is an array of one or two 32-bit registers that are updated
4198 // in-place. The incoming registers may be null.
4199 //
4200 // In some edge cases, carry-ins can be consumed "for free". In that case,
4201 // the consumed carry bits are removed from CarryIn in-place.
4202 auto buildMadChain =
4203 [&](MutableArrayRef<Register> LocalAccum, unsigned DstIndex, Carry &CarryIn)
4204 -> Carry {
4205 assert((DstIndex + 1 < Accum.size() && LocalAccum.size() == 2) ||
4206 (DstIndex + 1 >= Accum.size() && LocalAccum.size() == 1));
4207
4208 Carry CarryOut;
4209 unsigned j0 = 0;
4210
4211 // Use plain 32-bit multiplication for the most significant part of the
4212 // result by default.
4213 if (LocalAccum.size() == 1 &&
4214 (!UsePartialMad64_32 || !CarryIn.empty())) {
4215 do {
4216 // Skip multiplication if one of the operands is 0
4217 unsigned j1 = DstIndex - j0;
4218 if (Src0KnownZeros[j0] || Src1KnownZeros[j1]) {
4219 ++j0;
4220 continue;
4221 }
4222 auto Mul = B.buildMul(S32, Src0[j0], Src1[j1]);
4223 if (!LocalAccum[0] || VT.getKnownBits(LocalAccum[0]).isZero()) {
4224 LocalAccum[0] = Mul.getReg(0);
4225 } else {
4226 if (CarryIn.empty()) {
4227 LocalAccum[0] = B.buildAdd(S32, LocalAccum[0], Mul).getReg(0);
4228 } else {
4229 LocalAccum[0] =
4230 B.buildUAdde(S32, S1, LocalAccum[0], Mul, CarryIn.back())
4231 .getReg(0);
4232 CarryIn.pop_back();
4233 }
4234 }
4235 ++j0;
4236 } while (j0 <= DstIndex && (!UsePartialMad64_32 || !CarryIn.empty()));
4237 }
4238
4239 // Build full 64-bit multiplies.
4240 if (j0 <= DstIndex) {
4241 bool HaveSmallAccum = false;
4242 Register Tmp;
4243
4244 if (LocalAccum[0]) {
4245 if (LocalAccum.size() == 1) {
4246 Tmp = B.buildAnyExt(S64, LocalAccum[0]).getReg(0);
4247 HaveSmallAccum = true;
4248 } else if (LocalAccum[1]) {
4249 Tmp = B.buildMergeLikeInstr(S64, LocalAccum).getReg(0);
4250 HaveSmallAccum = false;
4251 } else {
4252 Tmp = B.buildZExt(S64, LocalAccum[0]).getReg(0);
4253 HaveSmallAccum = true;
4254 }
4255 } else {
4256 assert(LocalAccum.size() == 1 || !LocalAccum[1]);
4257 Tmp = getZero64();
4258 HaveSmallAccum = true;
4259 }
4260
4261 do {
4262 unsigned j1 = DstIndex - j0;
4263 if (Src0KnownZeros[j0] || Src1KnownZeros[j1]) {
4264 ++j0;
4265 continue;
4266 }
4267 auto Mad = B.buildInstr(AMDGPU::G_AMDGPU_MAD_U64_U32, {S64, S1},
4268 {Src0[j0], Src1[j1], Tmp});
4269 Tmp = Mad.getReg(0);
4270 if (!HaveSmallAccum)
4271 CarryOut.push_back(Mad.getReg(1));
4272 HaveSmallAccum = false;
4273
4274 ++j0;
4275 } while (j0 <= DstIndex);
4276
4277 auto Unmerge = B.buildUnmerge(S32, Tmp);
4278 LocalAccum[0] = Unmerge.getReg(0);
4279 if (LocalAccum.size() > 1)
4280 LocalAccum[1] = Unmerge.getReg(1);
4281 }
4282
4283 return CarryOut;
4284 };
4285
4286 // Outer multiply loop, iterating over destination parts from least
4287 // significant to most significant parts.
4288 //
4289 // The columns of the following diagram correspond to the destination parts
4290 // affected by one iteration of the outer loop (ignoring boundary
4291 // conditions).
4292 //
4293 // Dest index relative to 2 * i: 1 0 -1
4294 // ------
4295 // Carries from previous iteration: e o
4296 // Even-aligned partial product sum: E E .
4297 // Odd-aligned partial product sum: O O
4298 //
4299 // 'o' is OddCarry, 'e' is EvenCarry.
4300 // EE and OO are computed from partial products via buildMadChain and use
4301 // accumulation where possible and appropriate.
4302 //
4303 Register SeparateOddCarry;
4304 Carry EvenCarry;
4305 Carry OddCarry;
4306
4307 for (unsigned i = 0; i <= Accum.size() / 2; ++i) {
4308 Carry OddCarryIn = std::move(OddCarry);
4309 Carry EvenCarryIn = std::move(EvenCarry);
4310 OddCarry.clear();
4311 EvenCarry.clear();
4312
4313 // Partial products at offset 2 * i.
4314 if (2 * i < Accum.size()) {
4315 auto LocalAccum = Accum.drop_front(2 * i).take_front(2);
4316 EvenCarry = buildMadChain(LocalAccum, 2 * i, EvenCarryIn);
4317 }
4318
4319 // Partial products at offset 2 * i - 1.
4320 if (i > 0) {
4321 if (!SeparateOddAlignedProducts) {
4322 auto LocalAccum = Accum.drop_front(2 * i - 1).take_front(2);
4323 OddCarry = buildMadChain(LocalAccum, 2 * i - 1, OddCarryIn);
4324 } else {
4325 bool IsHighest = 2 * i >= Accum.size();
4326 Register SeparateOddOut[2];
4327 auto LocalAccum = MutableArrayRef(SeparateOddOut)
4328 .take_front(IsHighest ? 1 : 2);
4329 OddCarry = buildMadChain(LocalAccum, 2 * i - 1, OddCarryIn);
4330
4332
4333 if (i == 1) {
4334 if (!IsHighest)
4335 Lo = B.buildUAddo(S32, S1, Accum[2 * i - 1], SeparateOddOut[0]);
4336 else
4337 Lo = B.buildAdd(S32, Accum[2 * i - 1], SeparateOddOut[0]);
4338 } else {
4339 Lo = B.buildUAdde(S32, S1, Accum[2 * i - 1], SeparateOddOut[0],
4340 SeparateOddCarry);
4341 }
4342 Accum[2 * i - 1] = Lo->getOperand(0).getReg();
4343
4344 if (!IsHighest) {
4345 auto Hi = B.buildUAdde(S32, S1, Accum[2 * i], SeparateOddOut[1],
4346 Lo->getOperand(1).getReg());
4347 Accum[2 * i] = Hi.getReg(0);
4348 SeparateOddCarry = Hi.getReg(1);
4349 }
4350 }
4351 }
4352
4353 // Add in the carries from the previous iteration
4354 if (i > 0) {
4355 if (Register CarryOut = mergeCarry(Accum[2 * i - 1], OddCarryIn))
4356 EvenCarryIn.push_back(CarryOut);
4357
4358 if (2 * i < Accum.size()) {
4359 if (Register CarryOut = mergeCarry(Accum[2 * i], EvenCarryIn))
4360 OddCarry.push_back(CarryOut);
4361 }
4362 }
4363 }
4364}
4365
4366// Custom narrowing of wide multiplies using wide multiply-add instructions.
4367//
4368// TODO: If the multiply is followed by an addition, we should attempt to
4369// integrate it to make better use of V_MAD_U64_U32's multiply-add capabilities.
4371 MachineInstr &MI) const {
4372 assert(ST.hasMad64_32());
4373 assert(MI.getOpcode() == TargetOpcode::G_MUL);
4374
4375 MachineIRBuilder &B = Helper.MIRBuilder;
4376 MachineRegisterInfo &MRI = *B.getMRI();
4377
4378 Register DstReg = MI.getOperand(0).getReg();
4379 Register Src0 = MI.getOperand(1).getReg();
4380 Register Src1 = MI.getOperand(2).getReg();
4381
4382 LLT Ty = MRI.getType(DstReg);
4383 assert(Ty.isScalar());
4384
4385 unsigned Size = Ty.getSizeInBits();
4386 if (ST.hasVectorMulU64() && Size == 64)
4387 return true;
4388
4389 unsigned NumParts = Size / 32;
4390 assert((Size % 32) == 0);
4391 assert(NumParts >= 2);
4392
4393 // Whether to use MAD_64_32 for partial products whose high half is
4394 // discarded. This avoids some ADD instructions but risks false dependency
4395 // stalls on some subtargets in some cases.
4396 const bool UsePartialMad64_32 = ST.getGeneration() < AMDGPUSubtarget::GFX10;
4397
4398 // Whether to compute odd-aligned partial products separately. This is
4399 // advisable on subtargets where the accumulator of MAD_64_32 must be placed
4400 // in an even-aligned VGPR.
4401 const bool SeparateOddAlignedProducts = ST.hasFullRate64Ops();
4402
4403 LLT S32 = LLT::scalar(32);
4404 SmallVector<Register, 2> Src0Parts, Src1Parts;
4405 for (unsigned i = 0; i < NumParts; ++i) {
4406 Src0Parts.push_back(MRI.createGenericVirtualRegister(S32));
4407 Src1Parts.push_back(MRI.createGenericVirtualRegister(S32));
4408 }
4409 B.buildUnmerge(Src0Parts, Src0);
4410 B.buildUnmerge(Src1Parts, Src1);
4411
4412 SmallVector<Register, 2> AccumRegs(NumParts);
4413 buildMultiply(Helper, AccumRegs, Src0Parts, Src1Parts, UsePartialMad64_32,
4414 SeparateOddAlignedProducts);
4415
4416 B.buildMergeLikeInstr(DstReg, AccumRegs);
4417 MI.eraseFromParent();
4418 return true;
4419}
4420
4421// Legalize ctlz/cttz to ffbh/ffbl instead of the default legalization to
4422// ctlz/cttz_zero_undef. This allows us to fix up the result for the zero input
4423// case with a single min instruction instead of a compare+select.
4426 MachineIRBuilder &B) const {
4427 Register Dst = MI.getOperand(0).getReg();
4428 Register Src = MI.getOperand(1).getReg();
4429 LLT DstTy = MRI.getType(Dst);
4430 LLT SrcTy = MRI.getType(Src);
4431
4432 unsigned NewOpc = MI.getOpcode() == AMDGPU::G_CTLZ
4433 ? AMDGPU::G_AMDGPU_FFBH_U32
4434 : AMDGPU::G_AMDGPU_FFBL_B32;
4435 auto Tmp = B.buildInstr(NewOpc, {DstTy}, {Src});
4436 B.buildUMin(Dst, Tmp, B.buildConstant(DstTy, SrcTy.getSizeInBits()));
4437
4438 MI.eraseFromParent();
4439 return true;
4440}
4441
4444 MachineIRBuilder &B) const {
4445 Register Dst = MI.getOperand(0).getReg();
4446 Register Src = MI.getOperand(1).getReg();
4447 LLT SrcTy = MRI.getType(Src);
4448 TypeSize NumBits = SrcTy.getSizeInBits();
4449
4450 assert(NumBits < 32u);
4451
4452 auto ShiftAmt = B.buildConstant(S32, 32u - NumBits);
4453 auto Extend = B.buildAnyExt(S32, {Src}).getReg(0u);
4454 auto Shift = B.buildShl(S32, Extend, ShiftAmt);
4455 auto Ctlz = B.buildInstr(AMDGPU::G_AMDGPU_FFBH_U32, {S32}, {Shift});
4456 B.buildTrunc(Dst, Ctlz);
4457 MI.eraseFromParent();
4458 return true;
4459}
4460
4461// Check that this is a G_XOR x, -1
4462static bool isNot(const MachineRegisterInfo &MRI, const MachineInstr &MI) {
4463 if (MI.getOpcode() != TargetOpcode::G_XOR)
4464 return false;
4465 auto ConstVal = getIConstantVRegSExtVal(MI.getOperand(2).getReg(), MRI);
4466 return ConstVal == -1;
4467}
4468
4469// Return the use branch instruction, otherwise null if the usage is invalid.
4470static MachineInstr *
4472 MachineBasicBlock *&UncondBrTarget, bool &Negated) {
4473 Register CondDef = MI.getOperand(0).getReg();
4474 if (!MRI.hasOneNonDBGUse(CondDef))
4475 return nullptr;
4476
4477 MachineBasicBlock *Parent = MI.getParent();
4478 MachineInstr *UseMI = &*MRI.use_instr_nodbg_begin(CondDef);
4479
4480 if (isNot(MRI, *UseMI)) {
4481 Register NegatedCond = UseMI->getOperand(0).getReg();
4482 if (!MRI.hasOneNonDBGUse(NegatedCond))
4483 return nullptr;
4484
4485 // We're deleting the def of this value, so we need to remove it.
4486 eraseInstr(*UseMI, MRI);
4487
4488 UseMI = &*MRI.use_instr_nodbg_begin(NegatedCond);
4489 Negated = true;
4490 }
4491
4492 if (UseMI->getParent() != Parent || UseMI->getOpcode() != AMDGPU::G_BRCOND)
4493 return nullptr;
4494
4495 // Make sure the cond br is followed by a G_BR, or is the last instruction.
4496 MachineBasicBlock::iterator Next = std::next(UseMI->getIterator());
4497 if (Next == Parent->end()) {
4498 MachineFunction::iterator NextMBB = std::next(Parent->getIterator());
4499 if (NextMBB == Parent->getParent()->end()) // Illegal intrinsic use.
4500 return nullptr;
4501 UncondBrTarget = &*NextMBB;
4502 } else {
4503 if (Next->getOpcode() != AMDGPU::G_BR)
4504 return nullptr;
4505 Br = &*Next;
4506 UncondBrTarget = Br->getOperand(0).getMBB();
4507 }
4508
4509 return UseMI;
4510}
4511
4514 const ArgDescriptor *Arg,
4515 const TargetRegisterClass *ArgRC,
4516 LLT ArgTy) const {
4517 MCRegister SrcReg = Arg->getRegister();
4518 assert(SrcReg.isPhysical() && "Physical register expected");
4519 assert(DstReg.isVirtual() && "Virtual register expected");
4520
4521 Register LiveIn = getFunctionLiveInPhysReg(B.getMF(), B.getTII(), SrcReg,
4522 *ArgRC, B.getDebugLoc(), ArgTy);
4523 if (Arg->isMasked()) {
4524 // TODO: Should we try to emit this once in the entry block?
4525 const LLT S32 = LLT::scalar(32);
4526 const unsigned Mask = Arg->getMask();
4527 const unsigned Shift = llvm::countr_zero<unsigned>(Mask);
4528
4529 Register AndMaskSrc = LiveIn;
4530
4531 // TODO: Avoid clearing the high bits if we know workitem id y/z are always
4532 // 0.
4533 if (Shift != 0) {
4534 auto ShiftAmt = B.buildConstant(S32, Shift);
4535 AndMaskSrc = B.buildLShr(S32, LiveIn, ShiftAmt).getReg(0);
4536 }
4537
4538 B.buildAnd(DstReg, AndMaskSrc, B.buildConstant(S32, Mask >> Shift));
4539 } else {
4540 B.buildCopy(DstReg, LiveIn);
4541 }
4542}
4543
4548 AMDGPUFunctionArgInfo::PreloadedValue ClusterWorkGroupIdPV) const {
4549 Register DstReg = MI.getOperand(0).getReg();
4550 if (!ST.hasClusters()) {
4551 if (!loadInputValue(DstReg, B, WorkGroupIdPV))
4552 return false;
4553 MI.eraseFromParent();
4554 return true;
4555 }
4556
4557 // Clusters are supported. Return the global position in the grid. If clusters
4558 // are enabled, WorkGroupIdPV returns the cluster ID not the workgroup ID.
4559
4560 // WorkGroupIdXYZ = ClusterId == 0 ?
4561 // ClusterIdXYZ :
4562 // ClusterIdXYZ * (ClusterMaxIdXYZ + 1) + ClusterWorkGroupIdXYZ
4563 MachineRegisterInfo &MRI = *B.getMRI();
4564 const LLT S32 = LLT::scalar(32);
4565 Register ClusterIdXYZ = MRI.createGenericVirtualRegister(S32);
4566 Register ClusterMaxIdXYZ = MRI.createGenericVirtualRegister(S32);
4567 Register ClusterWorkGroupIdXYZ = MRI.createGenericVirtualRegister(S32);
4568 if (!loadInputValue(ClusterIdXYZ, B, WorkGroupIdPV) ||
4569 !loadInputValue(ClusterWorkGroupIdXYZ, B, ClusterWorkGroupIdPV) ||
4570 !loadInputValue(ClusterMaxIdXYZ, B, ClusterMaxIdPV))
4571 return false;
4572
4573 auto One = B.buildConstant(S32, 1);
4574 auto ClusterSizeXYZ = B.buildAdd(S32, ClusterMaxIdXYZ, One);
4575 auto GlobalIdXYZ = B.buildAdd(S32, ClusterWorkGroupIdXYZ,
4576 B.buildMul(S32, ClusterIdXYZ, ClusterSizeXYZ));
4577
4578 const SIMachineFunctionInfo *MFI = B.getMF().getInfo<SIMachineFunctionInfo>();
4579
4580 switch (MFI->getClusterDims().getKind()) {
4583 B.buildCopy(DstReg, GlobalIdXYZ);
4584 MI.eraseFromParent();
4585 return true;
4586 }
4588 B.buildCopy(DstReg, ClusterIdXYZ);
4589 MI.eraseFromParent();
4590 return true;
4591 }
4593 using namespace AMDGPU::Hwreg;
4594 unsigned ClusterIdField = HwregEncoding::encode(ID_IB_STS2, 6, 4);
4595 Register ClusterId = MRI.createGenericVirtualRegister(S32);
4596 MRI.setRegClass(ClusterId, &AMDGPU::SReg_32RegClass);
4597 B.buildInstr(AMDGPU::S_GETREG_B32_const)
4598 .addDef(ClusterId)
4599 .addImm(ClusterIdField);
4600 auto Zero = B.buildConstant(S32, 0);
4601 auto NoClusters =
4602 B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1), ClusterId, Zero);
4603 B.buildSelect(DstReg, NoClusters, ClusterIdXYZ, GlobalIdXYZ);
4604 MI.eraseFromParent();
4605 return true;
4606 }
4607 }
4608
4609 llvm_unreachable("nothing should reach here");
4610}
4611
4613 Register DstReg, MachineIRBuilder &B,
4615 const SIMachineFunctionInfo *MFI = B.getMF().getInfo<SIMachineFunctionInfo>();
4616 const ArgDescriptor *Arg = nullptr;
4617 const TargetRegisterClass *ArgRC;
4618 LLT ArgTy;
4619
4620 CallingConv::ID CC = B.getMF().getFunction().getCallingConv();
4621 const ArgDescriptor WorkGroupIDX =
4622 ArgDescriptor::createRegister(AMDGPU::TTMP9);
4623 // If GridZ is not programmed in an entry function then the hardware will set
4624 // it to all zeros, so there is no need to mask the GridY value in the low
4625 // order bits.
4626 const ArgDescriptor WorkGroupIDY = ArgDescriptor::createRegister(
4627 AMDGPU::TTMP7,
4628 AMDGPU::isEntryFunctionCC(CC) && !MFI->hasWorkGroupIDZ() ? ~0u : 0xFFFFu);
4629 const ArgDescriptor WorkGroupIDZ =
4630 ArgDescriptor::createRegister(AMDGPU::TTMP7, 0xFFFF0000u);
4631 const ArgDescriptor ClusterWorkGroupIDX =
4632 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0000000Fu);
4633 const ArgDescriptor ClusterWorkGroupIDY =
4634 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x000000F0u);
4635 const ArgDescriptor ClusterWorkGroupIDZ =
4636 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x00000F00u);
4637 const ArgDescriptor ClusterWorkGroupMaxIDX =
4638 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0000F000u);
4639 const ArgDescriptor ClusterWorkGroupMaxIDY =
4640 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x000F0000u);
4641 const ArgDescriptor ClusterWorkGroupMaxIDZ =
4642 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x00F00000u);
4643 const ArgDescriptor ClusterWorkGroupMaxFlatID =
4644 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0F000000u);
4645
4646 auto LoadConstant = [&](unsigned N) {
4647 B.buildConstant(DstReg, N);
4648 return true;
4649 };
4650
4651 if (ST.hasArchitectedSGPRs() &&
4653 AMDGPU::ClusterDimsAttr ClusterDims = MFI->getClusterDims();
4654 bool HasFixedDims = ClusterDims.isFixedDims();
4655
4656 switch (ArgType) {
4658 Arg = &WorkGroupIDX;
4659 ArgRC = &AMDGPU::SReg_32RegClass;
4660 ArgTy = LLT::scalar(32);
4661 break;
4663 Arg = &WorkGroupIDY;
4664 ArgRC = &AMDGPU::SReg_32RegClass;
4665 ArgTy = LLT::scalar(32);
4666 break;
4668 Arg = &WorkGroupIDZ;
4669 ArgRC = &AMDGPU::SReg_32RegClass;
4670 ArgTy = LLT::scalar(32);
4671 break;
4673 if (HasFixedDims && ClusterDims.getDims()[0] == 1)
4674 return LoadConstant(0);
4675 Arg = &ClusterWorkGroupIDX;
4676 ArgRC = &AMDGPU::SReg_32RegClass;
4677 ArgTy = LLT::scalar(32);
4678 break;
4680 if (HasFixedDims && ClusterDims.getDims()[1] == 1)
4681 return LoadConstant(0);
4682 Arg = &ClusterWorkGroupIDY;
4683 ArgRC = &AMDGPU::SReg_32RegClass;
4684 ArgTy = LLT::scalar(32);
4685 break;
4687 if (HasFixedDims && ClusterDims.getDims()[2] == 1)
4688 return LoadConstant(0);
4689 Arg = &ClusterWorkGroupIDZ;
4690 ArgRC = &AMDGPU::SReg_32RegClass;
4691 ArgTy = LLT::scalar(32);
4692 break;
4694 if (HasFixedDims)
4695 return LoadConstant(ClusterDims.getDims()[0] - 1);
4696 Arg = &ClusterWorkGroupMaxIDX;
4697 ArgRC = &AMDGPU::SReg_32RegClass;
4698 ArgTy = LLT::scalar(32);
4699 break;
4701 if (HasFixedDims)
4702 return LoadConstant(ClusterDims.getDims()[1] - 1);
4703 Arg = &ClusterWorkGroupMaxIDY;
4704 ArgRC = &AMDGPU::SReg_32RegClass;
4705 ArgTy = LLT::scalar(32);
4706 break;
4708 if (HasFixedDims)
4709 return LoadConstant(ClusterDims.getDims()[2] - 1);
4710 Arg = &ClusterWorkGroupMaxIDZ;
4711 ArgRC = &AMDGPU::SReg_32RegClass;
4712 ArgTy = LLT::scalar(32);
4713 break;
4715 Arg = &ClusterWorkGroupMaxFlatID;
4716 ArgRC = &AMDGPU::SReg_32RegClass;
4717 ArgTy = LLT::scalar(32);
4718 break;
4719 default:
4720 break;
4721 }
4722 }
4723
4724 if (!Arg)
4725 std::tie(Arg, ArgRC, ArgTy) = MFI->getPreloadedValue(ArgType);
4726
4727 if (!Arg) {
4729 // The intrinsic may appear when we have a 0 sized kernarg segment, in
4730 // which case the pointer argument may be missing and we use null.
4731 return LoadConstant(0);
4732 }
4733
4734 // It's undefined behavior if a function marked with the amdgpu-no-*
4735 // attributes uses the corresponding intrinsic.
4736 B.buildUndef(DstReg);
4737 return true;
4738 }
4739
4740 if (!Arg->isRegister() || !Arg->getRegister().isValid())
4741 return false; // TODO: Handle these
4742 buildLoadInputValue(DstReg, B, Arg, ArgRC, ArgTy);
4743 return true;
4744}
4745
4749 if (!loadInputValue(MI.getOperand(0).getReg(), B, ArgType))
4750 return false;
4751
4752 MI.eraseFromParent();
4753 return true;
4754}
4755
4757 int64_t C) {
4758 B.buildConstant(MI.getOperand(0).getReg(), C);
4759 MI.eraseFromParent();
4760 return true;
4761}
4762
4765 unsigned Dim, AMDGPUFunctionArgInfo::PreloadedValue ArgType) const {
4766 unsigned MaxID = ST.getMaxWorkitemID(B.getMF().getFunction(), Dim);
4767 if (MaxID == 0)
4768 return replaceWithConstant(B, MI, 0);
4769
4770 const SIMachineFunctionInfo *MFI = B.getMF().getInfo<SIMachineFunctionInfo>();
4771 const ArgDescriptor *Arg;
4772 const TargetRegisterClass *ArgRC;
4773 LLT ArgTy;
4774 std::tie(Arg, ArgRC, ArgTy) = MFI->getPreloadedValue(ArgType);
4775
4776 Register DstReg = MI.getOperand(0).getReg();
4777 if (!Arg) {
4778 // It's undefined behavior if a function marked with the amdgpu-no-*
4779 // attributes uses the corresponding intrinsic.
4780 B.buildUndef(DstReg);
4781 MI.eraseFromParent();
4782 return true;
4783 }
4784
4785 if (Arg->isMasked()) {
4786 // Don't bother inserting AssertZext for packed IDs since we're emitting the
4787 // masking operations anyway.
4788 //
4789 // TODO: We could assert the top bit is 0 for the source copy.
4790 if (!loadInputValue(DstReg, B, ArgType))
4791 return false;
4792 } else {
4793 Register TmpReg = MRI.createGenericVirtualRegister(LLT::scalar(32));
4794 if (!loadInputValue(TmpReg, B, ArgType))
4795 return false;
4796 B.buildAssertZExt(DstReg, TmpReg, llvm::bit_width(MaxID));
4797 }
4798
4799 MI.eraseFromParent();
4800 return true;
4801}
4802
4805 // This isn't really a constant pool but close enough.
4808 return PtrInfo;
4809}
4810
4812 int64_t Offset) const {
4814 Register KernArgReg = B.getMRI()->createGenericVirtualRegister(PtrTy);
4815
4816 // TODO: If we passed in the base kernel offset we could have a better
4817 // alignment than 4, but we don't really need it.
4818 if (!loadInputValue(KernArgReg, B,
4820 llvm_unreachable("failed to find kernarg segment ptr");
4821
4822 auto COffset = B.buildConstant(LLT::scalar(64), Offset);
4823 return B.buildObjectPtrOffset(PtrTy, KernArgReg, COffset).getReg(0);
4824}
4825
4826/// Legalize a value that's loaded from kernel arguments. This is only used by
4827/// legacy intrinsics.
4831 Align Alignment) const {
4832 Register DstReg = MI.getOperand(0).getReg();
4833
4834 assert(B.getMRI()->getType(DstReg) == LLT::scalar(32) &&
4835 "unexpected kernarg parameter type");
4836
4839 B.buildLoad(DstReg, Ptr, PtrInfo.getWithOffset(Offset), Align(4),
4842 MI.eraseFromParent();
4843 return true;
4844}
4845
4848 MachineIRBuilder &B) const {
4849 Register Dst = MI.getOperand(0).getReg();
4850 LLT DstTy = MRI.getType(Dst);
4851 LLT S16 = LLT::scalar(16);
4852 LLT S32 = LLT::scalar(32);
4853 LLT S64 = LLT::scalar(64);
4854
4855 if (DstTy == S16)
4856 return legalizeFDIV16(MI, MRI, B);
4857 if (DstTy == S32)
4858 return legalizeFDIV32(MI, MRI, B);
4859 if (DstTy == S64)
4860 return legalizeFDIV64(MI, MRI, B);
4861
4862 return false;
4863}
4864
4866 Register DstDivReg,
4867 Register DstRemReg,
4868 Register X,
4869 Register Y) const {
4870 const LLT S1 = LLT::scalar(1);
4871 const LLT S32 = LLT::scalar(32);
4872
4873 // See AMDGPUCodeGenPrepare::expandDivRem32 for a description of the
4874 // algorithm used here.
4875
4876 // Initial estimate of inv(y).
4877 auto FloatY = B.buildUITOFP(S32, Y);
4878 auto RcpIFlag = B.buildInstr(AMDGPU::G_AMDGPU_RCP_IFLAG, {S32}, {FloatY});
4879 auto Scale = B.buildFConstant(S32, llvm::bit_cast<float>(0x4f7ffffe));
4880 auto ScaledY = B.buildFMul(S32, RcpIFlag, Scale);
4881 auto Z = B.buildFPTOUI(S32, ScaledY);
4882
4883 // One round of UNR.
4884 auto NegY = B.buildSub(S32, B.buildConstant(S32, 0), Y);
4885 auto NegYZ = B.buildMul(S32, NegY, Z);
4886 Z = B.buildAdd(S32, Z, B.buildUMulH(S32, Z, NegYZ));
4887
4888 // Quotient/remainder estimate.
4889 auto Q = B.buildUMulH(S32, X, Z);
4890 auto R = B.buildSub(S32, X, B.buildMul(S32, Q, Y));
4891
4892 // First quotient/remainder refinement.
4893 auto One = B.buildConstant(S32, 1);
4894 auto Cond = B.buildICmp(CmpInst::ICMP_UGE, S1, R, Y);
4895 if (DstDivReg)
4896 Q = B.buildSelect(S32, Cond, B.buildAdd(S32, Q, One), Q);
4897 R = B.buildSelect(S32, Cond, B.buildSub(S32, R, Y), R);
4898
4899 // Second quotient/remainder refinement.
4900 Cond = B.buildICmp(CmpInst::ICMP_UGE, S1, R, Y);
4901 if (DstDivReg)
4902 B.buildSelect(DstDivReg, Cond, B.buildAdd(S32, Q, One), Q);
4903
4904 if (DstRemReg)
4905 B.buildSelect(DstRemReg, Cond, B.buildSub(S32, R, Y), R);
4906}
4907
4908// Build integer reciprocal sequence around V_RCP_IFLAG_F32
4909//
4910// Return lo, hi of result
4911//
4912// %cvt.lo = G_UITOFP Val.lo
4913// %cvt.hi = G_UITOFP Val.hi
4914// %mad = G_FMAD %cvt.hi, 2**32, %cvt.lo
4915// %rcp = G_AMDGPU_RCP_IFLAG %mad
4916// %mul1 = G_FMUL %rcp, 0x5f7ffffc
4917// %mul2 = G_FMUL %mul1, 2**(-32)
4918// %trunc = G_INTRINSIC_TRUNC %mul2
4919// %mad2 = G_FMAD %trunc, -(2**32), %mul1
4920// return {G_FPTOUI %mad2, G_FPTOUI %trunc}
4921static std::pair<Register, Register> emitReciprocalU64(MachineIRBuilder &B,
4922 Register Val) {
4923 const LLT S32 = LLT::scalar(32);
4924 auto Unmerge = B.buildUnmerge(S32, Val);
4925
4926 auto CvtLo = B.buildUITOFP(S32, Unmerge.getReg(0));
4927 auto CvtHi = B.buildUITOFP(S32, Unmerge.getReg(1));
4928
4929 auto Mad = B.buildFMAD(
4930 S32, CvtHi, // 2**32
4931 B.buildFConstant(S32, llvm::bit_cast<float>(0x4f800000)), CvtLo);
4932
4933 auto Rcp = B.buildInstr(AMDGPU::G_AMDGPU_RCP_IFLAG, {S32}, {Mad});
4934 auto Mul1 = B.buildFMul(
4935 S32, Rcp, B.buildFConstant(S32, llvm::bit_cast<float>(0x5f7ffffc)));
4936
4937 // 2**(-32)
4938 auto Mul2 = B.buildFMul(
4939 S32, Mul1, B.buildFConstant(S32, llvm::bit_cast<float>(0x2f800000)));
4940 auto Trunc = B.buildIntrinsicTrunc(S32, Mul2);
4941
4942 // -(2**32)
4943 auto Mad2 = B.buildFMAD(
4944 S32, Trunc, B.buildFConstant(S32, llvm::bit_cast<float>(0xcf800000)),
4945 Mul1);
4946
4947 auto ResultLo = B.buildFPTOUI(S32, Mad2);
4948 auto ResultHi = B.buildFPTOUI(S32, Trunc);
4949
4950 return {ResultLo.getReg(0), ResultHi.getReg(0)};
4951}
4952
4954 Register DstDivReg,
4955 Register DstRemReg,
4956 Register Numer,
4957 Register Denom) const {
4958 const LLT S32 = LLT::scalar(32);
4959 const LLT S64 = LLT::scalar(64);
4960 const LLT S1 = LLT::scalar(1);
4961 Register RcpLo, RcpHi;
4962
4963 std::tie(RcpLo, RcpHi) = emitReciprocalU64(B, Denom);
4964
4965 auto Rcp = B.buildMergeLikeInstr(S64, {RcpLo, RcpHi});
4966
4967 auto Zero64 = B.buildConstant(S64, 0);
4968 auto NegDenom = B.buildSub(S64, Zero64, Denom);
4969
4970 auto MulLo1 = B.buildMul(S64, NegDenom, Rcp);
4971 auto MulHi1 = B.buildUMulH(S64, Rcp, MulLo1);
4972
4973 auto UnmergeMulHi1 = B.buildUnmerge(S32, MulHi1);
4974 Register MulHi1_Lo = UnmergeMulHi1.getReg(0);
4975 Register MulHi1_Hi = UnmergeMulHi1.getReg(1);
4976
4977 auto Add1_Lo = B.buildUAddo(S32, S1, RcpLo, MulHi1_Lo);
4978 auto Add1_Hi = B.buildUAdde(S32, S1, RcpHi, MulHi1_Hi, Add1_Lo.getReg(1));
4979 auto Add1 = B.buildMergeLikeInstr(S64, {Add1_Lo, Add1_Hi});
4980
4981 auto MulLo2 = B.buildMul(S64, NegDenom, Add1);
4982 auto MulHi2 = B.buildUMulH(S64, Add1, MulLo2);
4983 auto UnmergeMulHi2 = B.buildUnmerge(S32, MulHi2);
4984 Register MulHi2_Lo = UnmergeMulHi2.getReg(0);
4985 Register MulHi2_Hi = UnmergeMulHi2.getReg(1);
4986
4987 auto Zero32 = B.buildConstant(S32, 0);
4988 auto Add2_Lo = B.buildUAddo(S32, S1, Add1_Lo, MulHi2_Lo);
4989 auto Add2_Hi = B.buildUAdde(S32, S1, Add1_Hi, MulHi2_Hi, Add2_Lo.getReg(1));
4990 auto Add2 = B.buildMergeLikeInstr(S64, {Add2_Lo, Add2_Hi});
4991
4992 auto UnmergeNumer = B.buildUnmerge(S32, Numer);
4993 Register NumerLo = UnmergeNumer.getReg(0);
4994 Register NumerHi = UnmergeNumer.getReg(1);
4995
4996 auto MulHi3 = B.buildUMulH(S64, Numer, Add2);
4997 auto Mul3 = B.buildMul(S64, Denom, MulHi3);
4998 auto UnmergeMul3 = B.buildUnmerge(S32, Mul3);
4999 Register Mul3_Lo = UnmergeMul3.getReg(0);
5000 Register Mul3_Hi = UnmergeMul3.getReg(1);
5001 auto Sub1_Lo = B.buildUSubo(S32, S1, NumerLo, Mul3_Lo);
5002 auto Sub1_Hi = B.buildUSube(S32, S1, NumerHi, Mul3_Hi, Sub1_Lo.getReg(1));
5003 auto Sub1_Mi = B.buildSub(S32, NumerHi, Mul3_Hi);
5004 auto Sub1 = B.buildMergeLikeInstr(S64, {Sub1_Lo, Sub1_Hi});
5005
5006 auto UnmergeDenom = B.buildUnmerge(S32, Denom);
5007 Register DenomLo = UnmergeDenom.getReg(0);
5008 Register DenomHi = UnmergeDenom.getReg(1);
5009
5010 auto CmpHi = B.buildICmp(CmpInst::ICMP_UGE, S1, Sub1_Hi, DenomHi);
5011 auto C1 = B.buildSExt(S32, CmpHi);
5012
5013 auto CmpLo = B.buildICmp(CmpInst::ICMP_UGE, S1, Sub1_Lo, DenomLo);
5014 auto C2 = B.buildSExt(S32, CmpLo);
5015
5016 auto CmpEq = B.buildICmp(CmpInst::ICMP_EQ, S1, Sub1_Hi, DenomHi);
5017 auto C3 = B.buildSelect(S32, CmpEq, C2, C1);
5018
5019 // TODO: Here and below portions of the code can be enclosed into if/endif.
5020 // Currently control flow is unconditional and we have 4 selects after
5021 // potential endif to substitute PHIs.
5022
5023 // if C3 != 0 ...
5024 auto Sub2_Lo = B.buildUSubo(S32, S1, Sub1_Lo, DenomLo);
5025 auto Sub2_Mi = B.buildUSube(S32, S1, Sub1_Mi, DenomHi, Sub1_Lo.getReg(1));
5026 auto Sub2_Hi = B.buildUSube(S32, S1, Sub2_Mi, Zero32, Sub2_Lo.getReg(1));
5027 auto Sub2 = B.buildMergeLikeInstr(S64, {Sub2_Lo, Sub2_Hi});
5028
5029 auto One64 = B.buildConstant(S64, 1);
5030 auto Add3 = B.buildAdd(S64, MulHi3, One64);
5031
5032 auto C4 =
5033 B.buildSExt(S32, B.buildICmp(CmpInst::ICMP_UGE, S1, Sub2_Hi, DenomHi));
5034 auto C5 =
5035 B.buildSExt(S32, B.buildICmp(CmpInst::ICMP_UGE, S1, Sub2_Lo, DenomLo));
5036 auto C6 = B.buildSelect(
5037 S32, B.buildICmp(CmpInst::ICMP_EQ, S1, Sub2_Hi, DenomHi), C5, C4);
5038
5039 // if (C6 != 0)
5040 auto Add4 = B.buildAdd(S64, Add3, One64);
5041 auto Sub3_Lo = B.buildUSubo(S32, S1, Sub2_Lo, DenomLo);
5042
5043 auto Sub3_Mi = B.buildUSube(S32, S1, Sub2_Mi, DenomHi, Sub2_Lo.getReg(1));
5044 auto Sub3_Hi = B.buildUSube(S32, S1, Sub3_Mi, Zero32, Sub3_Lo.getReg(1));
5045 auto Sub3 = B.buildMergeLikeInstr(S64, {Sub3_Lo, Sub3_Hi});
5046
5047 // endif C6
5048 // endif C3
5049
5050 if (DstDivReg) {
5051 auto Sel1 = B.buildSelect(
5052 S64, B.buildICmp(CmpInst::ICMP_NE, S1, C6, Zero32), Add4, Add3);
5053 B.buildSelect(DstDivReg, B.buildICmp(CmpInst::ICMP_NE, S1, C3, Zero32),
5054 Sel1, MulHi3);
5055 }
5056
5057 if (DstRemReg) {
5058 auto Sel2 = B.buildSelect(
5059 S64, B.buildICmp(CmpInst::ICMP_NE, S1, C6, Zero32), Sub3, Sub2);
5060 B.buildSelect(DstRemReg, B.buildICmp(CmpInst::ICMP_NE, S1, C3, Zero32),
5061 Sel2, Sub1);
5062 }
5063}
5064
5067 MachineIRBuilder &B) const {
5068 Register DstDivReg, DstRemReg;
5069 switch (MI.getOpcode()) {
5070 default:
5071 llvm_unreachable("Unexpected opcode!");
5072 case AMDGPU::G_UDIV: {
5073 DstDivReg = MI.getOperand(0).getReg();
5074 break;
5075 }
5076 case AMDGPU::G_UREM: {
5077 DstRemReg = MI.getOperand(0).getReg();
5078 break;
5079 }
5080 case AMDGPU::G_UDIVREM: {
5081 DstDivReg = MI.getOperand(0).getReg();
5082 DstRemReg = MI.getOperand(1).getReg();
5083 break;
5084 }
5085 }
5086
5087 const LLT S64 = LLT::scalar(64);
5088 const LLT S32 = LLT::scalar(32);
5089 const unsigned FirstSrcOpIdx = MI.getNumExplicitDefs();
5090 Register Num = MI.getOperand(FirstSrcOpIdx).getReg();
5091 Register Den = MI.getOperand(FirstSrcOpIdx + 1).getReg();
5092 LLT Ty = MRI.getType(MI.getOperand(0).getReg());
5093
5094 if (Ty == S32)
5095 legalizeUnsignedDIV_REM32Impl(B, DstDivReg, DstRemReg, Num, Den);
5096 else if (Ty == S64)
5097 legalizeUnsignedDIV_REM64Impl(B, DstDivReg, DstRemReg, Num, Den);
5098 else
5099 return false;
5100
5101 MI.eraseFromParent();
5102 return true;
5103}
5104
5107 MachineIRBuilder &B) const {
5108 const LLT S64 = LLT::scalar(64);
5109 const LLT S32 = LLT::scalar(32);
5110
5111 LLT Ty = MRI.getType(MI.getOperand(0).getReg());
5112 if (Ty != S32 && Ty != S64)
5113 return false;
5114
5115 const unsigned FirstSrcOpIdx = MI.getNumExplicitDefs();
5116 Register LHS = MI.getOperand(FirstSrcOpIdx).getReg();
5117 Register RHS = MI.getOperand(FirstSrcOpIdx + 1).getReg();
5118
5119 auto SignBitOffset = B.buildConstant(S32, Ty.getSizeInBits() - 1);
5120 auto LHSign = B.buildAShr(Ty, LHS, SignBitOffset);
5121 auto RHSign = B.buildAShr(Ty, RHS, SignBitOffset);
5122
5123 LHS = B.buildAdd(Ty, LHS, LHSign).getReg(0);
5124 RHS = B.buildAdd(Ty, RHS, RHSign).getReg(0);
5125
5126 LHS = B.buildXor(Ty, LHS, LHSign).getReg(0);
5127 RHS = B.buildXor(Ty, RHS, RHSign).getReg(0);
5128
5129 Register DstDivReg, DstRemReg, TmpDivReg, TmpRemReg;
5130 switch (MI.getOpcode()) {
5131 default:
5132 llvm_unreachable("Unexpected opcode!");
5133 case AMDGPU::G_SDIV: {
5134 DstDivReg = MI.getOperand(0).getReg();
5135 TmpDivReg = MRI.createGenericVirtualRegister(Ty);
5136 break;
5137 }
5138 case AMDGPU::G_SREM: {
5139 DstRemReg = MI.getOperand(0).getReg();
5140 TmpRemReg = MRI.createGenericVirtualRegister(Ty);
5141 break;
5142 }
5143 case AMDGPU::G_SDIVREM: {
5144 DstDivReg = MI.getOperand(0).getReg();
5145 DstRemReg = MI.getOperand(1).getReg();
5146 TmpDivReg = MRI.createGenericVirtualRegister(Ty);
5147 TmpRemReg = MRI.createGenericVirtualRegister(Ty);
5148 break;
5149 }
5150 }
5151
5152 if (Ty == S32)
5153 legalizeUnsignedDIV_REM32Impl(B, TmpDivReg, TmpRemReg, LHS, RHS);
5154 else
5155 legalizeUnsignedDIV_REM64Impl(B, TmpDivReg, TmpRemReg, LHS, RHS);
5156
5157 if (DstDivReg) {
5158 auto Sign = B.buildXor(Ty, LHSign, RHSign).getReg(0);
5159 auto SignXor = B.buildXor(Ty, TmpDivReg, Sign).getReg(0);
5160 B.buildSub(DstDivReg, SignXor, Sign);
5161 }
5162
5163 if (DstRemReg) {
5164 auto Sign = LHSign.getReg(0); // Remainder sign is the same as LHS
5165 auto SignXor = B.buildXor(Ty, TmpRemReg, Sign).getReg(0);
5166 B.buildSub(DstRemReg, SignXor, Sign);
5167 }
5168
5169 MI.eraseFromParent();
5170 return true;
5171}
5172
5175 MachineIRBuilder &B) const {
5176 Register Res = MI.getOperand(0).getReg();
5177 Register LHS = MI.getOperand(1).getReg();
5178 Register RHS = MI.getOperand(2).getReg();
5179 uint16_t Flags = MI.getFlags();
5180 LLT ResTy = MRI.getType(Res);
5181
5182 bool AllowInaccurateRcp = MI.getFlag(MachineInstr::FmAfn);
5183
5184 if (const auto *CLHS = getConstantFPVRegVal(LHS, MRI)) {
5185 if (!AllowInaccurateRcp && ResTy != LLT::scalar(16))
5186 return false;
5187
5188 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
5189 // the CI documentation has a worst case error of 1 ulp.
5190 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
5191 // use it as long as we aren't trying to use denormals.
5192 //
5193 // v_rcp_f16 and v_rsq_f16 DO support denormals and 0.51ulp.
5194
5195 // 1 / x -> RCP(x)
5196 if (CLHS->isExactlyValue(1.0)) {
5197 B.buildIntrinsic(Intrinsic::amdgcn_rcp, Res)
5198 .addUse(RHS)
5199 .setMIFlags(Flags);
5200
5201 MI.eraseFromParent();
5202 return true;
5203 }
5204
5205 // -1 / x -> RCP( FNEG(x) )
5206 if (CLHS->isExactlyValue(-1.0)) {
5207 auto FNeg = B.buildFNeg(ResTy, RHS, Flags);
5208 B.buildIntrinsic(Intrinsic::amdgcn_rcp, Res)
5209 .addUse(FNeg.getReg(0))
5210 .setMIFlags(Flags);
5211
5212 MI.eraseFromParent();
5213 return true;
5214 }
5215 }
5216
5217 // For f16 require afn or arcp.
5218 // For f32 require afn.
5219 if (!AllowInaccurateRcp && (ResTy != LLT::scalar(16) ||
5220 !MI.getFlag(MachineInstr::FmArcp)))
5221 return false;
5222
5223 // x / y -> x * (1.0 / y)
5224 auto RCP = B.buildIntrinsic(Intrinsic::amdgcn_rcp, {ResTy})
5225 .addUse(RHS)
5226 .setMIFlags(Flags);
5227 B.buildFMul(Res, LHS, RCP, Flags);
5228
5229 MI.eraseFromParent();
5230 return true;
5231}
5232
5235 MachineIRBuilder &B) const {
5236 Register Res = MI.getOperand(0).getReg();
5237 Register X = MI.getOperand(1).getReg();
5238 Register Y = MI.getOperand(2).getReg();
5239 uint16_t Flags = MI.getFlags();
5240 LLT ResTy = MRI.getType(Res);
5241
5242 bool AllowInaccurateRcp = MI.getFlag(MachineInstr::FmAfn);
5243
5244 if (!AllowInaccurateRcp)
5245 return false;
5246
5247 auto NegY = B.buildFNeg(ResTy, Y);
5248 auto One = B.buildFConstant(ResTy, 1.0);
5249
5250 auto R = B.buildIntrinsic(Intrinsic::amdgcn_rcp, {ResTy})
5251 .addUse(Y)
5252 .setMIFlags(Flags);
5253
5254 auto Tmp0 = B.buildFMA(ResTy, NegY, R, One);
5255 R = B.buildFMA(ResTy, Tmp0, R, R);
5256
5257 auto Tmp1 = B.buildFMA(ResTy, NegY, R, One);
5258 R = B.buildFMA(ResTy, Tmp1, R, R);
5259
5260 auto Ret = B.buildFMul(ResTy, X, R);
5261 auto Tmp2 = B.buildFMA(ResTy, NegY, Ret, X);
5262
5263 B.buildFMA(Res, Tmp2, R, Ret);
5264 MI.eraseFromParent();
5265 return true;
5266}
5267
5270 MachineIRBuilder &B) const {
5272 return true;
5273
5274 Register Res = MI.getOperand(0).getReg();
5275 Register LHS = MI.getOperand(1).getReg();
5276 Register RHS = MI.getOperand(2).getReg();
5277
5278 uint16_t Flags = MI.getFlags();
5279
5280 LLT S16 = LLT::scalar(16);
5281 LLT S32 = LLT::scalar(32);
5282
5283 // a32.u = opx(V_CVT_F32_F16, a.u); // CVT to F32
5284 // b32.u = opx(V_CVT_F32_F16, b.u); // CVT to F32
5285 // r32.u = opx(V_RCP_F32, b32.u); // rcp = 1 / d
5286 // q32.u = opx(V_MUL_F32, a32.u, r32.u); // q = n * rcp
5287 // e32.u = opx(V_MAD_F32, (b32.u^_neg32), q32.u, a32.u); // err = -d * q + n
5288 // q32.u = opx(V_MAD_F32, e32.u, r32.u, q32.u); // q = n * rcp
5289 // e32.u = opx(V_MAD_F32, (b32.u^_neg32), q32.u, a32.u); // err = -d * q + n
5290 // tmp.u = opx(V_MUL_F32, e32.u, r32.u);
5291 // tmp.u = opx(V_AND_B32, tmp.u, 0xff800000)
5292 // q32.u = opx(V_ADD_F32, tmp.u, q32.u);
5293 // q16.u = opx(V_CVT_F16_F32, q32.u);
5294 // q16.u = opx(V_DIV_FIXUP_F16, q16.u, b.u, a.u); // q = touchup(q, d, n)
5295
5296 auto LHSExt = B.buildFPExt(S32, LHS, Flags);
5297 auto RHSExt = B.buildFPExt(S32, RHS, Flags);
5298 auto NegRHSExt = B.buildFNeg(S32, RHSExt);
5299 auto Rcp = B.buildIntrinsic(Intrinsic::amdgcn_rcp, {S32})
5300 .addUse(RHSExt.getReg(0))
5301 .setMIFlags(Flags);
5302 auto Quot = B.buildFMul(S32, LHSExt, Rcp, Flags);
5304 if (ST.hasMadMacF32Insts()) {
5305 Err = B.buildFMAD(S32, NegRHSExt, Quot, LHSExt, Flags);
5306 Quot = B.buildFMAD(S32, Err, Rcp, Quot, Flags);
5307 Err = B.buildFMAD(S32, NegRHSExt, Quot, LHSExt, Flags);
5308 } else {
5309 Err = B.buildFMA(S32, NegRHSExt, Quot, LHSExt, Flags);
5310 Quot = B.buildFMA(S32, Err, Rcp, Quot, Flags);
5311 Err = B.buildFMA(S32, NegRHSExt, Quot, LHSExt, Flags);
5312 }
5313 auto Tmp = B.buildFMul(S32, Err, Rcp, Flags);
5314 Tmp = B.buildAnd(S32, Tmp, B.buildConstant(S32, 0xff800000));
5315 Quot = B.buildFAdd(S32, Tmp, Quot, Flags);
5316 auto RDst = B.buildFPTrunc(S16, Quot, Flags);
5317 B.buildIntrinsic(Intrinsic::amdgcn_div_fixup, Res)
5318 .addUse(RDst.getReg(0))
5319 .addUse(RHS)
5320 .addUse(LHS)
5321 .setMIFlags(Flags);
5322
5323 MI.eraseFromParent();
5324 return true;
5325}
5326
5327static constexpr unsigned SPDenormModeBitField =
5329
5330// Enable or disable FP32 denorm mode. When 'Enable' is true, emit instructions
5331// to enable denorm mode. When 'Enable' is false, disable denorm mode.
5333 const GCNSubtarget &ST,
5335 // Set SP denorm mode to this value.
5336 unsigned SPDenormMode =
5337 Enable ? FP_DENORM_FLUSH_NONE : Mode.fpDenormModeSPValue();
5338
5339 if (ST.hasDenormModeInst()) {
5340 // Preserve default FP64FP16 denorm mode while updating FP32 mode.
5341 uint32_t DPDenormModeDefault = Mode.fpDenormModeDPValue();
5342
5343 uint32_t NewDenormModeValue = SPDenormMode | (DPDenormModeDefault << 2);
5344 B.buildInstr(AMDGPU::S_DENORM_MODE)
5345 .addImm(NewDenormModeValue);
5346
5347 } else {
5348 B.buildInstr(AMDGPU::S_SETREG_IMM32_B32)
5349 .addImm(SPDenormMode)
5350 .addImm(SPDenormModeBitField);
5351 }
5352}
5353
5356 MachineIRBuilder &B) const {
5358 return true;
5359
5360 Register Res = MI.getOperand(0).getReg();
5361 Register LHS = MI.getOperand(1).getReg();
5362 Register RHS = MI.getOperand(2).getReg();
5363 const SIMachineFunctionInfo *MFI = B.getMF().getInfo<SIMachineFunctionInfo>();
5364 SIModeRegisterDefaults Mode = MFI->getMode();
5365
5366 uint16_t Flags = MI.getFlags();
5367
5368 LLT S32 = LLT::scalar(32);
5369 LLT S1 = LLT::scalar(1);
5370
5371 auto One = B.buildFConstant(S32, 1.0f);
5372
5373 auto DenominatorScaled =
5374 B.buildIntrinsic(Intrinsic::amdgcn_div_scale, {S32, S1})
5375 .addUse(LHS)
5376 .addUse(RHS)
5377 .addImm(0)
5378 .setMIFlags(Flags);
5379 auto NumeratorScaled =
5380 B.buildIntrinsic(Intrinsic::amdgcn_div_scale, {S32, S1})
5381 .addUse(LHS)
5382 .addUse(RHS)
5383 .addImm(1)
5384 .setMIFlags(Flags);
5385
5386 auto ApproxRcp = B.buildIntrinsic(Intrinsic::amdgcn_rcp, {S32})
5387 .addUse(DenominatorScaled.getReg(0))
5388 .setMIFlags(Flags);
5389 auto NegDivScale0 = B.buildFNeg(S32, DenominatorScaled, Flags);
5390
5391 const bool PreservesDenormals = Mode.FP32Denormals == DenormalMode::getIEEE();
5392 const bool HasDynamicDenormals =
5393 (Mode.FP32Denormals.Input == DenormalMode::Dynamic) ||
5394 (Mode.FP32Denormals.Output == DenormalMode::Dynamic);
5395
5396 Register SavedSPDenormMode;
5397 if (!PreservesDenormals) {
5398 if (HasDynamicDenormals) {
5399 SavedSPDenormMode = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5400 B.buildInstr(AMDGPU::S_GETREG_B32)
5401 .addDef(SavedSPDenormMode)
5402 .addImm(SPDenormModeBitField);
5403 }
5404 toggleSPDenormMode(true, B, ST, Mode);
5405 }
5406
5407 auto Fma0 = B.buildFMA(S32, NegDivScale0, ApproxRcp, One, Flags);
5408 auto Fma1 = B.buildFMA(S32, Fma0, ApproxRcp, ApproxRcp, Flags);
5409 auto Mul = B.buildFMul(S32, NumeratorScaled, Fma1, Flags);
5410 auto Fma2 = B.buildFMA(S32, NegDivScale0, Mul, NumeratorScaled, Flags);
5411 auto Fma3 = B.buildFMA(S32, Fma2, Fma1, Mul, Flags);
5412 auto Fma4 = B.buildFMA(S32, NegDivScale0, Fma3, NumeratorScaled, Flags);
5413
5414 if (!PreservesDenormals) {
5415 if (HasDynamicDenormals) {
5416 assert(SavedSPDenormMode);
5417 B.buildInstr(AMDGPU::S_SETREG_B32)
5418 .addReg(SavedSPDenormMode)
5419 .addImm(SPDenormModeBitField);
5420 } else
5421 toggleSPDenormMode(false, B, ST, Mode);
5422 }
5423
5424 auto Fmas = B.buildIntrinsic(Intrinsic::amdgcn_div_fmas, {S32})
5425 .addUse(Fma4.getReg(0))
5426 .addUse(Fma1.getReg(0))
5427 .addUse(Fma3.getReg(0))
5428 .addUse(NumeratorScaled.getReg(1))
5429 .setMIFlags(Flags);
5430
5431 B.buildIntrinsic(Intrinsic::amdgcn_div_fixup, Res)
5432 .addUse(Fmas.getReg(0))
5433 .addUse(RHS)
5434 .addUse(LHS)
5435 .setMIFlags(Flags);
5436
5437 MI.eraseFromParent();
5438 return true;
5439}
5440
5443 MachineIRBuilder &B) const {
5445 return true;
5446
5447 Register Res = MI.getOperand(0).getReg();
5448 Register LHS = MI.getOperand(1).getReg();
5449 Register RHS = MI.getOperand(2).getReg();
5450
5451 uint16_t Flags = MI.getFlags();
5452
5453 LLT S64 = LLT::scalar(64);
5454 LLT S1 = LLT::scalar(1);
5455
5456 auto One = B.buildFConstant(S64, 1.0);
5457
5458 auto DivScale0 = B.buildIntrinsic(Intrinsic::amdgcn_div_scale, {S64, S1})
5459 .addUse(LHS)
5460 .addUse(RHS)
5461 .addImm(0)
5462 .setMIFlags(Flags);
5463
5464 auto NegDivScale0 = B.buildFNeg(S64, DivScale0.getReg(0), Flags);
5465
5466 auto Rcp = B.buildIntrinsic(Intrinsic::amdgcn_rcp, {S64})
5467 .addUse(DivScale0.getReg(0))
5468 .setMIFlags(Flags);
5469
5470 auto Fma0 = B.buildFMA(S64, NegDivScale0, Rcp, One, Flags);
5471 auto Fma1 = B.buildFMA(S64, Rcp, Fma0, Rcp, Flags);
5472 auto Fma2 = B.buildFMA(S64, NegDivScale0, Fma1, One, Flags);
5473
5474 auto DivScale1 = B.buildIntrinsic(Intrinsic::amdgcn_div_scale, {S64, S1})
5475 .addUse(LHS)
5476 .addUse(RHS)
5477 .addImm(1)
5478 .setMIFlags(Flags);
5479
5480 auto Fma3 = B.buildFMA(S64, Fma1, Fma2, Fma1, Flags);
5481 auto Mul = B.buildFMul(S64, DivScale1.getReg(0), Fma3, Flags);
5482 auto Fma4 = B.buildFMA(S64, NegDivScale0, Mul, DivScale1.getReg(0), Flags);
5483
5484 Register Scale;
5485 if (!ST.hasUsableDivScaleConditionOutput()) {
5486 // Workaround a hardware bug on SI where the condition output from div_scale
5487 // is not usable.
5488
5489 LLT S32 = LLT::scalar(32);
5490
5491 auto NumUnmerge = B.buildUnmerge(S32, LHS);
5492 auto DenUnmerge = B.buildUnmerge(S32, RHS);
5493 auto Scale0Unmerge = B.buildUnmerge(S32, DivScale0);
5494 auto Scale1Unmerge = B.buildUnmerge(S32, DivScale1);
5495
5496 auto CmpNum = B.buildICmp(ICmpInst::ICMP_EQ, S1, NumUnmerge.getReg(1),
5497 Scale1Unmerge.getReg(1));
5498 auto CmpDen = B.buildICmp(ICmpInst::ICMP_EQ, S1, DenUnmerge.getReg(1),
5499 Scale0Unmerge.getReg(1));
5500 Scale = B.buildXor(S1, CmpNum, CmpDen).getReg(0);
5501 } else {
5502 Scale = DivScale1.getReg(1);
5503 }
5504
5505 auto Fmas = B.buildIntrinsic(Intrinsic::amdgcn_div_fmas, {S64})
5506 .addUse(Fma4.getReg(0))
5507 .addUse(Fma3.getReg(0))
5508 .addUse(Mul.getReg(0))
5509 .addUse(Scale)
5510 .setMIFlags(Flags);
5511
5512 B.buildIntrinsic(Intrinsic::amdgcn_div_fixup, ArrayRef(Res))
5513 .addUse(Fmas.getReg(0))
5514 .addUse(RHS)
5515 .addUse(LHS)
5516 .setMIFlags(Flags);
5517
5518 MI.eraseFromParent();
5519 return true;
5520}
5521
5524 MachineIRBuilder &B) const {
5525 Register Res0 = MI.getOperand(0).getReg();
5526 Register Res1 = MI.getOperand(1).getReg();
5527 Register Val = MI.getOperand(2).getReg();
5528 uint16_t Flags = MI.getFlags();
5529
5530 LLT Ty = MRI.getType(Res0);
5531 LLT InstrExpTy = Ty == LLT::scalar(16) ? LLT::scalar(16) : LLT::scalar(32);
5532
5533 auto Mant = B.buildIntrinsic(Intrinsic::amdgcn_frexp_mant, {Ty})
5534 .addUse(Val)
5535 .setMIFlags(Flags);
5536 auto Exp = B.buildIntrinsic(Intrinsic::amdgcn_frexp_exp, {InstrExpTy})
5537 .addUse(Val)
5538 .setMIFlags(Flags);
5539
5540 if (ST.hasFractBug()) {
5541 auto Fabs = B.buildFAbs(Ty, Val);
5542 auto Inf = B.buildFConstant(Ty, APFloat::getInf(getFltSemanticForLLT(Ty)));
5543 auto IsFinite =
5544 B.buildFCmp(CmpInst::FCMP_OLT, LLT::scalar(1), Fabs, Inf, Flags);
5545 auto Zero = B.buildConstant(InstrExpTy, 0);
5546 Exp = B.buildSelect(InstrExpTy, IsFinite, Exp, Zero);
5547 Mant = B.buildSelect(Ty, IsFinite, Mant, Val);
5548 }
5549
5550 B.buildCopy(Res0, Mant);
5551 B.buildSExtOrTrunc(Res1, Exp);
5552
5553 MI.eraseFromParent();
5554 return true;
5555}
5556
5559 MachineIRBuilder &B) const {
5560 Register Res = MI.getOperand(0).getReg();
5561 Register LHS = MI.getOperand(2).getReg();
5562 Register RHS = MI.getOperand(3).getReg();
5563 uint16_t Flags = MI.getFlags();
5564
5565 LLT S32 = LLT::scalar(32);
5566 LLT S1 = LLT::scalar(1);
5567
5568 auto Abs = B.buildFAbs(S32, RHS, Flags);
5569 const APFloat C0Val(1.0f);
5570
5571 auto C0 = B.buildFConstant(S32, 0x1p+96f);
5572 auto C1 = B.buildFConstant(S32, 0x1p-32f);
5573 auto C2 = B.buildFConstant(S32, 1.0f);
5574
5575 auto CmpRes = B.buildFCmp(CmpInst::FCMP_OGT, S1, Abs, C0, Flags);
5576 auto Sel = B.buildSelect(S32, CmpRes, C1, C2, Flags);
5577
5578 auto Mul0 = B.buildFMul(S32, RHS, Sel, Flags);
5579
5580 auto RCP = B.buildIntrinsic(Intrinsic::amdgcn_rcp, {S32})
5581 .addUse(Mul0.getReg(0))
5582 .setMIFlags(Flags);
5583
5584 auto Mul1 = B.buildFMul(S32, LHS, RCP, Flags);
5585
5586 B.buildFMul(Res, Sel, Mul1, Flags);
5587
5588 MI.eraseFromParent();
5589 return true;
5590}
5591
5594 MachineIRBuilder &B) const {
5595 // Bypass the correct expansion a standard promotion through G_FSQRT would
5596 // get. The f32 op is accurate enough for the f16 cas.
5597 unsigned Flags = MI.getFlags();
5598 assert(!ST.has16BitInsts());
5599 const LLT F32 = LLT::scalar(32);
5600 auto Ext = B.buildFPExt(F32, MI.getOperand(1), Flags);
5601 auto Log2 = B.buildIntrinsic(Intrinsic::amdgcn_sqrt, {F32})
5602 .addUse(Ext.getReg(0))
5603 .setMIFlags(Flags);
5604 B.buildFPTrunc(MI.getOperand(0), Log2, Flags);
5605 MI.eraseFromParent();
5606 return true;
5607}
5608
5611 MachineIRBuilder &B) const {
5612 MachineFunction &MF = B.getMF();
5613 Register Dst = MI.getOperand(0).getReg();
5614 Register X = MI.getOperand(1).getReg();
5615 const unsigned Flags = MI.getFlags();
5616 const LLT S1 = LLT::scalar(1);
5617 const LLT F32 = LLT::scalar(32);
5618 const LLT I32 = LLT::scalar(32);
5619
5620 if (allowApproxFunc(MF, Flags)) {
5621 B.buildIntrinsic(Intrinsic::amdgcn_sqrt, ArrayRef<Register>({Dst}))
5622 .addUse(X)
5623 .setMIFlags(Flags);
5624 MI.eraseFromParent();
5625 return true;
5626 }
5627
5628 auto ScaleThreshold = B.buildFConstant(F32, 0x1.0p-96f);
5629 auto NeedScale = B.buildFCmp(CmpInst::FCMP_OGT, S1, ScaleThreshold, X, Flags);
5630 auto ScaleUpFactor = B.buildFConstant(F32, 0x1.0p+32f);
5631 auto ScaledX = B.buildFMul(F32, X, ScaleUpFactor, Flags);
5632 auto SqrtX = B.buildSelect(F32, NeedScale, ScaledX, X, Flags);
5633
5634 Register SqrtS = MRI.createGenericVirtualRegister(F32);
5635 if (needsDenormHandlingF32(MF, X, Flags)) {
5636 B.buildIntrinsic(Intrinsic::amdgcn_sqrt, ArrayRef<Register>({SqrtS}))
5637 .addUse(SqrtX.getReg(0))
5638 .setMIFlags(Flags);
5639
5640 auto NegOne = B.buildConstant(I32, -1);
5641 auto SqrtSNextDown = B.buildAdd(I32, SqrtS, NegOne);
5642
5643 auto NegSqrtSNextDown = B.buildFNeg(F32, SqrtSNextDown, Flags);
5644 auto SqrtVP = B.buildFMA(F32, NegSqrtSNextDown, SqrtS, SqrtX, Flags);
5645
5646 auto PosOne = B.buildConstant(I32, 1);
5647 auto SqrtSNextUp = B.buildAdd(I32, SqrtS, PosOne);
5648
5649 auto NegSqrtSNextUp = B.buildFNeg(F32, SqrtSNextUp, Flags);
5650 auto SqrtVS = B.buildFMA(F32, NegSqrtSNextUp, SqrtS, SqrtX, Flags);
5651
5652 auto Zero = B.buildFConstant(F32, 0.0f);
5653 auto SqrtVPLE0 = B.buildFCmp(CmpInst::FCMP_OLE, S1, SqrtVP, Zero, Flags);
5654
5655 SqrtS =
5656 B.buildSelect(F32, SqrtVPLE0, SqrtSNextDown, SqrtS, Flags).getReg(0);
5657
5658 auto SqrtVPVSGT0 = B.buildFCmp(CmpInst::FCMP_OGT, S1, SqrtVS, Zero, Flags);
5659 SqrtS =
5660 B.buildSelect(F32, SqrtVPVSGT0, SqrtSNextUp, SqrtS, Flags).getReg(0);
5661 } else {
5662 auto SqrtR =
5663 B.buildIntrinsic(Intrinsic::amdgcn_rsq, {F32}).addReg(SqrtX.getReg(0));
5664 B.buildFMul(SqrtS, SqrtX, SqrtR, Flags);
5665
5666 auto Half = B.buildFConstant(F32, 0.5f);
5667 auto SqrtH = B.buildFMul(F32, SqrtR, Half, Flags);
5668 auto NegSqrtH = B.buildFNeg(F32, SqrtH, Flags);
5669 auto SqrtE = B.buildFMA(F32, NegSqrtH, SqrtS, Half, Flags);
5670 SqrtH = B.buildFMA(F32, SqrtH, SqrtE, SqrtH, Flags);
5671 SqrtS = B.buildFMA(F32, SqrtS, SqrtE, SqrtS, Flags).getReg(0);
5672 auto NegSqrtS = B.buildFNeg(F32, SqrtS, Flags);
5673 auto SqrtD = B.buildFMA(F32, NegSqrtS, SqrtS, SqrtX, Flags);
5674 SqrtS = B.buildFMA(F32, SqrtD, SqrtH, SqrtS, Flags).getReg(0);
5675 }
5676
5677 auto ScaleDownFactor = B.buildFConstant(F32, 0x1.0p-16f);
5678
5679 auto ScaledDown = B.buildFMul(F32, SqrtS, ScaleDownFactor, Flags);
5680
5681 SqrtS = B.buildSelect(F32, NeedScale, ScaledDown, SqrtS, Flags).getReg(0);
5682
5683 auto IsZeroOrInf = B.buildIsFPClass(LLT::scalar(1), SqrtX, fcZero | fcPosInf);
5684 B.buildSelect(Dst, IsZeroOrInf, SqrtX, SqrtS, Flags);
5685
5686 MI.eraseFromParent();
5687 return true;
5688}
5689
5692 MachineIRBuilder &B) const {
5693 // For double type, the SQRT and RSQ instructions don't have required
5694 // precision, we apply Goldschmidt's algorithm to improve the result:
5695 //
5696 // y0 = rsq(x)
5697 // g0 = x * y0
5698 // h0 = 0.5 * y0
5699 //
5700 // r0 = 0.5 - h0 * g0
5701 // g1 = g0 * r0 + g0
5702 // h1 = h0 * r0 + h0
5703 //
5704 // r1 = 0.5 - h1 * g1 => d0 = x - g1 * g1
5705 // g2 = g1 * r1 + g1 g2 = d0 * h1 + g1
5706 // h2 = h1 * r1 + h1
5707 //
5708 // r2 = 0.5 - h2 * g2 => d1 = x - g2 * g2
5709 // g3 = g2 * r2 + g2 g3 = d1 * h1 + g2
5710 //
5711 // sqrt(x) = g3
5712
5713 const LLT S1 = LLT::scalar(1);
5714 const LLT S32 = LLT::scalar(32);
5715 const LLT F64 = LLT::scalar(64);
5716
5717 Register Dst = MI.getOperand(0).getReg();
5718 assert(MRI.getType(Dst) == F64 && "only expect to lower f64 sqrt");
5719
5720 Register X = MI.getOperand(1).getReg();
5721 unsigned Flags = MI.getFlags();
5722
5723 auto ScaleConstant = B.buildFConstant(F64, 0x1.0p-767);
5724
5725 auto ZeroInt = B.buildConstant(S32, 0);
5726 auto Scaling = B.buildFCmp(FCmpInst::FCMP_OLT, S1, X, ScaleConstant);
5727
5728 // Scale up input if it is too small.
5729 auto ScaleUpFactor = B.buildConstant(S32, 256);
5730 auto ScaleUp = B.buildSelect(S32, Scaling, ScaleUpFactor, ZeroInt);
5731 auto SqrtX = B.buildFLdexp(F64, X, ScaleUp, Flags);
5732
5733 auto SqrtY =
5734 B.buildIntrinsic(Intrinsic::amdgcn_rsq, {F64}).addReg(SqrtX.getReg(0));
5735
5736 auto Half = B.buildFConstant(F64, 0.5);
5737 auto SqrtH0 = B.buildFMul(F64, SqrtY, Half);
5738 auto SqrtS0 = B.buildFMul(F64, SqrtX, SqrtY);
5739
5740 auto NegSqrtH0 = B.buildFNeg(F64, SqrtH0);
5741 auto SqrtR0 = B.buildFMA(F64, NegSqrtH0, SqrtS0, Half);
5742
5743 auto SqrtS1 = B.buildFMA(F64, SqrtS0, SqrtR0, SqrtS0);
5744 auto SqrtH1 = B.buildFMA(F64, SqrtH0, SqrtR0, SqrtH0);
5745
5746 auto NegSqrtS1 = B.buildFNeg(F64, SqrtS1);
5747 auto SqrtD0 = B.buildFMA(F64, NegSqrtS1, SqrtS1, SqrtX);
5748
5749 auto SqrtS2 = B.buildFMA(F64, SqrtD0, SqrtH1, SqrtS1);
5750
5751 auto NegSqrtS2 = B.buildFNeg(F64, SqrtS2);
5752 auto SqrtD1 = B.buildFMA(F64, NegSqrtS2, SqrtS2, SqrtX);
5753
5754 auto SqrtRet = B.buildFMA(F64, SqrtD1, SqrtH1, SqrtS2);
5755
5756 // Scale down the result.
5757 auto ScaleDownFactor = B.buildConstant(S32, -128);
5758 auto ScaleDown = B.buildSelect(S32, Scaling, ScaleDownFactor, ZeroInt);
5759 SqrtRet = B.buildFLdexp(F64, SqrtRet, ScaleDown, Flags);
5760
5761 // TODO: Switch to fcmp oeq 0 for finite only. Can't fully remove this check
5762 // with finite only or nsz because rsq(+/-0) = +/-inf
5763
5764 // TODO: Check for DAZ and expand to subnormals
5765 auto IsZeroOrInf = B.buildIsFPClass(LLT::scalar(1), SqrtX, fcZero | fcPosInf);
5766
5767 // If x is +INF, +0, or -0, use its original value
5768 B.buildSelect(Dst, IsZeroOrInf, SqrtX, SqrtRet, Flags);
5769
5770 MI.eraseFromParent();
5771 return true;
5772}
5773
5776 MachineIRBuilder &B) const {
5777 LLT Ty = MRI.getType(MI.getOperand(0).getReg());
5778 if (Ty == LLT::scalar(32))
5779 return legalizeFSQRTF32(MI, MRI, B);
5780 if (Ty == LLT::scalar(64))
5781 return legalizeFSQRTF64(MI, MRI, B);
5782 if (Ty == LLT::scalar(16))
5783 return legalizeFSQRTF16(MI, MRI, B);
5784 return false;
5785}
5786
5787// Expand llvm.amdgcn.rsq.clamp on targets that don't support the instruction.
5788// FIXME: Why do we handle this one but not other removed instructions?
5789//
5790// Reciprocal square root. The clamp prevents infinite results, clamping
5791// infinities to max_float. D.f = 1.0 / sqrt(S0.f), result clamped to
5792// +-max_float.
5795 MachineIRBuilder &B) const {
5796 if (ST.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5797 return true;
5798
5799 Register Dst = MI.getOperand(0).getReg();
5800 Register Src = MI.getOperand(2).getReg();
5801 auto Flags = MI.getFlags();
5802
5803 LLT Ty = MRI.getType(Dst);
5804
5805 const fltSemantics *FltSemantics;
5806 if (Ty == LLT::scalar(32))
5807 FltSemantics = &APFloat::IEEEsingle();
5808 else if (Ty == LLT::scalar(64))
5809 FltSemantics = &APFloat::IEEEdouble();
5810 else
5811 return false;
5812
5813 auto Rsq = B.buildIntrinsic(Intrinsic::amdgcn_rsq, {Ty})
5814 .addUse(Src)
5815 .setMIFlags(Flags);
5816
5817 // We don't need to concern ourselves with the snan handling difference, since
5818 // the rsq quieted (or not) so use the one which will directly select.
5819 const SIMachineFunctionInfo *MFI = B.getMF().getInfo<SIMachineFunctionInfo>();
5820 const bool UseIEEE = MFI->getMode().IEEE;
5821
5822 auto MaxFlt = B.buildFConstant(Ty, APFloat::getLargest(*FltSemantics));
5823 auto ClampMax = UseIEEE ? B.buildFMinNumIEEE(Ty, Rsq, MaxFlt, Flags) :
5824 B.buildFMinNum(Ty, Rsq, MaxFlt, Flags);
5825
5826 auto MinFlt = B.buildFConstant(Ty, APFloat::getLargest(*FltSemantics, true));
5827
5828 if (UseIEEE)
5829 B.buildFMaxNumIEEE(Dst, ClampMax, MinFlt, Flags);
5830 else
5831 B.buildFMaxNum(Dst, ClampMax, MinFlt, Flags);
5832 MI.eraseFromParent();
5833 return true;
5834}
5835
5836// TODO: Fix pointer type handling
5839 Intrinsic::ID IID) const {
5840
5841 MachineIRBuilder &B = Helper.MIRBuilder;
5842 MachineRegisterInfo &MRI = *B.getMRI();
5843
5844 bool IsPermLane16 = IID == Intrinsic::amdgcn_permlane16 ||
5845 IID == Intrinsic::amdgcn_permlanex16;
5846 bool IsSetInactive = IID == Intrinsic::amdgcn_set_inactive ||
5847 IID == Intrinsic::amdgcn_set_inactive_chain_arg;
5848
5849 auto createLaneOp = [&IID, &B, &MI](Register Src0, Register Src1,
5850 Register Src2, LLT VT) -> Register {
5851 auto LaneOp = B.buildIntrinsic(IID, {VT}).addUse(Src0);
5852 switch (IID) {
5853 case Intrinsic::amdgcn_readfirstlane:
5854 case Intrinsic::amdgcn_permlane64:
5855 return LaneOp.getReg(0);
5856 case Intrinsic::amdgcn_readlane:
5857 case Intrinsic::amdgcn_set_inactive:
5858 case Intrinsic::amdgcn_set_inactive_chain_arg:
5859 return LaneOp.addUse(Src1).getReg(0);
5860 case Intrinsic::amdgcn_writelane:
5861 return LaneOp.addUse(Src1).addUse(Src2).getReg(0);
5862 case Intrinsic::amdgcn_permlane16:
5863 case Intrinsic::amdgcn_permlanex16: {
5864 Register Src3 = MI.getOperand(5).getReg();
5865 int64_t Src4 = MI.getOperand(6).getImm();
5866 int64_t Src5 = MI.getOperand(7).getImm();
5867 return LaneOp.addUse(Src1)
5868 .addUse(Src2)
5869 .addUse(Src3)
5870 .addImm(Src4)
5871 .addImm(Src5)
5872 .getReg(0);
5873 }
5874 case Intrinsic::amdgcn_mov_dpp8:
5875 return LaneOp.addImm(MI.getOperand(3).getImm()).getReg(0);
5876 case Intrinsic::amdgcn_update_dpp:
5877 return LaneOp.addUse(Src1)
5878 .addImm(MI.getOperand(4).getImm())
5879 .addImm(MI.getOperand(5).getImm())
5880 .addImm(MI.getOperand(6).getImm())
5881 .addImm(MI.getOperand(7).getImm())
5882 .getReg(0);
5883 default:
5884 llvm_unreachable("unhandled lane op");
5885 }
5886 };
5887
5888 Register DstReg = MI.getOperand(0).getReg();
5889 Register Src0 = MI.getOperand(2).getReg();
5890 Register Src1, Src2;
5891 if (IID == Intrinsic::amdgcn_readlane || IID == Intrinsic::amdgcn_writelane ||
5892 IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16) {
5893 Src1 = MI.getOperand(3).getReg();
5894 if (IID == Intrinsic::amdgcn_writelane || IsPermLane16) {
5895 Src2 = MI.getOperand(4).getReg();
5896 }
5897 }
5898
5899 LLT Ty = MRI.getType(DstReg);
5900 unsigned Size = Ty.getSizeInBits();
5901
5902 unsigned SplitSize = 32;
5903 if (IID == Intrinsic::amdgcn_update_dpp && (Size % 64 == 0) &&
5904 ST.hasDPALU_DPP() &&
5905 AMDGPU::isLegalDPALU_DPPControl(ST, MI.getOperand(4).getImm()))
5906 SplitSize = 64;
5907
5908 if (Size == SplitSize) {
5909 // Already legal
5910 return true;
5911 }
5912
5913 if (Size < 32) {
5914 Src0 = B.buildAnyExt(S32, Src0).getReg(0);
5915
5916 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16)
5917 Src1 = B.buildAnyExt(LLT::scalar(32), Src1).getReg(0);
5918
5919 if (IID == Intrinsic::amdgcn_writelane)
5920 Src2 = B.buildAnyExt(LLT::scalar(32), Src2).getReg(0);
5921
5922 Register LaneOpDst = createLaneOp(Src0, Src1, Src2, S32);
5923 B.buildTrunc(DstReg, LaneOpDst);
5924 MI.eraseFromParent();
5925 return true;
5926 }
5927
5928 if (Size % SplitSize != 0)
5929 return false;
5930
5931 LLT PartialResTy = LLT::scalar(SplitSize);
5932 bool NeedsBitcast = false;
5933 if (Ty.isVector()) {
5934 LLT EltTy = Ty.getElementType();
5935 unsigned EltSize = EltTy.getSizeInBits();
5936 if (EltSize == SplitSize) {
5937 PartialResTy = EltTy;
5938 } else if (EltSize == 16 || EltSize == 32) {
5939 unsigned NElem = SplitSize / EltSize;
5940 PartialResTy = Ty.changeElementCount(ElementCount::getFixed(NElem));
5941 } else {
5942 // Handle all other cases via S32/S64 pieces
5943 NeedsBitcast = true;
5944 }
5945 }
5946
5947 SmallVector<Register, 4> PartialRes;
5948 unsigned NumParts = Size / SplitSize;
5949 MachineInstrBuilder Src0Parts = B.buildUnmerge(PartialResTy, Src0);
5950 MachineInstrBuilder Src1Parts, Src2Parts;
5951
5952 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16)
5953 Src1Parts = B.buildUnmerge(PartialResTy, Src1);
5954
5955 if (IID == Intrinsic::amdgcn_writelane)
5956 Src2Parts = B.buildUnmerge(PartialResTy, Src2);
5957
5958 for (unsigned i = 0; i < NumParts; ++i) {
5959 Src0 = Src0Parts.getReg(i);
5960
5961 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16)
5962 Src1 = Src1Parts.getReg(i);
5963
5964 if (IID == Intrinsic::amdgcn_writelane)
5965 Src2 = Src2Parts.getReg(i);
5966
5967 PartialRes.push_back(createLaneOp(Src0, Src1, Src2, PartialResTy));
5968 }
5969
5970 if (NeedsBitcast)
5971 B.buildBitcast(DstReg, B.buildMergeLikeInstr(
5972 LLT::scalar(Ty.getSizeInBits()), PartialRes));
5973 else
5974 B.buildMergeLikeInstr(DstReg, PartialRes);
5975
5976 MI.eraseFromParent();
5977 return true;
5978}
5979
5982 MachineIRBuilder &B) const {
5984 ST.getTargetLowering()->getImplicitParameterOffset(
5986 LLT DstTy = MRI.getType(DstReg);
5987 LLT IdxTy = LLT::scalar(DstTy.getSizeInBits());
5988
5989 Register KernargPtrReg = MRI.createGenericVirtualRegister(DstTy);
5990 if (!loadInputValue(KernargPtrReg, B,
5992 return false;
5993
5994 B.buildObjectPtrOffset(DstReg, KernargPtrReg,
5995 B.buildConstant(IdxTy, Offset).getReg(0));
5996 return true;
5997}
5998
5999/// To create a buffer resource from a 64-bit pointer, mask off the upper 32
6000/// bits of the pointer and replace them with the stride argument, then
6001/// merge_values everything together. In the common case of a raw buffer (the
6002/// stride component is 0), we can just AND off the upper half.
6005 Register Result = MI.getOperand(0).getReg();
6006 Register Pointer = MI.getOperand(2).getReg();
6007 Register Stride = MI.getOperand(3).getReg();
6008 Register NumRecords = MI.getOperand(4).getReg();
6009 Register Flags = MI.getOperand(5).getReg();
6010
6011 LLT S32 = LLT::scalar(32);
6012 LLT S64 = LLT::scalar(64);
6013
6014 B.setInsertPt(B.getMBB(), ++B.getInsertPt());
6015
6016 auto ExtStride = B.buildAnyExt(S32, Stride);
6017
6018 if (ST.has45BitNumRecordsBufferResource()) {
6019 Register Zero = B.buildConstant(S32, 0).getReg(0);
6020 // Build the lower 64-bit value, which has a 57-bit base and the lower 7-bit
6021 // num_records.
6022 LLT PtrIntTy = LLT::scalar(MRI.getType(Pointer).getSizeInBits());
6023 auto PointerInt = B.buildPtrToInt(PtrIntTy, Pointer);
6024 auto ExtPointer = B.buildAnyExtOrTrunc(S64, PointerInt);
6025 auto NumRecordsLHS = B.buildShl(S64, NumRecords, B.buildConstant(S32, 57));
6026 Register LowHalf = B.buildOr(S64, ExtPointer, NumRecordsLHS).getReg(0);
6027
6028 // Build the higher 64-bit value, which has the higher 38-bit num_records,
6029 // 6-bit zero (omit), 16-bit stride and scale and 4-bit flag.
6030 auto NumRecordsRHS = B.buildLShr(S64, NumRecords, B.buildConstant(S32, 7));
6031 auto ShiftedStride = B.buildShl(S32, ExtStride, B.buildConstant(S32, 12));
6032 auto ExtShiftedStride =
6033 B.buildMergeValues(S64, {Zero, ShiftedStride.getReg(0)});
6034 auto ShiftedFlags = B.buildShl(S32, Flags, B.buildConstant(S32, 28));
6035 auto ExtShiftedFlags =
6036 B.buildMergeValues(S64, {Zero, ShiftedFlags.getReg(0)});
6037 auto CombinedFields = B.buildOr(S64, NumRecordsRHS, ExtShiftedStride);
6038 Register HighHalf =
6039 B.buildOr(S64, CombinedFields, ExtShiftedFlags).getReg(0);
6040 B.buildMergeValues(Result, {LowHalf, HighHalf});
6041 } else {
6042 NumRecords = B.buildTrunc(S32, NumRecords).getReg(0);
6043 auto Unmerge = B.buildUnmerge(S32, Pointer);
6044 auto LowHalf = Unmerge.getReg(0);
6045 auto HighHalf = Unmerge.getReg(1);
6046
6047 auto AndMask = B.buildConstant(S32, 0x0000ffff);
6048 auto Masked = B.buildAnd(S32, HighHalf, AndMask);
6049 auto ShiftConst = B.buildConstant(S32, 16);
6050 auto ShiftedStride = B.buildShl(S32, ExtStride, ShiftConst);
6051 auto NewHighHalf = B.buildOr(S32, Masked, ShiftedStride);
6052 Register NewHighHalfReg = NewHighHalf.getReg(0);
6053 B.buildMergeValues(Result, {LowHalf, NewHighHalfReg, NumRecords, Flags});
6054 }
6055
6056 MI.eraseFromParent();
6057 return true;
6058}
6059
6062 MachineIRBuilder &B) const {
6063 const SIMachineFunctionInfo *MFI = B.getMF().getInfo<SIMachineFunctionInfo>();
6064 if (!MFI->isEntryFunction()) {
6067 }
6068
6069 Register DstReg = MI.getOperand(0).getReg();
6070 if (!getImplicitArgPtr(DstReg, MRI, B))
6071 return false;
6072
6073 MI.eraseFromParent();
6074 return true;
6075}
6076
6079 MachineIRBuilder &B) const {
6080 Function &F = B.getMF().getFunction();
6081 std::optional<uint32_t> KnownSize =
6083 if (KnownSize.has_value())
6084 B.buildConstant(DstReg, *KnownSize);
6085 return false;
6086}
6087
6090 MachineIRBuilder &B) const {
6091
6092 const SIMachineFunctionInfo *MFI = B.getMF().getInfo<SIMachineFunctionInfo>();
6093 if (!MFI->isEntryFunction()) {
6096 }
6097
6098 Register DstReg = MI.getOperand(0).getReg();
6099 if (!getLDSKernelId(DstReg, MRI, B))
6100 return false;
6101
6102 MI.eraseFromParent();
6103 return true;
6104}
6105
6109 unsigned AddrSpace) const {
6110 const LLT S32 = LLT::scalar(32);
6111 auto Unmerge = B.buildUnmerge(S32, MI.getOperand(2).getReg());
6112 Register Hi32 = Unmerge.getReg(1);
6113
6114 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS &&
6115 ST.hasGloballyAddressableScratch()) {
6116 Register FlatScratchBaseHi =
6117 B.buildInstr(AMDGPU::S_MOV_B32, {S32},
6118 {Register(AMDGPU::SRC_FLAT_SCRATCH_BASE_HI)})
6119 .getReg(0);
6120 MRI.setRegClass(FlatScratchBaseHi, &AMDGPU::SReg_32RegClass);
6121 // Test bits 63..58 against the aperture address.
6122 Register XOR = B.buildXor(S32, Hi32, FlatScratchBaseHi).getReg(0);
6123 B.buildICmp(ICmpInst::ICMP_ULT, MI.getOperand(0), XOR,
6124 B.buildConstant(S32, 1u << 26));
6125 } else {
6126 Register ApertureReg = getSegmentAperture(AddrSpace, MRI, B);
6127 B.buildICmp(ICmpInst::ICMP_EQ, MI.getOperand(0), Hi32, ApertureReg);
6128 }
6129 MI.eraseFromParent();
6130 return true;
6131}
6132
6133// The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
6134// offset (the offset that is included in bounds checking and swizzling, to be
6135// split between the instruction's voffset and immoffset fields) and soffset
6136// (the offset that is excluded from bounds checking and swizzling, to go in
6137// the instruction's soffset field). This function takes the first kind of
6138// offset and figures out how to split it between voffset and immoffset.
6139std::pair<Register, unsigned>
6141 Register OrigOffset) const {
6142 const unsigned MaxImm = SIInstrInfo::getMaxMUBUFImmOffset(ST);
6143 Register BaseReg;
6144 unsigned ImmOffset;
6145 const LLT S32 = LLT::scalar(32);
6146 MachineRegisterInfo &MRI = *B.getMRI();
6147
6148 // On GFX1250+, voffset and immoffset are zero-extended from 32 bits before
6149 // being added, so we can only safely match a 32-bit addition with no unsigned
6150 // overflow.
6151 bool CheckNUW = AMDGPU::isGFX1250(ST);
6152 std::tie(BaseReg, ImmOffset) = AMDGPU::getBaseWithConstantOffset(
6153 MRI, OrigOffset, /*KnownBits=*/nullptr, CheckNUW);
6154
6155 // If BaseReg is a pointer, convert it to int.
6156 if (MRI.getType(BaseReg).isPointer())
6157 BaseReg = B.buildPtrToInt(MRI.getType(OrigOffset), BaseReg).getReg(0);
6158
6159 // If the immediate value is too big for the immoffset field, put only bits
6160 // that would normally fit in the immoffset field. The remaining value that
6161 // is copied/added for the voffset field is a large power of 2, and it
6162 // stands more chance of being CSEd with the copy/add for another similar
6163 // load/store.
6164 // However, do not do that rounding down if that is a negative
6165 // number, as it appears to be illegal to have a negative offset in the
6166 // vgpr, even if adding the immediate offset makes it positive.
6167 unsigned Overflow = ImmOffset & ~MaxImm;
6168 ImmOffset -= Overflow;
6169 if ((int32_t)Overflow < 0) {
6170 Overflow += ImmOffset;
6171 ImmOffset = 0;
6172 }
6173
6174 if (Overflow != 0) {
6175 if (!BaseReg) {
6176 BaseReg = B.buildConstant(S32, Overflow).getReg(0);
6177 } else {
6178 auto OverflowVal = B.buildConstant(S32, Overflow);
6179 BaseReg = B.buildAdd(S32, BaseReg, OverflowVal).getReg(0);
6180 }
6181 }
6182
6183 if (!BaseReg)
6184 BaseReg = B.buildConstant(S32, 0).getReg(0);
6185
6186 return std::pair(BaseReg, ImmOffset);
6187}
6188
6189/// Handle register layout difference for f16 images for some subtargets.
6192 Register Reg,
6193 bool ImageStore) const {
6194 const LLT S16 = LLT::scalar(16);
6195 const LLT S32 = LLT::scalar(32);
6196 LLT StoreVT = MRI.getType(Reg);
6197 assert(StoreVT.isVector() && StoreVT.getElementType() == S16);
6198
6199 if (ST.hasUnpackedD16VMem()) {
6200 auto Unmerge = B.buildUnmerge(S16, Reg);
6201
6202 SmallVector<Register, 4> WideRegs;
6203 for (int I = 0, E = Unmerge->getNumOperands() - 1; I != E; ++I)
6204 WideRegs.push_back(B.buildAnyExt(S32, Unmerge.getReg(I)).getReg(0));
6205
6206 int NumElts = StoreVT.getNumElements();
6207
6208 return B.buildBuildVector(LLT::fixed_vector(NumElts, S32), WideRegs)
6209 .getReg(0);
6210 }
6211
6212 if (ImageStore && ST.hasImageStoreD16Bug()) {
6213 if (StoreVT.getNumElements() == 2) {
6214 SmallVector<Register, 4> PackedRegs;
6215 Reg = B.buildBitcast(S32, Reg).getReg(0);
6216 PackedRegs.push_back(Reg);
6217 PackedRegs.resize(2, B.buildUndef(S32).getReg(0));
6218 return B.buildBuildVector(LLT::fixed_vector(2, S32), PackedRegs)
6219 .getReg(0);
6220 }
6221
6222 if (StoreVT.getNumElements() == 3) {
6223 SmallVector<Register, 4> PackedRegs;
6224 auto Unmerge = B.buildUnmerge(S16, Reg);
6225 for (int I = 0, E = Unmerge->getNumOperands() - 1; I != E; ++I)
6226 PackedRegs.push_back(Unmerge.getReg(I));
6227 PackedRegs.resize(6, B.buildUndef(S16).getReg(0));
6228 Reg = B.buildBuildVector(LLT::fixed_vector(6, S16), PackedRegs).getReg(0);
6229 return B.buildBitcast(LLT::fixed_vector(3, S32), Reg).getReg(0);
6230 }
6231
6232 if (StoreVT.getNumElements() == 4) {
6233 SmallVector<Register, 4> PackedRegs;
6234 Reg = B.buildBitcast(LLT::fixed_vector(2, S32), Reg).getReg(0);
6235 auto Unmerge = B.buildUnmerge(S32, Reg);
6236 for (int I = 0, E = Unmerge->getNumOperands() - 1; I != E; ++I)
6237 PackedRegs.push_back(Unmerge.getReg(I));
6238 PackedRegs.resize(4, B.buildUndef(S32).getReg(0));
6239 return B.buildBuildVector(LLT::fixed_vector(4, S32), PackedRegs)
6240 .getReg(0);
6241 }
6242
6243 llvm_unreachable("invalid data type");
6244 }
6245
6246 if (StoreVT == LLT::fixed_vector(3, S16)) {
6247 Reg = B.buildPadVectorWithUndefElements(LLT::fixed_vector(4, S16), Reg)
6248 .getReg(0);
6249 }
6250 return Reg;
6251}
6252
6254 Register VData, LLT MemTy,
6255 bool IsFormat) const {
6256 MachineRegisterInfo *MRI = B.getMRI();
6257 LLT Ty = MRI->getType(VData);
6258
6259 const LLT S16 = LLT::scalar(16);
6260
6261 // Fixup buffer resources themselves needing to be v4i128.
6263 return castBufferRsrcToV4I32(VData, B);
6264
6265 if (shouldBitcastLoadStoreType(ST, Ty, MemTy)) {
6266 Ty = getBitcastRegisterType(Ty);
6267 VData = B.buildBitcast(Ty, VData).getReg(0);
6268 }
6269 // Fixup illegal register types for i8 stores.
6270 if (Ty == LLT::scalar(8) || Ty == S16) {
6271 Register AnyExt = B.buildAnyExt(LLT::scalar(32), VData).getReg(0);
6272 return AnyExt;
6273 }
6274
6275 if (Ty.isVector()) {
6276 if (Ty.getElementType() == S16 && Ty.getNumElements() <= 4) {
6277 if (IsFormat)
6278 return handleD16VData(B, *MRI, VData);
6279 }
6280 }
6281
6282 return VData;
6283}
6284
6286 LegalizerHelper &Helper,
6287 bool IsTyped,
6288 bool IsFormat) const {
6289 MachineIRBuilder &B = Helper.MIRBuilder;
6290 MachineRegisterInfo &MRI = *B.getMRI();
6291
6292 Register VData = MI.getOperand(1).getReg();
6293 LLT Ty = MRI.getType(VData);
6294 LLT EltTy = Ty.getScalarType();
6295 const bool IsD16 = IsFormat && (EltTy.getSizeInBits() == 16);
6296 const LLT S32 = LLT::scalar(32);
6297
6298 MachineMemOperand *MMO = *MI.memoperands_begin();
6299 const int MemSize = MMO->getSize().getValue();
6300 LLT MemTy = MMO->getMemoryType();
6301
6302 VData = fixStoreSourceType(B, VData, MemTy, IsFormat);
6303
6305 Register RSrc = MI.getOperand(2).getReg();
6306
6307 unsigned ImmOffset;
6308
6309 // The typed intrinsics add an immediate after the registers.
6310 const unsigned NumVIndexOps = IsTyped ? 8 : 7;
6311
6312 // The struct intrinsic variants add one additional operand over raw.
6313 const bool HasVIndex = MI.getNumOperands() == NumVIndexOps;
6314 Register VIndex;
6315 int OpOffset = 0;
6316 if (HasVIndex) {
6317 VIndex = MI.getOperand(3).getReg();
6318 OpOffset = 1;
6319 } else {
6320 VIndex = B.buildConstant(S32, 0).getReg(0);
6321 }
6322
6323 Register VOffset = MI.getOperand(3 + OpOffset).getReg();
6324 Register SOffset = MI.getOperand(4 + OpOffset).getReg();
6325
6326 unsigned Format = 0;
6327 if (IsTyped) {
6328 Format = MI.getOperand(5 + OpOffset).getImm();
6329 ++OpOffset;
6330 }
6331
6332 unsigned AuxiliaryData = MI.getOperand(5 + OpOffset).getImm();
6333
6334 std::tie(VOffset, ImmOffset) = splitBufferOffsets(B, VOffset);
6335
6336 unsigned Opc;
6337 if (IsTyped) {
6338 Opc = IsD16 ? AMDGPU::G_AMDGPU_TBUFFER_STORE_FORMAT_D16 :
6339 AMDGPU::G_AMDGPU_TBUFFER_STORE_FORMAT;
6340 } else if (IsFormat) {
6341 Opc = IsD16 ? AMDGPU::G_AMDGPU_BUFFER_STORE_FORMAT_D16 :
6342 AMDGPU::G_AMDGPU_BUFFER_STORE_FORMAT;
6343 } else {
6344 switch (MemSize) {
6345 case 1:
6346 Opc = AMDGPU::G_AMDGPU_BUFFER_STORE_BYTE;
6347 break;
6348 case 2:
6349 Opc = AMDGPU::G_AMDGPU_BUFFER_STORE_SHORT;
6350 break;
6351 default:
6352 Opc = AMDGPU::G_AMDGPU_BUFFER_STORE;
6353 break;
6354 }
6355 }
6356
6357 auto MIB = B.buildInstr(Opc)
6358 .addUse(VData) // vdata
6359 .addUse(RSrc) // rsrc
6360 .addUse(VIndex) // vindex
6361 .addUse(VOffset) // voffset
6362 .addUse(SOffset) // soffset
6363 .addImm(ImmOffset); // offset(imm)
6364
6365 if (IsTyped)
6366 MIB.addImm(Format);
6367
6368 MIB.addImm(AuxiliaryData) // cachepolicy, swizzled buffer(imm)
6369 .addImm(HasVIndex ? -1 : 0) // idxen(imm)
6370 .addMemOperand(MMO);
6371
6372 MI.eraseFromParent();
6373 return true;
6374}
6375
6376static void buildBufferLoad(unsigned Opc, Register LoadDstReg, Register RSrc,
6377 Register VIndex, Register VOffset, Register SOffset,
6378 unsigned ImmOffset, unsigned Format,
6379 unsigned AuxiliaryData, MachineMemOperand *MMO,
6380 bool IsTyped, bool HasVIndex, MachineIRBuilder &B) {
6381 auto MIB = B.buildInstr(Opc)
6382 .addDef(LoadDstReg) // vdata
6383 .addUse(RSrc) // rsrc
6384 .addUse(VIndex) // vindex
6385 .addUse(VOffset) // voffset
6386 .addUse(SOffset) // soffset
6387 .addImm(ImmOffset); // offset(imm)
6388
6389 if (IsTyped)
6390 MIB.addImm(Format);
6391
6392 MIB.addImm(AuxiliaryData) // cachepolicy, swizzled buffer(imm)
6393 .addImm(HasVIndex ? -1 : 0) // idxen(imm)
6394 .addMemOperand(MMO);
6395}
6396
6398 LegalizerHelper &Helper,
6399 bool IsFormat,
6400 bool IsTyped) const {
6401 MachineIRBuilder &B = Helper.MIRBuilder;
6402 MachineRegisterInfo &MRI = *B.getMRI();
6403 GISelChangeObserver &Observer = Helper.Observer;
6404
6405 // FIXME: Verifier should enforce 1 MMO for these intrinsics.
6406 MachineMemOperand *MMO = *MI.memoperands_begin();
6407 const LLT MemTy = MMO->getMemoryType();
6408 const LLT S32 = LLT::scalar(32);
6409
6410 Register Dst = MI.getOperand(0).getReg();
6411
6412 Register StatusDst;
6413 int OpOffset = 0;
6414 assert(MI.getNumExplicitDefs() == 1 || MI.getNumExplicitDefs() == 2);
6415 bool IsTFE = MI.getNumExplicitDefs() == 2;
6416 if (IsTFE) {
6417 StatusDst = MI.getOperand(1).getReg();
6418 ++OpOffset;
6419 }
6420
6421 castBufferRsrcArgToV4I32(MI, B, 2 + OpOffset);
6422 Register RSrc = MI.getOperand(2 + OpOffset).getReg();
6423
6424 // The typed intrinsics add an immediate after the registers.
6425 const unsigned NumVIndexOps = IsTyped ? 8 : 7;
6426
6427 // The struct intrinsic variants add one additional operand over raw.
6428 const bool HasVIndex = MI.getNumOperands() == NumVIndexOps + OpOffset;
6429 Register VIndex;
6430 if (HasVIndex) {
6431 VIndex = MI.getOperand(3 + OpOffset).getReg();
6432 ++OpOffset;
6433 } else {
6434 VIndex = B.buildConstant(S32, 0).getReg(0);
6435 }
6436
6437 Register VOffset = MI.getOperand(3 + OpOffset).getReg();
6438 Register SOffset = MI.getOperand(4 + OpOffset).getReg();
6439
6440 unsigned Format = 0;
6441 if (IsTyped) {
6442 Format = MI.getOperand(5 + OpOffset).getImm();
6443 ++OpOffset;
6444 }
6445
6446 unsigned AuxiliaryData = MI.getOperand(5 + OpOffset).getImm();
6447 unsigned ImmOffset;
6448
6449 LLT Ty = MRI.getType(Dst);
6450 // Make addrspace 8 pointers loads into 4xs32 loads here, so the rest of the
6451 // logic doesn't have to handle that case.
6452 if (hasBufferRsrcWorkaround(Ty)) {
6453 Observer.changingInstr(MI);
6454 Ty = castBufferRsrcFromV4I32(MI, B, MRI, 0);
6455 Observer.changedInstr(MI);
6456 Dst = MI.getOperand(0).getReg();
6457 B.setInsertPt(B.getMBB(), MI);
6458 }
6459 if (shouldBitcastLoadStoreType(ST, Ty, MemTy)) {
6460 Ty = getBitcastRegisterType(Ty);
6461 Observer.changingInstr(MI);
6462 Helper.bitcastDst(MI, Ty, 0);
6463 Observer.changedInstr(MI);
6464 Dst = MI.getOperand(0).getReg();
6465 B.setInsertPt(B.getMBB(), MI);
6466 }
6467
6468 LLT EltTy = Ty.getScalarType();
6469 const bool IsD16 = IsFormat && (EltTy.getSizeInBits() == 16);
6470 const bool Unpacked = ST.hasUnpackedD16VMem();
6471
6472 std::tie(VOffset, ImmOffset) = splitBufferOffsets(B, VOffset);
6473
6474 unsigned Opc;
6475
6476 // TODO: Support TFE for typed and narrow loads.
6477 if (IsTyped) {
6478 if (IsTFE)
6479 return false;
6480 Opc = IsD16 ? AMDGPU::G_AMDGPU_TBUFFER_LOAD_FORMAT_D16 :
6481 AMDGPU::G_AMDGPU_TBUFFER_LOAD_FORMAT;
6482 } else if (IsFormat) {
6483 if (IsD16) {
6484 if (IsTFE)
6485 return false;
6486 Opc = AMDGPU::G_AMDGPU_BUFFER_LOAD_FORMAT_D16;
6487 } else {
6488 Opc = IsTFE ? AMDGPU::G_AMDGPU_BUFFER_LOAD_FORMAT_TFE
6489 : AMDGPU::G_AMDGPU_BUFFER_LOAD_FORMAT;
6490 }
6491 } else {
6492 switch (MemTy.getSizeInBits()) {
6493 case 8:
6494 Opc = IsTFE ? AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE_TFE
6495 : AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE;
6496 break;
6497 case 16:
6498 Opc = IsTFE ? AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT_TFE
6499 : AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT;
6500 break;
6501 default:
6502 Opc = IsTFE ? AMDGPU::G_AMDGPU_BUFFER_LOAD_TFE
6503 : AMDGPU::G_AMDGPU_BUFFER_LOAD;
6504 break;
6505 }
6506 }
6507
6508 if (IsTFE) {
6509 unsigned NumValueDWords = divideCeil(Ty.getSizeInBits(), 32);
6510 unsigned NumLoadDWords = NumValueDWords + 1;
6511 LLT LoadTy = LLT::fixed_vector(NumLoadDWords, S32);
6512 Register LoadDstReg = B.getMRI()->createGenericVirtualRegister(LoadTy);
6513 buildBufferLoad(Opc, LoadDstReg, RSrc, VIndex, VOffset, SOffset, ImmOffset,
6514 Format, AuxiliaryData, MMO, IsTyped, HasVIndex, B);
6515 if (MemTy.getSizeInBits() < 32) {
6516 Register ExtDst = B.getMRI()->createGenericVirtualRegister(S32);
6517 B.buildUnmerge({ExtDst, StatusDst}, LoadDstReg);
6518 B.buildTrunc(Dst, ExtDst);
6519 } else if (NumValueDWords == 1) {
6520 B.buildUnmerge({Dst, StatusDst}, LoadDstReg);
6521 } else {
6522 SmallVector<Register, 5> LoadElts;
6523 for (unsigned I = 0; I != NumValueDWords; ++I)
6524 LoadElts.push_back(B.getMRI()->createGenericVirtualRegister(S32));
6525 LoadElts.push_back(StatusDst);
6526 B.buildUnmerge(LoadElts, LoadDstReg);
6527 LoadElts.truncate(NumValueDWords);
6528 B.buildMergeLikeInstr(Dst, LoadElts);
6529 }
6530 } else if ((!IsD16 && MemTy.getSizeInBits() < 32) ||
6531 (IsD16 && !Ty.isVector())) {
6532 Register LoadDstReg = B.getMRI()->createGenericVirtualRegister(S32);
6533 buildBufferLoad(Opc, LoadDstReg, RSrc, VIndex, VOffset, SOffset, ImmOffset,
6534 Format, AuxiliaryData, MMO, IsTyped, HasVIndex, B);
6535 B.setInsertPt(B.getMBB(), ++B.getInsertPt());
6536 B.buildTrunc(Dst, LoadDstReg);
6537 } else if (Unpacked && IsD16 && Ty.isVector()) {
6538 LLT UnpackedTy = Ty.changeElementSize(32);
6539 Register LoadDstReg = B.getMRI()->createGenericVirtualRegister(UnpackedTy);
6540 buildBufferLoad(Opc, LoadDstReg, RSrc, VIndex, VOffset, SOffset, ImmOffset,
6541 Format, AuxiliaryData, MMO, IsTyped, HasVIndex, B);
6542 B.setInsertPt(B.getMBB(), ++B.getInsertPt());
6543 // FIXME: G_TRUNC should work, but legalization currently fails
6544 auto Unmerge = B.buildUnmerge(S32, LoadDstReg);
6546 for (unsigned I = 0, N = Unmerge->getNumOperands() - 1; I != N; ++I)
6547 Repack.push_back(B.buildTrunc(EltTy, Unmerge.getReg(I)).getReg(0));
6548 B.buildMergeLikeInstr(Dst, Repack);
6549 } else {
6550 buildBufferLoad(Opc, Dst, RSrc, VIndex, VOffset, SOffset, ImmOffset, Format,
6551 AuxiliaryData, MMO, IsTyped, HasVIndex, B);
6552 }
6553
6554 MI.eraseFromParent();
6555 return true;
6556}
6557
6558static unsigned getBufferAtomicPseudo(Intrinsic::ID IntrID) {
6559 switch (IntrID) {
6560 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6561 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_swap:
6562 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6563 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_swap:
6564 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_SWAP;
6565 case Intrinsic::amdgcn_raw_buffer_atomic_add:
6566 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_add:
6567 case Intrinsic::amdgcn_struct_buffer_atomic_add:
6568 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_add:
6569 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_ADD;
6570 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6571 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub:
6572 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6573 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub:
6574 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_SUB;
6575 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6576 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smin:
6577 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6578 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smin:
6579 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_SMIN;
6580 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6581 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umin:
6582 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6583 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umin:
6584 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_UMIN;
6585 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6586 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smax:
6587 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6588 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smax:
6589 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_SMAX;
6590 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6591 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umax:
6592 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6593 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umax:
6594 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_UMAX;
6595 case Intrinsic::amdgcn_raw_buffer_atomic_and:
6596 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_and:
6597 case Intrinsic::amdgcn_struct_buffer_atomic_and:
6598 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_and:
6599 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_AND;
6600 case Intrinsic::amdgcn_raw_buffer_atomic_or:
6601 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_or:
6602 case Intrinsic::amdgcn_struct_buffer_atomic_or:
6603 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_or:
6604 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_OR;
6605 case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6606 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_xor:
6607 case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6608 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_xor:
6609 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_XOR;
6610 case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6611 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_inc:
6612 case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6613 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_inc:
6614 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_INC;
6615 case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6616 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_dec:
6617 case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6618 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_dec:
6619 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_DEC;
6620 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap:
6621 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_cmpswap:
6622 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap:
6623 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_cmpswap:
6624 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_CMPSWAP;
6625 case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
6626 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fadd:
6627 case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
6628 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fadd:
6629 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_FADD;
6630 case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
6631 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmin:
6632 case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
6633 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmin:
6634 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_FMIN;
6635 case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
6636 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmax:
6637 case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
6638 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmax:
6639 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_FMAX;
6640 case Intrinsic::amdgcn_raw_buffer_atomic_sub_clamp_u32:
6641 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub_clamp_u32:
6642 case Intrinsic::amdgcn_struct_buffer_atomic_sub_clamp_u32:
6643 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub_clamp_u32:
6644 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_SUB_CLAMP_U32;
6645 case Intrinsic::amdgcn_raw_buffer_atomic_cond_sub_u32:
6646 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_cond_sub_u32:
6647 case Intrinsic::amdgcn_struct_buffer_atomic_cond_sub_u32:
6648 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_cond_sub_u32:
6649 return AMDGPU::G_AMDGPU_BUFFER_ATOMIC_COND_SUB_U32;
6650 default:
6651 llvm_unreachable("unhandled atomic opcode");
6652 }
6653}
6654
6657 Intrinsic::ID IID) const {
6658 const bool IsCmpSwap =
6659 IID == Intrinsic::amdgcn_raw_buffer_atomic_cmpswap ||
6660 IID == Intrinsic::amdgcn_struct_buffer_atomic_cmpswap ||
6661 IID == Intrinsic::amdgcn_raw_ptr_buffer_atomic_cmpswap ||
6662 IID == Intrinsic::amdgcn_struct_ptr_buffer_atomic_cmpswap;
6663
6664 Register Dst = MI.getOperand(0).getReg();
6665 // Since we don't have 128-bit atomics, we don't need to handle the case of
6666 // p8 argmunents to the atomic itself
6667 Register VData = MI.getOperand(2).getReg();
6668
6669 Register CmpVal;
6670 int OpOffset = 0;
6671
6672 if (IsCmpSwap) {
6673 CmpVal = MI.getOperand(3).getReg();
6674 ++OpOffset;
6675 }
6676
6677 castBufferRsrcArgToV4I32(MI, B, 3 + OpOffset);
6678 Register RSrc = MI.getOperand(3 + OpOffset).getReg();
6679 const unsigned NumVIndexOps = IsCmpSwap ? 9 : 8;
6680
6681 // The struct intrinsic variants add one additional operand over raw.
6682 const bool HasVIndex = MI.getNumOperands() == NumVIndexOps;
6683 Register VIndex;
6684 if (HasVIndex) {
6685 VIndex = MI.getOperand(4 + OpOffset).getReg();
6686 ++OpOffset;
6687 } else {
6688 VIndex = B.buildConstant(LLT::scalar(32), 0).getReg(0);
6689 }
6690
6691 Register VOffset = MI.getOperand(4 + OpOffset).getReg();
6692 Register SOffset = MI.getOperand(5 + OpOffset).getReg();
6693 unsigned AuxiliaryData = MI.getOperand(6 + OpOffset).getImm();
6694
6695 MachineMemOperand *MMO = *MI.memoperands_begin();
6696
6697 unsigned ImmOffset;
6698 std::tie(VOffset, ImmOffset) = splitBufferOffsets(B, VOffset);
6699
6700 auto MIB = B.buildInstr(getBufferAtomicPseudo(IID))
6701 .addDef(Dst)
6702 .addUse(VData); // vdata
6703
6704 if (IsCmpSwap)
6705 MIB.addReg(CmpVal);
6706
6707 MIB.addUse(RSrc) // rsrc
6708 .addUse(VIndex) // vindex
6709 .addUse(VOffset) // voffset
6710 .addUse(SOffset) // soffset
6711 .addImm(ImmOffset) // offset(imm)
6712 .addImm(AuxiliaryData) // cachepolicy, swizzled buffer(imm)
6713 .addImm(HasVIndex ? -1 : 0) // idxen(imm)
6714 .addMemOperand(MMO);
6715
6716 MI.eraseFromParent();
6717 return true;
6718}
6719
6720/// Turn a set of s16 typed registers in \p AddrRegs into a dword sized
6721/// vector with s16 typed elements.
6723 SmallVectorImpl<Register> &PackedAddrs,
6724 unsigned ArgOffset,
6726 bool IsA16, bool IsG16) {
6727 const LLT S16 = LLT::scalar(16);
6728 const LLT V2S16 = LLT::fixed_vector(2, 16);
6729 auto EndIdx = Intr->VAddrEnd;
6730
6731 for (unsigned I = Intr->VAddrStart; I < EndIdx; I++) {
6732 MachineOperand &SrcOp = MI.getOperand(ArgOffset + I);
6733 if (!SrcOp.isReg())
6734 continue; // _L to _LZ may have eliminated this.
6735
6736 Register AddrReg = SrcOp.getReg();
6737
6738 if ((I < Intr->GradientStart) ||
6739 (I >= Intr->GradientStart && I < Intr->CoordStart && !IsG16) ||
6740 (I >= Intr->CoordStart && !IsA16)) {
6741 if ((I < Intr->GradientStart) && IsA16 &&
6742 (B.getMRI()->getType(AddrReg) == S16)) {
6743 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6744 // Special handling of bias when A16 is on. Bias is of type half but
6745 // occupies full 32-bit.
6746 PackedAddrs.push_back(
6747 B.buildBuildVector(V2S16, {AddrReg, B.buildUndef(S16).getReg(0)})
6748 .getReg(0));
6749 } else {
6750 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6751 "Bias needs to be converted to 16 bit in A16 mode");
6752 // Handle any gradient or coordinate operands that should not be packed
6753 AddrReg = B.buildBitcast(V2S16, AddrReg).getReg(0);
6754 PackedAddrs.push_back(AddrReg);
6755 }
6756 } else {
6757 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, in 1D,
6758 // derivatives dx/dh and dx/dv are packed with undef.
6759 if (((I + 1) >= EndIdx) ||
6760 ((Intr->NumGradients / 2) % 2 == 1 &&
6761 (I == static_cast<unsigned>(Intr->GradientStart +
6762 (Intr->NumGradients / 2) - 1) ||
6763 I == static_cast<unsigned>(Intr->GradientStart +
6764 Intr->NumGradients - 1))) ||
6765 // Check for _L to _LZ optimization
6766 !MI.getOperand(ArgOffset + I + 1).isReg()) {
6767 PackedAddrs.push_back(
6768 B.buildBuildVector(V2S16, {AddrReg, B.buildUndef(S16).getReg(0)})
6769 .getReg(0));
6770 } else {
6771 PackedAddrs.push_back(
6772 B.buildBuildVector(
6773 V2S16, {AddrReg, MI.getOperand(ArgOffset + I + 1).getReg()})
6774 .getReg(0));
6775 ++I;
6776 }
6777 }
6778 }
6779}
6780
6781/// Convert from separate vaddr components to a single vector address register,
6782/// and replace the remaining operands with $noreg.
6784 int DimIdx, int NumVAddrs) {
6785 const LLT S32 = LLT::scalar(32);
6786 (void)S32;
6787 SmallVector<Register, 8> AddrRegs;
6788 for (int I = 0; I != NumVAddrs; ++I) {
6789 MachineOperand &SrcOp = MI.getOperand(DimIdx + I);
6790 if (SrcOp.isReg()) {
6791 AddrRegs.push_back(SrcOp.getReg());
6792 assert(B.getMRI()->getType(SrcOp.getReg()) == S32);
6793 }
6794 }
6795
6796 int NumAddrRegs = AddrRegs.size();
6797 if (NumAddrRegs != 1) {
6798 auto VAddr =
6799 B.buildBuildVector(LLT::fixed_vector(NumAddrRegs, 32), AddrRegs);
6800 MI.getOperand(DimIdx).setReg(VAddr.getReg(0));
6801 }
6802
6803 for (int I = 1; I != NumVAddrs; ++I) {
6804 MachineOperand &SrcOp = MI.getOperand(DimIdx + I);
6805 if (SrcOp.isReg())
6806 MI.getOperand(DimIdx + I).setReg(AMDGPU::NoRegister);
6807 }
6808}
6809
6810/// Rewrite image intrinsics to use register layouts expected by the subtarget.
6811///
6812/// Depending on the subtarget, load/store with 16-bit element data need to be
6813/// rewritten to use the low half of 32-bit registers, or directly use a packed
6814/// layout. 16-bit addresses should also sometimes be packed into 32-bit
6815/// registers.
6816///
6817/// We don't want to directly select image instructions just yet, but also want
6818/// to exposes all register repacking to the legalizer/combiners. We also don't
6819/// want a selected instruction entering RegBankSelect. In order to avoid
6820/// defining a multitude of intermediate image instructions, directly hack on
6821/// the intrinsic's arguments. In cases like a16 addresses, this requires
6822/// padding now unnecessary arguments with $noreg.
6825 const AMDGPU::ImageDimIntrinsicInfo *Intr) const {
6826
6827 const MachineFunction &MF = *MI.getMF();
6828 const unsigned NumDefs = MI.getNumExplicitDefs();
6829 const unsigned ArgOffset = NumDefs + 1;
6830 bool IsTFE = NumDefs == 2;
6831 // We are only processing the operands of d16 image operations on subtargets
6832 // that use the unpacked register layout, or need to repack the TFE result.
6833
6834 // TODO: Do we need to guard against already legalized intrinsics?
6835 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6837
6838 MachineRegisterInfo *MRI = B.getMRI();
6839 const LLT S32 = LLT::scalar(32);
6840 const LLT S16 = LLT::scalar(16);
6841 const LLT V2S16 = LLT::fixed_vector(2, 16);
6842
6843 unsigned DMask = 0;
6844 Register VData;
6845 LLT Ty;
6846
6847 if (!BaseOpcode->NoReturn || BaseOpcode->Store) {
6848 VData = MI.getOperand(NumDefs == 0 ? 1 : 0).getReg();
6849 Ty = MRI->getType(VData);
6850 }
6851
6852 const bool IsAtomicPacked16Bit =
6853 (BaseOpcode->BaseOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_F16 ||
6854 BaseOpcode->BaseOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_BF16);
6855
6856 // Check for 16 bit addresses and pack if true.
6857 LLT GradTy =
6858 MRI->getType(MI.getOperand(ArgOffset + Intr->GradientStart).getReg());
6859 LLT AddrTy =
6860 MRI->getType(MI.getOperand(ArgOffset + Intr->CoordStart).getReg());
6861 const bool IsG16 =
6862 ST.hasG16() ? (BaseOpcode->Gradients && GradTy == S16) : GradTy == S16;
6863 const bool IsA16 = AddrTy == S16;
6864 const bool IsD16 = !IsAtomicPacked16Bit && Ty.getScalarType() == S16;
6865
6866 int DMaskLanes = 0;
6867 if (!BaseOpcode->Atomic) {
6868 DMask = MI.getOperand(ArgOffset + Intr->DMaskIndex).getImm();
6869 if (BaseOpcode->Gather4) {
6870 DMaskLanes = 4;
6871 } else if (DMask != 0) {
6872 DMaskLanes = llvm::popcount(DMask);
6873 } else if (!IsTFE && !BaseOpcode->Store) {
6874 // If dmask is 0, this is a no-op load. This can be eliminated.
6875 B.buildUndef(MI.getOperand(0));
6876 MI.eraseFromParent();
6877 return true;
6878 }
6879 }
6880
6881 Observer.changingInstr(MI);
6882 auto ChangedInstr = make_scope_exit([&] { Observer.changedInstr(MI); });
6883
6884 const unsigned StoreOpcode = IsD16 ? AMDGPU::G_AMDGPU_INTRIN_IMAGE_STORE_D16
6885 : AMDGPU::G_AMDGPU_INTRIN_IMAGE_STORE;
6886 const unsigned LoadOpcode = IsD16 ? AMDGPU::G_AMDGPU_INTRIN_IMAGE_LOAD_D16
6887 : AMDGPU::G_AMDGPU_INTRIN_IMAGE_LOAD;
6888 unsigned NewOpcode = LoadOpcode;
6889 if (BaseOpcode->Store)
6890 NewOpcode = StoreOpcode;
6891 else if (BaseOpcode->NoReturn)
6892 NewOpcode = AMDGPU::G_AMDGPU_INTRIN_IMAGE_LOAD_NORET;
6893
6894 // Track that we legalized this
6895 MI.setDesc(B.getTII().get(NewOpcode));
6896
6897 // Expecting to get an error flag since TFC is on - and dmask is 0 Force
6898 // dmask to be at least 1 otherwise the instruction will fail
6899 if (IsTFE && DMask == 0) {
6900 DMask = 0x1;
6901 DMaskLanes = 1;
6902 MI.getOperand(ArgOffset + Intr->DMaskIndex).setImm(DMask);
6903 }
6904
6905 if (BaseOpcode->Atomic) {
6906 Register VData0 = MI.getOperand(2).getReg();
6907 LLT Ty = MRI->getType(VData0);
6908
6909 // TODO: Allow atomic swap and bit ops for v2s16/v4s16
6910 if (Ty.isVector() && !IsAtomicPacked16Bit)
6911 return false;
6912
6913 if (BaseOpcode->AtomicX2) {
6914 Register VData1 = MI.getOperand(3).getReg();
6915 // The two values are packed in one register.
6916 LLT PackedTy = LLT::fixed_vector(2, Ty);
6917 auto Concat = B.buildBuildVector(PackedTy, {VData0, VData1});
6918 MI.getOperand(2).setReg(Concat.getReg(0));
6919 MI.getOperand(3).setReg(AMDGPU::NoRegister);
6920 }
6921 }
6922
6923 unsigned CorrectedNumVAddrs = Intr->NumVAddrs;
6924
6925 // Rewrite the addressing register layout before doing anything else.
6926 if (BaseOpcode->Gradients && !ST.hasG16() && (IsA16 != IsG16)) {
6927 // 16 bit gradients are supported, but are tied to the A16 control
6928 // so both gradients and addresses must be 16 bit
6929 return false;
6930 }
6931
6932 if (IsA16 && !ST.hasA16()) {
6933 // A16 not supported
6934 return false;
6935 }
6936
6937 const unsigned NSAMaxSize = ST.getNSAMaxSize(BaseOpcode->Sampler);
6938 const unsigned HasPartialNSA = ST.hasPartialNSAEncoding();
6939
6940 if (IsA16 || IsG16) {
6941 // Even if NumVAddrs == 1 we should pack it into a 32-bit value, because the
6942 // instructions expect VGPR_32
6943 SmallVector<Register, 4> PackedRegs;
6944
6945 packImage16bitOpsToDwords(B, MI, PackedRegs, ArgOffset, Intr, IsA16, IsG16);
6946
6947 // See also below in the non-a16 branch
6948 const bool UseNSA = ST.hasNSAEncoding() &&
6949 PackedRegs.size() >= ST.getNSAThreshold(MF) &&
6950 (PackedRegs.size() <= NSAMaxSize || HasPartialNSA);
6951 const bool UsePartialNSA =
6952 UseNSA && HasPartialNSA && PackedRegs.size() > NSAMaxSize;
6953
6954 if (UsePartialNSA) {
6955 // Pack registers that would go over NSAMaxSize into last VAddr register
6956 LLT PackedAddrTy =
6957 LLT::fixed_vector(2 * (PackedRegs.size() - NSAMaxSize + 1), 16);
6958 auto Concat = B.buildConcatVectors(
6959 PackedAddrTy, ArrayRef(PackedRegs).slice(NSAMaxSize - 1));
6960 PackedRegs[NSAMaxSize - 1] = Concat.getReg(0);
6961 PackedRegs.resize(NSAMaxSize);
6962 } else if (!UseNSA && PackedRegs.size() > 1) {
6963 LLT PackedAddrTy = LLT::fixed_vector(2 * PackedRegs.size(), 16);
6964 auto Concat = B.buildConcatVectors(PackedAddrTy, PackedRegs);
6965 PackedRegs[0] = Concat.getReg(0);
6966 PackedRegs.resize(1);
6967 }
6968
6969 const unsigned NumPacked = PackedRegs.size();
6970 for (unsigned I = Intr->VAddrStart; I < Intr->VAddrEnd; I++) {
6971 MachineOperand &SrcOp = MI.getOperand(ArgOffset + I);
6972 if (!SrcOp.isReg()) {
6973 assert(SrcOp.isImm() && SrcOp.getImm() == 0);
6974 continue;
6975 }
6976
6977 assert(SrcOp.getReg() != AMDGPU::NoRegister);
6978
6979 if (I - Intr->VAddrStart < NumPacked)
6980 SrcOp.setReg(PackedRegs[I - Intr->VAddrStart]);
6981 else
6982 SrcOp.setReg(AMDGPU::NoRegister);
6983 }
6984 } else {
6985 // If the register allocator cannot place the address registers contiguously
6986 // without introducing moves, then using the non-sequential address encoding
6987 // is always preferable, since it saves VALU instructions and is usually a
6988 // wash in terms of code size or even better.
6989 //
6990 // However, we currently have no way of hinting to the register allocator
6991 // that MIMG addresses should be placed contiguously when it is possible to
6992 // do so, so force non-NSA for the common 2-address case as a heuristic.
6993 //
6994 // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6995 // allocation when possible.
6996 //
6997 // Partial NSA is allowed on GFX11+ where the final register is a contiguous
6998 // set of the remaining addresses.
6999 const bool UseNSA = ST.hasNSAEncoding() &&
7000 CorrectedNumVAddrs >= ST.getNSAThreshold(MF) &&
7001 (CorrectedNumVAddrs <= NSAMaxSize || HasPartialNSA);
7002 const bool UsePartialNSA =
7003 UseNSA && HasPartialNSA && CorrectedNumVAddrs > NSAMaxSize;
7004
7005 if (UsePartialNSA) {
7007 ArgOffset + Intr->VAddrStart + NSAMaxSize - 1,
7008 Intr->NumVAddrs - NSAMaxSize + 1);
7009 } else if (!UseNSA && Intr->NumVAddrs > 1) {
7010 convertImageAddrToPacked(B, MI, ArgOffset + Intr->VAddrStart,
7011 Intr->NumVAddrs);
7012 }
7013 }
7014
7015 int Flags = 0;
7016 if (IsA16)
7017 Flags |= 1;
7018 if (IsG16)
7019 Flags |= 2;
7020 MI.addOperand(MachineOperand::CreateImm(Flags));
7021
7022 if (BaseOpcode->NoReturn) { // No TFE for stores?
7023 // TODO: Handle dmask trim
7024 if (!Ty.isVector() || !IsD16)
7025 return true;
7026
7027 Register RepackedReg = handleD16VData(B, *MRI, VData, true);
7028 if (RepackedReg != VData) {
7029 MI.getOperand(1).setReg(RepackedReg);
7030 }
7031
7032 return true;
7033 }
7034
7035 Register DstReg = MI.getOperand(0).getReg();
7036 const LLT EltTy = Ty.getScalarType();
7037 const int NumElts = Ty.isVector() ? Ty.getNumElements() : 1;
7038
7039 // Confirm that the return type is large enough for the dmask specified
7040 if (NumElts < DMaskLanes)
7041 return false;
7042
7043 if (NumElts > 4 || DMaskLanes > 4)
7044 return false;
7045
7046 // Image atomic instructions are using DMask to specify how many bits
7047 // input/output data will have. 32-bits (s32, v2s16) or 64-bits (s64, v4s16).
7048 // DMaskLanes for image atomic has default value '0'.
7049 // We must be sure that atomic variants (especially packed) will not be
7050 // truncated from v2s16 or v4s16 to s16 type.
7051 //
7052 // ChangeElementCount will be needed for image load where Ty is always scalar.
7053 const unsigned AdjustedNumElts = DMaskLanes == 0 ? 1 : DMaskLanes;
7054 const LLT AdjustedTy =
7055 DMaskLanes == 0
7056 ? Ty
7057 : Ty.changeElementCount(ElementCount::getFixed(AdjustedNumElts));
7058
7059 // The raw dword aligned data component of the load. The only legal cases
7060 // where this matters should be when using the packed D16 format, for
7061 // s16 -> <2 x s16>, and <3 x s16> -> <4 x s16>,
7062 LLT RoundedTy;
7063
7064 // S32 vector to cover all data, plus TFE result element.
7065 LLT TFETy;
7066
7067 // Register type to use for each loaded component. Will be S32 or V2S16.
7068 LLT RegTy;
7069
7070 if (IsD16 && ST.hasUnpackedD16VMem()) {
7071 RoundedTy =
7072 LLT::scalarOrVector(ElementCount::getFixed(AdjustedNumElts), 32);
7073 TFETy = LLT::fixed_vector(AdjustedNumElts + 1, 32);
7074 RegTy = S32;
7075 } else {
7076 unsigned EltSize = EltTy.getSizeInBits();
7077 unsigned RoundedElts = (AdjustedTy.getSizeInBits() + 31) / 32;
7078 unsigned RoundedSize = 32 * RoundedElts;
7079 RoundedTy = LLT::scalarOrVector(
7080 ElementCount::getFixed(RoundedSize / EltSize), EltSize);
7081 TFETy = LLT::fixed_vector(RoundedSize / 32 + 1, S32);
7082 RegTy = !IsTFE && EltSize == 16 ? V2S16 : S32;
7083 }
7084
7085 // The return type does not need adjustment.
7086 // TODO: Should we change s16 case to s32 or <2 x s16>?
7087 if (!IsTFE && (RoundedTy == Ty || !Ty.isVector()))
7088 return true;
7089
7090 Register Dst1Reg;
7091
7092 // Insert after the instruction.
7093 B.setInsertPt(*MI.getParent(), ++MI.getIterator());
7094
7095 // TODO: For TFE with d16, if we used a TFE type that was a multiple of <2 x
7096 // s16> instead of s32, we would only need 1 bitcast instead of multiple.
7097 const LLT LoadResultTy = IsTFE ? TFETy : RoundedTy;
7098 const int ResultNumRegs = LoadResultTy.getSizeInBits() / 32;
7099
7100 Register NewResultReg = MRI->createGenericVirtualRegister(LoadResultTy);
7101
7102 MI.getOperand(0).setReg(NewResultReg);
7103
7104 // In the IR, TFE is supposed to be used with a 2 element struct return
7105 // type. The instruction really returns these two values in one contiguous
7106 // register, with one additional dword beyond the loaded data. Rewrite the
7107 // return type to use a single register result.
7108
7109 if (IsTFE) {
7110 Dst1Reg = MI.getOperand(1).getReg();
7111 if (MRI->getType(Dst1Reg) != S32)
7112 return false;
7113
7114 // TODO: Make sure the TFE operand bit is set.
7115 MI.removeOperand(1);
7116
7117 // Handle the easy case that requires no repack instructions.
7118 if (Ty == S32) {
7119 B.buildUnmerge({DstReg, Dst1Reg}, NewResultReg);
7120 return true;
7121 }
7122 }
7123
7124 // Now figure out how to copy the new result register back into the old
7125 // result.
7126 SmallVector<Register, 5> ResultRegs(ResultNumRegs, Dst1Reg);
7127
7128 const int NumDataRegs = IsTFE ? ResultNumRegs - 1 : ResultNumRegs;
7129
7130 if (ResultNumRegs == 1) {
7131 assert(!IsTFE);
7132 ResultRegs[0] = NewResultReg;
7133 } else {
7134 // We have to repack into a new vector of some kind.
7135 for (int I = 0; I != NumDataRegs; ++I)
7136 ResultRegs[I] = MRI->createGenericVirtualRegister(RegTy);
7137 B.buildUnmerge(ResultRegs, NewResultReg);
7138
7139 // Drop the final TFE element to get the data part. The TFE result is
7140 // directly written to the right place already.
7141 if (IsTFE)
7142 ResultRegs.resize(NumDataRegs);
7143 }
7144
7145 // For an s16 scalar result, we form an s32 result with a truncate regardless
7146 // of packed vs. unpacked.
7147 if (IsD16 && !Ty.isVector()) {
7148 B.buildTrunc(DstReg, ResultRegs[0]);
7149 return true;
7150 }
7151
7152 // Avoid a build/concat_vector of 1 entry.
7153 if (Ty == V2S16 && NumDataRegs == 1 && !ST.hasUnpackedD16VMem()) {
7154 B.buildBitcast(DstReg, ResultRegs[0]);
7155 return true;
7156 }
7157
7158 assert(Ty.isVector());
7159
7160 if (IsD16) {
7161 // For packed D16 results with TFE enabled, all the data components are
7162 // S32. Cast back to the expected type.
7163 //
7164 // TODO: We don't really need to use load s32 elements. We would only need one
7165 // cast for the TFE result if a multiple of v2s16 was used.
7166 if (RegTy != V2S16 && !ST.hasUnpackedD16VMem()) {
7167 for (Register &Reg : ResultRegs)
7168 Reg = B.buildBitcast(V2S16, Reg).getReg(0);
7169 } else if (ST.hasUnpackedD16VMem()) {
7170 for (Register &Reg : ResultRegs)
7171 Reg = B.buildTrunc(S16, Reg).getReg(0);
7172 }
7173 }
7174
7175 auto padWithUndef = [&](LLT Ty, int NumElts) {
7176 if (NumElts == 0)
7177 return;
7178 Register Undef = B.buildUndef(Ty).getReg(0);
7179 for (int I = 0; I != NumElts; ++I)
7180 ResultRegs.push_back(Undef);
7181 };
7182
7183 // Pad out any elements eliminated due to the dmask.
7184 LLT ResTy = MRI->getType(ResultRegs[0]);
7185 if (!ResTy.isVector()) {
7186 padWithUndef(ResTy, NumElts - ResultRegs.size());
7187 B.buildBuildVector(DstReg, ResultRegs);
7188 return true;
7189 }
7190
7191 assert(!ST.hasUnpackedD16VMem() && ResTy == V2S16);
7192 const int RegsToCover = (Ty.getSizeInBits() + 31) / 32;
7193
7194 // Deal with the one annoying legal case.
7195 const LLT V3S16 = LLT::fixed_vector(3, 16);
7196 if (Ty == V3S16) {
7197 if (IsTFE) {
7198 if (ResultRegs.size() == 1) {
7199 NewResultReg = ResultRegs[0];
7200 } else if (ResultRegs.size() == 2) {
7201 LLT V4S16 = LLT::fixed_vector(4, 16);
7202 NewResultReg = B.buildConcatVectors(V4S16, ResultRegs).getReg(0);
7203 } else {
7204 return false;
7205 }
7206 }
7207
7208 if (MRI->getType(DstReg).getNumElements() <
7209 MRI->getType(NewResultReg).getNumElements()) {
7210 B.buildDeleteTrailingVectorElements(DstReg, NewResultReg);
7211 } else {
7212 B.buildPadVectorWithUndefElements(DstReg, NewResultReg);
7213 }
7214 return true;
7215 }
7216
7217 padWithUndef(ResTy, RegsToCover - ResultRegs.size());
7218 B.buildConcatVectors(DstReg, ResultRegs);
7219 return true;
7220}
7221
7223 MachineInstr &MI) const {
7224 MachineIRBuilder &B = Helper.MIRBuilder;
7225 GISelChangeObserver &Observer = Helper.Observer;
7226
7227 Register OrigDst = MI.getOperand(0).getReg();
7228 Register Dst;
7229 LLT Ty = B.getMRI()->getType(OrigDst);
7230 unsigned Size = Ty.getSizeInBits();
7231 MachineFunction &MF = B.getMF();
7232 unsigned Opc = 0;
7233 if (Size < 32 && ST.hasScalarSubwordLoads()) {
7234 assert(Size == 8 || Size == 16);
7235 Opc = Size == 8 ? AMDGPU::G_AMDGPU_S_BUFFER_LOAD_UBYTE
7236 : AMDGPU::G_AMDGPU_S_BUFFER_LOAD_USHORT;
7237 // The 8-bit and 16-bit scalar buffer load instructions have 32-bit
7238 // destination register.
7239 Dst = B.getMRI()->createGenericVirtualRegister(LLT::scalar(32));
7240 } else {
7241 Opc = AMDGPU::G_AMDGPU_S_BUFFER_LOAD;
7242 Dst = OrigDst;
7243 }
7244
7245 Observer.changingInstr(MI);
7246
7247 // Handle needing to s.buffer.load() a p8 value.
7248 if (hasBufferRsrcWorkaround(Ty)) {
7249 Ty = castBufferRsrcFromV4I32(MI, B, *B.getMRI(), 0);
7250 B.setInsertPt(B.getMBB(), MI);
7251 }
7253 Ty = getBitcastRegisterType(Ty);
7254 Helper.bitcastDst(MI, Ty, 0);
7255 B.setInsertPt(B.getMBB(), MI);
7256 }
7257
7258 // FIXME: We don't really need this intermediate instruction. The intrinsic
7259 // should be fixed to have a memory operand. Since it's readnone, we're not
7260 // allowed to add one.
7261 MI.setDesc(B.getTII().get(Opc));
7262 MI.removeOperand(1); // Remove intrinsic ID
7263
7264 // FIXME: When intrinsic definition is fixed, this should have an MMO already.
7265 const unsigned MemSize = (Size + 7) / 8;
7266 const Align MemAlign = B.getDataLayout().getABITypeAlign(
7272 MemSize, MemAlign);
7273 MI.addMemOperand(MF, MMO);
7274 if (Dst != OrigDst) {
7275 MI.getOperand(0).setReg(Dst);
7276 B.setInsertPt(B.getMBB(), ++B.getInsertPt());
7277 B.buildTrunc(OrigDst, Dst);
7278 }
7279
7280 // If we don't have 96-bit result scalar loads, widening to 128-bit should
7281 // always be legal. We may need to restore this to a 96-bit result if it turns
7282 // out this needs to be converted to a vector load during RegBankSelect.
7283 if (!isPowerOf2_32(Size) && (Size != 96 || !ST.hasScalarDwordx3Loads())) {
7284 if (Ty.isVector())
7286 else
7287 Helper.widenScalarDst(MI, getPow2ScalarType(Ty), 0);
7288 }
7289
7290 Observer.changedInstr(MI);
7291 return true;
7292}
7293
7295 MachineInstr &MI) const {
7296 MachineIRBuilder &B = Helper.MIRBuilder;
7297 GISelChangeObserver &Observer = Helper.Observer;
7298 Observer.changingInstr(MI);
7299 MI.setDesc(B.getTII().get(AMDGPU::G_AMDGPU_S_BUFFER_PREFETCH));
7300 MI.removeOperand(0); // Remove intrinsic ID
7302 Observer.changedInstr(MI);
7303 return true;
7304}
7305
7306// TODO: Move to selection
7309 MachineIRBuilder &B) const {
7310 if (!ST.isTrapHandlerEnabled() ||
7311 ST.getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
7312 return legalizeTrapEndpgm(MI, MRI, B);
7313
7314 return ST.supportsGetDoorbellID() ?
7316}
7317
7320 const DebugLoc &DL = MI.getDebugLoc();
7321 MachineBasicBlock &BB = B.getMBB();
7322 MachineFunction *MF = BB.getParent();
7323
7324 if (BB.succ_empty() && std::next(MI.getIterator()) == BB.end()) {
7325 BuildMI(BB, BB.end(), DL, B.getTII().get(AMDGPU::S_ENDPGM))
7326 .addImm(0);
7327 MI.eraseFromParent();
7328 return true;
7329 }
7330
7331 // We need a block split to make the real endpgm a terminator. We also don't
7332 // want to break phis in successor blocks, so we can't just delete to the
7333 // end of the block.
7334 BB.splitAt(MI, false /*UpdateLiveIns*/);
7336 MF->push_back(TrapBB);
7337 BuildMI(*TrapBB, TrapBB->end(), DL, B.getTII().get(AMDGPU::S_ENDPGM))
7338 .addImm(0);
7339 BuildMI(BB, &MI, DL, B.getTII().get(AMDGPU::S_CBRANCH_EXECNZ))
7340 .addMBB(TrapBB);
7341
7342 BB.addSuccessor(TrapBB);
7343 MI.eraseFromParent();
7344 return true;
7345}
7346
7349 MachineFunction &MF = B.getMF();
7350 const LLT S64 = LLT::scalar(64);
7351
7352 Register SGPR01(AMDGPU::SGPR0_SGPR1);
7353 // For code object version 5, queue_ptr is passed through implicit kernarg.
7359 ST.getTargetLowering()->getImplicitParameterOffset(B.getMF(), Param);
7360
7361 Register KernargPtrReg = MRI.createGenericVirtualRegister(
7363
7364 if (!loadInputValue(KernargPtrReg, B,
7366 return false;
7367
7368 // TODO: can we be smarter about machine pointer info?
7371 PtrInfo.getWithOffset(Offset),
7375
7376 // Pointer address
7377 Register LoadAddr = MRI.createGenericVirtualRegister(
7379 B.buildObjectPtrOffset(LoadAddr, KernargPtrReg,
7380 B.buildConstant(LLT::scalar(64), Offset).getReg(0));
7381 // Load address
7382 Register Temp = B.buildLoad(S64, LoadAddr, *MMO).getReg(0);
7383 B.buildCopy(SGPR01, Temp);
7384 B.buildInstr(AMDGPU::S_TRAP)
7385 .addImm(static_cast<unsigned>(GCNSubtarget::TrapID::LLVMAMDHSATrap))
7386 .addReg(SGPR01, RegState::Implicit);
7387 MI.eraseFromParent();
7388 return true;
7389 }
7390
7391 // Pass queue pointer to trap handler as input, and insert trap instruction
7392 // Reference: https://llvm.org/docs/AMDGPUUsage.html#trap-handler-abi
7393 Register LiveIn =
7394 MRI.createGenericVirtualRegister(LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
7396 return false;
7397
7398 B.buildCopy(SGPR01, LiveIn);
7399 B.buildInstr(AMDGPU::S_TRAP)
7400 .addImm(static_cast<unsigned>(GCNSubtarget::TrapID::LLVMAMDHSATrap))
7401 .addReg(SGPR01, RegState::Implicit);
7402
7403 MI.eraseFromParent();
7404 return true;
7405}
7406
7409 MachineIRBuilder &B) const {
7410 // We need to simulate the 's_trap 2' instruction on targets that run in
7411 // PRIV=1 (where it is treated as a nop).
7412 if (ST.hasPrivEnabledTrap2NopBug()) {
7413 ST.getInstrInfo()->insertSimulatedTrap(MRI, B.getMBB(), MI,
7414 MI.getDebugLoc());
7415 MI.eraseFromParent();
7416 return true;
7417 }
7418
7419 B.buildInstr(AMDGPU::S_TRAP)
7420 .addImm(static_cast<unsigned>(GCNSubtarget::TrapID::LLVMAMDHSATrap));
7421 MI.eraseFromParent();
7422 return true;
7423}
7424
7427 MachineIRBuilder &B) const {
7428 // Is non-HSA path or trap-handler disabled? Then, report a warning
7429 // accordingly
7430 if (!ST.isTrapHandlerEnabled() ||
7431 ST.getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
7432 Function &Fn = B.getMF().getFunction();
7434 Fn, "debugtrap handler not supported", MI.getDebugLoc(), DS_Warning));
7435 } else {
7436 // Insert debug-trap instruction
7437 B.buildInstr(AMDGPU::S_TRAP)
7438 .addImm(static_cast<unsigned>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap));
7439 }
7440
7441 MI.eraseFromParent();
7442 return true;
7443}
7444
7446 MachineInstr &MI, MachineIRBuilder &B) const {
7447 MachineRegisterInfo &MRI = *B.getMRI();
7448 const LLT S16 = LLT::scalar(16);
7449 const LLT S32 = LLT::scalar(32);
7450 const LLT V2S16 = LLT::fixed_vector(2, 16);
7451 const LLT V3S32 = LLT::fixed_vector(3, 32);
7452
7453 Register DstReg = MI.getOperand(0).getReg();
7454 Register NodePtr = MI.getOperand(2).getReg();
7455 Register RayExtent = MI.getOperand(3).getReg();
7456 Register RayOrigin = MI.getOperand(4).getReg();
7457 Register RayDir = MI.getOperand(5).getReg();
7458 Register RayInvDir = MI.getOperand(6).getReg();
7459 Register TDescr = MI.getOperand(7).getReg();
7460
7461 if (!ST.hasGFX10_AEncoding()) {
7462 Function &Fn = B.getMF().getFunction();
7464 Fn, "intrinsic not supported on subtarget", MI.getDebugLoc()));
7465 return false;
7466 }
7467
7468 const bool IsGFX11 = AMDGPU::isGFX11(ST);
7469 const bool IsGFX11Plus = AMDGPU::isGFX11Plus(ST);
7470 const bool IsGFX12Plus = AMDGPU::isGFX12Plus(ST);
7471 const bool IsA16 = MRI.getType(RayDir).getElementType().getSizeInBits() == 16;
7472 const bool Is64 = MRI.getType(NodePtr).getSizeInBits() == 64;
7473 const unsigned NumVDataDwords = 4;
7474 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7475 const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords;
7476 const bool UseNSA =
7477 IsGFX12Plus || (ST.hasNSAEncoding() && NumVAddrs <= ST.getNSAMaxSize());
7478
7479 const unsigned BaseOpcodes[2][2] = {
7480 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7481 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7482 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7483 int Opcode;
7484 if (UseNSA) {
7485 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7486 IsGFX12Plus ? AMDGPU::MIMGEncGfx12
7487 : IsGFX11 ? AMDGPU::MIMGEncGfx11NSA
7488 : AMDGPU::MIMGEncGfx10NSA,
7489 NumVDataDwords, NumVAddrDwords);
7490 } else {
7491 assert(!IsGFX12Plus);
7492 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7493 IsGFX11 ? AMDGPU::MIMGEncGfx11Default
7494 : AMDGPU::MIMGEncGfx10Default,
7495 NumVDataDwords, NumVAddrDwords);
7496 }
7497 assert(Opcode != -1);
7498
7500 if (UseNSA && IsGFX11Plus) {
7501 auto packLanes = [&Ops, &S32, &V3S32, &B](Register Src) {
7502 auto Unmerge = B.buildUnmerge({S32, S32, S32}, Src);
7503 auto Merged = B.buildMergeLikeInstr(
7504 V3S32, {Unmerge.getReg(0), Unmerge.getReg(1), Unmerge.getReg(2)});
7505 Ops.push_back(Merged.getReg(0));
7506 };
7507
7508 Ops.push_back(NodePtr);
7509 Ops.push_back(RayExtent);
7510 packLanes(RayOrigin);
7511
7512 if (IsA16) {
7513 auto UnmergeRayDir = B.buildUnmerge({S16, S16, S16}, RayDir);
7514 auto UnmergeRayInvDir = B.buildUnmerge({S16, S16, S16}, RayInvDir);
7515 auto MergedDir = B.buildMergeLikeInstr(
7516 V3S32,
7517 {B.buildBitcast(
7518 S32, B.buildMergeLikeInstr(V2S16, {UnmergeRayInvDir.getReg(0),
7519 UnmergeRayDir.getReg(0)}))
7520 .getReg(0),
7521 B.buildBitcast(
7522 S32, B.buildMergeLikeInstr(V2S16, {UnmergeRayInvDir.getReg(1),
7523 UnmergeRayDir.getReg(1)}))
7524 .getReg(0),
7525 B.buildBitcast(
7526 S32, B.buildMergeLikeInstr(V2S16, {UnmergeRayInvDir.getReg(2),
7527 UnmergeRayDir.getReg(2)}))
7528 .getReg(0)});
7529 Ops.push_back(MergedDir.getReg(0));
7530 } else {
7531 packLanes(RayDir);
7532 packLanes(RayInvDir);
7533 }
7534 } else {
7535 if (Is64) {
7536 auto Unmerge = B.buildUnmerge({S32, S32}, NodePtr);
7537 Ops.push_back(Unmerge.getReg(0));
7538 Ops.push_back(Unmerge.getReg(1));
7539 } else {
7540 Ops.push_back(NodePtr);
7541 }
7542 Ops.push_back(RayExtent);
7543
7544 auto packLanes = [&Ops, &S32, &B](Register Src) {
7545 auto Unmerge = B.buildUnmerge({S32, S32, S32}, Src);
7546 Ops.push_back(Unmerge.getReg(0));
7547 Ops.push_back(Unmerge.getReg(1));
7548 Ops.push_back(Unmerge.getReg(2));
7549 };
7550
7551 packLanes(RayOrigin);
7552 if (IsA16) {
7553 auto UnmergeRayDir = B.buildUnmerge({S16, S16, S16}, RayDir);
7554 auto UnmergeRayInvDir = B.buildUnmerge({S16, S16, S16}, RayInvDir);
7555 Register R1 = MRI.createGenericVirtualRegister(S32);
7556 Register R2 = MRI.createGenericVirtualRegister(S32);
7557 Register R3 = MRI.createGenericVirtualRegister(S32);
7558 B.buildMergeLikeInstr(R1,
7559 {UnmergeRayDir.getReg(0), UnmergeRayDir.getReg(1)});
7560 B.buildMergeLikeInstr(
7561 R2, {UnmergeRayDir.getReg(2), UnmergeRayInvDir.getReg(0)});
7562 B.buildMergeLikeInstr(
7563 R3, {UnmergeRayInvDir.getReg(1), UnmergeRayInvDir.getReg(2)});
7564 Ops.push_back(R1);
7565 Ops.push_back(R2);
7566 Ops.push_back(R3);
7567 } else {
7568 packLanes(RayDir);
7569 packLanes(RayInvDir);
7570 }
7571 }
7572
7573 if (!UseNSA) {
7574 // Build a single vector containing all the operands so far prepared.
7575 LLT OpTy = LLT::fixed_vector(Ops.size(), 32);
7576 Register MergedOps = B.buildMergeLikeInstr(OpTy, Ops).getReg(0);
7577 Ops.clear();
7578 Ops.push_back(MergedOps);
7579 }
7580
7581 auto MIB = B.buildInstr(AMDGPU::G_AMDGPU_BVH_INTERSECT_RAY)
7582 .addDef(DstReg)
7583 .addImm(Opcode);
7584
7585 for (Register R : Ops) {
7586 MIB.addUse(R);
7587 }
7588
7589 MIB.addUse(TDescr)
7590 .addImm(IsA16 ? 1 : 0)
7591 .cloneMemRefs(MI);
7592
7593 MI.eraseFromParent();
7594 return true;
7595}
7596
7598 MachineInstr &MI, MachineIRBuilder &B) const {
7599 const LLT S32 = LLT::scalar(32);
7600 const LLT V2S32 = LLT::fixed_vector(2, 32);
7601
7602 Register DstReg = MI.getOperand(0).getReg();
7603 Register DstOrigin = MI.getOperand(1).getReg();
7604 Register DstDir = MI.getOperand(2).getReg();
7605 Register NodePtr = MI.getOperand(4).getReg();
7606 Register RayExtent = MI.getOperand(5).getReg();
7607 Register InstanceMask = MI.getOperand(6).getReg();
7608 Register RayOrigin = MI.getOperand(7).getReg();
7609 Register RayDir = MI.getOperand(8).getReg();
7610 Register Offsets = MI.getOperand(9).getReg();
7611 Register TDescr = MI.getOperand(10).getReg();
7612
7613 if (!ST.hasBVHDualAndBVH8Insts()) {
7614 Function &Fn = B.getMF().getFunction();
7616 Fn, "intrinsic not supported on subtarget", MI.getDebugLoc()));
7617 return false;
7618 }
7619
7620 bool IsBVH8 = cast<GIntrinsic>(MI).getIntrinsicID() ==
7621 Intrinsic::amdgcn_image_bvh8_intersect_ray;
7622 const unsigned NumVDataDwords = 10;
7623 const unsigned NumVAddrDwords = IsBVH8 ? 11 : 12;
7624 int Opcode = AMDGPU::getMIMGOpcode(
7625 IsBVH8 ? AMDGPU::IMAGE_BVH8_INTERSECT_RAY
7626 : AMDGPU::IMAGE_BVH_DUAL_INTERSECT_RAY,
7627 AMDGPU::MIMGEncGfx12, NumVDataDwords, NumVAddrDwords);
7628 assert(Opcode != -1);
7629
7630 auto RayExtentInstanceMaskVec = B.buildMergeLikeInstr(
7631 V2S32, {RayExtent, B.buildAnyExt(S32, InstanceMask)});
7632
7633 B.buildInstr(IsBVH8 ? AMDGPU::G_AMDGPU_BVH8_INTERSECT_RAY
7634 : AMDGPU::G_AMDGPU_BVH_DUAL_INTERSECT_RAY)
7635 .addDef(DstReg)
7636 .addDef(DstOrigin)
7637 .addDef(DstDir)
7638 .addImm(Opcode)
7639 .addUse(NodePtr)
7640 .addUse(RayExtentInstanceMaskVec.getReg(0))
7641 .addUse(RayOrigin)
7642 .addUse(RayDir)
7643 .addUse(Offsets)
7644 .addUse(TDescr)
7645 .cloneMemRefs(MI);
7646
7647 MI.eraseFromParent();
7648 return true;
7649}
7650
7652 MachineIRBuilder &B) const {
7653 const SITargetLowering *TLI = ST.getTargetLowering();
7655 Register DstReg = MI.getOperand(0).getReg();
7656 B.buildInstr(AMDGPU::G_AMDGPU_WAVE_ADDRESS, {DstReg}, {StackPtr});
7657 MI.eraseFromParent();
7658 return true;
7659}
7660
7662 MachineIRBuilder &B) const {
7663 // With architected SGPRs, waveIDinGroup is in TTMP8[29:25].
7664 if (!ST.hasArchitectedSGPRs())
7665 return false;
7666 LLT S32 = LLT::scalar(32);
7667 Register DstReg = MI.getOperand(0).getReg();
7668 auto TTMP8 = B.buildCopy(S32, Register(AMDGPU::TTMP8));
7669 auto LSB = B.buildConstant(S32, 25);
7670 auto Width = B.buildConstant(S32, 5);
7671 B.buildUbfx(DstReg, TTMP8, LSB, Width);
7672 MI.eraseFromParent();
7673 return true;
7674}
7675
7678 AMDGPU::Hwreg::Id HwReg,
7679 unsigned LowBit,
7680 unsigned Width) const {
7681 MachineRegisterInfo &MRI = *B.getMRI();
7682 Register DstReg = MI.getOperand(0).getReg();
7683 if (!MRI.getRegClassOrNull(DstReg))
7684 MRI.setRegClass(DstReg, &AMDGPU::SReg_32RegClass);
7685 B.buildInstr(AMDGPU::S_GETREG_B32_const)
7686 .addDef(DstReg)
7687 .addImm(AMDGPU::Hwreg::HwregEncoding::encode(HwReg, LowBit, Width));
7688 MI.eraseFromParent();
7689 return true;
7690}
7691
7692static constexpr unsigned FPEnvModeBitField =
7694
7695static constexpr unsigned FPEnvTrapBitField =
7697
7700 MachineIRBuilder &B) const {
7701 Register Src = MI.getOperand(0).getReg();
7702 if (MRI.getType(Src) != S64)
7703 return false;
7704
7705 auto ModeReg =
7706 B.buildIntrinsic(Intrinsic::amdgcn_s_getreg, {S32},
7707 /*HasSideEffects=*/true, /*isConvergent=*/false)
7708 .addImm(FPEnvModeBitField);
7709 auto TrapReg =
7710 B.buildIntrinsic(Intrinsic::amdgcn_s_getreg, {S32},
7711 /*HasSideEffects=*/true, /*isConvergent=*/false)
7712 .addImm(FPEnvTrapBitField);
7713 B.buildMergeLikeInstr(Src, {ModeReg, TrapReg});
7714 MI.eraseFromParent();
7715 return true;
7716}
7717
7720 MachineIRBuilder &B) const {
7721 Register Src = MI.getOperand(0).getReg();
7722 if (MRI.getType(Src) != S64)
7723 return false;
7724
7725 auto Unmerge = B.buildUnmerge({S32, S32}, MI.getOperand(0));
7726 B.buildIntrinsic(Intrinsic::amdgcn_s_setreg, ArrayRef<DstOp>(),
7727 /*HasSideEffects=*/true, /*isConvergent=*/false)
7728 .addImm(static_cast<int16_t>(FPEnvModeBitField))
7729 .addReg(Unmerge.getReg(0));
7730 B.buildIntrinsic(Intrinsic::amdgcn_s_setreg, ArrayRef<DstOp>(),
7731 /*HasSideEffects=*/true, /*isConvergent=*/false)
7732 .addImm(static_cast<int16_t>(FPEnvTrapBitField))
7733 .addReg(Unmerge.getReg(1));
7734 MI.eraseFromParent();
7735 return true;
7736}
7737
7739 MachineInstr &MI) const {
7740 MachineIRBuilder &B = Helper.MIRBuilder;
7741 MachineRegisterInfo &MRI = *B.getMRI();
7742
7743 // Replace the use G_BRCOND with the exec manipulate and branch pseudos.
7744 auto IntrID = cast<GIntrinsic>(MI).getIntrinsicID();
7745 switch (IntrID) {
7746 case Intrinsic::amdgcn_if:
7747 case Intrinsic::amdgcn_else: {
7748 MachineInstr *Br = nullptr;
7749 MachineBasicBlock *UncondBrTarget = nullptr;
7750 bool Negated = false;
7751 if (MachineInstr *BrCond =
7752 verifyCFIntrinsic(MI, MRI, Br, UncondBrTarget, Negated)) {
7753 const SIRegisterInfo *TRI
7754 = static_cast<const SIRegisterInfo *>(MRI.getTargetRegisterInfo());
7755
7756 Register Def = MI.getOperand(1).getReg();
7757 Register Use = MI.getOperand(3).getReg();
7758
7759 MachineBasicBlock *CondBrTarget = BrCond->getOperand(1).getMBB();
7760
7761 if (Negated)
7762 std::swap(CondBrTarget, UncondBrTarget);
7763
7764 B.setInsertPt(B.getMBB(), BrCond->getIterator());
7765 if (IntrID == Intrinsic::amdgcn_if) {
7766 B.buildInstr(AMDGPU::SI_IF)
7767 .addDef(Def)
7768 .addUse(Use)
7769 .addMBB(UncondBrTarget);
7770 } else {
7771 B.buildInstr(AMDGPU::SI_ELSE)
7772 .addDef(Def)
7773 .addUse(Use)
7774 .addMBB(UncondBrTarget);
7775 }
7776
7777 if (Br) {
7778 Br->getOperand(0).setMBB(CondBrTarget);
7779 } else {
7780 // The IRTranslator skips inserting the G_BR for fallthrough cases, but
7781 // since we're swapping branch targets it needs to be reinserted.
7782 // FIXME: IRTranslator should probably not do this
7783 B.buildBr(*CondBrTarget);
7784 }
7785
7786 MRI.setRegClass(Def, TRI->getWaveMaskRegClass());
7787 MRI.setRegClass(Use, TRI->getWaveMaskRegClass());
7788 MI.eraseFromParent();
7789 BrCond->eraseFromParent();
7790 return true;
7791 }
7792
7793 return false;
7794 }
7795 case Intrinsic::amdgcn_loop: {
7796 MachineInstr *Br = nullptr;
7797 MachineBasicBlock *UncondBrTarget = nullptr;
7798 bool Negated = false;
7799 if (MachineInstr *BrCond =
7800 verifyCFIntrinsic(MI, MRI, Br, UncondBrTarget, Negated)) {
7801 const SIRegisterInfo *TRI
7802 = static_cast<const SIRegisterInfo *>(MRI.getTargetRegisterInfo());
7803
7804 MachineBasicBlock *CondBrTarget = BrCond->getOperand(1).getMBB();
7805 Register Reg = MI.getOperand(2).getReg();
7806
7807 if (Negated)
7808 std::swap(CondBrTarget, UncondBrTarget);
7809
7810 B.setInsertPt(B.getMBB(), BrCond->getIterator());
7811 B.buildInstr(AMDGPU::SI_LOOP)
7812 .addUse(Reg)
7813 .addMBB(UncondBrTarget);
7814
7815 if (Br)
7816 Br->getOperand(0).setMBB(CondBrTarget);
7817 else
7818 B.buildBr(*CondBrTarget);
7819
7820 MI.eraseFromParent();
7821 BrCond->eraseFromParent();
7822 MRI.setRegClass(Reg, TRI->getWaveMaskRegClass());
7823 return true;
7824 }
7825
7826 return false;
7827 }
7828 case Intrinsic::amdgcn_addrspacecast_nonnull:
7829 return legalizeAddrSpaceCast(MI, MRI, B);
7830 case Intrinsic::amdgcn_make_buffer_rsrc:
7832 case Intrinsic::amdgcn_kernarg_segment_ptr:
7833 if (!AMDGPU::isKernel(B.getMF().getFunction())) {
7834 // This only makes sense to call in a kernel, so just lower to null.
7835 B.buildConstant(MI.getOperand(0).getReg(), 0);
7836 MI.eraseFromParent();
7837 return true;
7838 }
7839
7842 case Intrinsic::amdgcn_implicitarg_ptr:
7843 return legalizeImplicitArgPtr(MI, MRI, B);
7844 case Intrinsic::amdgcn_workitem_id_x:
7845 return legalizeWorkitemIDIntrinsic(MI, MRI, B, 0,
7847 case Intrinsic::amdgcn_workitem_id_y:
7848 return legalizeWorkitemIDIntrinsic(MI, MRI, B, 1,
7850 case Intrinsic::amdgcn_workitem_id_z:
7851 return legalizeWorkitemIDIntrinsic(MI, MRI, B, 2,
7853 case Intrinsic::amdgcn_workgroup_id_x:
7854 return legalizeWorkGroupId(
7858 case Intrinsic::amdgcn_workgroup_id_y:
7859 return legalizeWorkGroupId(
7863 case Intrinsic::amdgcn_workgroup_id_z:
7864 return legalizeWorkGroupId(
7868 case Intrinsic::amdgcn_cluster_id_x:
7869 return ST.hasClusters() &&
7872 case Intrinsic::amdgcn_cluster_id_y:
7873 return ST.hasClusters() &&
7876 case Intrinsic::amdgcn_cluster_id_z:
7877 return ST.hasClusters() &&
7880 case Intrinsic::amdgcn_cluster_workgroup_id_x:
7881 return ST.hasClusters() &&
7884 case Intrinsic::amdgcn_cluster_workgroup_id_y:
7885 return ST.hasClusters() &&
7888 case Intrinsic::amdgcn_cluster_workgroup_id_z:
7889 return ST.hasClusters() &&
7892 case Intrinsic::amdgcn_cluster_workgroup_flat_id:
7893 return ST.hasClusters() &&
7895 case Intrinsic::amdgcn_cluster_workgroup_max_id_x:
7896 return ST.hasClusters() &&
7899 case Intrinsic::amdgcn_cluster_workgroup_max_id_y:
7900 return ST.hasClusters() &&
7903 case Intrinsic::amdgcn_cluster_workgroup_max_id_z:
7904 return ST.hasClusters() &&
7907 case Intrinsic::amdgcn_cluster_workgroup_max_flat_id:
7908 return ST.hasClusters() &&
7910 MI, MRI, B,
7912 case Intrinsic::amdgcn_wave_id:
7913 return legalizeWaveID(MI, B);
7914 case Intrinsic::amdgcn_lds_kernel_id:
7917 case Intrinsic::amdgcn_dispatch_ptr:
7920 case Intrinsic::amdgcn_queue_ptr:
7923 case Intrinsic::amdgcn_implicit_buffer_ptr:
7926 case Intrinsic::amdgcn_dispatch_id:
7929 case Intrinsic::r600_read_ngroups_x:
7930 // TODO: Emit error for hsa
7933 case Intrinsic::r600_read_ngroups_y:
7936 case Intrinsic::r600_read_ngroups_z:
7939 case Intrinsic::r600_read_local_size_x:
7940 // TODO: Could insert G_ASSERT_ZEXT from s16
7942 case Intrinsic::r600_read_local_size_y:
7943 // TODO: Could insert G_ASSERT_ZEXT from s16
7945 // TODO: Could insert G_ASSERT_ZEXT from s16
7946 case Intrinsic::r600_read_local_size_z:
7949 case Intrinsic::amdgcn_fdiv_fast:
7950 return legalizeFDIVFastIntrin(MI, MRI, B);
7951 case Intrinsic::amdgcn_is_shared:
7953 case Intrinsic::amdgcn_is_private:
7955 case Intrinsic::amdgcn_wavefrontsize: {
7956 B.buildConstant(MI.getOperand(0), ST.getWavefrontSize());
7957 MI.eraseFromParent();
7958 return true;
7959 }
7960 case Intrinsic::amdgcn_s_buffer_load:
7961 return legalizeSBufferLoad(Helper, MI);
7962 case Intrinsic::amdgcn_raw_buffer_store:
7963 case Intrinsic::amdgcn_raw_ptr_buffer_store:
7964 case Intrinsic::amdgcn_struct_buffer_store:
7965 case Intrinsic::amdgcn_struct_ptr_buffer_store:
7966 return legalizeBufferStore(MI, Helper, false, false);
7967 case Intrinsic::amdgcn_raw_buffer_store_format:
7968 case Intrinsic::amdgcn_raw_ptr_buffer_store_format:
7969 case Intrinsic::amdgcn_struct_buffer_store_format:
7970 case Intrinsic::amdgcn_struct_ptr_buffer_store_format:
7971 return legalizeBufferStore(MI, Helper, false, true);
7972 case Intrinsic::amdgcn_raw_tbuffer_store:
7973 case Intrinsic::amdgcn_raw_ptr_tbuffer_store:
7974 case Intrinsic::amdgcn_struct_tbuffer_store:
7975 case Intrinsic::amdgcn_struct_ptr_tbuffer_store:
7976 return legalizeBufferStore(MI, Helper, true, true);
7977 case Intrinsic::amdgcn_raw_buffer_load:
7978 case Intrinsic::amdgcn_raw_ptr_buffer_load:
7979 case Intrinsic::amdgcn_raw_atomic_buffer_load:
7980 case Intrinsic::amdgcn_raw_ptr_atomic_buffer_load:
7981 case Intrinsic::amdgcn_struct_buffer_load:
7982 case Intrinsic::amdgcn_struct_ptr_buffer_load:
7983 case Intrinsic::amdgcn_struct_atomic_buffer_load:
7984 case Intrinsic::amdgcn_struct_ptr_atomic_buffer_load:
7985 return legalizeBufferLoad(MI, Helper, false, false);
7986 case Intrinsic::amdgcn_raw_buffer_load_format:
7987 case Intrinsic::amdgcn_raw_ptr_buffer_load_format:
7988 case Intrinsic::amdgcn_struct_buffer_load_format:
7989 case Intrinsic::amdgcn_struct_ptr_buffer_load_format:
7990 return legalizeBufferLoad(MI, Helper, true, false);
7991 case Intrinsic::amdgcn_raw_tbuffer_load:
7992 case Intrinsic::amdgcn_raw_ptr_tbuffer_load:
7993 case Intrinsic::amdgcn_struct_tbuffer_load:
7994 case Intrinsic::amdgcn_struct_ptr_tbuffer_load:
7995 return legalizeBufferLoad(MI, Helper, true, true);
7996 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7997 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_swap:
7998 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7999 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_swap:
8000 case Intrinsic::amdgcn_raw_buffer_atomic_add:
8001 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_add:
8002 case Intrinsic::amdgcn_struct_buffer_atomic_add:
8003 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_add:
8004 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
8005 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub:
8006 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
8007 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub:
8008 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
8009 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smin:
8010 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
8011 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smin:
8012 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
8013 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umin:
8014 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
8015 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umin:
8016 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
8017 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smax:
8018 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
8019 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smax:
8020 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
8021 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umax:
8022 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
8023 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umax:
8024 case Intrinsic::amdgcn_raw_buffer_atomic_and:
8025 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_and:
8026 case Intrinsic::amdgcn_struct_buffer_atomic_and:
8027 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_and:
8028 case Intrinsic::amdgcn_raw_buffer_atomic_or:
8029 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_or:
8030 case Intrinsic::amdgcn_struct_buffer_atomic_or:
8031 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_or:
8032 case Intrinsic::amdgcn_raw_buffer_atomic_xor:
8033 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_xor:
8034 case Intrinsic::amdgcn_struct_buffer_atomic_xor:
8035 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_xor:
8036 case Intrinsic::amdgcn_raw_buffer_atomic_inc:
8037 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_inc:
8038 case Intrinsic::amdgcn_struct_buffer_atomic_inc:
8039 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_inc:
8040 case Intrinsic::amdgcn_raw_buffer_atomic_dec:
8041 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_dec:
8042 case Intrinsic::amdgcn_struct_buffer_atomic_dec:
8043 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_dec:
8044 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap:
8045 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_cmpswap:
8046 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap:
8047 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_cmpswap:
8048 case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
8049 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmin:
8050 case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
8051 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmin:
8052 case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
8053 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmax:
8054 case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
8055 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmax:
8056 case Intrinsic::amdgcn_raw_buffer_atomic_sub_clamp_u32:
8057 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub_clamp_u32:
8058 case Intrinsic::amdgcn_struct_buffer_atomic_sub_clamp_u32:
8059 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub_clamp_u32:
8060 case Intrinsic::amdgcn_raw_buffer_atomic_cond_sub_u32:
8061 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_cond_sub_u32:
8062 case Intrinsic::amdgcn_struct_buffer_atomic_cond_sub_u32:
8063 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_cond_sub_u32:
8064 case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
8065 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fadd:
8066 case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
8067 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fadd:
8068 return legalizeBufferAtomic(MI, B, IntrID);
8069 case Intrinsic::amdgcn_rsq_clamp:
8071 case Intrinsic::amdgcn_image_bvh_intersect_ray:
8073 case Intrinsic::amdgcn_image_bvh_dual_intersect_ray:
8074 case Intrinsic::amdgcn_image_bvh8_intersect_ray:
8076 case Intrinsic::amdgcn_swmmac_f32_16x16x128_fp8_fp8:
8077 case Intrinsic::amdgcn_swmmac_f32_16x16x128_fp8_bf8:
8078 case Intrinsic::amdgcn_swmmac_f32_16x16x128_bf8_fp8:
8079 case Intrinsic::amdgcn_swmmac_f32_16x16x128_bf8_bf8:
8080 case Intrinsic::amdgcn_swmmac_f16_16x16x128_fp8_fp8:
8081 case Intrinsic::amdgcn_swmmac_f16_16x16x128_fp8_bf8:
8082 case Intrinsic::amdgcn_swmmac_f16_16x16x128_bf8_fp8:
8083 case Intrinsic::amdgcn_swmmac_f16_16x16x128_bf8_bf8: {
8084 Register Index = MI.getOperand(5).getReg();
8085 LLT S64 = LLT::scalar(64);
8086 if (MRI.getType(Index) != S64)
8087 MI.getOperand(5).setReg(B.buildAnyExt(S64, Index).getReg(0));
8088 return true;
8089 }
8090 case Intrinsic::amdgcn_swmmac_f16_16x16x32_f16:
8091 case Intrinsic::amdgcn_swmmac_bf16_16x16x32_bf16:
8092 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf16:
8093 case Intrinsic::amdgcn_swmmac_f32_16x16x32_f16:
8094 case Intrinsic::amdgcn_swmmac_f32_16x16x32_fp8_fp8:
8095 case Intrinsic::amdgcn_swmmac_f32_16x16x32_fp8_bf8:
8096 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf8_fp8:
8097 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf8_bf8: {
8098 Register Index = MI.getOperand(5).getReg();
8099 LLT S32 = LLT::scalar(32);
8100 if (MRI.getType(Index) != S32)
8101 MI.getOperand(5).setReg(B.buildAnyExt(S32, Index).getReg(0));
8102 return true;
8103 }
8104 case Intrinsic::amdgcn_swmmac_f16_16x16x64_f16:
8105 case Intrinsic::amdgcn_swmmac_bf16_16x16x64_bf16:
8106 case Intrinsic::amdgcn_swmmac_f32_16x16x64_bf16:
8107 case Intrinsic::amdgcn_swmmac_bf16f32_16x16x64_bf16:
8108 case Intrinsic::amdgcn_swmmac_f32_16x16x64_f16:
8109 case Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8:
8110 case Intrinsic::amdgcn_swmmac_i32_16x16x32_iu4:
8111 case Intrinsic::amdgcn_swmmac_i32_16x16x32_iu8:
8112 case Intrinsic::amdgcn_swmmac_i32_16x16x64_iu4: {
8113 Register Index = MI.getOperand(7).getReg();
8114 LLT IdxTy = IntrID == Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8
8115 ? LLT::scalar(64)
8116 : LLT::scalar(32);
8117 if (MRI.getType(Index) != IdxTy)
8118 MI.getOperand(7).setReg(B.buildAnyExt(IdxTy, Index).getReg(0));
8119 return true;
8120 }
8121
8122 case Intrinsic::amdgcn_fmed3: {
8123 GISelChangeObserver &Observer = Helper.Observer;
8124
8125 // FIXME: This is to workaround the inability of tablegen match combiners to
8126 // match intrinsics in patterns.
8127 Observer.changingInstr(MI);
8128 MI.setDesc(B.getTII().get(AMDGPU::G_AMDGPU_FMED3));
8129 MI.removeOperand(1);
8130 Observer.changedInstr(MI);
8131 return true;
8132 }
8133 case Intrinsic::amdgcn_readlane:
8134 case Intrinsic::amdgcn_writelane:
8135 case Intrinsic::amdgcn_readfirstlane:
8136 case Intrinsic::amdgcn_permlane16:
8137 case Intrinsic::amdgcn_permlanex16:
8138 case Intrinsic::amdgcn_permlane64:
8139 case Intrinsic::amdgcn_set_inactive:
8140 case Intrinsic::amdgcn_set_inactive_chain_arg:
8141 case Intrinsic::amdgcn_mov_dpp8:
8142 case Intrinsic::amdgcn_update_dpp:
8143 return legalizeLaneOp(Helper, MI, IntrID);
8144 case Intrinsic::amdgcn_s_buffer_prefetch_data:
8145 return legalizeSBufferPrefetch(Helper, MI);
8146 case Intrinsic::amdgcn_dead: {
8147 // TODO: Use poison instead of undef
8148 for (const MachineOperand &Def : MI.defs())
8149 B.buildUndef(Def);
8150 MI.eraseFromParent();
8151 return true;
8152 }
8153 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
8154 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
8155 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B:
8156 assert(MI.hasOneMemOperand() && "Expected IRTranslator to set MemOp!");
8157 B.buildLoad(MI.getOperand(0), MI.getOperand(2), **MI.memoperands_begin());
8158 MI.eraseFromParent();
8159 return true;
8160 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
8161 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
8162 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B:
8163 assert(MI.hasOneMemOperand() && "Expected IRTranslator to set MemOp!");
8164 B.buildStore(MI.getOperand(2), MI.getOperand(1), **MI.memoperands_begin());
8165 MI.eraseFromParent();
8166 return true;
8167 default: {
8168 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8170 return legalizeImageIntrinsic(MI, B, Helper.Observer, ImageDimIntr);
8171 return true;
8172 }
8173 }
8174
8175 return true;
8176}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
static unsigned getIntrinsicID(const SDNode *N)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static SDValue extractF64Exponent(SDValue Hi, const SDLoc &SL, SelectionDAG &DAG)
static SDValue getMad(SelectionDAG &DAG, const SDLoc &SL, EVT VT, SDValue X, SDValue Y, SDValue C, SDNodeFlags Flags=SDNodeFlags())
static bool valueIsKnownNeverF32Denorm(SDValue Src)
Return true if it's known that Src can never be an f32 denormal value.
Contains the definition of a TargetInstrInfo class that is common to all AMD GPUs.
static void packImage16bitOpsToDwords(MachineIRBuilder &B, MachineInstr &MI, SmallVectorImpl< Register > &PackedAddrs, unsigned ArgOffset, const AMDGPU::ImageDimIntrinsicInfo *Intr, bool IsA16, bool IsG16)
Turn a set of s16 typed registers in AddrRegs into a dword sized vector with s16 typed elements.
static unsigned getBufferAtomicPseudo(Intrinsic::ID IntrID)
static LLT getBufferRsrcScalarType(const LLT Ty)
static LegalityPredicate isIllegalRegisterType(const GCNSubtarget &ST, unsigned TypeIdx)
static cl::opt< bool > EnableNewLegality("amdgpu-global-isel-new-legality", cl::desc("Use GlobalISel desired legality, rather than try to use" "rules compatible with selection patterns"), cl::init(false), cl::ReallyHidden)
static MachineInstrBuilder buildExp(MachineIRBuilder &B, const DstOp &Dst, const SrcOp &Src, unsigned Flags)
static bool needsDenormHandlingF32(const MachineFunction &MF, Register Src, unsigned Flags)
constexpr std::initializer_list< LLT > AllVectors
static LegalizeMutation bitcastToVectorElement32(unsigned TypeIdx)
static LegalityPredicate isSmallOddVector(unsigned TypeIdx)
static LegalizeMutation oneMoreElement(unsigned TypeIdx)
constexpr LLT F64
static LegalityPredicate vectorSmallerThan(unsigned TypeIdx, unsigned Size)
constexpr LLT V2S8
static bool allowApproxFunc(const MachineFunction &MF, unsigned Flags)
constexpr LLT V4S128
constexpr LLT S16
constexpr LLT S1
static bool shouldBitcastLoadStoreType(const GCNSubtarget &ST, const LLT Ty, const LLT MemTy)
Return true if a load or store of the type should be lowered with a bitcast to a different type.
constexpr LLT S1024
static constexpr unsigned FPEnvModeBitField
constexpr LLT V7S64
static LegalizeMutation getScalarTypeFromMemDesc(unsigned TypeIdx)
static LegalityPredicate vectorWiderThan(unsigned TypeIdx, unsigned Size)
static bool shouldWidenLoad(const GCNSubtarget &ST, LLT MemoryTy, uint64_t AlignInBits, unsigned AddrSpace, unsigned Opcode)
Return true if we should legalize a load by widening an odd sized memory access up to the alignment.
static bool isRegisterVectorElementType(LLT EltTy)
static LegalizeMutation fewerEltsToSize64Vector(unsigned TypeIdx)
static LegalityPredicate isWideVec16(unsigned TypeIdx)
constexpr std::initializer_list< LLT > AllScalarTypes
static LegalityPredicate isTruncStoreToSizePowerOf2(unsigned TypeIdx)
constexpr LLT V2S16
constexpr LLT V8S16
constexpr LLT V9S32
constexpr std::initializer_list< LLT > AllS32Vectors
constexpr LLT S224
static LegalizeMutation moreElementsToNextExistingRegClass(unsigned TypeIdx)
constexpr LLT S512
constexpr LLT MaxScalar
static Register castBufferRsrcToV4I32(Register Pointer, MachineIRBuilder &B)
Cast a buffer resource (an address space 8 pointer) into a 4xi32, which is the form in which the valu...
constexpr LLT V11S32
static bool isRegisterClassType(const GCNSubtarget &ST, LLT Ty)
constexpr LLT V6S64
constexpr LLT V2S64
static std::pair< Register, Register > emitReciprocalU64(MachineIRBuilder &B, Register Val)
static LLT getBitcastRegisterType(const LLT Ty)
static LLT getBufferRsrcRegisterType(const LLT Ty)
constexpr LLT S32
constexpr LLT V2F16
static LegalizeMutation bitcastToRegisterType(unsigned TypeIdx)
static Register stripAnySourceMods(Register OrigSrc, MachineRegisterInfo &MRI)
constexpr LLT V8S32
constexpr LLT V2BF16
constexpr LLT S192
static LLT castBufferRsrcFromV4I32(MachineInstr &MI, MachineIRBuilder &B, MachineRegisterInfo &MRI, unsigned Idx)
Mutates IR (typicaly a load instruction) to use a <4 x s32> as the initial type of the operand idx an...
static bool replaceWithConstant(MachineIRBuilder &B, MachineInstr &MI, int64_t C)
static constexpr unsigned SPDenormModeBitField
constexpr LLT F32
static unsigned maxSizeForAddrSpace(const GCNSubtarget &ST, unsigned AS, bool IsLoad, bool IsAtomic)
constexpr LLT V6S32
static bool isLoadStoreSizeLegal(const GCNSubtarget &ST, const LegalityQuery &Query)
constexpr LLT S160
static MachineInstr * verifyCFIntrinsic(MachineInstr &MI, MachineRegisterInfo &MRI, MachineInstr *&Br, MachineBasicBlock *&UncondBrTarget, bool &Negated)
constexpr LLT V4S16
constexpr LLT V2S128
constexpr LLT V10S16
static LegalityPredicate numElementsNotEven(unsigned TypeIdx)
constexpr LLT V4S32
constexpr LLT V3S32
constexpr LLT V6S16
constexpr std::initializer_list< LLT > AllS64Vectors
constexpr LLT S256
static void castBufferRsrcArgToV4I32(MachineInstr &MI, MachineIRBuilder &B, unsigned Idx)
constexpr LLT V4S64
static constexpr unsigned FPEnvTrapBitField
constexpr LLT V10S32
constexpr LLT V16S32
static constexpr unsigned MaxRegisterSize
constexpr LLT V7S32
constexpr LLT S96
constexpr LLT V12S16
constexpr LLT V16S64
static bool isRegisterSize(const GCNSubtarget &ST, unsigned Size)
static LegalityPredicate isWideScalarExtLoadTruncStore(unsigned TypeIdx)
static bool hasBufferRsrcWorkaround(const LLT Ty)
constexpr LLT V32S32
static void toggleSPDenormMode(bool Enable, MachineIRBuilder &B, const GCNSubtarget &ST, SIModeRegisterDefaults Mode)
constexpr LLT S64
constexpr std::initializer_list< LLT > AllS16Vectors
static bool loadStoreBitcastWorkaround(const LLT Ty)
static LLT widenToNextPowerOf2(LLT Ty)
static bool isNot(const MachineRegisterInfo &MRI, const MachineInstr &MI)
constexpr LLT V16S16
static void convertImageAddrToPacked(MachineIRBuilder &B, MachineInstr &MI, int DimIdx, int NumVAddrs)
Convert from separate vaddr components to a single vector address register, and replace the remaining...
static bool isLoadStoreLegal(const GCNSubtarget &ST, const LegalityQuery &Query)
static LegalizeMutation moreEltsToNext32Bit(unsigned TypeIdx)
constexpr LLT V5S32
constexpr LLT V5S64
constexpr LLT V3S64
static LLT getPow2VectorType(LLT Ty)
static void buildBufferLoad(unsigned Opc, Register LoadDstReg, Register RSrc, Register VIndex, Register VOffset, Register SOffset, unsigned ImmOffset, unsigned Format, unsigned AuxiliaryData, MachineMemOperand *MMO, bool IsTyped, bool HasVIndex, MachineIRBuilder &B)
constexpr LLT V8S64
static LLT getPow2ScalarType(LLT Ty)
static LegalityPredicate elementTypeIsLegal(unsigned TypeIdx)
constexpr LLT V2S32
static bool isRegisterVectorType(LLT Ty)
constexpr LLT V12S32
constexpr LLT S128
static LegalityPredicate sizeIsMultipleOf32(unsigned TypeIdx)
constexpr LLT S8
static bool isRegisterType(const GCNSubtarget &ST, LLT Ty)
static bool isKnownNonNull(Register Val, MachineRegisterInfo &MRI, const AMDGPUTargetMachine &TM, unsigned AddrSpace)
Return true if the value is a known valid address, such that a null check is not necessary.
This file declares the targeting of the Machinelegalizer class for AMDGPU.
Provides AMDGPU specific target descriptions.
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static Error unsupported(const char *Str, const Triple &T)
Definition MachO.cpp:71
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
@ Enable
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Interface for Targets to specify which operations they can successfully select and how the others sho...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
This file declares the MachineIRBuilder class.
Register const TargetRegisterInfo * TRI
#define R2(n)
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ppc ctr loops verify
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
#define CH(x, y, z)
Definition SHA256.cpp:34
#define FP_DENORM_FLUSH_NONE
Definition SIDefines.h:1258
Interface definition for SIInstrInfo.
Interface definition for SIRegisterInfo.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static constexpr int Concat[]
bool legalizeConstHwRegRead(MachineInstr &MI, MachineIRBuilder &B, AMDGPU::Hwreg::Id HwReg, unsigned LowBit, unsigned Width) const
void buildMultiply(LegalizerHelper &Helper, MutableArrayRef< Register > Accum, ArrayRef< Register > Src0, ArrayRef< Register > Src1, bool UsePartialMad64_32, bool SeparateOddAlignedProducts) const
bool legalizeGlobalValue(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFSQRTF16(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeIntrinsicTrunc(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
std::pair< Register, unsigned > splitBufferOffsets(MachineIRBuilder &B, Register OrigOffset) const
bool legalizeBVHIntersectRayIntrinsic(MachineInstr &MI, MachineIRBuilder &B) const
bool legalizeIsAddrSpace(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B, unsigned AddrSpace) const
bool legalizeUnsignedDIV_REM(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFSQRTF32(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeAtomicCmpXChg(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeTrapHsa(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeBufferStore(MachineInstr &MI, LegalizerHelper &Helper, bool IsTyped, bool IsFormat) const
bool legalizeMul(LegalizerHelper &Helper, MachineInstr &MI) const
bool legalizeFFREXP(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
Register getSegmentAperture(unsigned AddrSpace, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFDIV64(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizePointerAsRsrcIntrin(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
To create a buffer resource from a 64-bit pointer, mask off the upper 32 bits of the pointer and repl...
bool legalizeFlogCommon(MachineInstr &MI, MachineIRBuilder &B) const
bool getLDSKernelId(Register DstReg, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFExp2(MachineInstr &MI, MachineIRBuilder &B) const
bool legalizeTrap(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeBufferAtomic(MachineInstr &MI, MachineIRBuilder &B, Intrinsic::ID IID) const
void legalizeUnsignedDIV_REM32Impl(MachineIRBuilder &B, Register DstDivReg, Register DstRemReg, Register Num, Register Den) const
Register handleD16VData(MachineIRBuilder &B, MachineRegisterInfo &MRI, Register Reg, bool ImageStore=false) const
Handle register layout difference for f16 images for some subtargets.
bool legalizeCTLZ_CTTZ(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeBuildVector(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFFloor(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
AMDGPULegalizerInfo(const GCNSubtarget &ST, const GCNTargetMachine &TM)
bool legalizeFDIV32(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFMad(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFDIV(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeSBufferPrefetch(LegalizerHelper &Helper, MachineInstr &MI) const
bool legalizeFExp10Unsafe(MachineIRBuilder &B, Register Dst, Register Src, unsigned Flags) const
bool legalizeFExp(MachineInstr &MI, MachineIRBuilder &B) const
bool legalizeIntrinsic(LegalizerHelper &Helper, MachineInstr &MI) const override
bool legalizeFrem(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizePreloadedArgIntrin(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B, AMDGPUFunctionArgInfo::PreloadedValue ArgType) const
bool legalizeStore(LegalizerHelper &Helper, MachineInstr &MI) const
bool legalizeCustom(LegalizerHelper &Helper, MachineInstr &MI, LostDebugLocObserver &LocObserver) const override
Called for instructions with the Custom LegalizationAction.
bool buildPCRelGlobalAddress(Register DstReg, LLT PtrTy, MachineIRBuilder &B, const GlobalValue *GV, int64_t Offset, unsigned GAFlags=SIInstrInfo::MO_NONE) const
MachinePointerInfo getKernargSegmentPtrInfo(MachineFunction &MF) const
bool legalizeFDIV16(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeRsqClampIntrinsic(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFExpUnsafeImpl(MachineIRBuilder &B, Register Dst, Register Src, unsigned Flags, bool IsExp10) const
std::pair< Register, Register > getScaledLogInput(MachineIRBuilder &B, Register Src, unsigned Flags) const
bool legalizeFDIVFastIntrin(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool loadInputValue(Register DstReg, MachineIRBuilder &B, AMDGPUFunctionArgInfo::PreloadedValue ArgType) const
bool legalizeBVHDualOrBVH8IntersectRayIntrinsic(MachineInstr &MI, MachineIRBuilder &B) const
bool legalizeInsertVectorElt(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFExpUnsafe(MachineIRBuilder &B, Register Dst, Register Src, unsigned Flags) const
bool legalizeAddrSpaceCast(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeBufferLoad(MachineInstr &MI, LegalizerHelper &Helper, bool IsFormat, bool IsTyped) const
bool legalizeImplicitArgPtr(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeMinNumMaxNum(LegalizerHelper &Helper, MachineInstr &MI) const
void legalizeUnsignedDIV_REM64Impl(MachineIRBuilder &B, Register DstDivReg, Register DstRemReg, Register Num, Register Den) const
bool legalizeDebugTrap(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFastUnsafeFDIV(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeSinCos(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeWaveID(MachineInstr &MI, MachineIRBuilder &B) const
bool legalizeFroundeven(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeLDSKernelId(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeWorkGroupId(MachineInstr &MI, MachineIRBuilder &B, AMDGPUFunctionArgInfo::PreloadedValue ClusterIdPV, AMDGPUFunctionArgInfo::PreloadedValue ClusterMaxIdPV, AMDGPUFunctionArgInfo::PreloadedValue ClusterWorkGroupIdPV) const
bool legalizeSignedDIV_REM(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeITOFP(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B, bool Signed) const
bool legalizeFPow(MachineInstr &MI, MachineIRBuilder &B) const
bool legalizeFastUnsafeFDIV64(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFPTOI(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B, bool Signed) const
bool legalizeStackSave(MachineInstr &MI, MachineIRBuilder &B) const
bool legalizeFlogUnsafe(MachineIRBuilder &B, Register Dst, Register Src, bool IsLog10, unsigned Flags) const
bool legalizeKernargMemParameter(MachineInstr &MI, MachineIRBuilder &B, uint64_t Offset, Align Alignment=Align(4)) const
Legalize a value that's loaded from kernel arguments.
bool legalizeImageIntrinsic(MachineInstr &MI, MachineIRBuilder &B, GISelChangeObserver &Observer, const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr) const
Rewrite image intrinsics to use register layouts expected by the subtarget.
void buildAbsGlobalAddress(Register DstReg, LLT PtrTy, MachineIRBuilder &B, const GlobalValue *GV, MachineRegisterInfo &MRI) const
bool legalizeGetFPEnv(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool getImplicitArgPtr(Register DstReg, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFSQRT(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
Register getKernargParameterPtr(MachineIRBuilder &B, int64_t Offset) const
bool legalizeSBufferLoad(LegalizerHelper &Helper, MachineInstr &MI) const
bool legalizeFceil(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFSQRTF64(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeExtractVectorElt(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeLoad(LegalizerHelper &Helper, MachineInstr &MI) const
bool legalizeCTLZ_ZERO_UNDEF(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
Register fixStoreSourceType(MachineIRBuilder &B, Register VData, LLT MemTy, bool IsFormat) const
bool legalizeLaneOp(LegalizerHelper &Helper, MachineInstr &MI, Intrinsic::ID IID) const
bool legalizeSetFPEnv(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeWorkitemIDIntrinsic(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B, unsigned Dim, AMDGPUFunctionArgInfo::PreloadedValue ArgType) const
void buildLoadInputValue(Register DstReg, MachineIRBuilder &B, const ArgDescriptor *Arg, const TargetRegisterClass *ArgRC, LLT ArgTy) const
bool legalizeTrapHsaQueuePtr(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
bool legalizeFlog2(MachineInstr &MI, MachineIRBuilder &B) const
bool legalizeTrapEndpgm(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &B) const
static std::optional< uint32_t > getLDSKernelIdMetadata(const Function &F)
void setDynLDSAlign(const Function &F, const GlobalVariable &GV)
unsigned allocateLDSGlobal(const DataLayout &DL, const GlobalVariable &GV)
static int64_t getNullPointerValue(unsigned AddrSpace)
Get the integer value of a null pointer in the given address space.
bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast between SrcAS and DestAS is a noop.
const std::array< unsigned, 3 > & getDims() const
static const fltSemantics & IEEEsingle()
Definition APFloat.h:296
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1140
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1120
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1080
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
This is the shared class of boolean and integer constants.
Definition Constants.h:87
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
A debug info location.
Definition DebugLoc.h:123
Diagnostic information for unsupported feature in backend.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:359
Abstract class that contains various methods for clients to notify about changes.
virtual void changingInstr(MachineInstr &MI)=0
This instruction is about to be mutated in some way.
virtual void changedInstr(MachineInstr &MI)=0
This instruction was mutated in some way.
Simple wrapper observer that takes several observers, and calls each one for each event.
KnownBits getKnownBits(Register R)
bool hasExternalLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
Type * getValueType() const
static constexpr LLT float64()
Get a 64-bit IEEE double value.
constexpr unsigned getScalarSizeInBits() const
constexpr LLT changeElementType(LLT NewEltTy) const
If this type is a vector, return a vector with the same number of elements but the new element type.
static constexpr LLT vector(ElementCount EC, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isVector() const
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr bool isPointer() const
constexpr LLT getElementType() const
Returns the vector's element type. Only valid for vector types.
constexpr LLT changeElementSize(unsigned NewEltSize) const
If this type is a vector, return a vector with the same number of elements but the new element size.
static constexpr LLT float16()
Get a 16-bit IEEE half value.
constexpr unsigned getAddressSpace() const
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
constexpr LLT changeElementCount(ElementCount EC) const
Return a vector or scalar with the same element type and the new element count.
constexpr LLT getScalarType() const
static constexpr LLT scalarOrVector(ElementCount EC, LLT ScalarTy)
static constexpr LLT float32()
Get a 32-bit IEEE float value.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
LLVM_ABI void computeTables()
Compute any ancillary tables needed to quickly decide how an operation should be handled.
LegalizeRuleSet & minScalar(unsigned TypeIdx, const LLT Ty)
Ensure the scalar is at least as wide as Ty.
LegalizeRuleSet & legalFor(std::initializer_list< LLT > Types)
The instruction is legal when type index 0 is any type in the given list.
LegalizeRuleSet & unsupported()
The instruction is unsupported.
LegalizeRuleSet & scalarSameSizeAs(unsigned TypeIdx, unsigned SameSizeIdx)
Change the type TypeIdx to have the same scalar size as type SameSizeIdx.
LegalizeRuleSet & fewerElementsIf(LegalityPredicate Predicate, LegalizeMutation Mutation)
Remove elements to reach the type selected by the mutation if the predicate is true.
LegalizeRuleSet & clampScalarOrElt(unsigned TypeIdx, const LLT MinTy, const LLT MaxTy)
Limit the range of scalar sizes to MinTy and MaxTy.
LegalizeRuleSet & bitcastIf(LegalityPredicate Predicate, LegalizeMutation Mutation)
The specified type index is coerced if predicate is true.
LegalizeRuleSet & maxScalar(unsigned TypeIdx, const LLT Ty)
Ensure the scalar is at most as wide as Ty.
LegalizeRuleSet & minScalarOrElt(unsigned TypeIdx, const LLT Ty)
Ensure the scalar or element is at least as wide as Ty.
LegalizeRuleSet & clampMaxNumElements(unsigned TypeIdx, const LLT EltTy, unsigned MaxElements)
Limit the number of elements in EltTy vectors to at most MaxElements.
LegalizeRuleSet & unsupportedFor(std::initializer_list< LLT > Types)
LegalizeRuleSet & lower()
The instruction is lowered.
LegalizeRuleSet & moreElementsIf(LegalityPredicate Predicate, LegalizeMutation Mutation)
Add more elements to reach the type selected by the mutation if the predicate is true.
LegalizeRuleSet & lowerFor(std::initializer_list< LLT > Types)
The instruction is lowered when type index 0 is any type in the given list.
LegalizeRuleSet & lowerIf(LegalityPredicate Predicate)
The instruction is lowered if predicate is true.
LegalizeRuleSet & clampScalar(unsigned TypeIdx, const LLT MinTy, const LLT MaxTy)
Limit the range of scalar sizes to MinTy and MaxTy.
LegalizeRuleSet & custom()
Unconditionally custom lower.
LegalizeRuleSet & clampMaxNumElementsStrict(unsigned TypeIdx, const LLT EltTy, unsigned NumElts)
Express EltTy vectors strictly using vectors with NumElts elements (or scalars when NumElts equals 1)...
LegalizeRuleSet & unsupportedIf(LegalityPredicate Predicate)
LegalizeRuleSet & widenScalarIf(LegalityPredicate Predicate, LegalizeMutation Mutation)
Widen the scalar to the one selected by the mutation if the predicate is true.
LegalizeRuleSet & alwaysLegal()
LegalizeRuleSet & clampNumElements(unsigned TypeIdx, const LLT MinTy, const LLT MaxTy)
Limit the number of elements for the given vectors to at least MinTy's number of elements and at most...
LegalizeRuleSet & maxScalarIf(LegalityPredicate Predicate, unsigned TypeIdx, const LLT Ty)
Conditionally limit the maximum size of the scalar.
LegalizeRuleSet & customIf(LegalityPredicate Predicate)
LegalizeRuleSet & widenScalarToNextPow2(unsigned TypeIdx, unsigned MinSize=0)
Widen the scalar to the next power of two that is at least MinSize.
LegalizeRuleSet & scalarize(unsigned TypeIdx)
LegalizeRuleSet & legalForCartesianProduct(std::initializer_list< LLT > Types)
The instruction is legal when type indexes 0 and 1 are both in the given list.
LegalizeRuleSet & legalIf(LegalityPredicate Predicate)
The instruction is legal if predicate is true.
LegalizeRuleSet & customFor(std::initializer_list< LLT > Types)
LegalizeRuleSet & widenScalarToNextMultipleOf(unsigned TypeIdx, unsigned Size)
Widen the scalar to the next multiple of Size.
LLVM_ABI LegalizeResult lowerFMinNumMaxNum(MachineInstr &MI)
LLVM_ABI void moreElementsVectorDst(MachineInstr &MI, LLT MoreTy, unsigned OpIdx)
Legalize a single operand OpIdx of the machine instruction MI as a Def by performing it with addition...
GISelValueTracking * getValueTracking() const
@ Legalized
Instruction has been legalized and the MachineFunction changed.
GISelChangeObserver & Observer
To keep track of changes made by the LegalizerHelper.
LLVM_ABI void bitcastDst(MachineInstr &MI, LLT CastTy, unsigned OpIdx)
Legalize a single operand OpIdx of the machine instruction MI as a def by inserting a G_BITCAST from ...
LLVM_ABI LegalizeResult lowerFMad(MachineInstr &MI)
MachineIRBuilder & MIRBuilder
Expose MIRBuilder so clients can set their own RecordInsertInstruction functions.
LLVM_ABI void widenScalarDst(MachineInstr &MI, LLT WideTy, unsigned OpIdx=0, unsigned TruncOpcode=TargetOpcode::G_TRUNC)
Legalize a single operand OpIdx of the machine instruction MI as a Def by extending the operand's typ...
LegalizeRuleSet & getActionDefinitionsBuilder(unsigned Opcode)
Get the action definition builder for the given opcode.
const LegacyLegalizerInfo & getLegacyLegalizerInfo() const
TypeSize getValue() const
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition MCRegister.h:72
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
PseudoSourceValueManager & getPSVManager() const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, Align base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
void push_back(MachineBasicBlock *MBB)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Helper class to build MachineInstr.
MachineFunction & getMF()
Getter for the function we currently build.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addGlobalAddress(const GlobalValue *GV, int64_t Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
LocationSize getSize() const
Return the size in bytes of the memory reference.
LLT getMemoryType() const
Return the memory type of the memory reference.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
LLVM_ABI Align getAlign() const
Return the minimum known alignment in bytes of the actual memory reference.
MachineOperand class - Representation of each machine instruction operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setMBB(MachineBasicBlock *MBB)
static MachineOperand CreateImm(int64_t Val)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition ArrayRef.h:298
MutableArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:387
LLVM_ABI const PseudoSourceValue * getConstantPool()
Return a pseudo source value referencing the constant pool.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
static unsigned getMaxMUBUFImmOffset(const GCNSubtarget &ST)
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
AMDGPU::ClusterDimsAttr getClusterDims() const
SIModeRegisterDefaults getMode() const
std::tuple< const ArgDescriptor *, const TargetRegisterClass *, LLT > getPreloadedValue(AMDGPUFunctionArgInfo::PreloadedValue Value) const
static LLVM_READONLY const TargetRegisterClass * getSGPRClassForBitWidth(unsigned BitWidth)
bool allowsMisalignedMemoryAccessesImpl(unsigned Size, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *IsFast=nullptr) const
bool shouldEmitFixup(const GlobalValue *GV) const
bool shouldUseLDSConstAddress(const GlobalValue *GV) const
bool shouldEmitPCReloc(const GlobalValue *GV) const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void truncate(size_type N)
Like resize, but requires that N is less than size().
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
int64_t getImm() const
Register getReg() const
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
unsigned getPointerSizeInBits(unsigned AS) const
TargetOptions Options
unsigned NoNaNsFPMath
NoNaNsFPMath - This flag is enabled when the -enable-no-nans-fp-math flag is specified on the command...
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CONSTANT_ADDRESS_32BIT
Address space for 32-bit constant memory.
@ BUFFER_STRIDED_POINTER
Address space for 192-bit fat buffer pointers with an additional index.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ BUFFER_FAT_POINTER
Address space for 160-bit buffer fat pointers.
@ PRIVATE_ADDRESS
Address space for private memory.
@ BUFFER_RESOURCE
Address space for 128-bit buffer resources.
int getMIMGOpcode(unsigned BaseOpcode, unsigned MIMGEncoding, unsigned VDataDwords, unsigned VAddrDwords)
bool isFlatGlobalAddrSpace(unsigned AS)
bool isGFX12Plus(const MCSubtargetInfo &STI)
bool isGFX11(const MCSubtargetInfo &STI)
LLVM_READNONE bool isLegalDPALU_DPPControl(const MCSubtargetInfo &ST, unsigned DC)
unsigned getAMDHSACodeObjectVersion(const Module &M)
LLVM_READNONE constexpr bool isKernel(CallingConv::ID CC)
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
LLVM_READNONE constexpr bool isCompute(CallingConv::ID CC)
TargetExtType * isNamedBarrier(const GlobalVariable &GV)
bool isGFX11Plus(const MCSubtargetInfo &STI)
bool isGFX1250(const MCSubtargetInfo &STI)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
std::pair< Register, unsigned > getBaseWithConstantOffset(MachineRegisterInfo &MRI, Register Reg, GISelValueTracking *ValueTracking=nullptr, bool CheckNUW=false)
Returns base register and constant offset.
const ImageDimIntrinsicInfo * getImageDimIntrinsicInfo(unsigned Intr)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ MaxID
The highest possible ID. Must be some 2^k - 1.
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI LegalityPredicate scalarOrEltWiderThan(unsigned TypeIdx, unsigned Size)
True iff the specified type index is a scalar or a vector with an element type that's wider than the ...
LLVM_ABI LegalityPredicate isScalar(unsigned TypeIdx)
True iff the specified type index is a scalar.
LLVM_ABI LegalityPredicate isPointer(unsigned TypeIdx)
True iff the specified type index is a pointer (with any address space).
LLVM_ABI LegalityPredicate typeInSet(unsigned TypeIdx, std::initializer_list< LLT > TypesInit)
True iff the given type index is one of the specified types.
LLVM_ABI LegalityPredicate smallerThan(unsigned TypeIdx0, unsigned TypeIdx1)
True iff the first type index has a smaller total bit size than second type index.
LLVM_ABI LegalityPredicate largerThan(unsigned TypeIdx0, unsigned TypeIdx1)
True iff the first type index has a larger total bit size than second type index.
LLVM_ABI LegalityPredicate elementTypeIs(unsigned TypeIdx, LLT EltTy)
True if the type index is a vector with element type EltTy.
LLVM_ABI LegalityPredicate sameSize(unsigned TypeIdx0, unsigned TypeIdx1)
True iff the specified type indices are both the same bit size.
LLVM_ABI LegalityPredicate scalarOrEltNarrowerThan(unsigned TypeIdx, unsigned Size)
True iff the specified type index is a scalar or vector with an element type that's narrower than the...
LLVM_ABI LegalityPredicate sizeIs(unsigned TypeIdx, unsigned Size)
True if the total bitwidth of the specified type index is Size bits.
LegalityPredicate typeIsNot(unsigned TypeIdx, LLT Type)
True iff the given type index is not the specified type.
Predicate all(Predicate P0, Predicate P1)
True iff P0 and P1 are true.
LLVM_ABI LegalityPredicate typeIs(unsigned TypeIdx, LLT TypesInit)
True iff the given type index is the specified type.
LLVM_ABI LegalityPredicate scalarNarrowerThan(unsigned TypeIdx, unsigned Size)
True iff the specified type index is a scalar that's narrower than the given size.
LLVM_ABI LegalizeMutation scalarize(unsigned TypeIdx)
Break up the vector type for the given type index into the element type.
LLVM_ABI LegalizeMutation widenScalarOrEltToNextPow2(unsigned TypeIdx, unsigned Min=0)
Widen the scalar type or vector element type for the given type index to the next power of 2.
LLVM_ABI LegalizeMutation changeTo(unsigned TypeIdx, LLT Ty)
Select this specific type for the given type index.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
Invariant opcodes: All instruction sets have these as their low opcodes.
initializer< Ty > init(const Ty &Val)
constexpr double inv_pi
constexpr double ln2
constexpr double ln10
constexpr float log2ef
Definition MathExtras.h:51
constexpr double log2e
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Register getFunctionLiveInPhysReg(MachineFunction &MF, const TargetInstrInfo &TII, MCRegister PhysReg, const TargetRegisterClass &RC, const DebugLoc &DL, LLT RegTy=LLT())
Return a virtual register corresponding to the incoming argument register PhysReg.
Definition Utils.cpp:920
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:344
@ Offset
Definition DWP.cpp:532
LLVM_ABI Type * getTypeForLLT(LLT Ty, LLVMContext &C)
Get the type back from LLT.
Definition Utils.cpp:2039
LLVM_ABI MachineInstr * getOpcodeDef(unsigned Opcode, Register Reg, const MachineRegisterInfo &MRI)
See if Reg is defined by an single def instruction that is Opcode.
Definition Utils.cpp:652
LLVM_ABI const ConstantFP * getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:460
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition ScopeExit.h:59
LLVM_ABI const llvm::fltSemantics & getFltSemanticForLLT(LLT Ty)
Get the appropriate floating point arithmetic semantic based on the bit size of the given scalar LLT.
std::function< std::pair< unsigned, LLT >(const LegalityQuery &)> LegalizeMutation
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:303
void * PointerTy
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:154
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:385
LLVM_ABI std::optional< int64_t > getIConstantVRegSExtVal(Register VReg, const MachineRegisterInfo &MRI)
If VReg is defined by a G_CONSTANT fits in int64_t returns it.
Definition Utils.cpp:315
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:202
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:147
std::function< bool(const LegalityQuery &)> LegalityPredicate
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:394
To bit_cast(const From &from) noexcept
Definition bit.h:90
@ Mul
Product of integers.
@ FMul
Product of floats.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI void eraseInstr(MachineInstr &MI, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver=nullptr)
Definition Utils.cpp:1724
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< ValueAndVReg > getIConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT returns its...
Definition Utils.cpp:434
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1909
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:330
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:373
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#define N
static constexpr uint64_t encode(Fields... Values)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
MCRegister getRegister() const
static ArgDescriptor createRegister(Register Reg, unsigned Mask=~0u)
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ Dynamic
Denormals have unknown treatment.
static constexpr DenormalMode getPreserveSign()
static constexpr DenormalMode getIEEE()
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:80
The LegalityQuery object bundles together all the information that's needed to decide whether a given...
ArrayRef< MemDesc > MMODescrs
Operations which require memory can use this to place requirements on the memory type for each MMO.
ArrayRef< LLT > Types
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
DenormalMode FP64FP16Denormals
If this is set, neither input or output denormals are flushed for both f64 and f16/v2f16 instructions...
bool IEEE
Floating point opcodes that support exception flag gathering quiet and propagate signaling NaN inputs...
DenormalMode FP32Denormals
If this is set, neither input or output denormals are flushed for most f32 instructions.