LLVM 24.0.0git
SIISelLowering.cpp
Go to the documentation of this file.
1//===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Custom DAG lowering for SI
11//
12//===----------------------------------------------------------------------===//
13
14#include "SIISelLowering.h"
15#include "AMDGPU.h"
16#include "AMDGPUIGroupLP.h"
17#include "AMDGPUInstrInfo.h"
18#include "AMDGPULaneMaskUtils.h"
19#include "AMDGPUMemoryUtils.h"
21#include "AMDGPUTargetMachine.h"
22#include "GCNSubtarget.h"
25#include "SIRegisterInfo.h"
26#include "llvm/ADT/APFloat.h"
27#include "llvm/ADT/APInt.h"
29#include "llvm/ADT/Statistic.h"
45#include "llvm/IR/IRBuilder.h"
47#include "llvm/IR/IntrinsicsAMDGPU.h"
48#include "llvm/IR/IntrinsicsR600.h"
49#include "llvm/IR/MDBuilder.h"
52#include "llvm/Support/ModRef.h"
55#include <optional>
56
57using namespace llvm;
58using namespace llvm::SDPatternMatch;
59
60#define DEBUG_TYPE "si-lower"
61
62STATISTIC(NumTailCalls, "Number of tail calls");
63
65 return MF.getInfo<SIMachineFunctionInfo>()->getMode().getDenormalFPEnv();
66}
67
72
77
78static unsigned findFirstFreeSGPR(CCState &CCInfo) {
79 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
80 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
81 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
82 return AMDGPU::SGPR0 + Reg;
83 }
84 }
85 llvm_unreachable("Cannot allocate sgpr");
86}
87
89 const GCNSubtarget &STI)
90 : AMDGPUTargetLowering(TM, STI, STI), Subtarget(&STI) {
91 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
92 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
93
94 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
95
96 const SIRegisterInfo *TRI = STI.getRegisterInfo();
97 const TargetRegisterClass *V32RegClass =
98 TRI->getDefaultVectorSuperClassForBitWidth(32);
99 addRegisterClass(MVT::f32, V32RegClass);
100
101 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
102
103 const TargetRegisterClass *V64RegClass =
104 TRI->getDefaultVectorSuperClassForBitWidth(64);
105
106 addRegisterClass(MVT::f64, V64RegClass);
107 addRegisterClass(MVT::v2f32, V64RegClass);
108 addRegisterClass(MVT::Untyped, V64RegClass);
109
110 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
111 addRegisterClass(MVT::v3f32, TRI->getDefaultVectorSuperClassForBitWidth(96));
112
113 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
114 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
115
116 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
117 addRegisterClass(MVT::v4f32, TRI->getDefaultVectorSuperClassForBitWidth(128));
118
119 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
120 addRegisterClass(MVT::v5f32, TRI->getDefaultVectorSuperClassForBitWidth(160));
121
122 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
123 addRegisterClass(MVT::v6f32, TRI->getDefaultVectorSuperClassForBitWidth(192));
124
125 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
126 addRegisterClass(MVT::v3f64, TRI->getDefaultVectorSuperClassForBitWidth(192));
127
128 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
129 addRegisterClass(MVT::v7f32, TRI->getDefaultVectorSuperClassForBitWidth(224));
130
131 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
132 addRegisterClass(MVT::v8f32, TRI->getDefaultVectorSuperClassForBitWidth(256));
133
134 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
135 addRegisterClass(MVT::v4f64, TRI->getDefaultVectorSuperClassForBitWidth(256));
136
137 addRegisterClass(MVT::v9i32, &AMDGPU::SGPR_288RegClass);
138 addRegisterClass(MVT::v9f32, TRI->getDefaultVectorSuperClassForBitWidth(288));
139
140 addRegisterClass(MVT::v10i32, &AMDGPU::SGPR_320RegClass);
141 addRegisterClass(MVT::v10f32,
142 TRI->getDefaultVectorSuperClassForBitWidth(320));
143
144 addRegisterClass(MVT::v11i32, &AMDGPU::SGPR_352RegClass);
145 addRegisterClass(MVT::v11f32,
146 TRI->getDefaultVectorSuperClassForBitWidth(352));
147
148 addRegisterClass(MVT::v12i32, &AMDGPU::SGPR_384RegClass);
149 addRegisterClass(MVT::v12f32,
150 TRI->getDefaultVectorSuperClassForBitWidth(384));
151
152 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
153 addRegisterClass(MVT::v16f32,
154 TRI->getDefaultVectorSuperClassForBitWidth(512));
155
156 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
157 addRegisterClass(MVT::v8f64, TRI->getDefaultVectorSuperClassForBitWidth(512));
158
159 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
160 addRegisterClass(MVT::v16f64,
161 TRI->getDefaultVectorSuperClassForBitWidth(1024));
162
163 if (Subtarget->has16BitInsts()) {
164 if (Subtarget->useRealTrue16Insts()) {
165 addRegisterClass(MVT::i16, &AMDGPU::VGPR_16RegClass);
166 addRegisterClass(MVT::f16, &AMDGPU::VGPR_16RegClass);
167 addRegisterClass(MVT::bf16, &AMDGPU::VGPR_16RegClass);
168 } else {
169 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
170 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
171 addRegisterClass(MVT::bf16, &AMDGPU::SReg_32RegClass);
172 }
173
174 // Unless there are also VOP3P operations, not operations are really legal.
175 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
176 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
177 addRegisterClass(MVT::v2bf16, &AMDGPU::SReg_32RegClass);
178 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
179 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
180 addRegisterClass(MVT::v4bf16, &AMDGPU::SReg_64RegClass);
181 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
182 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
183 addRegisterClass(MVT::v8bf16, &AMDGPU::SGPR_128RegClass);
184 addRegisterClass(MVT::v16i16, &AMDGPU::SGPR_256RegClass);
185 addRegisterClass(MVT::v16f16, &AMDGPU::SGPR_256RegClass);
186 addRegisterClass(MVT::v16bf16, &AMDGPU::SGPR_256RegClass);
187 addRegisterClass(MVT::v32i16, &AMDGPU::SGPR_512RegClass);
188 addRegisterClass(MVT::v32f16, &AMDGPU::SGPR_512RegClass);
189 addRegisterClass(MVT::v32bf16, &AMDGPU::SGPR_512RegClass);
190 }
191
192 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
193 addRegisterClass(MVT::v32f32,
194 TRI->getDefaultVectorSuperClassForBitWidth(1024));
195
196 computeRegisterProperties(Subtarget->getRegisterInfo());
197
200
201 // The boolean content concept here is too inflexible. Compares only ever
202 // really produce a 1-bit result. Any copy/extend from these will turn into a
203 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
204 // it's what most targets use.
207
208 // We need to custom lower vector stores from local memory
210 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
211 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
212 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
213 MVT::i1, MVT::v32i32},
214 Custom);
215
217 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
218 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
219 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
220 MVT::i1, MVT::v32i32},
221 Custom);
222
223 if (isTypeLegal(MVT::bf16)) {
224 for (unsigned Opc :
233 ISD::SETCC}) {
234 setOperationAction(Opc, MVT::bf16, Promote);
235 }
236
237 // Only targets with packed bf16 instructions, e.g. gfx13.
238 if (Subtarget->hasBF16PackedInsts()) {
239 // Don't use Expand for fsub - the DAG combiner will undo fadd+fneg back
240 // to fsub, causing a libcall (which doesn't exist for bf16). Instead,
241 // directly expand to widened v2bf16 operations.
244 Promote);
245 // Promote scalar operations to a v2bf16 operation with an unused high
246 // lane.
247 for (unsigned Opc :
250 AddPromotedToType(Opc, MVT::bf16, MVT::v2bf16);
251 }
252
254
256 AddPromotedToType(ISD::SELECT, MVT::bf16, MVT::i16);
257
261
262 // We only need to custom lower because we can't specify an action for bf16
263 // sources.
266 }
267
268 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
269 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
270 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
271 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
272 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
273 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
274 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
275 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
276 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
277 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
278 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
279 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
280 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
281 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
282 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
283 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
284
285 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
286 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
287 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
288 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
289 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
290 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
291 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
292
293 setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom);
294 setOperationAction(ISD::BlockAddress, {MVT::i32, MVT::i64}, Custom);
295 setOperationAction(ISD::ExternalSymbol, {MVT::i32, MVT::i64}, Custom);
296
300 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
301
302 setOperationAction(ISD::FSQRT, {MVT::f32, MVT::f64}, Custom);
303
305 {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand);
306
308 setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand);
309 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
310
312 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
313 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
314 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32},
315 Expand);
317 {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32,
318 MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v9f32,
319 MVT::v10f32, MVT::v11f32, MVT::v12f32, MVT::v16f32},
320 Expand);
321
323 {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16,
324 MVT::v3i16, MVT::v4i16, MVT::Other},
325 Custom);
326
329 {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand);
330
333
336
338 Expand);
339
341
342 // We only support LOAD/STORE and vector manipulation ops for vectors
343 // with > 4 elements.
344 for (MVT VT :
345 {MVT::v8i32, MVT::v8f32, MVT::v9i32, MVT::v9f32, MVT::v10i32,
346 MVT::v10f32, MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32,
347 MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64, MVT::v4i16,
348 MVT::v4f16, MVT::v4bf16, MVT::v3i64, MVT::v3f64, MVT::v6i32,
349 MVT::v6f32, MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
350 MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16, MVT::v16f16,
351 MVT::v16bf16, MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32,
352 MVT::v32i16, MVT::v32f16, MVT::v32bf16}) {
353 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
354 switch (Op) {
355 case ISD::LOAD:
356 case ISD::STORE:
357 case ISD::ATOMIC_LOAD:
360 case ISD::BITCAST:
361 case ISD::UNDEF:
362 case ISD::POISON:
366 case ISD::IS_FPCLASS:
367 break;
372 break;
373 default:
375 break;
376 }
377 }
378 }
379
381
382 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
383 // is expanded to avoid having two separate loops in case the index is a VGPR.
384
385 // Most operations are naturally 32-bit vector operations. We only support
386 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
387 for (MVT Vec64 : {MVT::v2i64, MVT::v2f64}) {
389 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
390
392 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
393
395 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
396
398 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
399 }
400
401 for (MVT Vec64 : {MVT::v3i64, MVT::v3f64}) {
403 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
404
406 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
407
409 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
410
412 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
413 }
414
415 for (MVT Vec64 : {MVT::v4i64, MVT::v4f64}) {
417 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
418
420 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
421
423 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
424
426 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
427 }
428
429 for (MVT Vec64 : {MVT::v8i64, MVT::v8f64}) {
431 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
432
434 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
435
437 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
438
440 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
441 }
442
443 for (MVT Vec64 : {MVT::v16i64, MVT::v16f64}) {
445 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
446
448 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
449
451 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
452
454 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
455 }
456
458 {MVT::v4i32, MVT::v4f32, MVT::v8i32, MVT::v8f32,
459 MVT::v16i32, MVT::v16f32, MVT::v32i32, MVT::v32f32},
460 Custom);
461
462 if (Subtarget->hasPkMovB32()) {
463 // TODO: 16-bit element vectors should be legal with even aligned elements.
464 // TODO: Can be legal with wider source types than the result with
465 // subregister extracts.
466 setOperationAction(ISD::VECTOR_SHUFFLE, {MVT::v2i32, MVT::v2f32}, Legal);
467 }
468
470 // Prevent SELECT v2i32 from being implemented with the above bitwise ops and
471 // instead lower to cndmask in SITargetLowering::LowerSELECT().
473 // Enable MatchRotate to produce ISD::ROTR, which is later transformed to
474 // alignbit.
475 setOperationAction(ISD::ROTR, MVT::v2i32, Custom);
476
477 setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16, MVT::v4bf16},
478 Custom);
479
480 // Avoid stack access for these.
481 // TODO: Generalize to wider i8 vectors.
483 {MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::v2i8, MVT::v4i8,
484 MVT::v8i8, MVT::v4i16, MVT::v4f16, MVT::v4bf16},
485 Custom);
486
487 // Deal with vec3 vector operations when widened to vec4.
489 {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom);
490
491 // Deal with vec5/6/7 vector operations when widened to vec8.
493 {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32,
494 MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32,
495 MVT::v9i32, MVT::v9f32, MVT::v10i32, MVT::v10f32,
496 MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32},
497 Custom);
498
499 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
500 // and output demarshalling
501 setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom);
502
503 // We can't return success/failure, only the old value,
504 // let LLVM add the comparison
506 Expand);
507
508 setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
509
510 setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal);
511
512 // FIXME: This should be narrowed to i32, but that only happens if i64 is
513 // illegal.
514 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
515 setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal);
516
517 // On SI this is s_memtime and s_memrealtime on VI.
519
520 if (Subtarget->hasSMemRealTime() ||
521 Subtarget->getGeneration() >= AMDGPUSubtarget::GFX11)
524
525 if (Subtarget->has16BitInsts()) {
528 setOperationAction(ISD::IS_FPCLASS, {MVT::f16, MVT::f32, MVT::f64}, Legal);
531 } else {
533 }
534
535 if (Subtarget->hasMadMacF32Insts())
537
541
542 // We only really have 32-bit BFE instructions (and 16-bit on VI).
543 //
544 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
545 // effort to match them now. We want this to be false for i64 cases when the
546 // extraction isn't restricted to the upper or lower half. Ideally we would
547 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
548 // span the midpoint are probably relatively rare, so don't worry about them
549 // for now.
551
552 // Clamp modifier on add/sub
553 if (Subtarget->hasIntClamp())
555
556 if (Subtarget->hasAddNoCarryInsts())
557 setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32},
558 Legal);
559
560 // Do not have s_{min|max}_*f64 instruction f64 will only be lowered to
561 // v_{min|max}_*f64
562 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
565 {MVT::f64, MVT::f32}, Legal);
566 } else {
569 {MVT::f64, MVT::f32}, Custom);
570 // These are really only legal for ieee_mode functions. We should be
571 // avoiding them for functions that don't have ieee_mode enabled, so just
572 // say they are legal.
574 {MVT::f64, MVT::f32}, Legal);
575 }
576
577 if (Subtarget->haveRoundOpsF64())
579 Legal);
580 else
582 MVT::f64, Custom);
583
585 setOperationAction({ISD::FLDEXP, ISD::STRICT_FLDEXP}, {MVT::f32, MVT::f64},
586 Legal);
587 setOperationAction(ISD::FFREXP, {MVT::f32, MVT::f64}, Custom);
588
591
592 setOperationAction(ISD::BF16_TO_FP, {MVT::i16, MVT::f32, MVT::f64}, Expand);
593 setOperationAction(ISD::FP_TO_BF16, {MVT::i16, MVT::f32, MVT::f64}, Expand);
594
596 Custom);
598 Custom);
600 Custom);
601
602 // Custom lower these because we can't specify a rule based on an illegal
603 // source bf16.
606
607 if (Subtarget->has16BitInsts()) {
610 MVT::i16, Legal);
611
612 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
613
615 MVT::i16, Expand);
616
620 ISD::CTPOP},
621 MVT::i16, Promote);
622
624
625 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
626
628 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
630 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
631
636
638
639 // F16 - Constant Actions.
642
643 // F16 - Load/Store Actions.
645 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
647 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
648
649 // BF16 - Load/Store Actions.
651 AddPromotedToType(ISD::LOAD, MVT::bf16, MVT::i16);
653 AddPromotedToType(ISD::STORE, MVT::bf16, MVT::i16);
654
655 if (!Subtarget->useRealTrue16Insts() ||
656 !Subtarget->d16PreservesUnusedBits()) {
657 for (MVT VT : {MVT::i16, MVT::f16, MVT::bf16}) {
659 AddPromotedToType(ISD::ATOMIC_LOAD, VT, MVT::i32);
660 }
661 }
662
663 if (!Subtarget->useRealTrue16Insts()) {
664 for (MVT VT : {MVT::i16, MVT::f16, MVT::bf16}) {
667 }
668 }
669
670 // F16 - VOP1 Actions.
673 MVT::f16, Custom);
674
675 // BF16 - VOP1 Actions.
676 if (Subtarget->hasBF16TransInsts())
678
679 // F16 - VOP2 Actions.
680 setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, {MVT::f16, MVT::bf16},
681 Expand);
685
686 // F16 - VOP3 Actions.
688 if (STI.hasMadF16())
690
691 for (MVT VT :
692 {MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::v4i16, MVT::v4f16,
693 MVT::v4bf16, MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16,
694 MVT::v16f16, MVT::v16bf16, MVT::v32i16, MVT::v32f16}) {
695 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
696 switch (Op) {
697 case ISD::LOAD:
698 case ISD::STORE:
699 case ISD::ATOMIC_LOAD:
702 case ISD::BITCAST:
703 case ISD::UNDEF:
704 case ISD::POISON:
709 case ISD::IS_FPCLASS:
710 break;
713 case ISD::FSIN:
714 case ISD::FCOS:
716 break;
717 default:
719 break;
720 }
721 }
722 }
723
724 // v_perm_b32 can handle either of these.
725 setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal);
727
728 // Legalize vector types for sat conversions to select v_cvt_pk_[iu]16_f32.
729 if (Subtarget->hasVCvtPkIU16F32())
732 {MVT::v2i16, MVT::v4i16, MVT::v8i16, MVT::v16i16, MVT::v32i16},
733 Custom);
734
735 // XXX - Do these do anything? Vector constants turn into build_vector.
736 setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal);
737
739 {MVT::v2i16, MVT::v2f16, MVT::v2bf16}, Legal);
740
742 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
744 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
745
747 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
749 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
750
751 setOperationAction(ISD::AND, MVT::v2i16, Promote);
752 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
753 setOperationAction(ISD::OR, MVT::v2i16, Promote);
754 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
755 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
756 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
757
759 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
761 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
762 setOperationAction(ISD::LOAD, MVT::v4bf16, Promote);
763 AddPromotedToType(ISD::LOAD, MVT::v4bf16, MVT::v2i32);
764
766 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
768 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
770 AddPromotedToType(ISD::STORE, MVT::v4bf16, MVT::v2i32);
771
773 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
775 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
776 setOperationAction(ISD::LOAD, MVT::v8bf16, Promote);
777 AddPromotedToType(ISD::LOAD, MVT::v8bf16, MVT::v4i32);
778
780 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
782 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
783
785 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
787 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
789 AddPromotedToType(ISD::STORE, MVT::v8bf16, MVT::v4i32);
790
791 setOperationAction(ISD::LOAD, MVT::v16i16, Promote);
792 AddPromotedToType(ISD::LOAD, MVT::v16i16, MVT::v8i32);
793 setOperationAction(ISD::LOAD, MVT::v16f16, Promote);
794 AddPromotedToType(ISD::LOAD, MVT::v16f16, MVT::v8i32);
795 setOperationAction(ISD::LOAD, MVT::v16bf16, Promote);
796 AddPromotedToType(ISD::LOAD, MVT::v16bf16, MVT::v8i32);
797
799 AddPromotedToType(ISD::STORE, MVT::v16i16, MVT::v8i32);
801 AddPromotedToType(ISD::STORE, MVT::v16f16, MVT::v8i32);
802 setOperationAction(ISD::STORE, MVT::v16bf16, Promote);
803 AddPromotedToType(ISD::STORE, MVT::v16bf16, MVT::v8i32);
804
805 setOperationAction(ISD::LOAD, MVT::v32i16, Promote);
806 AddPromotedToType(ISD::LOAD, MVT::v32i16, MVT::v16i32);
807 setOperationAction(ISD::LOAD, MVT::v32f16, Promote);
808 AddPromotedToType(ISD::LOAD, MVT::v32f16, MVT::v16i32);
809 setOperationAction(ISD::LOAD, MVT::v32bf16, Promote);
810 AddPromotedToType(ISD::LOAD, MVT::v32bf16, MVT::v16i32);
811
813 AddPromotedToType(ISD::STORE, MVT::v32i16, MVT::v16i32);
815 AddPromotedToType(ISD::STORE, MVT::v32f16, MVT::v16i32);
816 setOperationAction(ISD::STORE, MVT::v32bf16, Promote);
817 AddPromotedToType(ISD::STORE, MVT::v32bf16, MVT::v16i32);
818
820 MVT::v2i32, Expand);
822
824 MVT::v4i32, Expand);
825
827 MVT::v8i32, Expand);
828
829 setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16, MVT::v2bf16},
830 Subtarget->hasVOP3PInsts() ? Legal : Custom);
831
832 setOperationAction(ISD::FNEG, {MVT::v2f16, MVT::v2bf16}, Legal);
833 // This isn't really legal, but this avoids the legalizer unrolling it (and
834 // allows matching fneg (fabs x) patterns)
835 setOperationAction(ISD::FABS, {MVT::v2f16, MVT::v2bf16}, Legal);
836
837 // Can do this in one BFI plus a constant materialize.
839 {MVT::v2f16, MVT::v2bf16, MVT::v4f16, MVT::v4bf16,
840 MVT::v8f16, MVT::v8bf16, MVT::v16f16, MVT::v16bf16,
841 MVT::v32f16, MVT::v32bf16},
842 Custom);
843 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
846 MVT::f16, Legal);
847
850 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16}, Custom);
851 } else {
854 MVT::f16, Custom);
855
857 Legal);
858
861 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
862 Custom);
863
865 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
866 Expand);
867 }
868
869 for (MVT Vec16 :
870 {MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16, MVT::v16f16,
871 MVT::v16bf16, MVT::v32i16, MVT::v32f16, MVT::v32bf16}) {
874 Vec16, Custom);
875 }
876 }
877
878 if (Subtarget->hasVOP3PInsts()) {
882 MVT::v2i16, Legal);
883
886 MVT::v2f16, Legal);
887
889 {MVT::v2i16, MVT::v2f16, MVT::v2bf16}, Custom);
890
892 {MVT::v4f16, MVT::v4i16, MVT::v4bf16, MVT::v8f16,
893 MVT::v8i16, MVT::v8bf16, MVT::v16f16, MVT::v16i16,
894 MVT::v16bf16, MVT::v32f16, MVT::v32i16, MVT::v32bf16},
895 Custom);
896
897 for (MVT VT : {MVT::v4i16, MVT::v8i16, MVT::v16i16, MVT::v32i16})
898 // Split vector operations.
903 VT, Custom);
904
905 for (MVT VT : {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16})
906 // Split vector operations.
909 VT, Custom);
910
911 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
914 MVT::v2f16, Legal);
915 } else {
917 Legal);
918
921 {MVT::v2f16, MVT::v4f16}, Custom);
922 }
923 setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
924 setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16, MVT::v4bf16},
925 Custom);
926
927 if (Subtarget->hasBF16PackedInsts()) {
931 MVT::v2bf16, Legal);
932
933 for (MVT VT : {MVT::v4bf16, MVT::v8bf16, MVT::v16bf16, MVT::v32bf16})
934 // Split vector operations.
938 VT, Custom);
939 }
940
941 if (Subtarget->hasAnyPackedFP32Ops()) {
943 MVT::v2f32, Legal);
945 {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32},
946 Custom);
947 }
948 if (Subtarget->hasAnyPackedFP64Ops()) {
951 MVT::v2f64, Legal);
954 {MVT::v4f64, MVT::v8f64, MVT::v16f64, MVT::v32f64}, Custom);
955
956 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
959 MVT::v2f64, Legal);
960
963 {MVT::v4f64, MVT::v8f64, MVT::v16f64, MVT::v32f64}, Custom);
964 } else {
966 Legal);
969 MVT::v2f64, Custom);
972 {MVT::v4f64, MVT::v8f64, MVT::v16f64, MVT::v32f64},
973 Custom);
974 }
975 }
976
977 if (Subtarget->hasAnyPackedU64Ops()) {
979 MVT::v2i64, Legal);
981 {MVT::v4i64, MVT::v8i64, MVT::v16i64, MVT::v32i64},
982 Custom);
983 }
984 }
985
987
988 if (Subtarget->has16BitInsts()) {
990 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
992 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
994 AddPromotedToType(ISD::SELECT, MVT::v2bf16, MVT::i32);
995 } else {
996 // Legalization hack.
997 setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom);
998
1000 }
1001
1003 {MVT::v4i16, MVT::v4f16, MVT::v4bf16, MVT::v2i8, MVT::v4i8,
1004 MVT::v8i8, MVT::v8i16, MVT::v8f16, MVT::v8bf16,
1005 MVT::v16i16, MVT::v16f16, MVT::v16bf16, MVT::v32i16,
1006 MVT::v32f16, MVT::v32bf16},
1007 Custom);
1008
1010
1011 if (Subtarget->useVMulU64Inst())
1012 setOperationAction(ISD::MUL, MVT::i64, Legal);
1013 else if (Subtarget->hasScalarSMulU64())
1015
1016 if (Subtarget->hasMad64_32())
1018
1019 if (Subtarget->hasSafeSmemPrefetch() || Subtarget->hasVmemPrefInsts())
1021 // Type legalization cannot expand the i128 pointer of a buffer resource
1022 // prefetch; lowerPREFETCH drops the prefetch instead.
1024
1025 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
1027 {MVT::f16, MVT::f32, MVT::f64, MVT::v2f16}, Legal);
1028 } else {
1029 // FIXME: For nnan fmaximum, emit the fmaximum3 instead of fmaxnum
1030 if (Subtarget->hasMinimum3Maximum3F32())
1032
1033 if (Subtarget->hasMinimum3Maximum3PKF16()) {
1035
1036 // If only the vector form is available, we need to widen to a vector.
1037 if (!Subtarget->hasMinimum3Maximum3F16())
1039 MVT::v2f16);
1040 }
1041 }
1042
1043 if (Subtarget->hasVOP3PInsts()) {
1044 // We want to break these into v2f16 pieces, not scalarize.
1046 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
1047 Custom);
1048 }
1049
1050 if (Subtarget->useMinMaxI64Insts())
1052 Legal);
1053
1055 {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
1056 MVT::bf16, MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::i128,
1057 MVT::i8},
1058 Custom);
1059
1061 {MVT::v2f16, MVT::v2i16, MVT::v2bf16, MVT::v3f16,
1062 MVT::v3i16, MVT::v4f16, MVT::v4i16, MVT::v4bf16,
1063 MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::Other, MVT::f16,
1064 MVT::i16, MVT::bf16, MVT::i8, MVT::i128},
1065 Custom);
1066
1067 // The s_buffer_load intrinsics accept any result type in IR, but only a few
1068 // of them can be selected. Mark the remaining illegal result types Custom so
1069 // ReplaceNodeResults gets a chance to diagnose them instead of letting the
1070 // type legalizer abort. Its INTRINSIC_WO_CHAIN case dispatches on the
1071 // intrinsic ID, but INTRINSIC_W_CHAIN does not, so remember the types added
1072 // here to keep other chained intrinsics on generic legalization.
1073 for (MVT VT : MVT::all_valuetypes()) {
1074 if (VT.isScalableVector() || isTypeLegal(VT))
1075 continue;
1079 SBufferLoadDiagnosticVTs.set(VT.SimpleTy);
1080 }
1081 }
1082
1084 {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v2bf16,
1085 MVT::v3i16, MVT::v3f16, MVT::v4f16, MVT::v4i16,
1086 MVT::v4bf16, MVT::v8i16, MVT::v8f16, MVT::v8bf16,
1087 MVT::f16, MVT::i16, MVT::bf16, MVT::i8, MVT::i128},
1088 Custom);
1089
1095
1096 // TODO: Could move this to custom lowering, could benefit from combines on
1097 // extract of relevant bits.
1099
1101
1102 if (Subtarget->hasBF16ConversionInsts()) {
1104 {MVT::bf16, MVT::v2bf16}, Custom);
1106 }
1107
1108 if (Subtarget->hasBF16TransInsts()) {
1110 }
1111
1112 const bool HasE5M3ConversionInsts =
1113 Subtarget->hasFP8ConversionInsts() && Subtarget->hasFP8E5M3Insts();
1114 if (Subtarget->hasOCPFP8ConversionInsts() || HasE5M3ConversionInsts) {
1115 setOperationAction(ISD::CONVERT_FROM_ARBITRARY_FP, {MVT::f32, MVT::v2f32},
1116 Custom);
1118
1119 // i8 result promotes to i16, wider vectors split down to v2i8, and v2i8 is
1120 // handled in ReplaceNodeResults before the legalizer splits it per lane.
1121 setOperationAction(ISD::CONVERT_TO_ARBITRARY_FP, {MVT::i16, MVT::v2i8},
1122 Custom);
1123 }
1124
1125 if (Subtarget->hasFP8F16ConversionInsts()) {
1126 setOperationAction(ISD::CONVERT_FROM_ARBITRARY_FP, {MVT::f16, MVT::v2f16},
1127 Custom);
1128 }
1129
1130 if (Subtarget->hasCvtPkF16F32Inst()) {
1132 {MVT::v2f16, MVT::v4f16, MVT::v8f16, MVT::v16f16},
1133 Custom);
1134 }
1135
1138 ISD::SUB,
1139 ISD::MUL,
1140 ISD::FADD,
1141 ISD::FSUB,
1142 ISD::FDIV,
1143 ISD::FMUL,
1152 ISD::FMA,
1153 ISD::ABS,
1154 ISD::SMIN,
1155 ISD::SMAX,
1156 ISD::UMIN,
1157 ISD::UMAX,
1158 ISD::SETCC,
1160 ISD::SMIN,
1161 ISD::SMAX,
1162 ISD::UMIN,
1163 ISD::UMAX,
1166 ISD::AND,
1167 ISD::OR,
1168 ISD::XOR,
1169 ISD::SHL,
1170 ISD::SRL,
1171 ISD::SRA,
1172 ISD::FSHR,
1184
1185 if (Subtarget->has16BitInsts() && !Subtarget->hasMed3_16())
1187
1188 // All memory operations. Some folding on the pointer operand is done to help
1189 // matching the constant offsets in the addressing modes.
1191 ISD::STORE,
1216
1217 // FIXME: In other contexts we pretend this is a per-function property.
1219
1221}
1222
1223const GCNSubtarget *SITargetLowering::getSubtarget() const { return Subtarget; }
1224
1226 static const MCPhysReg RCRegs[] = {AMDGPU::MODE};
1227 return RCRegs;
1228}
1229
1230//===----------------------------------------------------------------------===//
1231// TargetLowering queries
1232//===----------------------------------------------------------------------===//
1233
1234// v_mad_mix* support a conversion from f16 to f32.
1235//
1236// There is only one special case when denormals are enabled we don't currently,
1237// where this is OK to use.
1238bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
1239 EVT DestVT, EVT SrcVT) const {
1240 return DestVT.getScalarType() == MVT::f32 &&
1241 ((((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
1242 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
1243 SrcVT.getScalarType() == MVT::f16) ||
1244 (Opcode == ISD::FMA && Subtarget->hasFmaMixBF16Insts() &&
1245 SrcVT.getScalarType() == MVT::bf16)) &&
1246 // TODO: This probably only requires no input flushing?
1248}
1249
1251 LLT DestTy, LLT SrcTy) const {
1252 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
1253 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
1254 DestTy.getScalarSizeInBits() == 32 &&
1255 SrcTy.getScalarSizeInBits() == 16 &&
1256 // TODO: This probably only requires no input flushing?
1257 denormalModeIsFlushAllF32(*MI.getMF());
1258}
1259
1261 // SI has some legal vector types, but no legal vector operations. Say no
1262 // shuffles are legal in order to prefer scalarizing some vector operations.
1263 return false;
1264}
1265
1268 EVT VT) const {
1271
1272 if (VT.isVector()) {
1273 EVT ScalarVT = VT.getScalarType();
1274 unsigned Size = ScalarVT.getSizeInBits();
1275 if (Size == 16) {
1276 return Subtarget->has16BitInsts()
1277 ? MVT::getVectorVT(ScalarVT.getSimpleVT(), 2)
1278 : MVT::i32;
1279 }
1280
1281 if (Size < 16)
1282 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
1283 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
1284 }
1285
1286 if (!Subtarget->has16BitInsts() && VT.getSizeInBits() == 16)
1287 return MVT::i32;
1288
1289 if (VT.getSizeInBits() > 32)
1290 return MVT::i32;
1291
1293}
1294
1297 EVT VT) const {
1300
1301 if (VT.isVector()) {
1302 unsigned NumElts = VT.getVectorNumElements();
1303 EVT ScalarVT = VT.getScalarType();
1304 unsigned Size = ScalarVT.getSizeInBits();
1305
1306 // FIXME: Should probably promote 8-bit vectors to i16.
1307 if (Size == 16)
1308 return (NumElts + 1) / 2;
1309
1310 if (Size <= 32)
1311 return NumElts;
1312
1313 if (Size > 32)
1314 return NumElts * ((Size + 31) / 32);
1315 } else if (VT.getSizeInBits() > 32)
1316 return (VT.getSizeInBits() + 31) / 32;
1317
1319}
1320
1322 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
1323 unsigned &NumIntermediates, MVT &RegisterVT) const {
1324 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1325 unsigned NumElts = VT.getVectorNumElements();
1326 EVT ScalarVT = VT.getScalarType();
1327 unsigned Size = ScalarVT.getSizeInBits();
1328 // FIXME: We should fix the ABI to be the same on targets without 16-bit
1329 // support, but unless we can properly handle 3-vectors, it will be still be
1330 // inconsistent.
1331 if (Size == 16) {
1332 MVT SimpleIntermediateVT =
1334 IntermediateVT = SimpleIntermediateVT;
1335 RegisterVT = Subtarget->has16BitInsts() ? SimpleIntermediateVT : MVT::i32;
1336 NumIntermediates = (NumElts + 1) / 2;
1337 return (NumElts + 1) / 2;
1338 }
1339
1340 if (Size == 32) {
1341 RegisterVT = ScalarVT.getSimpleVT();
1342 IntermediateVT = RegisterVT;
1343 NumIntermediates = NumElts;
1344 return NumIntermediates;
1345 }
1346
1347 if (Size < 16 && Subtarget->has16BitInsts()) {
1348 // FIXME: Should probably form v2i16 pieces
1349 RegisterVT = MVT::i16;
1350 IntermediateVT = ScalarVT;
1351 NumIntermediates = NumElts;
1352 return NumIntermediates;
1353 }
1354
1355 if (Size != 16 && Size <= 32) {
1356 RegisterVT = MVT::i32;
1357 IntermediateVT = ScalarVT;
1358 NumIntermediates = NumElts;
1359 return NumIntermediates;
1360 }
1361
1362 if (Size > 32) {
1363 RegisterVT = MVT::i32;
1364 IntermediateVT = RegisterVT;
1365 NumIntermediates = NumElts * ((Size + 31) / 32);
1366 return NumIntermediates;
1367 }
1368 }
1369
1371 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1372}
1373
1375 const DataLayout &DL, Type *Ty,
1376 unsigned MaxNumLanes) {
1377 assert(MaxNumLanes != 0);
1378
1379 LLVMContext &Ctx = Ty->getContext();
1380 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1381 unsigned NumElts = std::min(MaxNumLanes, VT->getNumElements());
1382 return EVT::getVectorVT(Ctx, TLI.getValueType(DL, VT->getElementType()),
1383 NumElts);
1384 }
1385
1386 return TLI.getValueType(DL, Ty);
1387}
1388
1389// Peek through TFE struct returns to only use the data size.
1391 const DataLayout &DL, Type *Ty,
1392 unsigned MaxNumLanes) {
1393 auto *ST = dyn_cast<StructType>(Ty);
1394 if (!ST)
1395 return memVTFromLoadIntrData(TLI, DL, Ty, MaxNumLanes);
1396
1397 // TFE intrinsics return an aggregate type.
1398 assert(ST->getNumContainedTypes() == 2 &&
1399 ST->getContainedType(1)->isIntegerTy(32));
1400 return memVTFromLoadIntrData(TLI, DL, ST->getContainedType(0), MaxNumLanes);
1401}
1402
1403/// Map address space 7 to MVT::amdgpuBufferFatPointer because that's its
1404/// in-memory representation. This return value is a custom type because there
1405/// is no MVT::i160 and adding one breaks integer promotion logic. While this
1406/// could cause issues during codegen, these address space 7 pointers will be
1407/// rewritten away by then. Therefore, we can return MVT::amdgpuBufferFatPointer
1408/// in order to allow pre-codegen passes that query TargetTransformInfo, often
1409/// for cost modeling, to work. (This also sets us up decently for doing the
1410/// buffer lowering in GlobalISel if SelectionDAG ever goes away.)
1412 if (AMDGPUAS::BUFFER_FAT_POINTER == AS && DL.getPointerSizeInBits(AS) == 160)
1413 return MVT::amdgpuBufferFatPointer;
1415 DL.getPointerSizeInBits(AS) == 192)
1416 return MVT::amdgpuBufferStridedPointer;
1418}
1419/// Similarly, the in-memory representation of a p7 is {p8, i32}, aka
1420/// v8i32 when padding is added.
1421/// The in-memory representation of a p9 is {p8, i32, i32}, which is
1422/// also v8i32 with padding.
1424 if ((AMDGPUAS::BUFFER_FAT_POINTER == AS &&
1425 DL.getPointerSizeInBits(AS) == 160) ||
1427 DL.getPointerSizeInBits(AS) == 192))
1428 return MVT::v8i32;
1430}
1431
1432static unsigned getIntrMemWidth(unsigned IntrID) {
1433 switch (IntrID) {
1434 case Intrinsic::amdgcn_global_load_async_to_lds_b8:
1435 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
1436 case Intrinsic::amdgcn_global_store_async_from_lds_b8:
1437 return 8;
1438 case Intrinsic::amdgcn_global_load_async_to_lds_b32:
1439 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
1440 case Intrinsic::amdgcn_global_store_async_from_lds_b32:
1441 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
1442 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
1443 case Intrinsic::amdgcn_flat_load_monitor_b32:
1444 case Intrinsic::amdgcn_global_load_monitor_b32:
1445 return 32;
1446 case Intrinsic::amdgcn_global_load_async_to_lds_b64:
1447 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
1448 case Intrinsic::amdgcn_global_store_async_from_lds_b64:
1449 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
1450 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
1451 case Intrinsic::amdgcn_flat_load_monitor_b64:
1452 case Intrinsic::amdgcn_global_load_monitor_b64:
1453 return 64;
1454 case Intrinsic::amdgcn_global_load_async_to_lds_b128:
1455 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128:
1456 case Intrinsic::amdgcn_global_store_async_from_lds_b128:
1457 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B:
1458 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B:
1459 case Intrinsic::amdgcn_flat_load_monitor_b128:
1460 case Intrinsic::amdgcn_global_load_monitor_b128:
1461 return 128;
1462 default:
1463 llvm_unreachable("Unknown width");
1464 }
1465}
1466
1468 unsigned ArgIdx) {
1469 Value *OrderingArg = CI.getArgOperand(ArgIdx);
1470 unsigned Ord = cast<ConstantInt>(OrderingArg)->getZExtValue();
1471 switch (AtomicOrderingCABI(Ord)) {
1474 break;
1477 break;
1480 break;
1481 default:
1483 }
1484}
1485
1486static unsigned parseSyncscopeMDArg(const CallBase &CI, unsigned ArgIdx) {
1487 MDNode *ScopeMD = cast<MDNode>(
1488 cast<MetadataAsValue>(CI.getArgOperand(ArgIdx))->getMetadata());
1489 StringRef Scope = cast<MDString>(ScopeMD->getOperand(0))->getString();
1490 return CI.getContext().getOrInsertSyncScopeID(Scope);
1491}
1492
1494 const CallBase &CI,
1495 MachineFunction &MF,
1496 unsigned IntrID) const {
1498 if (CI.hasMetadata(LLVMContext::MD_invariant_load))
1500 if (CI.hasMetadata(LLVMContext::MD_nontemporal))
1502 Flags |= getTargetMMOFlags(CI);
1503
1504 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1506 AttributeSet Attr =
1508 MemoryEffects ME = Attr.getMemoryEffects();
1509 if (ME.doesNotAccessMemory())
1510 return;
1511
1512 bool IsSPrefetch = IntrID == Intrinsic::amdgcn_s_buffer_prefetch_data;
1513 if (!IsSPrefetch) {
1514 auto *Aux = cast<ConstantInt>(CI.getArgOperand(CI.arg_size() - 1));
1515 if (Aux->getZExtValue() & AMDGPU::CPol::VOLATILE)
1517 }
1518
1520
1521 IntrinsicInfo Info;
1522 // TODO: Should images get their own address space?
1524
1525 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = nullptr;
1526 if (RsrcIntr->IsImage) {
1527 const AMDGPU::ImageDimIntrinsicInfo *Intr =
1529 BaseOpcode = AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1530 Info.align.reset();
1531 }
1532
1533 Value *RsrcArg = CI.getArgOperand(RsrcIntr->RsrcArg);
1534 if (auto *RsrcPtrTy = dyn_cast<PointerType>(RsrcArg->getType())) {
1535 if (RsrcPtrTy->getAddressSpace() == AMDGPUAS::BUFFER_RESOURCE)
1536 // We conservatively set the memory operand of a buffer intrinsic to the
1537 // base resource pointer, so that we can access alias information about
1538 // those pointers. Cases like "this points at the same value
1539 // but with a different offset" are handled in
1540 // areMemAccessesTriviallyDisjoint.
1541 Info.ptrVal = RsrcArg;
1542 }
1543
1544 if (ME.onlyReadsMemory()) {
1545 if (RsrcIntr->IsImage) {
1546 unsigned MaxNumLanes = 4;
1547
1548 if (!BaseOpcode->Gather4) {
1549 // If this isn't a gather, we may have excess loaded elements in the
1550 // IR type. Check the dmask for the real number of elements loaded.
1551 unsigned DMask =
1552 cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1553 MaxNumLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1554 }
1555
1556 Info.memVT = memVTFromLoadIntrReturn(*this, MF.getDataLayout(),
1557 CI.getType(), MaxNumLanes);
1558 } else {
1559 Info.memVT =
1561 std::numeric_limits<unsigned>::max());
1562 }
1563
1564 // FIXME: What does alignment mean for an image?
1565 Info.opc = ISD::INTRINSIC_W_CHAIN;
1566 Info.flags = Flags | MachineMemOperand::MOLoad;
1567 } else if (ME.onlyWritesMemory()) {
1568 Info.opc = ISD::INTRINSIC_VOID;
1569
1570 Type *DataTy = CI.getArgOperand(0)->getType();
1571 if (RsrcIntr->IsImage) {
1572 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1573 unsigned DMaskLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1574 Info.memVT = memVTFromLoadIntrData(*this, MF.getDataLayout(), DataTy,
1575 DMaskLanes);
1576 } else
1577 Info.memVT = getValueType(MF.getDataLayout(), DataTy);
1578
1579 Info.flags = Flags | MachineMemOperand::MOStore;
1580 } else {
1581 // Atomic, NoReturn Sampler or prefetch
1582 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID
1584
1585 switch (IntrID) {
1586 default:
1587 Info.flags = Flags | MachineMemOperand::MOLoad;
1588 if (!IsSPrefetch)
1589 Info.flags |= MachineMemOperand::MOStore;
1590
1591 if ((RsrcIntr->IsImage && BaseOpcode->NoReturn) || IsSPrefetch) {
1592 // Fake memory access type for no return sampler intrinsics
1593 Info.memVT = MVT::i32;
1594 } else {
1595 // XXX - Should this be volatile without known ordering?
1596 Info.flags |= MachineMemOperand::MOVolatile;
1597 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1598 }
1599 break;
1600 case Intrinsic::amdgcn_raw_buffer_load_lds:
1601 case Intrinsic::amdgcn_raw_buffer_load_async_lds:
1602 case Intrinsic::amdgcn_raw_ptr_buffer_load_lds:
1603 case Intrinsic::amdgcn_raw_ptr_buffer_load_async_lds:
1604 case Intrinsic::amdgcn_struct_buffer_load_lds:
1605 case Intrinsic::amdgcn_struct_buffer_load_async_lds:
1606 case Intrinsic::amdgcn_struct_ptr_buffer_load_lds:
1607 case Intrinsic::amdgcn_struct_ptr_buffer_load_async_lds: {
1608 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1609
1610 // Entry 0: Load from buffer.
1611 // Don't set an offset, since the pointer value always represents the
1612 // base of the buffer.
1613 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1614 Info.flags = Flags | MachineMemOperand::MOLoad;
1615 Infos.push_back(Info);
1616
1617 // Entry 1: Store to LDS.
1618 // Instruction offset is applied, and an additional per-lane offset
1619 // which we simulate using a larger memory type.
1620 Info.memVT = EVT::getIntegerVT(
1621 CI.getContext(), Width * 8 * Subtarget->getWavefrontSize());
1622 Info.ptrVal = CI.getArgOperand(1); // LDS destination pointer
1623 Info.offset = cast<ConstantInt>(CI.getArgOperand(CI.arg_size() - 2))
1624 ->getZExtValue();
1625 Info.fallbackAddressSpace = AMDGPUAS::LOCAL_ADDRESS;
1626 Info.flags = Flags | MachineMemOperand::MOStore;
1627 Infos.push_back(Info);
1628 return;
1629 }
1630 case Intrinsic::amdgcn_raw_atomic_buffer_load:
1631 case Intrinsic::amdgcn_raw_ptr_atomic_buffer_load:
1632 case Intrinsic::amdgcn_struct_atomic_buffer_load:
1633 case Intrinsic::amdgcn_struct_ptr_atomic_buffer_load: {
1634 Info.memVT =
1636 std::numeric_limits<unsigned>::max());
1637 Info.flags = Flags | MachineMemOperand::MOLoad;
1638 Infos.push_back(Info);
1639 return;
1640 }
1641 }
1642 }
1643 Infos.push_back(Info);
1644 return;
1645 }
1646
1647 IntrinsicInfo Info;
1648 switch (IntrID) {
1649 case Intrinsic::amdgcn_ds_ordered_add:
1650 case Intrinsic::amdgcn_ds_ordered_swap: {
1651 Info.opc = ISD::INTRINSIC_W_CHAIN;
1652 Info.memVT = MVT::getVT(CI.getType());
1653 Info.ptrVal = CI.getOperand(0);
1654 Info.align.reset();
1656
1657 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1658 if (!Vol->isZero())
1659 Info.flags |= MachineMemOperand::MOVolatile;
1660
1661 Infos.push_back(Info);
1662 return;
1663 }
1664 case Intrinsic::amdgcn_ds_add_gs_reg_rtn:
1665 case Intrinsic::amdgcn_ds_sub_gs_reg_rtn: {
1666 Info.opc = ISD::INTRINSIC_W_CHAIN;
1667 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1668 Info.ptrVal = nullptr;
1669 Info.fallbackAddressSpace = AMDGPUAS::STREAMOUT_REGISTER;
1671 Infos.push_back(Info);
1672 return;
1673 }
1674 case Intrinsic::amdgcn_ds_append:
1675 case Intrinsic::amdgcn_ds_consume: {
1676 Info.opc = ISD::INTRINSIC_W_CHAIN;
1677 Info.memVT = MVT::getVT(CI.getType());
1678 Info.ptrVal = CI.getOperand(0);
1679 Info.align.reset();
1681
1682 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1683 if (!Vol->isZero())
1684 Info.flags |= MachineMemOperand::MOVolatile;
1685
1686 Infos.push_back(Info);
1687 return;
1688 }
1689 case Intrinsic::amdgcn_ds_atomic_async_barrier_arrive_b64:
1690 case Intrinsic::amdgcn_ds_atomic_barrier_arrive_rtn_b64: {
1691 Info.opc = (IntrID == Intrinsic::amdgcn_ds_atomic_barrier_arrive_rtn_b64)
1694 Info.memVT = MVT::getVT(CI.getType());
1695 Info.ptrVal = CI.getOperand(0);
1696 Info.memVT = MVT::i64;
1697 Info.size = 8;
1698 Info.align.reset();
1700 Info.order = AtomicOrdering::Monotonic;
1701 Infos.push_back(Info);
1702 return;
1703 }
1704 case Intrinsic::amdgcn_image_bvh_dual_intersect_ray:
1705 case Intrinsic::amdgcn_image_bvh_intersect_ray:
1706 case Intrinsic::amdgcn_image_bvh8_intersect_ray: {
1707 Info.opc = ISD::INTRINSIC_W_CHAIN;
1708 Info.memVT =
1709 MVT::getVT(IntrID == Intrinsic::amdgcn_image_bvh_intersect_ray
1710 ? CI.getType()
1712 ->getElementType(0)); // XXX: what is correct VT?
1713
1714 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1715 Info.align.reset();
1716 Info.flags = Flags | MachineMemOperand::MOLoad |
1718 Infos.push_back(Info);
1719 return;
1720 }
1721 case Intrinsic::amdgcn_global_atomic_fmin_num:
1722 case Intrinsic::amdgcn_global_atomic_fmax_num:
1723 case Intrinsic::amdgcn_global_atomic_ordered_add_b64:
1724 case Intrinsic::amdgcn_flat_atomic_fmin_num:
1725 case Intrinsic::amdgcn_flat_atomic_fmax_num: {
1726 Info.opc = ISD::INTRINSIC_W_CHAIN;
1727 Info.memVT = MVT::getVT(CI.getType());
1728 Info.ptrVal = CI.getOperand(0);
1729 Info.align.reset();
1730 Info.flags =
1733 Infos.push_back(Info);
1734 return;
1735 }
1736 case Intrinsic::amdgcn_cluster_load_b32:
1737 case Intrinsic::amdgcn_cluster_load_b64:
1738 case Intrinsic::amdgcn_cluster_load_b128:
1739 case Intrinsic::amdgcn_ds_load_tr6_b96:
1740 case Intrinsic::amdgcn_ds_load_tr4_b64:
1741 case Intrinsic::amdgcn_ds_load_tr8_b64:
1742 case Intrinsic::amdgcn_ds_load_tr16_b128:
1743 case Intrinsic::amdgcn_global_load_tr6_b96:
1744 case Intrinsic::amdgcn_global_load_tr4_b64:
1745 case Intrinsic::amdgcn_global_load_tr_b64:
1746 case Intrinsic::amdgcn_global_load_tr_b128:
1747 case Intrinsic::amdgcn_ds_read_tr4_b64:
1748 case Intrinsic::amdgcn_ds_read_tr6_b96:
1749 case Intrinsic::amdgcn_ds_read_tr8_b64:
1750 case Intrinsic::amdgcn_ds_read_tr16_b64: {
1751 Info.opc = ISD::INTRINSIC_W_CHAIN;
1752 Info.memVT = MVT::getVT(CI.getType());
1753 Info.ptrVal = CI.getOperand(0);
1754 Info.align.reset();
1755 Info.flags = Flags | MachineMemOperand::MOLoad;
1756 Infos.push_back(Info);
1757 return;
1758 }
1759 case Intrinsic::amdgcn_flat_load_monitor_b32:
1760 case Intrinsic::amdgcn_flat_load_monitor_b64:
1761 case Intrinsic::amdgcn_flat_load_monitor_b128:
1762 case Intrinsic::amdgcn_global_load_monitor_b32:
1763 case Intrinsic::amdgcn_global_load_monitor_b64:
1764 case Intrinsic::amdgcn_global_load_monitor_b128: {
1765 Info.opc = ISD::INTRINSIC_W_CHAIN;
1766 Info.memVT = EVT::getIntegerVT(CI.getContext(), getIntrMemWidth(IntrID));
1767 Info.ptrVal = CI.getOperand(0);
1768 Info.align.reset();
1769 Info.flags = MachineMemOperand::MOLoad;
1770 Info.order = parseAtomicOrderingCABIArg(CI, 1);
1771 Info.ssid = parseSyncscopeMDArg(CI, 2);
1772 Infos.push_back(Info);
1773 return;
1774 }
1775 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
1776 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
1777 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B: {
1778 Info.opc = ISD::INTRINSIC_W_CHAIN;
1779 Info.memVT = MVT::getVT(CI.getType());
1780 Info.ptrVal = CI.getOperand(0);
1781 Info.align.reset();
1783 Info.order = parseAtomicOrderingCABIArg(CI, 1);
1784 Info.ssid = parseSyncscopeMDArg(CI, 2);
1785 Infos.push_back(Info);
1786 return;
1787 }
1788 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
1789 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
1790 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
1791 Info.opc = ISD::INTRINSIC_VOID;
1792 Info.memVT = MVT::getVT(CI.getArgOperand(1)->getType());
1793 Info.ptrVal = CI.getArgOperand(0);
1794 Info.align.reset();
1796 Info.order = parseAtomicOrderingCABIArg(CI, 2);
1797 Info.ssid = parseSyncscopeMDArg(CI, 3);
1798 Infos.push_back(Info);
1799 return;
1800 }
1801 case Intrinsic::amdgcn_ds_gws_init:
1802 case Intrinsic::amdgcn_ds_gws_barrier:
1803 case Intrinsic::amdgcn_ds_gws_sema_v:
1804 case Intrinsic::amdgcn_ds_gws_sema_br:
1805 case Intrinsic::amdgcn_ds_gws_sema_p:
1806 case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1807 Info.opc = ISD::INTRINSIC_VOID;
1808
1809 const GCNTargetMachine &TM =
1810 static_cast<const GCNTargetMachine &>(getTargetMachine());
1811
1813 Info.ptrVal = MFI->getGWSPSV(TM);
1814
1815 // This is an abstract access, but we need to specify a type and size.
1816 Info.memVT = MVT::i32;
1817 Info.size = 4;
1818 Info.align = Align(4);
1819
1820 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1821 Info.flags = Flags | MachineMemOperand::MOLoad;
1822 else
1823 Info.flags = Flags | MachineMemOperand::MOStore;
1824 Infos.push_back(Info);
1825 return;
1826 }
1827 case Intrinsic::amdgcn_global_load_async_to_lds_b8:
1828 case Intrinsic::amdgcn_global_load_async_to_lds_b32:
1829 case Intrinsic::amdgcn_global_load_async_to_lds_b64:
1830 case Intrinsic::amdgcn_global_load_async_to_lds_b128:
1831 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
1832 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
1833 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
1834 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128: {
1835 // Entry 0: Load from source (global/flat).
1836 Info.opc = ISD::INTRINSIC_VOID;
1837 Info.memVT = EVT::getIntegerVT(CI.getContext(), getIntrMemWidth(IntrID));
1838 Info.ptrVal = CI.getArgOperand(0); // Global pointer
1839 Info.offset = cast<ConstantInt>(CI.getArgOperand(2))->getSExtValue();
1840 Info.flags = Flags | MachineMemOperand::MOLoad;
1841 Infos.push_back(Info);
1842
1843 // Entry 1: Store to LDS (same offset).
1844 Info.flags = Flags | MachineMemOperand::MOStore;
1845 Info.ptrVal = CI.getArgOperand(1); // LDS pointer
1846 Infos.push_back(Info);
1847 return;
1848 }
1849 case Intrinsic::amdgcn_global_store_async_from_lds_b8:
1850 case Intrinsic::amdgcn_global_store_async_from_lds_b32:
1851 case Intrinsic::amdgcn_global_store_async_from_lds_b64:
1852 case Intrinsic::amdgcn_global_store_async_from_lds_b128: {
1853 // Entry 0: Load from LDS.
1854 Info.opc = ISD::INTRINSIC_VOID;
1855 Info.memVT = EVT::getIntegerVT(CI.getContext(), getIntrMemWidth(IntrID));
1856 Info.ptrVal = CI.getArgOperand(1); // LDS pointer
1857 Info.offset = cast<ConstantInt>(CI.getArgOperand(2))->getSExtValue();
1858 Info.flags = Flags | MachineMemOperand::MOLoad;
1859 Infos.push_back(Info);
1860
1861 // Entry 1: Store to global (same offset).
1862 Info.flags = Flags | MachineMemOperand::MOStore;
1863 Info.ptrVal = CI.getArgOperand(0); // Global pointer
1864 Infos.push_back(Info);
1865 return;
1866 }
1867 case Intrinsic::amdgcn_av_load_b8:
1868 case Intrinsic::amdgcn_av_load_b16:
1869 case Intrinsic::amdgcn_av_load_b32:
1870 case Intrinsic::amdgcn_av_load_b64:
1871 case Intrinsic::amdgcn_av_load_b128:
1872 case Intrinsic::amdgcn_av_store_b8:
1873 case Intrinsic::amdgcn_av_store_b16:
1874 case Intrinsic::amdgcn_av_store_b32:
1875 case Intrinsic::amdgcn_av_store_b64:
1876 case Intrinsic::amdgcn_av_store_b128: {
1877 bool IsStore = CI.getType()->isVoidTy();
1878 Type *DataTy = IsStore ? CI.getArgOperand(1)->getType() : CI.getType();
1879 Info.opc = IsStore ? ISD::INTRINSIC_VOID : ISD::INTRINSIC_W_CHAIN;
1880 Info.memVT = MVT::getVT(DataTy);
1881 Info.ptrVal = CI.getArgOperand(0);
1882 Info.align = Align(Info.memVT.getStoreSize());
1883 Info.flags |=
1885 // Pretend to be atomic so that SIMemoryLegalizer::expandStore sets cache
1886 // flags appropriately.
1887 Info.order = AtomicOrdering::Monotonic;
1888
1889 LLVMContext &Ctx = CI.getContext();
1890 unsigned ScopeIdx = CI.arg_size() - 1;
1891 MDNode *ScopeMD = cast<MDNode>(
1892 cast<MetadataAsValue>(CI.getArgOperand(ScopeIdx))->getMetadata());
1893 StringRef Scope = cast<MDString>(ScopeMD->getOperand(0))->getString();
1894 Info.ssid = Ctx.getOrInsertSyncScopeID(Scope);
1895 Infos.push_back(Info);
1896 return;
1897 }
1898 case Intrinsic::amdgcn_load_to_lds:
1899 case Intrinsic::amdgcn_load_async_to_lds:
1900 case Intrinsic::amdgcn_global_load_lds:
1901 case Intrinsic::amdgcn_global_load_async_lds: {
1902 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1903 auto *Aux = cast<ConstantInt>(CI.getArgOperand(CI.arg_size() - 1));
1904 bool IsVolatile = Aux->getZExtValue() & AMDGPU::CPol::VOLATILE;
1905 if (IsVolatile)
1907
1908 // Entry 0: Load from source (global/flat).
1909 Info.opc = ISD::INTRINSIC_VOID;
1910 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1911 Info.ptrVal = CI.getArgOperand(0); // Source pointer
1912 Info.offset = cast<ConstantInt>(CI.getArgOperand(3))->getSExtValue();
1913 Info.flags = Flags | MachineMemOperand::MOLoad;
1914 Infos.push_back(Info);
1915
1916 // Entry 1: Store to LDS.
1917 // Same offset from the instruction, but an additional per-lane offset is
1918 // added. Represent that using a wider memory type.
1919 Info.memVT = EVT::getIntegerVT(CI.getContext(),
1920 Width * 8 * Subtarget->getWavefrontSize());
1921 Info.ptrVal = CI.getArgOperand(1); // LDS destination pointer
1922 Info.flags = Flags | MachineMemOperand::MOStore;
1923 Infos.push_back(Info);
1924 return;
1925 }
1926 case Intrinsic::amdgcn_ds_bvh_stack_rtn:
1927 case Intrinsic::amdgcn_ds_bvh_stack_push4_pop1_rtn:
1928 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop1_rtn:
1929 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop2_rtn: {
1930 Info.opc = ISD::INTRINSIC_W_CHAIN;
1931
1932 const GCNTargetMachine &TM =
1933 static_cast<const GCNTargetMachine &>(getTargetMachine());
1934
1936 Info.ptrVal = MFI->getGWSPSV(TM);
1937
1938 // This is an abstract access, but we need to specify a type and size.
1939 Info.memVT = MVT::i32;
1940 Info.size = 4;
1941 Info.align = Align(4);
1942
1944 Infos.push_back(Info);
1945 return;
1946 }
1947 case Intrinsic::amdgcn_s_prefetch_data:
1948 case Intrinsic::amdgcn_s_prefetch_inst:
1949 case Intrinsic::amdgcn_flat_prefetch:
1950 case Intrinsic::amdgcn_global_prefetch: {
1951 Info.opc = ISD::INTRINSIC_VOID;
1952 Info.memVT = EVT::getIntegerVT(CI.getContext(), 8);
1953 Info.ptrVal = CI.getArgOperand(0);
1954 Info.flags = Flags | MachineMemOperand::MOLoad;
1955 Infos.push_back(Info);
1956 return;
1957 }
1958 default:
1959 return;
1960 }
1961}
1962
1965 Type *&AccessTy) const {
1966 Value *Ptr = nullptr;
1967 switch (II->getIntrinsicID()) {
1968 case Intrinsic::amdgcn_cluster_load_b128:
1969 case Intrinsic::amdgcn_cluster_load_b64:
1970 case Intrinsic::amdgcn_cluster_load_b32:
1971 case Intrinsic::amdgcn_ds_append:
1972 case Intrinsic::amdgcn_ds_consume:
1973 case Intrinsic::amdgcn_ds_load_tr8_b64:
1974 case Intrinsic::amdgcn_ds_load_tr16_b128:
1975 case Intrinsic::amdgcn_ds_load_tr4_b64:
1976 case Intrinsic::amdgcn_ds_load_tr6_b96:
1977 case Intrinsic::amdgcn_ds_read_tr4_b64:
1978 case Intrinsic::amdgcn_ds_read_tr6_b96:
1979 case Intrinsic::amdgcn_ds_read_tr8_b64:
1980 case Intrinsic::amdgcn_ds_read_tr16_b64:
1981 case Intrinsic::amdgcn_ds_ordered_add:
1982 case Intrinsic::amdgcn_ds_ordered_swap:
1983 case Intrinsic::amdgcn_ds_atomic_async_barrier_arrive_b64:
1984 case Intrinsic::amdgcn_ds_atomic_barrier_arrive_rtn_b64:
1985 case Intrinsic::amdgcn_flat_atomic_fmax_num:
1986 case Intrinsic::amdgcn_flat_atomic_fmin_num:
1987 case Intrinsic::amdgcn_global_atomic_fmax_num:
1988 case Intrinsic::amdgcn_global_atomic_fmin_num:
1989 case Intrinsic::amdgcn_global_atomic_ordered_add_b64:
1990 case Intrinsic::amdgcn_global_load_tr_b64:
1991 case Intrinsic::amdgcn_global_load_tr_b128:
1992 case Intrinsic::amdgcn_global_load_tr4_b64:
1993 case Intrinsic::amdgcn_global_load_tr6_b96:
1994 case Intrinsic::amdgcn_global_store_async_from_lds_b8:
1995 case Intrinsic::amdgcn_global_store_async_from_lds_b32:
1996 case Intrinsic::amdgcn_global_store_async_from_lds_b64:
1997 case Intrinsic::amdgcn_global_store_async_from_lds_b128:
1998 case Intrinsic::amdgcn_av_load_b8:
1999 case Intrinsic::amdgcn_av_load_b16:
2000 case Intrinsic::amdgcn_av_load_b32:
2001 case Intrinsic::amdgcn_av_load_b64:
2002 case Intrinsic::amdgcn_av_load_b128:
2003 case Intrinsic::amdgcn_av_store_b8:
2004 case Intrinsic::amdgcn_av_store_b16:
2005 case Intrinsic::amdgcn_av_store_b32:
2006 case Intrinsic::amdgcn_av_store_b64:
2007 case Intrinsic::amdgcn_av_store_b128:
2008 Ptr = II->getArgOperand(0);
2009 break;
2010 case Intrinsic::amdgcn_load_to_lds:
2011 case Intrinsic::amdgcn_load_async_to_lds:
2012 case Intrinsic::amdgcn_global_load_lds:
2013 case Intrinsic::amdgcn_global_load_async_lds:
2014 case Intrinsic::amdgcn_global_load_async_to_lds_b8:
2015 case Intrinsic::amdgcn_global_load_async_to_lds_b32:
2016 case Intrinsic::amdgcn_global_load_async_to_lds_b64:
2017 case Intrinsic::amdgcn_global_load_async_to_lds_b128:
2018 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
2019 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
2020 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
2021 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128:
2022 Ptr = II->getArgOperand(1);
2023 break;
2024 default:
2025 return false;
2026 }
2027 AccessTy = II->getType();
2028 Ops.push_back(Ptr);
2029 return true;
2030}
2031
2033 unsigned AddrSpace) const {
2034 if (!Subtarget->hasFlatInstOffsets()) {
2035 // Flat instructions do not have offsets, and only have the register
2036 // address.
2037 return AM.BaseOffs == 0 && AM.Scale == 0;
2038 }
2039
2041 FlatAddrSpace FlatVariant =
2042 AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ? FlatAddrSpace::FlatGlobal
2043 : AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ? FlatAddrSpace::FlatScratch
2044 : FlatAddrSpace::FLAT;
2045
2046 return AM.Scale == 0 &&
2047 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
2048 AM.BaseOffs, AddrSpace, FlatVariant));
2049}
2050
2052 if (Subtarget->hasFlatGlobalInsts())
2054
2055 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
2056 // Assume the we will use FLAT for all global memory accesses
2057 // on VI.
2058 // FIXME: This assumption is currently wrong. On VI we still use
2059 // MUBUF instructions for the r + i addressing mode. As currently
2060 // implemented, the MUBUF instructions only work on buffer < 4GB.
2061 // It may be possible to support > 4GB buffers with MUBUF instructions,
2062 // by setting the stride value in the resource descriptor which would
2063 // increase the size limit to (stride * 4GB). However, this is risky,
2064 // because it has never been validated.
2066 }
2067
2068 return isLegalMUBUFAddressingMode(AM);
2069}
2070
2071bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
2072 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
2073 // additionally can do r + r + i with addr64. 32-bit has more addressing
2074 // mode options. Depending on the resource constant, it can also do
2075 // (i64 r0) + (i32 r1) * (i14 i).
2076 //
2077 // Private arrays end up using a scratch buffer most of the time, so also
2078 // assume those use MUBUF instructions. Scratch loads / stores are currently
2079 // implemented as mubuf instructions with offen bit set, so slightly
2080 // different than the normal addr64.
2081 const SIInstrInfo *TII = Subtarget->getInstrInfo();
2082 if (!TII->isLegalMUBUFImmOffset(AM.BaseOffs))
2083 return false;
2084
2085 // FIXME: Since we can split immediate into soffset and immediate offset,
2086 // would it make sense to allow any immediate?
2087
2088 switch (AM.Scale) {
2089 case 0: // r + i or just i, depending on HasBaseReg.
2090 return true;
2091 case 1:
2092 return true; // We have r + r or r + i.
2093 case 2:
2094 if (AM.HasBaseReg) {
2095 // Reject 2 * r + r.
2096 return false;
2097 }
2098
2099 // Allow 2 * r as r + r
2100 // Or 2 * r + i is allowed as r + r + i.
2101 return true;
2102 default: // Don't allow n * r
2103 return false;
2104 }
2105}
2106
2108 const AddrMode &AM, Type *Ty,
2109 unsigned AS,
2110 Instruction *I) const {
2111 // No global is ever allowed as a base.
2112 if (AM.BaseGV)
2113 return false;
2114
2115 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
2116 return isLegalGlobalAddressingMode(AM);
2117
2118 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
2122 // If the offset isn't a multiple of 4, it probably isn't going to be
2123 // correctly aligned.
2124 // FIXME: Can we get the real alignment here?
2125 if (AM.BaseOffs % 4 != 0)
2126 return isLegalMUBUFAddressingMode(AM);
2127
2128 if (!Subtarget->hasScalarSubwordLoads()) {
2129 // There are no SMRD extloads, so if we have to do a small type access we
2130 // will use a MUBUF load.
2131 // FIXME?: We also need to do this if unaligned, but we don't know the
2132 // alignment here.
2133 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
2134 return isLegalGlobalAddressingMode(AM);
2135 }
2136
2137 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
2138 // SMRD instructions have an 8-bit, dword offset on SI.
2139 if (!isUInt<8>(AM.BaseOffs / 4))
2140 return false;
2141 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
2142 // On CI+, this can also be a 32-bit literal constant offset. If it fits
2143 // in 8-bits, it can use a smaller encoding.
2144 if (!isUInt<32>(AM.BaseOffs / 4))
2145 return false;
2146 } else if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX9) {
2147 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
2148 if (!isUInt<20>(AM.BaseOffs))
2149 return false;
2150 } else if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX12) {
2151 // On GFX9 the offset is signed 21-bit in bytes (but must not be negative
2152 // for S_BUFFER_* instructions).
2153 if (!isInt<21>(AM.BaseOffs))
2154 return false;
2155 } else {
2156 // On GFX12, all offsets are signed 24-bit in bytes.
2157 if (!isInt<24>(AM.BaseOffs))
2158 return false;
2159 }
2160
2161 if ((AS == AMDGPUAS::CONSTANT_ADDRESS ||
2163 AM.BaseOffs < 0) {
2164 // Scalar (non-buffer) loads can only use a negative offset if
2165 // soffset+offset is non-negative. Since the compiler can only prove that
2166 // in a few special cases, it is safer to claim that negative offsets are
2167 // not supported.
2168 return false;
2169 }
2170
2171 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
2172 return true;
2173
2174 if (AM.Scale == 1 && AM.HasBaseReg)
2175 return true;
2176
2177 return false;
2178 }
2179
2180 if (AS == AMDGPUAS::PRIVATE_ADDRESS)
2181 return Subtarget->hasFlatScratchEnabled()
2183 : isLegalMUBUFAddressingMode(AM);
2184
2185 if (AS == AMDGPUAS::LOCAL_ADDRESS ||
2186 (AS == AMDGPUAS::REGION_ADDRESS && Subtarget->hasGDS())) {
2187 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
2188 // field.
2189 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
2190 // an 8-bit dword offset but we don't know the alignment here.
2191 if (!isUInt<16>(AM.BaseOffs))
2192 return false;
2193
2194 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
2195 return true;
2196
2197 if (AM.Scale == 1 && AM.HasBaseReg)
2198 return true;
2199
2200 return false;
2201 }
2202
2204 // For an unknown address space, this usually means that this is for some
2205 // reason being used for pure arithmetic, and not based on some addressing
2206 // computation. We don't have instructions that compute pointers with any
2207 // addressing modes, so treat them as having no offset like flat
2208 // instructions.
2210 }
2211
2212 // Assume a user alias of global for unknown address spaces.
2213 return isLegalGlobalAddressingMode(AM);
2214}
2215
2217 const MachineFunction &MF) const {
2219 return (MemVT.getSizeInBits() <= 4 * 32);
2220 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
2221 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
2222 return (MemVT.getSizeInBits() <= MaxPrivateBits);
2223 }
2225 return (MemVT.getSizeInBits() <= 2 * 32);
2226 return true;
2227}
2228
2230 unsigned Size, unsigned AddrSpace, Align Alignment,
2231 MachineMemOperand::Flags Flags, unsigned *IsFast) const {
2232 if (IsFast)
2233 *IsFast = 0;
2234
2235 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
2236 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
2237 // Check if alignment requirements for ds_read/write instructions are
2238 // disabled.
2239 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
2240 return false;
2241
2242 Align RequiredAlignment(
2243 PowerOf2Ceil(divideCeil(Size, 8))); // Natural alignment.
2244 if (Subtarget->hasLDSMisalignedBugInWGPMode() && Size > 32 &&
2245 Alignment < RequiredAlignment)
2246 return false;
2247
2248 // Either, the alignment requirements are "enabled", or there is an
2249 // unaligned LDS access related hardware bug though alignment requirements
2250 // are "disabled". In either case, we need to check for proper alignment
2251 // requirements.
2252 //
2253 switch (Size) {
2254 case 64:
2255 // SI has a hardware bug in the LDS / GDS bounds checking: if the base
2256 // address is negative, then the instruction is incorrectly treated as
2257 // out-of-bounds even if base + offsets is in bounds. Split vectorized
2258 // loads here to avoid emitting ds_read2_b32. We may re-combine the
2259 // load later in the SILoadStoreOptimizer.
2260 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
2261 return false;
2262
2263 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
2264 // can do a 4 byte aligned, 8 byte access in a single operation using
2265 // ds_read2/write2_b32 with adjacent offsets.
2266 RequiredAlignment = Align(4);
2267
2268 if (Subtarget->hasUnalignedDSAccessEnabled()) {
2269 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
2270 // ds_write2_b32 depending on the alignment. In either case with either
2271 // alignment there is no faster way of doing this.
2272
2273 // The numbers returned here and below are not additive, it is a 'speed
2274 // rank'. They are just meant to be compared to decide if a certain way
2275 // of lowering an operation is faster than another. For that purpose
2276 // naturally aligned operation gets it bitsize to indicate that "it
2277 // operates with a speed comparable to N-bit wide load". With the full
2278 // alignment ds128 is slower than ds96 for example. If underaligned it
2279 // is comparable to a speed of a single dword access, which would then
2280 // mean 32 < 128 and it is faster to issue a wide load regardless.
2281 // 1 is simply "slow, don't do it". I.e. comparing an aligned load to a
2282 // wider load which will not be aligned anymore the latter is slower.
2283 if (IsFast)
2284 *IsFast = (Alignment >= RequiredAlignment) ? 64
2285 : (Alignment < Align(4)) ? 32
2286 : 1;
2287 return true;
2288 }
2289
2290 break;
2291 case 96:
2292 if (!Subtarget->hasDS96AndDS128())
2293 return false;
2294
2295 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
2296 // gfx8 and older.
2297
2298 if (Subtarget->hasUnalignedDSAccessEnabled()) {
2299 // Naturally aligned access is fastest. However, also report it is Fast
2300 // if memory is aligned less than DWORD. A narrow load or store will be
2301 // be equally slow as a single ds_read_b96/ds_write_b96, but there will
2302 // be more of them, so overall we will pay less penalty issuing a single
2303 // instruction.
2304
2305 // See comment on the values above.
2306 if (IsFast)
2307 *IsFast = (Alignment >= RequiredAlignment) ? 96
2308 : (Alignment < Align(4)) ? 32
2309 : 1;
2310 return true;
2311 }
2312
2313 break;
2314 case 128:
2315 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
2316 return false;
2317
2318 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
2319 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a
2320 // single operation using ds_read2/write2_b64.
2321 RequiredAlignment = Align(8);
2322
2323 if (Subtarget->hasUnalignedDSAccessEnabled()) {
2324 // Naturally aligned access is fastest. However, also report it is Fast
2325 // if memory is aligned less than DWORD. A narrow load or store will be
2326 // be equally slow as a single ds_read_b128/ds_write_b128, but there
2327 // will be more of them, so overall we will pay less penalty issuing a
2328 // single instruction.
2329
2330 // See comment on the values above.
2331 if (IsFast)
2332 *IsFast = (Alignment >= RequiredAlignment) ? 128
2333 : (Alignment < Align(4)) ? 32
2334 : 1;
2335 return true;
2336 }
2337
2338 break;
2339 default:
2340 if (Size > 32)
2341 return false;
2342
2343 break;
2344 }
2345
2346 // See comment on the values above.
2347 // Note that we have a single-dword or sub-dword here, so if underaligned
2348 // it is a slowest possible access, hence returned value is 0.
2349 if (IsFast)
2350 *IsFast = (Alignment >= RequiredAlignment) ? Size : 0;
2351
2352 return Alignment >= RequiredAlignment ||
2353 Subtarget->hasUnalignedDSAccessEnabled();
2354 }
2355
2356 // FIXME: We have to be conservative here and assume that flat operations
2357 // will access scratch. If we had access to the IR function, then we
2358 // could determine if any private memory was used in the function.
2359 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
2360 AddrSpace == AMDGPUAS::FLAT_ADDRESS) {
2361 bool AlignedBy4 = Alignment >= Align(4);
2362 if (Subtarget->hasUnalignedScratchAccessEnabled()) {
2363 if (IsFast)
2364 *IsFast = AlignedBy4 ? Size : 1;
2365 return true;
2366 }
2367
2368 if (IsFast)
2369 *IsFast = AlignedBy4;
2370
2371 return AlignedBy4;
2372 }
2373
2374 // So long as they are correct, wide global memory operations perform better
2375 // than multiple smaller memory ops -- even when misaligned
2376 if (AMDGPU::isExtendedGlobalAddrSpace(AddrSpace)) {
2377 if (IsFast)
2378 *IsFast = Size;
2379
2380 return Alignment >= Align(4) ||
2381 Subtarget->hasUnalignedBufferAccessEnabled();
2382 }
2383
2384 // Ensure robust out-of-bounds guarantees for buffer accesses are met when the
2385 // "amdgpu.buffer.oob.mode" module flag has not enabled relaxed untyped-buffer
2386 // OOB semantics. Normally hardware will ensure proper
2387 // out-of-bounds behavior, but in the edge case where an access starts
2388 // out-of-bounds and then enters in-bounds, the entire access would be treated
2389 // as out-of-bounds. Prevent misaligned memory accesses by requiring the
2390 // natural alignment of buffer accesses.
2391 if (AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER ||
2392 AddrSpace == AMDGPUAS::BUFFER_RESOURCE ||
2393 AddrSpace == AMDGPUAS::BUFFER_STRIDED_POINTER) {
2394 if (!Subtarget->hasRelaxedBufferOOBMode() &&
2395 Alignment < Align(PowerOf2Ceil(divideCeil(Size, 8))))
2396 return false;
2397 }
2398
2399 // Smaller than dword value must be aligned.
2400 if (Size < 32)
2401 return false;
2402
2403 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
2404 // byte-address are ignored, thus forcing Dword alignment.
2405 // This applies to private, global, and constant memory.
2406 if (IsFast)
2407 *IsFast = 1;
2408
2409 return Size >= 32 && Alignment >= Align(4);
2410}
2411
2413 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
2414 unsigned *IsFast) const {
2416 Alignment, Flags, IsFast);
2417}
2418
2420 LLVMContext &Context, const MemOp &Op,
2421 const AttributeList &FuncAttributes) const {
2422 // FIXME: Should account for address space here.
2423
2424 // The default fallback uses the private pointer size as a guess for a type to
2425 // use. Make sure we switch these to 64-bit accesses.
2426
2427 if (Op.size() >= 16 &&
2428 Op.isDstAligned(Align(4))) // XXX: Should only do for global
2429 return MVT::v4i32;
2430
2431 if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
2432 return MVT::v2i32;
2433
2434 // Use the default.
2435 return MVT::Other;
2436}
2437
2439 const MemSDNode *MemNode = cast<MemSDNode>(N);
2440 return MemNode->getMemOperand()->getFlags() & MONoClobber;
2441}
2442
2447
2449 unsigned DestAS) const {
2450 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
2451 if (DestAS == AMDGPUAS::PRIVATE_ADDRESS &&
2452 Subtarget->hasGloballyAddressableScratch()) {
2453 // Flat -> private requires subtracting src_flat_scratch_base_lo.
2454 return false;
2455 }
2456
2457 // Flat -> private/local is a simple truncate.
2458 // Flat -> global is no-op
2459 return true;
2460 }
2461
2462 const GCNTargetMachine &TM =
2463 static_cast<const GCNTargetMachine &>(getTargetMachine());
2464 return TM.isNoopAddrSpaceCast(DL, SrcAS, DestAS);
2465}
2466
2474
2476 Type *Ty) const {
2477 // FIXME: Could be smarter if called for vector constants.
2478 return true;
2479}
2480
2483 unsigned Index) const {
2486
2487 // TODO: Add more cases that are cheap.
2488 if (Index == 0)
2491}
2492
2493bool SITargetLowering::isExtractVecEltCheap(EVT VT, unsigned Index) const {
2494 // TODO: This should be more aggressive, particular for 16-bit element
2495 // vectors. However there are some mixed improvements and regressions.
2496 EVT EltTy = VT.getVectorElementType();
2497 unsigned MinAlign = Subtarget->useRealTrue16Insts() ? 16 : 32;
2498 return EltTy.getSizeInBits() % MinAlign == 0;
2499}
2500
2502 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
2503 switch (Op) {
2504 case ISD::LOAD:
2505 case ISD::STORE:
2506 return true;
2507 default:
2508 return false;
2509 }
2510 }
2511
2512 // SimplifySetCC uses this function to determine whether or not it should
2513 // create setcc with i1 operands. We don't have instructions for i1 setcc.
2514 if (VT == MVT::i1 && Op == ISD::SETCC)
2515 return false;
2516
2517 if (VT.getScalarType() == MVT::i64 &&
2519 return false;
2520
2521 // The DAGCombiner replaces a conversion from i1 with a select of the two
2522 // exact results. The select avoids an f32 conversion plus rounding for
2523 // f16/bf16, a 64-bit conversion for f64 and a missing libcall for f128, and
2524 // is the same single v_cndmask for f32.
2525 if (VT == MVT::i1 && (Op == ISD::SINT_TO_FP || Op == ISD::UINT_TO_FP))
2526 return false;
2527
2529}
2530
2532 // Do not convert uniform loads to 16-bit.
2533 // Uniform 16-bit loads are legalized to i16 = trunc (zextload i16->i32)
2534 // to match subword load patterns. Allowing conversion back to a 16-bit
2535 // load would create an infinite loop.
2536 if (Subtarget->hasScalarSubwordLoads() && N->getOpcode() == ISD::LOAD &&
2537 !VT.isVector() && VT.getSizeInBits() == 16) {
2538 auto *Load = dyn_cast<LoadSDNode>(N);
2539 if (Load && isUniformLoad(Load)) {
2540 return false;
2541 }
2542 }
2543
2544 return isTypeDesirableForOp(N->getOpcode(), VT);
2545}
2546
2548 const MachineMemOperand *MMO = Load->getMemOperand();
2549
2550 // FIXME: We ought to able able to take the direct isDivergent result. We
2551 // cannot rely on the MMO for a uniformity check, and should stop using
2552 // it. This is a hack for 2 ways that the IR divergence analysis is superior
2553 // to the DAG divergence: Recognizing shift-of-workitem-id as always
2554 // uniform, and isSingleLaneExecution. These should be handled in the DAG
2555 // version, and then this can be dropped.
2556 if (Load->isDivergent() && !AMDGPU::isUniformMMO(MMO))
2557 return false;
2558
2559 return MMO->getSize().hasValue() &&
2560 Load->getAlign() >=
2561 Align(std::min(MMO->getSize().getValue().getKnownMinValue(),
2562 uint64_t(4))) &&
2563 (MMO->isInvariant() ||
2564 (Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
2565 Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ||
2566 (Load->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
2567 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load)));
2568}
2569
2572 // This isn't really a constant pool but close enough.
2575 return PtrInfo;
2576}
2577
2578SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
2579 const SDLoc &SL,
2580 SDValue Chain,
2581 uint64_t Offset) const {
2582 const DataLayout &DL = DAG.getDataLayout();
2586
2587 auto [InputPtrReg, RC, ArgTy] =
2588 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
2589
2590 // We may not have the kernarg segment argument if we have no kernel
2591 // arguments.
2592 if (!InputPtrReg)
2593 return DAG.getConstant(Offset, SL, PtrVT);
2594
2596 SDValue BasePtr = DAG.getCopyFromReg(
2597 Chain, SL, MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
2598
2599 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Offset));
2600}
2601
2602SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
2603 const SDLoc &SL) const {
2606 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
2607}
2608
2609SDValue SITargetLowering::getLDSKernelId(SelectionDAG &DAG,
2610 const SDLoc &SL) const {
2611
2613 std::optional<uint32_t> KnownSize =
2615 if (KnownSize.has_value())
2616 return DAG.getConstant(*KnownSize, SL, MVT::i32);
2617 return SDValue();
2618}
2619
2620SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
2621 const SDLoc &SL, SDValue Val,
2622 bool Signed,
2623 const ISD::InputArg *Arg) const {
2624 // First, if it is a widened vector, narrow it.
2625 if (VT.isVector() &&
2627 EVT NarrowedVT =
2630 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
2631 DAG.getConstant(0, SL, MVT::i32));
2632 }
2633
2634 // Then convert the vector elements or scalar value.
2635 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && VT.bitsLT(MemVT)) {
2636 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
2637 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
2638 }
2639
2640 if (MemVT.isFloatingPoint()) {
2641 if (VT.isFloatingPoint()) {
2642 Val = getFPExtOrFPRound(DAG, Val, SL, VT);
2643 } else {
2644 assert(!MemVT.isVector());
2645 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
2646 SDValue Cast = DAG.getBitcast(IntVT, Val);
2647 Val = DAG.getAnyExtOrTrunc(Cast, SL, VT);
2648 }
2649 } else if (Signed)
2650 Val = DAG.getSExtOrTrunc(Val, SL, VT);
2651 else
2652 Val = DAG.getZExtOrTrunc(Val, SL, VT);
2653
2654 return Val;
2655}
2656
2657SDValue SITargetLowering::lowerKernargMemParameter(
2658 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
2659 uint64_t Offset, Align Alignment, bool Signed,
2660 const ISD::InputArg *Arg) const {
2661
2662 MachinePointerInfo PtrInfo =
2664
2665 // Try to avoid using an extload by loading earlier than the argument address,
2666 // and extracting the relevant bits. The load should hopefully be merged with
2667 // the previous argument.
2668 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
2669 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
2670 int64_t AlignDownOffset = alignDown(Offset, 4);
2671 int64_t OffsetDiff = Offset - AlignDownOffset;
2672
2673 EVT IntVT = MemVT.changeTypeToInteger();
2674
2675 // TODO: If we passed in the base kernel offset we could have a better
2676 // alignment than 4, but we don't really need it.
2677 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
2678 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr,
2679 PtrInfo.getWithOffset(AlignDownOffset), Align(4),
2682
2683 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
2684 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
2685
2686 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
2687 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
2688 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
2689
2690 return DAG.getMergeValues({ArgVal, Load.getValue(1)}, SL);
2691 }
2692
2693 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
2694 SDValue Load = DAG.getLoad(
2695 MemVT, SL, Chain, Ptr, PtrInfo.getWithOffset(Offset), Alignment,
2697
2698 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
2699 return DAG.getMergeValues({Val, Load.getValue(1)}, SL);
2700}
2701
2702/// Coerce an argument which was passed in a different ABI type to the original
2703/// expected value type.
2704SDValue SITargetLowering::convertABITypeToValueType(SelectionDAG &DAG,
2705 SDValue Val,
2706 CCValAssign &VA,
2707 const SDLoc &SL) const {
2708 EVT ValVT = VA.getValVT();
2709
2710 // If this is an 8 or 16-bit value, it is really passed promoted
2711 // to 32 bits. Insert an assert[sz]ext to capture this, then
2712 // truncate to the right size.
2713 switch (VA.getLocInfo()) {
2714 case CCValAssign::Full:
2715 return Val;
2716 case CCValAssign::BCvt:
2717 return DAG.getNode(ISD::BITCAST, SL, ValVT, Val);
2718 case CCValAssign::SExt:
2719 Val = DAG.getNode(ISD::AssertSext, SL, VA.getLocVT(), Val,
2720 DAG.getValueType(ValVT));
2721 return DAG.getNode(ISD::TRUNCATE, SL, ValVT, Val);
2722 case CCValAssign::ZExt:
2723 Val = DAG.getNode(ISD::AssertZext, SL, VA.getLocVT(), Val,
2724 DAG.getValueType(ValVT));
2725 return DAG.getNode(ISD::TRUNCATE, SL, ValVT, Val);
2726 case CCValAssign::AExt:
2727 return DAG.getNode(ISD::TRUNCATE, SL, ValVT, Val);
2728 default:
2729 llvm_unreachable("Unknown loc info!");
2730 }
2731}
2732
2733SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG,
2734 CCValAssign &VA, const SDLoc &SL,
2735 SDValue Chain,
2736 const ISD::InputArg &Arg) const {
2738 MachineFrameInfo &MFI = MF.getFrameInfo();
2739
2740 if (Arg.Flags.isByVal()) {
2741 unsigned Size = Arg.Flags.getByValSize();
2742 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
2743 return DAG.getFrameIndex(FrameIdx, MVT::i32);
2744 }
2745
2746 unsigned ArgOffset = VA.getLocMemOffset();
2747 unsigned ArgSize = VA.getValVT().getStoreSize();
2748
2749 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
2750
2751 // Create load nodes to retrieve arguments from the stack.
2752 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
2753
2754 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2756 MVT MemVT = VA.getValVT();
2757
2758 switch (VA.getLocInfo()) {
2759 default:
2760 break;
2761 case CCValAssign::BCvt:
2762 MemVT = VA.getLocVT();
2763 break;
2764 case CCValAssign::SExt:
2765 ExtType = ISD::SEXTLOAD;
2766 break;
2767 case CCValAssign::ZExt:
2768 ExtType = ISD::ZEXTLOAD;
2769 break;
2770 case CCValAssign::AExt:
2771 ExtType = ISD::EXTLOAD;
2772 break;
2773 }
2774
2775 SDValue ArgValue = DAG.getExtLoad(
2776 ExtType, SL, VA.getLocVT(), Chain, FIN,
2778
2779 SDValue ConvertedVal = convertABITypeToValueType(DAG, ArgValue, VA, SL);
2780 if (ConvertedVal == ArgValue)
2781 return ConvertedVal;
2782
2783 return DAG.getMergeValues({ConvertedVal, ArgValue.getValue(1)}, SL);
2784}
2785
2786SDValue SITargetLowering::lowerWorkGroupId(
2787 SelectionDAG &DAG, const SIMachineFunctionInfo &MFI, EVT VT,
2790 AMDGPUFunctionArgInfo::PreloadedValue ClusterWorkGroupIdPV) const {
2791 if (!Subtarget->hasClusters())
2792 return getPreloadedValue(DAG, MFI, VT, WorkGroupIdPV);
2793
2794 // Clusters are supported. Return the global position in the grid. If clusters
2795 // are enabled, WorkGroupIdPV returns the cluster ID not the workgroup ID.
2796
2797 // WorkGroupIdXYZ = ClusterId == 0 ?
2798 // ClusterIdXYZ :
2799 // ClusterIdXYZ * (ClusterMaxIdXYZ + 1) + ClusterWorkGroupIdXYZ
2800 SDValue ClusterIdXYZ = getPreloadedValue(DAG, MFI, VT, WorkGroupIdPV);
2801 SDLoc SL(ClusterIdXYZ);
2802 SDValue ClusterMaxIdXYZ = getPreloadedValue(DAG, MFI, VT, ClusterMaxIdPV);
2803 SDValue One = DAG.getConstant(1, SL, VT);
2804 SDValue ClusterSizeXYZ = DAG.getNode(ISD::ADD, SL, VT, ClusterMaxIdXYZ, One);
2805 SDValue ClusterWorkGroupIdXYZ =
2806 getPreloadedValue(DAG, MFI, VT, ClusterWorkGroupIdPV);
2807 SDValue GlobalIdXYZ =
2808 DAG.getNode(ISD::ADD, SL, VT, ClusterWorkGroupIdXYZ,
2809 DAG.getNode(ISD::MUL, SL, VT, ClusterIdXYZ, ClusterSizeXYZ));
2810
2811 switch (MFI.getClusterDims().getKind()) {
2814 return GlobalIdXYZ;
2816 return ClusterIdXYZ;
2818 using namespace AMDGPU::Hwreg;
2819 SDValue ClusterIdField =
2820 DAG.getTargetConstant(HwregEncoding::encode(ID_IB_STS2, 6, 4), SL, VT);
2821 SDNode *GetReg =
2822 DAG.getMachineNode(AMDGPU::S_GETREG_B32_const, SL, VT, ClusterIdField);
2823 SDValue ClusterId(GetReg, 0);
2824 SDValue Zero = DAG.getConstant(0, SL, VT);
2825 return DAG.getNode(ISD::SELECT_CC, SL, VT, ClusterId, Zero, ClusterIdXYZ,
2826 GlobalIdXYZ, DAG.getCondCode(ISD::SETEQ));
2827 }
2828 }
2829
2830 llvm_unreachable("nothing should reach here");
2831}
2832
2833SDValue SITargetLowering::getPreloadedValue(
2834 SelectionDAG &DAG, const SIMachineFunctionInfo &MFI, EVT VT,
2836 const ArgDescriptor *Reg = nullptr;
2837 const TargetRegisterClass *RC = nullptr;
2838 LLT Ty;
2839
2841 const ArgDescriptor WorkGroupIDX =
2842 ArgDescriptor::createRegister(AMDGPU::TTMP9);
2843 // If GridZ is not programmed in an entry function then the hardware will set
2844 // it to all zeros, so there is no need to mask the GridY value in the low
2845 // order bits.
2846 const ArgDescriptor WorkGroupIDY = ArgDescriptor::createRegister(
2847 AMDGPU::TTMP7,
2848 AMDGPU::isEntryFunctionCC(CC) && !MFI.hasWorkGroupIDZ() ? ~0u : 0xFFFFu);
2849 const ArgDescriptor WorkGroupIDZ =
2850 ArgDescriptor::createRegister(AMDGPU::TTMP7, 0xFFFF0000u);
2851 const ArgDescriptor ClusterWorkGroupIDX =
2852 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0000000Fu);
2853 const ArgDescriptor ClusterWorkGroupIDY =
2854 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x000000F0u);
2855 const ArgDescriptor ClusterWorkGroupIDZ =
2856 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x00000F00u);
2857 const ArgDescriptor ClusterWorkGroupMaxIDX =
2858 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0000F000u);
2859 const ArgDescriptor ClusterWorkGroupMaxIDY =
2860 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x000F0000u);
2861 const ArgDescriptor ClusterWorkGroupMaxIDZ =
2862 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x00F00000u);
2863 const ArgDescriptor ClusterWorkGroupMaxFlatID =
2864 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0F000000u);
2865
2866 auto LoadConstant = [&](unsigned N) {
2867 return DAG.getConstant(N, SDLoc(), VT);
2868 };
2869
2870 if (Subtarget->hasArchitectedSGPRs() &&
2873 AMDGPU::ClusterDimsAttr ClusterDims = MFI.getClusterDims();
2874 bool HasFixedDims = ClusterDims.isFixedDims();
2875
2876 switch (PVID) {
2878 Reg = &WorkGroupIDX;
2879 RC = &AMDGPU::SReg_32RegClass;
2880 Ty = LLT::scalar(32);
2881 break;
2883 Reg = &WorkGroupIDY;
2884 RC = &AMDGPU::SReg_32RegClass;
2885 Ty = LLT::scalar(32);
2886 break;
2888 Reg = &WorkGroupIDZ;
2889 RC = &AMDGPU::SReg_32RegClass;
2890 Ty = LLT::scalar(32);
2891 break;
2893 if (HasFixedDims && ClusterDims.getDims()[0] == 1)
2894 return LoadConstant(0);
2895 Reg = &ClusterWorkGroupIDX;
2896 RC = &AMDGPU::SReg_32RegClass;
2897 Ty = LLT::scalar(32);
2898 break;
2900 if (HasFixedDims && ClusterDims.getDims()[1] == 1)
2901 return LoadConstant(0);
2902 Reg = &ClusterWorkGroupIDY;
2903 RC = &AMDGPU::SReg_32RegClass;
2904 Ty = LLT::scalar(32);
2905 break;
2907 if (HasFixedDims && ClusterDims.getDims()[2] == 1)
2908 return LoadConstant(0);
2909 Reg = &ClusterWorkGroupIDZ;
2910 RC = &AMDGPU::SReg_32RegClass;
2911 Ty = LLT::scalar(32);
2912 break;
2914 if (HasFixedDims)
2915 return LoadConstant(ClusterDims.getDims()[0] - 1);
2916 Reg = &ClusterWorkGroupMaxIDX;
2917 RC = &AMDGPU::SReg_32RegClass;
2918 Ty = LLT::scalar(32);
2919 break;
2921 if (HasFixedDims)
2922 return LoadConstant(ClusterDims.getDims()[1] - 1);
2923 Reg = &ClusterWorkGroupMaxIDY;
2924 RC = &AMDGPU::SReg_32RegClass;
2925 Ty = LLT::scalar(32);
2926 break;
2928 if (HasFixedDims)
2929 return LoadConstant(ClusterDims.getDims()[2] - 1);
2930 Reg = &ClusterWorkGroupMaxIDZ;
2931 RC = &AMDGPU::SReg_32RegClass;
2932 Ty = LLT::scalar(32);
2933 break;
2935 Reg = &ClusterWorkGroupMaxFlatID;
2936 RC = &AMDGPU::SReg_32RegClass;
2937 Ty = LLT::scalar(32);
2938 break;
2939 default:
2940 break;
2941 }
2942 }
2943
2944 if (!Reg)
2945 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
2946 if (!Reg) {
2948 // It's possible for a kernarg intrinsic call to appear in a kernel with
2949 // no allocated segment, in which case we do not add the user sgpr
2950 // argument, so just return null.
2951 return DAG.getConstant(0, SDLoc(), VT);
2952 }
2953
2954 // It's undefined behavior if a function marked with the amdgpu-no-*
2955 // attributes uses the corresponding intrinsic.
2956 return DAG.getPOISON(VT);
2957 }
2958
2959 return loadInputValue(DAG, RC, VT, SDLoc(DAG.getEntryNode()), *Reg);
2960}
2961
2963 CallingConv::ID CallConv,
2964 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
2965 FunctionType *FType,
2966 SIMachineFunctionInfo *Info) {
2967 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
2968 const ISD::InputArg *Arg = &Ins[I];
2969
2970 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
2971 "vector type argument should have been split");
2972
2973 // First check if it's a PS input addr.
2974 if (CallConv == CallingConv::AMDGPU_PS && !Arg->Flags.isInReg() &&
2975 PSInputNum <= 15) {
2976 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
2977
2978 // Inconveniently only the first part of the split is marked as isSplit,
2979 // so skip to the end. We only want to increment PSInputNum once for the
2980 // entire split argument.
2981 if (Arg->Flags.isSplit()) {
2982 while (!Arg->Flags.isSplitEnd()) {
2983 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
2984 "unexpected vector split in ps argument type");
2985 if (!SkipArg)
2986 Splits.push_back(*Arg);
2987 Arg = &Ins[++I];
2988 }
2989 }
2990
2991 if (SkipArg) {
2992 // We can safely skip PS inputs.
2993 Skipped.set(Arg->getOrigArgIndex());
2994 ++PSInputNum;
2995 continue;
2996 }
2997
2998 Info->markPSInputAllocated(PSInputNum);
2999 if (Arg->Used)
3000 Info->markPSInputEnabled(PSInputNum);
3001
3002 ++PSInputNum;
3003 }
3004
3005 Splits.push_back(*Arg);
3006 }
3007}
3008
3009// Allocate special inputs passed in VGPRs.
3011 CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI,
3012 SIMachineFunctionInfo &Info) const {
3013 const LLT I32 = LLT::integer(32);
3015
3016 if (Info.hasWorkItemIDX()) {
3017 Register Reg = AMDGPU::VGPR0;
3018 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), I32);
3019
3020 CCInfo.AllocateReg(Reg);
3021 unsigned Mask =
3022 (Subtarget->hasPackedTID() && Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
3023 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
3024 }
3025
3026 if (Info.hasWorkItemIDY()) {
3027 assert(Info.hasWorkItemIDX());
3028 if (Subtarget->hasPackedTID()) {
3029 Info.setWorkItemIDY(
3030 ArgDescriptor::createRegister(AMDGPU::VGPR0, 0x3ff << 10));
3031 } else {
3032 unsigned Reg = AMDGPU::VGPR1;
3033 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), I32);
3034
3035 CCInfo.AllocateReg(Reg);
3036 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
3037 }
3038 }
3039
3040 if (Info.hasWorkItemIDZ()) {
3041 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
3042 if (Subtarget->hasPackedTID()) {
3043 Info.setWorkItemIDZ(
3044 ArgDescriptor::createRegister(AMDGPU::VGPR0, 0x3ff << 20));
3045 } else {
3046 unsigned Reg = AMDGPU::VGPR2;
3047 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), I32);
3048
3049 CCInfo.AllocateReg(Reg);
3050 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
3051 }
3052 }
3053}
3054
3056 const TargetRegisterClass *RC,
3057 unsigned NumArgRegs) {
3058 ArrayRef<MCPhysReg> ArgSGPRs = ArrayRef(RC->begin(), 32);
3059 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
3060 if (RegIdx == ArgSGPRs.size())
3061 report_fatal_error("ran out of SGPRs for arguments");
3062
3063 unsigned Reg = ArgSGPRs[RegIdx];
3064 Reg = CCInfo.AllocateReg(Reg);
3065 assert(Reg != AMDGPU::NoRegister);
3066
3067 MachineFunction &MF = CCInfo.getMachineFunction();
3068 MF.addLiveIn(Reg, RC);
3070}
3071
3072// If this has a fixed position, we still should allocate the register in the
3073// CCInfo state. Technically we could get away with this for values passed
3074// outside of the normal argument range.
3076 const TargetRegisterClass *RC,
3077 MCRegister Reg) {
3078 Reg = CCInfo.AllocateReg(Reg);
3079 assert(Reg != AMDGPU::NoRegister);
3080 MachineFunction &MF = CCInfo.getMachineFunction();
3081 MF.addLiveIn(Reg, RC);
3082}
3083
3084static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
3085 if (Arg) {
3086 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
3087 Arg.getRegister());
3088 } else
3089 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
3090}
3091
3092static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
3093 if (Arg) {
3094 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
3095 Arg.getRegister());
3096 } else
3097 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
3098}
3099
3100/// Allocate implicit function VGPR arguments in fixed registers.
3102 CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI,
3103 SIMachineFunctionInfo &Info) const {
3104 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
3105 if (!Reg)
3106 report_fatal_error("failed to allocate VGPR for implicit arguments");
3107
3108 const unsigned Mask = 0x3ff;
3109 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
3110 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
3111 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
3112}
3113
3115 CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI,
3116 SIMachineFunctionInfo &Info) const {
3117 auto &ArgInfo = Info.getArgInfo();
3118 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
3119
3120 // TODO: Unify handling with private memory pointers.
3121 if (UserSGPRInfo.hasDispatchPtr())
3122 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
3123
3124 if (UserSGPRInfo.hasQueuePtr())
3125 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
3126
3127 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
3128 // constant offset from the kernarg segment.
3129 if (Info.hasImplicitArgPtr())
3130 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
3131
3132 if (UserSGPRInfo.hasDispatchID())
3133 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
3134
3135 // flat_scratch_init is not applicable for non-kernel functions.
3136
3137 if (Info.hasWorkGroupIDX())
3138 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
3139
3140 if (Info.hasWorkGroupIDY())
3141 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
3142
3143 if (Info.hasWorkGroupIDZ())
3144 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
3145
3146 if (Info.hasLDSKernelId())
3147 allocateSGPR32Input(CCInfo, ArgInfo.LDSKernelId);
3148}
3149
3150// Allocate special inputs passed in user SGPRs.
3152 MachineFunction &MF,
3153 const SIRegisterInfo &TRI,
3154 SIMachineFunctionInfo &Info) const {
3155 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
3156 if (UserSGPRInfo.hasImplicitBufferPtr()) {
3157 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
3158 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
3159 CCInfo.AllocateReg(ImplicitBufferPtrReg);
3160 }
3161
3162 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
3163 if (UserSGPRInfo.hasPrivateSegmentBuffer()) {
3164 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
3165 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
3166 CCInfo.AllocateReg(PrivateSegmentBufferReg);
3167 }
3168
3169 if (UserSGPRInfo.hasDispatchPtr()) {
3170 Register DispatchPtrReg = Info.addDispatchPtr(TRI);
3171 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
3172 CCInfo.AllocateReg(DispatchPtrReg);
3173 }
3174
3175 if (UserSGPRInfo.hasQueuePtr()) {
3176 Register QueuePtrReg = Info.addQueuePtr(TRI);
3177 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
3178 CCInfo.AllocateReg(QueuePtrReg);
3179 }
3180
3181 if (UserSGPRInfo.hasKernargSegmentPtr()) {
3183 Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
3184 CCInfo.AllocateReg(InputPtrReg);
3185
3186 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
3187 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
3188 }
3189
3190 if (UserSGPRInfo.hasDispatchID()) {
3191 Register DispatchIDReg = Info.addDispatchID(TRI);
3192 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
3193 CCInfo.AllocateReg(DispatchIDReg);
3194 }
3195
3196 if (UserSGPRInfo.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
3197 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
3198 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
3199 CCInfo.AllocateReg(FlatScratchInitReg);
3200 }
3201
3202 if (UserSGPRInfo.hasPrivateSegmentSize()) {
3203 Register PrivateSegmentSizeReg = Info.addPrivateSegmentSize(TRI);
3204 MF.addLiveIn(PrivateSegmentSizeReg, &AMDGPU::SGPR_32RegClass);
3205 CCInfo.AllocateReg(PrivateSegmentSizeReg);
3206 }
3207
3208 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
3209 // these from the dispatch pointer.
3210}
3211
3212// Allocate pre-loaded kernel arguemtns. Arguments to be preloading must be
3213// sequential starting from the first argument.
3215 CCState &CCInfo, SmallVectorImpl<CCValAssign> &ArgLocs,
3217 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
3218 Function &F = MF.getFunction();
3219 unsigned LastExplicitArgOffset = Subtarget->getExplicitKernelArgOffset();
3220 GCNUserSGPRUsageInfo &SGPRInfo = Info.getUserSGPRInfo();
3221 bool InPreloadSequence = true;
3222 unsigned InIdx = 0;
3223 bool AlignedForImplictArgs = false;
3224 unsigned ImplicitArgOffset = 0;
3225 for (auto &Arg : F.args()) {
3226 if (!InPreloadSequence || !Arg.hasInRegAttr())
3227 break;
3228
3229 unsigned ArgIdx = Arg.getArgNo();
3230 // Don't preload non-original args or parts not in the current preload
3231 // sequence.
3232 if (InIdx < Ins.size() &&
3233 (!Ins[InIdx].isOrigArg() || Ins[InIdx].getOrigArgIndex() != ArgIdx))
3234 break;
3235
3236 for (; InIdx < Ins.size() && Ins[InIdx].isOrigArg() &&
3237 Ins[InIdx].getOrigArgIndex() == ArgIdx;
3238 InIdx++) {
3239 assert(ArgLocs[ArgIdx].isMemLoc());
3240 auto &ArgLoc = ArgLocs[InIdx];
3241 const Align KernelArgBaseAlign = Align(16);
3242 unsigned ArgOffset = ArgLoc.getLocMemOffset();
3243 Align Alignment = commonAlignment(KernelArgBaseAlign, ArgOffset);
3244 unsigned NumAllocSGPRs =
3245 alignTo(ArgLoc.getLocVT().getFixedSizeInBits(), 32) / 32;
3246
3247 // Fix alignment for hidden arguments.
3248 if (Arg.hasAttribute("amdgpu-hidden-argument")) {
3249 if (!AlignedForImplictArgs) {
3250 ImplicitArgOffset =
3251 alignTo(LastExplicitArgOffset,
3252 Subtarget->getAlignmentForImplicitArgPtr()) -
3253 LastExplicitArgOffset;
3254 AlignedForImplictArgs = true;
3255 }
3256 ArgOffset += ImplicitArgOffset;
3257 }
3258
3259 // Arg is preloaded into the previous SGPR.
3260 if (ArgLoc.getLocVT().getStoreSize() < 4 && Alignment < 4) {
3261 assert(InIdx >= 1 && "No previous SGPR");
3262 Info.getArgInfo().PreloadKernArgs[InIdx].Regs.push_back(
3263 Info.getArgInfo().PreloadKernArgs[InIdx - 1].Regs[0]);
3264 continue;
3265 }
3266
3267 unsigned Padding = ArgOffset - LastExplicitArgOffset;
3268 unsigned PaddingSGPRs = alignTo(Padding, 4) / 4;
3269 // Check for free user SGPRs for preloading.
3270 if (PaddingSGPRs + NumAllocSGPRs > SGPRInfo.getNumFreeUserSGPRs()) {
3271 InPreloadSequence = false;
3272 break;
3273 }
3274
3275 // Preload this argument.
3276 const TargetRegisterClass *RC =
3277 TRI.getSGPRClassForBitWidth(NumAllocSGPRs * 32);
3278 SmallVectorImpl<MCRegister> *PreloadRegs =
3279 Info.addPreloadedKernArg(TRI, RC, NumAllocSGPRs, InIdx, PaddingSGPRs);
3280
3281 if (PreloadRegs->size() > 1)
3282 RC = &AMDGPU::SGPR_32RegClass;
3283 for (auto &Reg : *PreloadRegs) {
3284 assert(Reg);
3285 MF.addLiveIn(Reg, RC);
3286 CCInfo.AllocateReg(Reg);
3287 }
3288
3289 LastExplicitArgOffset = NumAllocSGPRs * 4 + ArgOffset;
3290 }
3291 }
3292}
3293
3295 const SIRegisterInfo &TRI,
3296 SIMachineFunctionInfo &Info) const {
3297 // Always allocate this last since it is a synthetic preload.
3298 if (Info.hasLDSKernelId()) {
3299 Register Reg = Info.addLDSKernelId();
3300 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3301 CCInfo.AllocateReg(Reg);
3302 }
3303}
3304
3305// Allocate special input registers that are initialized per-wave.
3308 CallingConv::ID CallConv,
3309 bool IsShader) const {
3310 bool HasArchitectedSGPRs = Subtarget->hasArchitectedSGPRs();
3311 if (Subtarget->hasUserSGPRInit16BugInWave32() && !IsShader) {
3312 // Note: user SGPRs are handled by the front-end for graphics shaders
3313 // Pad up the used user SGPRs with dead inputs.
3314
3315 // TODO: NumRequiredSystemSGPRs computation should be adjusted appropriately
3316 // before enabling architected SGPRs for workgroup IDs.
3317 assert(!HasArchitectedSGPRs && "Unhandled feature for the subtarget");
3318
3319 unsigned CurrentUserSGPRs = Info.getNumUserSGPRs();
3320 // Note we do not count the PrivateSegmentWaveByteOffset. We do not want to
3321 // rely on it to reach 16 since if we end up having no stack usage, it will
3322 // not really be added.
3323 unsigned NumRequiredSystemSGPRs =
3324 Info.hasWorkGroupIDX() + Info.hasWorkGroupIDY() +
3325 Info.hasWorkGroupIDZ() + Info.hasWorkGroupInfo();
3326 for (unsigned i = NumRequiredSystemSGPRs + CurrentUserSGPRs; i < 16; ++i) {
3327 Register Reg = Info.addReservedUserSGPR();
3328 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3329 CCInfo.AllocateReg(Reg);
3330 }
3331 }
3332
3333 if (!HasArchitectedSGPRs) {
3334 if (Info.hasWorkGroupIDX()) {
3335 Register Reg = Info.addWorkGroupIDX();
3336 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3337 CCInfo.AllocateReg(Reg);
3338 }
3339
3340 if (Info.hasWorkGroupIDY()) {
3341 Register Reg = Info.addWorkGroupIDY();
3342 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3343 CCInfo.AllocateReg(Reg);
3344 }
3345
3346 if (Info.hasWorkGroupIDZ()) {
3347 Register Reg = Info.addWorkGroupIDZ();
3348 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3349 CCInfo.AllocateReg(Reg);
3350 }
3351 }
3352
3353 if (Info.hasWorkGroupInfo()) {
3354 Register Reg = Info.addWorkGroupInfo();
3355 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3356 CCInfo.AllocateReg(Reg);
3357 }
3358
3359 if (Info.hasPrivateSegmentWaveByteOffset()) {
3360 // Scratch wave offset passed in system SGPR.
3361 unsigned PrivateSegmentWaveByteOffsetReg;
3362
3363 if (IsShader) {
3364 PrivateSegmentWaveByteOffsetReg =
3365 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
3366
3367 // This is true if the scratch wave byte offset doesn't have a fixed
3368 // location.
3369 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
3370 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
3371 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
3372 }
3373 } else
3374 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
3375
3376 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
3377 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
3378 }
3379
3380 assert(!Subtarget->hasUserSGPRInit16BugInWave32() || IsShader ||
3381 Info.getNumPreloadedSGPRs() >= 16);
3382}
3383
3385 MachineFunction &MF,
3386 const SIRegisterInfo &TRI,
3387 SIMachineFunctionInfo &Info) {
3388 // Now that we've figured out where the scratch register inputs are, see if
3389 // should reserve the arguments and use them directly.
3390 MachineFrameInfo &MFI = MF.getFrameInfo();
3391 bool HasStackObjects = MFI.hasStackObjects();
3392 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3393
3394 // Record that we know we have non-spill stack objects so we don't need to
3395 // check all stack objects later.
3396 if (HasStackObjects)
3397 Info.setHasNonSpillStackObjects(true);
3398
3399 // Everything live out of a block is spilled with fast regalloc, so it's
3400 // almost certain that spilling will be required.
3402 HasStackObjects = true;
3403
3404 // For now assume stack access is needed in any callee functions, so we need
3405 // the scratch registers to pass in.
3406 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
3407
3408 if (!ST.hasFlatScratchEnabled()) {
3409 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
3410 // If we have stack objects, we unquestionably need the private buffer
3411 // resource. For the Code Object V2 ABI, this will be the first 4 user
3412 // SGPR inputs. We can reserve those and use them directly.
3413
3414 Register PrivateSegmentBufferReg =
3416 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
3417 } else {
3418 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
3419 // We tentatively reserve the last registers (skipping the last registers
3420 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
3421 // we'll replace these with the ones immediately after those which were
3422 // really allocated. In the prologue copies will be inserted from the
3423 // argument to these reserved registers.
3424
3425 // Without HSA, relocations are used for the scratch pointer and the
3426 // buffer resource setup is always inserted in the prologue. Scratch wave
3427 // offset is still in an input SGPR.
3428 Info.setScratchRSrcReg(ReservedBufferReg);
3429 }
3430 }
3431
3433
3434 // For entry functions we have to set up the stack pointer if we use it,
3435 // whereas non-entry functions get this "for free". This means there is no
3436 // intrinsic advantage to using S32 over S34 in cases where we do not have
3437 // calls but do need a frame pointer (i.e. if we are requested to have one
3438 // because frame pointer elimination is disabled). To keep things simple we
3439 // only ever use S32 as the call ABI stack pointer, and so using it does not
3440 // imply we need a separate frame pointer.
3441 //
3442 // Try to use s32 as the SP, but move it if it would interfere with input
3443 // arguments. This won't work with calls though.
3444 //
3445 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
3446 // registers.
3447 if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
3448 Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
3449 } else {
3451
3452 if (MFI.hasCalls())
3453 report_fatal_error("call in graphics shader with too many input SGPRs");
3454
3455 for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
3456 if (!MRI.isLiveIn(Reg)) {
3457 Info.setStackPtrOffsetReg(Reg);
3458 break;
3459 }
3460 }
3461
3462 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
3463 report_fatal_error("failed to find register for SP");
3464 }
3465
3466 // hasFP should be accurate for entry functions even before the frame is
3467 // finalized, because it does not rely on the known stack size, only
3468 // properties like whether variable sized objects are present.
3469 if (ST.getFrameLowering()->hasFP(MF)) {
3470 Info.setFrameOffsetReg(AMDGPU::SGPR33);
3471 }
3472}
3473
3476 return !Info->isEntryFunction();
3477}
3478
3480
3482 MachineBasicBlock *Entry,
3483 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
3485
3486 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
3487 if (!IStart)
3488 return;
3489
3490 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
3491 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
3492 MachineBasicBlock::iterator MBBI = Entry->begin();
3493 for (const MCPhysReg *I = IStart; *I; ++I) {
3494 const TargetRegisterClass *RC = nullptr;
3495 if (AMDGPU::SReg_64RegClass.contains(*I))
3496 RC = &AMDGPU::SGPR_64RegClass;
3497 else if (AMDGPU::SReg_32RegClass.contains(*I))
3498 RC = &AMDGPU::SGPR_32RegClass;
3499 else
3500 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3501
3502 Register NewVR = MRI->createVirtualRegister(RC);
3503 // Create copy from CSR to a virtual register.
3504 Entry->addLiveIn(*I);
3505 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
3506 .addReg(*I);
3507
3508 // Insert the copy-back instructions right before the terminator.
3509 for (auto *Exit : Exits)
3510 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
3511 TII->get(TargetOpcode::COPY), *I)
3512 .addReg(NewVR);
3513 }
3514}
3515
3517 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3518 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3519 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3521
3523 const Function &Fn = MF.getFunction();
3526 bool IsError = false;
3527
3528 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
3530 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()));
3531 IsError = true;
3532 }
3533
3536 BitVector Skipped(Fn.arg_size());
3537 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3538 *DAG.getContext());
3539
3540 bool IsGraphics = AMDGPU::isGraphics(CallConv);
3541 bool IsKernel = AMDGPU::isKernel(CallConv);
3542 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
3543
3544 if (IsGraphics) {
3545 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info->getUserSGPRInfo();
3546 assert(!UserSGPRInfo.hasDispatchPtr() &&
3547 !UserSGPRInfo.hasKernargSegmentPtr() && !Info->hasWorkGroupInfo() &&
3548 !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() &&
3549 !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ());
3550 (void)UserSGPRInfo;
3551 if (!Subtarget->hasFlatScratchEnabled())
3552 assert(!UserSGPRInfo.hasFlatScratchInit());
3553 if ((CallConv != CallingConv::AMDGPU_CS &&
3554 CallConv != CallingConv::AMDGPU_Gfx &&
3555 CallConv != CallingConv::AMDGPU_Gfx_WholeWave) ||
3556 !Subtarget->hasArchitectedSGPRs())
3557 assert(!Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
3558 !Info->hasWorkGroupIDZ());
3559 }
3560
3561 bool IsWholeWaveFunc = Info->isWholeWaveFunction();
3562
3563 if (CallConv == CallingConv::AMDGPU_PS) {
3564 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
3565
3566 // At least one interpolation mode must be enabled or else the GPU will
3567 // hang.
3568 //
3569 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
3570 // set PSInputAddr, the user wants to enable some bits after the compilation
3571 // based on run-time states. Since we can't know what the final PSInputEna
3572 // will look like, so we shouldn't do anything here and the user should take
3573 // responsibility for the correct programming.
3574 //
3575 // Otherwise, the following restrictions apply:
3576 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
3577 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
3578 // enabled too.
3579 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
3580 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
3581 CCInfo.AllocateReg(AMDGPU::VGPR0);
3582 CCInfo.AllocateReg(AMDGPU::VGPR1);
3583 Info->markPSInputAllocated(0);
3584 Info->markPSInputEnabled(0);
3585 }
3586 if (Subtarget->isAmdPalOS()) {
3587 // For isAmdPalOS, the user does not enable some bits after compilation
3588 // based on run-time states; the register values being generated here are
3589 // the final ones set in hardware. Therefore we need to apply the
3590 // workaround to PSInputAddr and PSInputEnable together. (The case where
3591 // a bit is set in PSInputAddr but not PSInputEnable is where the
3592 // frontend set up an input arg for a particular interpolation mode, but
3593 // nothing uses that input arg. Really we should have an earlier pass
3594 // that removes such an arg.)
3595 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
3596 if ((PsInputBits & 0x7F) == 0 ||
3597 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
3598 Info->markPSInputEnabled(llvm::countr_zero(Info->getPSInputAddr()));
3599 }
3600 } else if (IsKernel) {
3601 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
3602 } else {
3603 Splits.append(IsWholeWaveFunc ? std::next(Ins.begin()) : Ins.begin(),
3604 Ins.end());
3605 }
3606
3607 if (IsKernel)
3608 analyzeFormalArgumentsCompute(CCInfo, Ins);
3609
3610 if (IsEntryFunc) {
3611 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
3612 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
3613 if (IsKernel && Subtarget->hasKernargPreload())
3614 allocatePreloadKernArgSGPRs(CCInfo, ArgLocs, Ins, MF, *TRI, *Info);
3615
3616 allocateLDSKernelId(CCInfo, MF, *TRI, *Info);
3617 } else if (!IsGraphics) {
3618 // For the fixed ABI, pass workitem IDs in the last argument register.
3619 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
3620
3621 // FIXME: Sink this into allocateSpecialInputSGPRs
3622 if (!Subtarget->hasFlatScratchEnabled())
3623 CCInfo.AllocateReg(Info->getScratchRSrcReg());
3624
3625 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
3626 }
3627
3628 if (!IsKernel) {
3629 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
3630 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
3631
3632 // This assumes the registers are allocated by CCInfo in ascending order
3633 // with no gaps.
3634 Info->setNumWaveDispatchSGPRs(
3635 CCInfo.getFirstUnallocated(AMDGPU::SGPR_32RegClass.getRegisters()));
3636 Info->setNumWaveDispatchVGPRs(
3637 CCInfo.getFirstUnallocated(AMDGPU::VGPR_32RegClass.getRegisters()));
3638 } else if (Info->getNumKernargPreloadedSGPRs()) {
3639 Info->setNumWaveDispatchSGPRs(Info->getNumUserSGPRs());
3640 }
3641
3643
3644 if (IsWholeWaveFunc) {
3645 SDValue Setup = DAG.getNode(AMDGPUISD::WHOLE_WAVE_SETUP, DL,
3646 {MVT::i1, MVT::Other}, Chain);
3647 InVals.push_back(Setup.getValue(0));
3648 Chains.push_back(Setup.getValue(1));
3649 }
3650
3651 // FIXME: This is the minimum kernel argument alignment. We should improve
3652 // this to the maximum alignment of the arguments.
3653 //
3654 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
3655 // kern arg offset.
3656 const Align KernelArgBaseAlign = Align(16);
3657
3658 for (unsigned i = IsWholeWaveFunc ? 1 : 0, e = Ins.size(), ArgIdx = 0; i != e;
3659 ++i) {
3660 const ISD::InputArg &Arg = Ins[i];
3661 if ((Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) || IsError) {
3662 InVals.push_back(DAG.getPOISON(Arg.VT));
3663 continue;
3664 }
3665
3666 CCValAssign &VA = ArgLocs[ArgIdx++];
3667 MVT VT = VA.getLocVT();
3668
3669 if (IsEntryFunc && VA.isMemLoc()) {
3670 VT = Ins[i].VT;
3671 EVT MemVT = VA.getLocVT();
3672
3673 const uint64_t Offset = VA.getLocMemOffset();
3674 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
3675
3676 if (Arg.Flags.isByRef()) {
3677 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
3678
3679 const GCNTargetMachine &TM =
3680 static_cast<const GCNTargetMachine &>(getTargetMachine());
3681 if (!TM.isNoopAddrSpaceCast(DAG.getDataLayout(),
3683 Arg.Flags.getPointerAddrSpace())) {
3686 }
3687
3688 InVals.push_back(Ptr);
3689 continue;
3690 }
3691
3692 SDValue NewArg;
3693 if (Arg.isOrigArg() && Info->getArgInfo().PreloadKernArgs.count(i)) {
3694 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
3695 // In this case the argument is packed into the previous preload SGPR.
3696 int64_t AlignDownOffset = alignDown(Offset, 4);
3697 int64_t OffsetDiff = Offset - AlignDownOffset;
3698 EVT IntVT = MemVT.changeTypeToInteger();
3699
3700 const SIMachineFunctionInfo *Info =
3703 Register Reg =
3704 Info->getArgInfo().PreloadKernArgs.find(i)->getSecond().Regs[0];
3705
3706 assert(Reg);
3707 Register VReg = MRI.getLiveInVirtReg(Reg);
3708 SDValue Copy = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i32);
3709
3710 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, DL, MVT::i32);
3711 SDValue Extract = DAG.getNode(ISD::SRL, DL, MVT::i32, Copy, ShiftAmt);
3712
3713 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, Extract);
3714 ArgVal = DAG.getNode(ISD::BITCAST, DL, MemVT, ArgVal);
3715 NewArg = convertArgType(DAG, VT, MemVT, DL, ArgVal,
3716 Ins[i].Flags.isSExt(), &Ins[i]);
3717
3718 NewArg = DAG.getMergeValues({NewArg, Copy.getValue(1)}, DL);
3719 } else {
3720 const SIMachineFunctionInfo *Info =
3723 const SmallVectorImpl<MCRegister> &PreloadRegs =
3724 Info->getArgInfo().PreloadKernArgs.find(i)->getSecond().Regs;
3725
3726 SDValue Copy;
3727 if (PreloadRegs.size() == 1) {
3728 Register VReg = MRI.getLiveInVirtReg(PreloadRegs[0]);
3729 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
3730 NewArg = DAG.getCopyFromReg(
3731 Chain, DL, VReg,
3733 TRI->getRegSizeInBits(*RC)));
3734
3735 } else {
3736 // If the kernarg alignment does not match the alignment of the SGPR
3737 // tuple RC that can accommodate this argument, it will be built up
3738 // via copies from from the individual SGPRs that the argument was
3739 // preloaded to.
3741 for (auto Reg : PreloadRegs) {
3742 Register VReg = MRI.getLiveInVirtReg(Reg);
3743 Copy = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i32);
3744 Elts.push_back(Copy);
3745 }
3746 NewArg =
3747 DAG.getBuildVector(EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3748 PreloadRegs.size()),
3749 DL, Elts);
3750 }
3751
3752 // If the argument was preloaded to multiple consecutive 32-bit
3753 // registers because of misalignment between addressable SGPR tuples
3754 // and the argument size, we can still assume that because of kernarg
3755 // segment alignment restrictions that NewArg's size is the same as
3756 // MemVT and just do a bitcast. If MemVT is less than 32-bits we add a
3757 // truncate since we cannot preload to less than a single SGPR and the
3758 // MemVT may be smaller.
3759 EVT MemVTInt =
3761 if (MemVT.bitsLT(NewArg.getSimpleValueType()))
3762 NewArg = DAG.getNode(ISD::TRUNCATE, DL, MemVTInt, NewArg);
3763
3764 NewArg = DAG.getBitcast(MemVT, NewArg);
3765 NewArg = convertArgType(DAG, VT, MemVT, DL, NewArg,
3766 Ins[i].Flags.isSExt(), &Ins[i]);
3767 NewArg = DAG.getMergeValues({NewArg, Chain}, DL);
3768 }
3769 } else {
3770 // Hidden arguments that are in the kernel signature must be preloaded
3771 // to user SGPRs. Print a diagnostic error if a hidden argument is in
3772 // the argument list and is not preloaded.
3773 if (Arg.isOrigArg()) {
3774 Argument *OrigArg = Fn.getArg(Arg.getOrigArgIndex());
3775 if (OrigArg->hasAttribute("amdgpu-hidden-argument")) {
3777 *OrigArg->getParent(),
3778 "hidden argument in kernel signature was not preloaded",
3779 DL.getDebugLoc()));
3780 }
3781 }
3782
3783 NewArg =
3784 lowerKernargMemParameter(DAG, VT, MemVT, DL, Chain, Offset,
3785 Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
3786 }
3787 Chains.push_back(NewArg.getValue(1));
3788
3789 auto *ParamTy =
3790 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
3791 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
3792 ParamTy &&
3793 (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
3794 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
3795 // On SI local pointers are just offsets into LDS, so they are always
3796 // less than 16-bits. On CI and newer they could potentially be
3797 // real pointers, so we can't guarantee their size.
3798 NewArg = DAG.getNode(ISD::AssertZext, DL, NewArg.getValueType(), NewArg,
3799 DAG.getValueType(MVT::i16));
3800 }
3801
3802 InVals.push_back(NewArg);
3803 continue;
3804 }
3805 if (!IsEntryFunc && VA.isMemLoc()) {
3806 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
3807 InVals.push_back(Val);
3808 if (!Arg.Flags.isByVal())
3809 Chains.push_back(Val.getValue(1));
3810 continue;
3811 }
3812
3813 assert(VA.isRegLoc() && "Parameter must be in a register!");
3814
3815 Register Reg = VA.getLocReg();
3816 const TargetRegisterClass *RC = nullptr;
3817 if (AMDGPU::VGPR_32RegClass.contains(Reg))
3818 RC = &AMDGPU::VGPR_32RegClass;
3819 else if (AMDGPU::SGPR_32RegClass.contains(Reg))
3820 RC = &AMDGPU::SGPR_32RegClass;
3821 else
3822 llvm_unreachable("Unexpected register class in LowerFormalArguments!");
3823
3824 Reg = MF.addLiveIn(Reg, RC);
3825 bool CopyAsI32 =
3826 VT.getSizeInBits() == 16 &&
3827 (RC == &AMDGPU::SGPR_32RegClass || !Subtarget->useRealTrue16Insts());
3828 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, CopyAsI32 ? MVT::i32 : VT);
3829 if (Arg.Flags.isInReg() && RC == &AMDGPU::VGPR_32RegClass) {
3830 // FIXME: Need to forward the chains created by `CopyFromReg`s, make sure
3831 // they will read physical regs before any side effect instructions.
3832 SDValue ReadFirstLane =
3833 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
3835 ReadFirstLane, Val);
3836 }
3837
3838 if (CopyAsI32)
3839 Val = DAG.getBitcast(VT, DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val));
3840
3841 if (Arg.Flags.isSRet()) {
3842 // The return object should be reasonably addressable.
3843 Val = annotateStackObjectPointer(Val, DAG, DL,
3845 }
3846
3847 Val = convertABITypeToValueType(DAG, Val, VA, DL);
3848 InVals.push_back(Val);
3849 }
3850
3851 // Start adding system SGPRs.
3852 if (IsEntryFunc)
3853 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
3854
3855 unsigned StackArgSize = CCInfo.getStackSize();
3856 Info->setBytesInStackArgArea(StackArgSize);
3857
3858 return Chains.empty() ? Chain
3859 : DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3860}
3861
3862// TODO: If return values can't fit in registers, we should return as many as
3863// possible in registers before passing on stack.
3865 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
3866 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context,
3867 const Type *RetTy) const {
3868 // Replacing returns with sret/stack usage doesn't make sense for shaders.
3869 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
3870 // for shaders. Vector types should be explicitly handled by CC.
3871 if (AMDGPU::isEntryFunctionCC(CallConv))
3872 return true;
3873
3875 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3876 if (!CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)))
3877 return false;
3878
3879 // We must use the stack if return would require unavailable registers.
3880 unsigned MaxNumVGPRs = Subtarget->getMaxNumVGPRs(MF);
3881 unsigned TotalNumVGPRs = Subtarget->getAddressableNumArchVGPRs();
3882 for (unsigned i = MaxNumVGPRs; i < TotalNumVGPRs; ++i)
3883 if (CCInfo.isAllocated(AMDGPU::VGPR_32RegClass.getRegister(i)))
3884 return false;
3885
3886 return true;
3887}
3888
3889SDValue
3891 bool isVarArg,
3893 const SmallVectorImpl<SDValue> &OutVals,
3894 const SDLoc &DL, SelectionDAG &DAG) const {
3898
3899 if (AMDGPU::isKernel(CallConv)) {
3900 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
3901 OutVals, DL, DAG);
3902 }
3903
3904 bool IsShader = AMDGPU::isShader(CallConv);
3905
3906 Info->setIfReturnsVoid(Outs.empty());
3907 bool IsWaveEnd = Info->returnsVoid() && IsShader;
3908
3909 // CCValAssign - represent the assignment of the return value to a location.
3911
3912 // CCState - Info about the registers and stack slots.
3913 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3914 *DAG.getContext());
3915
3916 // Analyze outgoing return values.
3917 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3918
3919 SDValue Glue;
3921 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3922
3923 SDValue ReadFirstLane =
3924 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
3925 // Copy the result values into the output registers.
3926 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
3927 ++I, ++RealRVLocIdx) {
3928 CCValAssign &VA = RVLocs[I];
3929 assert(VA.isRegLoc() && "Can only return in registers!");
3930 // TODO: Partially return in registers if return values don't fit.
3931 SDValue Arg = OutVals[RealRVLocIdx];
3932
3933 // Copied from other backends.
3934 switch (VA.getLocInfo()) {
3935 case CCValAssign::Full:
3936 break;
3937 case CCValAssign::BCvt:
3938 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3939 break;
3940 case CCValAssign::SExt:
3941 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3942 break;
3943 case CCValAssign::ZExt:
3944 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3945 break;
3946 case CCValAssign::AExt:
3947 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3948 break;
3949 default:
3950 llvm_unreachable("Unknown loc info!");
3951 }
3952 if (TRI->isSGPRPhysReg(VA.getLocReg()))
3954 ReadFirstLane, Arg);
3955 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Glue);
3956 Glue = Chain.getValue(1);
3957 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3958 }
3959
3960 // FIXME: Does sret work properly?
3961 if (!Info->isEntryFunction()) {
3962 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
3963 const MCPhysReg *I =
3964 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3965 if (I) {
3966 for (; *I; ++I) {
3967 if (AMDGPU::SReg_64RegClass.contains(*I))
3968 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3969 else if (AMDGPU::SReg_32RegClass.contains(*I))
3970 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3971 else
3972 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3973 }
3974 }
3975 }
3976
3977 // Update chain and glue.
3978 RetOps[0] = Chain;
3979 if (Glue.getNode())
3980 RetOps.push_back(Glue);
3981
3982 unsigned Opc = AMDGPUISD::ENDPGM;
3983 if (!IsWaveEnd)
3984 Opc = Info->isWholeWaveFunction() ? AMDGPUISD::WHOLE_WAVE_RETURN
3985 : IsShader ? AMDGPUISD::RETURN_TO_EPILOG
3986 : AMDGPUISD::RET_GLUE;
3987 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
3988}
3989
3991 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
3992 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3993 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
3994 SDValue ThisVal) const {
3995 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
3996
3997 // Assign locations to each value returned by this call.
3999 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
4000 *DAG.getContext());
4001 CCInfo.AnalyzeCallResult(Ins, RetCC);
4002
4003 // Copy all of the result registers out of their specified physreg.
4004 for (CCValAssign VA : RVLocs) {
4005 SDValue Val;
4006
4007 if (VA.isRegLoc()) {
4008 Val =
4009 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InGlue);
4010 Chain = Val.getValue(1);
4011 InGlue = Val.getValue(2);
4012 } else if (VA.isMemLoc()) {
4013 report_fatal_error("TODO: return values in memory");
4014 } else
4015 llvm_unreachable("unknown argument location type");
4016
4017 switch (VA.getLocInfo()) {
4018 case CCValAssign::Full:
4019 break;
4020 case CCValAssign::BCvt:
4021 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
4022 break;
4023 case CCValAssign::ZExt:
4024 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
4025 DAG.getValueType(VA.getValVT()));
4026 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
4027 break;
4028 case CCValAssign::SExt:
4029 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
4030 DAG.getValueType(VA.getValVT()));
4031 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
4032 break;
4033 case CCValAssign::AExt:
4034 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
4035 break;
4036 default:
4037 llvm_unreachable("Unknown loc info!");
4038 }
4039
4040 InVals.push_back(Val);
4041 }
4042
4043 return Chain;
4044}
4045
4046// Add code to pass special inputs required depending on used features separate
4047// from the explicit user arguments present in the IR.
4049 CallLoweringInfo &CLI, CCState &CCInfo, const SIMachineFunctionInfo &Info,
4050 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4051 SmallVectorImpl<SDValue> &MemOpChains, SDValue Chain) const {
4052 // If we don't have a call site, this was a call inserted by
4053 // legalization. These can never use special inputs.
4054 if (!CLI.CB)
4055 return;
4056
4057 SelectionDAG &DAG = CLI.DAG;
4058 const SDLoc &DL = CLI.DL;
4059 const Function &F = DAG.getMachineFunction().getFunction();
4060
4061 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4062 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
4063
4064 const AMDGPUFunctionArgInfo &CalleeArgInfo =
4066
4067 // TODO: Unify with private memory register handling. This is complicated by
4068 // the fact that at least in kernels, the input argument is not necessarily
4069 // in the same location as the input.
4070 // clang-format off
4071 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
4072 std::array<StringLiteral, 2>> ImplicitAttrs[] = {
4073 {AMDGPUFunctionArgInfo::DISPATCH_PTR, {"amdgpu-no-dispatch-ptr", ""}},
4074 {AMDGPUFunctionArgInfo::QUEUE_PTR, {"amdgpu-no-queue-ptr", ""}},
4075 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, {"amdgpu-no-implicitarg-ptr", ""}},
4076 {AMDGPUFunctionArgInfo::DISPATCH_ID, {"amdgpu-no-dispatch-id", ""}},
4077 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, {"amdgpu-no-workgroup-id-x", "amdgpu-no-cluster-id-x"}},
4078 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, {"amdgpu-no-workgroup-id-y", "amdgpu-no-cluster-id-y"}},
4079 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, {"amdgpu-no-workgroup-id-z", "amdgpu-no-cluster-id-z"}},
4080 {AMDGPUFunctionArgInfo::LDS_KERNEL_ID, {"amdgpu-no-lds-kernel-id", ""}},
4081 };
4082 // clang-format on
4083
4084 for (auto [InputID, Attrs] : ImplicitAttrs) {
4085 // If the callee does not use the attribute value, skip copying the value.
4086 if (all_of(Attrs, [&](StringRef Attr) {
4087 return Attr.empty() || CLI.CB->hasFnAttr(Attr);
4088 }))
4089 continue;
4090
4091 const auto [OutgoingArg, ArgRC, ArgTy] =
4092 CalleeArgInfo.getPreloadedValue(InputID);
4093 if (!OutgoingArg)
4094 continue;
4095
4096 const auto [IncomingArg, IncomingArgRC, Ty] =
4097 CallerArgInfo.getPreloadedValue(InputID);
4098 assert(IncomingArgRC == ArgRC);
4099
4100 // All special arguments are ints for now.
4101 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
4102 SDValue InputReg;
4103
4104 if (IncomingArg) {
4105 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
4106 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
4107 // The implicit arg ptr is special because it doesn't have a corresponding
4108 // input for kernels, and is computed from the kernarg segment pointer.
4109 InputReg = getImplicitArgPtr(DAG, DL);
4110 } else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {
4111 std::optional<uint32_t> Id =
4113 if (Id.has_value()) {
4114 InputReg = DAG.getConstant(*Id, DL, ArgVT);
4115 } else {
4116 InputReg = DAG.getPOISON(ArgVT);
4117 }
4118 } else {
4119 // We may have proven the input wasn't needed, although the ABI is
4120 // requiring it. We just need to allocate the register appropriately.
4121 InputReg = DAG.getPOISON(ArgVT);
4122 }
4123
4124 if (OutgoingArg->isRegister()) {
4125 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
4126 if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
4127 report_fatal_error("failed to allocate implicit input argument");
4128 } else {
4129 unsigned SpecialArgOffset =
4130 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
4131 SDValue ArgStore =
4132 storeStackInputValue(DAG, DL, Chain, InputReg, SpecialArgOffset);
4133 MemOpChains.push_back(ArgStore);
4134 }
4135 }
4136
4137 // Pack workitem IDs into a single register or pass it as is if already
4138 // packed.
4139
4140 auto [OutgoingArg, ArgRC, Ty] =
4142 if (!OutgoingArg)
4143 std::tie(OutgoingArg, ArgRC, Ty) =
4145 if (!OutgoingArg)
4146 std::tie(OutgoingArg, ArgRC, Ty) =
4148 if (!OutgoingArg)
4149 return;
4150
4151 const ArgDescriptor *IncomingArgX = std::get<0>(
4153 const ArgDescriptor *IncomingArgY = std::get<0>(
4155 const ArgDescriptor *IncomingArgZ = std::get<0>(
4157
4158 SDValue InputReg;
4159 SDLoc SL;
4160
4161 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
4162 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
4163 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
4164
4165 // If incoming ids are not packed we need to pack them.
4166 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX &&
4167 NeedWorkItemIDX) {
4168 if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
4169 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
4170 } else {
4171 InputReg = DAG.getConstant(0, DL, MVT::i32);
4172 }
4173 }
4174
4175 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY &&
4176 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
4177 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
4178 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
4179 DAG.getShiftAmountConstant(10, MVT::i32, SL));
4180 InputReg = InputReg.getNode()
4181 ? DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y)
4182 : Y;
4183 }
4184
4185 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ &&
4186 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
4187 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
4188 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
4189 DAG.getShiftAmountConstant(20, MVT::i32, SL));
4190 InputReg = InputReg.getNode()
4191 ? DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z)
4192 : Z;
4193 }
4194
4195 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
4196 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
4197 // We're in a situation where the outgoing function requires the workitem
4198 // ID, but the calling function does not have it (e.g a graphics function
4199 // calling a C calling convention function). This is illegal, but we need
4200 // to produce something.
4201 InputReg = DAG.getPOISON(MVT::i32);
4202 } else {
4203 // Workitem ids are already packed, any of present incoming arguments
4204 // will carry all required fields.
4205 ArgDescriptor IncomingArg =
4206 ArgDescriptor::createArg(IncomingArgX ? *IncomingArgX
4207 : IncomingArgY ? *IncomingArgY
4208 : *IncomingArgZ,
4209 ~0u);
4210 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
4211 }
4212 }
4213
4214 if (OutgoingArg->isRegister()) {
4215 if (InputReg)
4216 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
4217
4218 CCInfo.AllocateReg(OutgoingArg->getRegister());
4219 } else {
4220 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
4221 if (InputReg) {
4222 SDValue ArgStore =
4223 storeStackInputValue(DAG, DL, Chain, InputReg, SpecialArgOffset);
4224 MemOpChains.push_back(ArgStore);
4225 }
4226 }
4227}
4228
4230 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
4232 const SmallVectorImpl<SDValue> &OutVals,
4233 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4234 if (AMDGPU::isChainCC(CalleeCC))
4235 return true;
4236
4237 if (!AMDGPU::mayTailCallThisCC(CalleeCC))
4238 return false;
4239
4240 // For a divergent call target, we need to do a waterfall loop over the
4241 // possible callees which precludes us from using a simple jump.
4242 if (Callee->isDivergent())
4243 return false;
4244
4246 const Function &CallerF = MF.getFunction();
4247 CallingConv::ID CallerCC = CallerF.getCallingConv();
4249 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4250
4251 // Kernels aren't callable, and don't have a live in return address so it
4252 // doesn't make sense to do a tail call with entry functions.
4253 if (!CallerPreserved)
4254 return false;
4255
4256 bool CCMatch = CallerCC == CalleeCC;
4257
4259 if (AMDGPU::canGuaranteeTCO(CalleeCC) && CCMatch)
4260 return true;
4261 return false;
4262 }
4263
4264 // TODO: Can we handle var args?
4265 if (IsVarArg)
4266 return false;
4267
4268 for (const Argument &Arg : CallerF.args()) {
4269 if (Arg.hasByValAttr())
4270 return false;
4271 }
4272
4273 LLVMContext &Ctx = *DAG.getContext();
4274
4275 // Check that the call results are passed in the same way.
4276 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
4277 CCAssignFnForCall(CalleeCC, IsVarArg),
4278 CCAssignFnForCall(CallerCC, IsVarArg)))
4279 return false;
4280
4281 // The callee has to preserve all registers the caller needs to preserve.
4282 if (!CCMatch) {
4283 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4284 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4285 return false;
4286 }
4287
4288 // Nothing more to check if the callee is taking no arguments.
4289 if (Outs.empty())
4290 return true;
4291
4293 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
4294
4295 // FIXME: We are not allocating special input registers, so we will be
4296 // deciding based on incorrect register assignments.
4297 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
4298
4299 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
4300 // If the stack arguments for this call do not fit into our own save area then
4301 // the call cannot be made tail.
4302 // TODO: Is this really necessary?
4303 if (CCInfo.getStackSize() > FuncInfo->getBytesInStackArgArea())
4304 return false;
4305
4306 for (const auto &[CCVA, ArgVal] : zip_equal(ArgLocs, OutVals)) {
4307 // FIXME: What about inreg arguments that end up passed in memory?
4308 if (!CCVA.isRegLoc())
4309 continue;
4310
4311 // If we are passing an argument in an SGPR, and the value is divergent,
4312 // this call requires a waterfall loop.
4313 if (ArgVal->isDivergent() && TRI->isSGPRPhysReg(CCVA.getLocReg())) {
4314 LLVM_DEBUG(
4315 dbgs() << "Cannot tail call due to divergent outgoing argument in "
4316 << printReg(CCVA.getLocReg(), TRI) << '\n');
4317 return false;
4318 }
4319 }
4320
4321 const MachineRegisterInfo &MRI = MF.getRegInfo();
4322 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
4323}
4324
4326 if (!CI->isTailCall())
4327 return false;
4328
4329 const Function *ParentFn = CI->getFunction();
4331 return false;
4332 return true;
4333}
4334
4335namespace {
4336// Chain calls have special arguments that we need to handle. These are
4337// tagging along at the end of the arguments list(s), after the SGPR and VGPR
4338// arguments (index 0 and 1 respectively).
4339enum ChainCallArgIdx {
4340 Exec = 2,
4341 Flags,
4342 NumVGPRs,
4343 FallbackExec,
4344 FallbackCallee
4345};
4346} // anonymous namespace
4347
4348// The wave scratch offset register is used as the global base pointer.
4350 SmallVectorImpl<SDValue> &InVals) const {
4351 CallingConv::ID CallConv = CLI.CallConv;
4352 bool IsChainCallConv = AMDGPU::isChainCC(CallConv);
4353
4354 SelectionDAG &DAG = CLI.DAG;
4355
4356 const SDLoc &DL = CLI.DL;
4357 SDValue Chain = CLI.Chain;
4358 SDValue Callee = CLI.Callee;
4359
4360 llvm::SmallVector<SDValue, 6> ChainCallSpecialArgs;
4361 bool UsesDynamicVGPRs = false;
4362 if (IsChainCallConv) {
4363 // The last arguments should be the value that we need to put in EXEC,
4364 // followed by the flags and any other arguments with special meanings.
4365 // Pop them out of CLI.Outs and CLI.OutVals before we do any processing so
4366 // we don't treat them like the "real" arguments.
4367 auto RequestedExecIt =
4368 llvm::find_if(CLI.Outs, [](const ISD::OutputArg &Arg) {
4369 return Arg.OrigArgIndex == 2;
4370 });
4371 assert(RequestedExecIt != CLI.Outs.end() && "No node for EXEC");
4372
4373 size_t SpecialArgsBeginIdx = RequestedExecIt - CLI.Outs.begin();
4374 CLI.OutVals.erase(CLI.OutVals.begin() + SpecialArgsBeginIdx,
4375 CLI.OutVals.end());
4376 CLI.Outs.erase(RequestedExecIt, CLI.Outs.end());
4377
4378 assert(CLI.Outs.back().OrigArgIndex < 2 &&
4379 "Haven't popped all the special args");
4380
4381 TargetLowering::ArgListEntry RequestedExecArg =
4382 CLI.Args[ChainCallArgIdx::Exec];
4383 if (!RequestedExecArg.Ty->isIntegerTy(Subtarget->getWavefrontSize()))
4384 return lowerUnhandledCall(CLI, InVals, "Invalid value for EXEC");
4385
4386 // Convert constants into TargetConstants, so they become immediate operands
4387 // instead of being selected into S_MOV.
4388 auto PushNodeOrTargetConstant = [&](TargetLowering::ArgListEntry Arg) {
4389 if (const auto *ArgNode = dyn_cast<ConstantSDNode>(Arg.Node)) {
4390 ChainCallSpecialArgs.push_back(DAG.getTargetConstant(
4391 ArgNode->getAPIntValue(), DL, ArgNode->getValueType(0)));
4392 } else
4393 ChainCallSpecialArgs.push_back(Arg.Node);
4394 };
4395
4396 PushNodeOrTargetConstant(RequestedExecArg);
4397
4398 // Process any other special arguments depending on the value of the flags.
4399 TargetLowering::ArgListEntry Flags = CLI.Args[ChainCallArgIdx::Flags];
4400
4401 const APInt &FlagsValue = cast<ConstantSDNode>(Flags.Node)->getAPIntValue();
4402 if (FlagsValue.isZero()) {
4403 if (CLI.Args.size() > ChainCallArgIdx::Flags + 1)
4404 return lowerUnhandledCall(CLI, InVals,
4405 "no additional args allowed if flags == 0");
4406 } else if (FlagsValue.isOneBitSet(0)) {
4407 if (CLI.Args.size() != ChainCallArgIdx::FallbackCallee + 1) {
4408 return lowerUnhandledCall(CLI, InVals, "expected 3 additional args");
4409 }
4410
4411 if (!Subtarget->isWave32()) {
4412 return lowerUnhandledCall(
4413 CLI, InVals, "dynamic VGPR mode is only supported for wave32");
4414 }
4415
4416 UsesDynamicVGPRs = true;
4417 std::for_each(CLI.Args.begin() + ChainCallArgIdx::NumVGPRs,
4418 CLI.Args.end(), PushNodeOrTargetConstant);
4419 }
4420 }
4421
4423 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4425 bool &IsTailCall = CLI.IsTailCall;
4426 bool IsVarArg = CLI.IsVarArg;
4427 bool IsSibCall = false;
4429
4430 if (Callee.isUndef() || isNullConstant(Callee)) {
4431 if (!CLI.IsTailCall) {
4432 for (ISD::InputArg &Arg : CLI.Ins)
4433 InVals.push_back(DAG.getPOISON(Arg.VT));
4434 }
4435
4436 return Chain;
4437 }
4438
4439 if (IsVarArg) {
4440 return lowerUnhandledCall(CLI, InVals,
4441 "unsupported call to variadic function ");
4442 }
4443
4444 if (!CLI.CB)
4445 return lowerUnhandledCall(CLI, InVals, "unsupported libcall legalization");
4446
4447 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
4448 return lowerUnhandledCall(CLI, InVals,
4449 "unsupported required tail call to function ");
4450 }
4451
4452 if (IsTailCall) {
4453 IsTailCall = isEligibleForTailCallOptimization(Callee, CallConv, IsVarArg,
4454 Outs, OutVals, Ins, DAG);
4455 if (!IsTailCall &&
4456 ((CLI.CB && CLI.CB->isMustTailCall()) || IsChainCallConv)) {
4457 report_fatal_error("failed to perform tail call elimination on a call "
4458 "site marked musttail or on llvm.amdgcn.cs.chain");
4459 }
4460
4461 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4462
4463 // A sibling call is one where we're under the usual C ABI and not planning
4464 // to change that but can still do a tail call:
4465 if (!TailCallOpt && IsTailCall)
4466 IsSibCall = true;
4467
4468 if (IsTailCall)
4469 ++NumTailCalls;
4470 }
4471
4474 SmallVector<SDValue, 8> MemOpChains;
4475
4476 // Analyze operands of the call, assigning locations to each operand.
4478 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
4479 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
4480
4481 if (CallConv != CallingConv::AMDGPU_Gfx && !AMDGPU::isChainCC(CallConv) &&
4483 // With a fixed ABI, allocate fixed registers before user arguments.
4484 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
4485 }
4486
4487 // Mark the scratch resource descriptor as allocated so the CC analysis
4488 // does not assign user arguments to these registers, matching the callee.
4489 if (!Subtarget->hasFlatScratchEnabled()) {
4490 CCInfo.AllocateReg(
4492 }
4493
4494 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
4495
4496 // Get a count of how many bytes are to be pushed on the stack.
4497 unsigned NumBytes = CCInfo.getStackSize();
4498
4499 if (IsSibCall) {
4500 // Since we're not changing the ABI to make this a tail call, the memory
4501 // operands are already available in the caller's incoming argument space.
4502 NumBytes = 0;
4503 }
4504
4505 // FPDiff is the byte offset of the call's argument area from the callee's.
4506 // Stores to callee stack arguments will be placed in FixedStackSlots offset
4507 // by this amount for a tail call. In a sibling call it must be 0 because the
4508 // caller will deallocate the entire stack and the callee still expects its
4509 // arguments to begin at SP+0. Completely unused for non-tail calls.
4510 int32_t FPDiff = 0;
4511 MachineFrameInfo &MFI = MF.getFrameInfo();
4512 auto *TRI = Subtarget->getRegisterInfo();
4513
4514 // Adjust the stack pointer for the new arguments...
4515 // These operations are automatically eliminated by the prolog/epilog pass
4516 if (!IsSibCall)
4517 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
4518
4519 if (!IsSibCall || IsChainCallConv) {
4520 if (!Subtarget->hasFlatScratchEnabled()) {
4521 SmallVector<SDValue, 4> CopyFromChains;
4522
4523 // In the HSA case, this should be an identity copy.
4524 SDValue ScratchRSrcReg =
4525 DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
4526 RegsToPass.emplace_back(
4528 ScratchRSrcReg);
4529 CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
4530 Chain = DAG.getTokenFactor(DL, CopyFromChains);
4531 }
4532 }
4533
4534 const unsigned NumSpecialInputs = RegsToPass.size();
4535
4536 MVT PtrVT = MVT::i32;
4537
4538 // Walk the register/memloc assignments, inserting copies/loads.
4539 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4540 CCValAssign &VA = ArgLocs[i];
4541 SDValue Arg = OutVals[i];
4542
4543 // Promote the value if needed.
4544 switch (VA.getLocInfo()) {
4545 case CCValAssign::Full:
4546 break;
4547 case CCValAssign::BCvt:
4548 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4549 break;
4550 case CCValAssign::ZExt:
4551 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4552 break;
4553 case CCValAssign::SExt:
4554 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4555 break;
4556 case CCValAssign::AExt:
4557 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4558 break;
4559 case CCValAssign::FPExt:
4560 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4561 break;
4562 default:
4563 llvm_unreachable("Unknown loc info!");
4564 }
4565
4566 if (VA.isRegLoc()) {
4567 RegsToPass.push_back(std::pair(VA.getLocReg(), Arg));
4568 } else {
4569 assert(VA.isMemLoc());
4570
4571 SDValue DstAddr;
4572 MachinePointerInfo DstInfo;
4573
4574 unsigned LocMemOffset = VA.getLocMemOffset();
4575 int32_t Offset = LocMemOffset;
4576
4577 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
4578 MaybeAlign Alignment;
4579
4580 if (IsTailCall) {
4581 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4582 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize()
4583 : VA.getValVT().getStoreSize();
4584
4585 // FIXME: We can have better than the minimum byval required alignment.
4586 Alignment =
4587 Flags.isByVal()
4588 ? Flags.getNonZeroByValAlign()
4589 : commonAlignment(Subtarget->getStackAlignment(), Offset);
4590
4591 Offset = Offset + FPDiff;
4592 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
4593
4594 DstAddr = DAG.getFrameIndex(FI, PtrVT);
4595 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
4596
4597 // Make sure any stack arguments overlapping with where we're storing
4598 // are loaded before this eventual operation. Otherwise they'll be
4599 // clobbered.
4600
4601 // FIXME: Why is this really necessary? This seems to just result in a
4602 // lot of code to copy the stack and write them back to the same
4603 // locations, which are supposed to be immutable?
4604 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
4605 } else {
4606 // Stores to the argument stack area are relative to the stack pointer.
4607 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
4608 MVT::i32);
4609 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
4610 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
4611 Alignment =
4612 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
4613 }
4614
4615 if (Outs[i].Flags.isByVal()) {
4616 SDValue SizeNode =
4617 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
4618 SDValue Cpy =
4619 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
4620 Outs[i].Flags.getNonZeroByValAlign(),
4621 Outs[i].Flags.getNonZeroByValAlign(),
4622 /*isVol = */ false, /*AlwaysInline = */ true,
4623 /*CI=*/nullptr, std::nullopt, DstInfo,
4625
4626 MemOpChains.push_back(Cpy);
4627 } else {
4628 SDValue Store =
4629 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
4630 MemOpChains.push_back(Store);
4631 }
4632 }
4633 }
4634
4635 if (!MemOpChains.empty())
4636 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4637
4638 SDValue ReadFirstLaneID =
4639 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
4640
4641 SDValue TokenGlue;
4642 if (CLI.ConvergenceControlToken) {
4643 TokenGlue = DAG.getNode(ISD::CONVERGENCECTRL_GLUE, DL, MVT::Glue,
4645 }
4646
4647 // Build a sequence of copy-to-reg nodes chained together with token chain
4648 // and flag operands which copy the outgoing args into the appropriate regs.
4649 SDValue InGlue;
4650
4651 unsigned ArgIdx = 0;
4652 for (auto [Reg, Val] : RegsToPass) {
4653 if (ArgIdx++ >= NumSpecialInputs &&
4654 (IsChainCallConv || !Val->isDivergent()) && TRI->isSGPRPhysReg(Reg)) {
4655 // For chain calls, the inreg arguments are required to be
4656 // uniform. Speculatively Insert a readfirstlane in case we cannot prove
4657 // they are uniform.
4658 //
4659 // For other calls, if an inreg arguments is known to be uniform,
4660 // speculatively insert a readfirstlane in case it is in a VGPR.
4661 //
4662 // FIXME: We need to execute this in a waterfall loop if it is a divergent
4663 // value, so let that continue to produce invalid code.
4664
4665 SmallVector<SDValue, 3> ReadfirstlaneArgs({ReadFirstLaneID, Val});
4666 if (TokenGlue)
4667 ReadfirstlaneArgs.push_back(TokenGlue);
4669 ReadfirstlaneArgs);
4670 }
4671
4672 Chain = DAG.getCopyToReg(Chain, DL, Reg, Val, InGlue);
4673 InGlue = Chain.getValue(1);
4674 }
4675
4676 // We don't usually want to end the call-sequence here because we would tidy
4677 // the frame up *after* the call, however in the ABI-changing tail-call case
4678 // we've carefully laid out the parameters so that when sp is reset they'll be
4679 // in the correct location.
4680 if (IsTailCall && !IsSibCall) {
4681 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, DL);
4682 InGlue = Chain.getValue(1);
4683 }
4684
4685 std::vector<SDValue> Ops({Chain});
4686
4687 // Add a redundant copy of the callee global which will not be legalized, as
4688 // we need direct access to the callee later.
4690 const GlobalValue *GV = GSD->getGlobal();
4691 Ops.push_back(Callee);
4692 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
4693 } else {
4694 if (IsTailCall) {
4695 // isEligibleForTailCallOptimization considered whether the call target is
4696 // divergent, but we may still end up with a uniform value in a VGPR.
4697 // Insert a readfirstlane just in case.
4698 SDValue ReadFirstLaneID =
4699 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
4700
4701 SmallVector<SDValue, 3> ReadfirstlaneArgs({ReadFirstLaneID, Callee});
4702 if (TokenGlue)
4703 ReadfirstlaneArgs.push_back(TokenGlue); // Wire up convergence token.
4704 Callee = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Callee.getValueType(),
4705 ReadfirstlaneArgs);
4706 }
4707
4708 Ops.push_back(Callee);
4709 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
4710 }
4711
4712 if (IsTailCall) {
4713 // Each tail call may have to adjust the stack by a different amount, so
4714 // this information must travel along with the operation for eventual
4715 // consumption by emitEpilogue.
4716 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4717 }
4718
4719 if (IsChainCallConv)
4720 llvm::append_range(Ops, ChainCallSpecialArgs);
4721
4722 // Add argument registers to the end of the list so that they are known live
4723 // into the call.
4724 for (auto &[Reg, Val] : RegsToPass)
4725 Ops.push_back(DAG.getRegister(Reg, Val.getValueType()));
4726
4727 // Add a register mask operand representing the call-preserved registers.
4728 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
4729 assert(Mask && "Missing call preserved mask for calling convention");
4730 Ops.push_back(DAG.getRegisterMask(Mask));
4731
4732 if (SDValue Token = CLI.ConvergenceControlToken) {
4734 GlueOps.push_back(Token);
4735 if (InGlue)
4736 GlueOps.push_back(InGlue);
4737
4738 InGlue = SDValue(DAG.getMachineNode(TargetOpcode::CONVERGENCECTRL_GLUE, DL,
4739 MVT::Glue, GlueOps),
4740 0);
4741 }
4742
4743 if (InGlue)
4744 Ops.push_back(InGlue);
4745
4746 // If we're doing a tall call, use a TC_RETURN here rather than an
4747 // actual call instruction.
4748 if (IsTailCall) {
4749 MFI.setHasTailCall();
4750 unsigned OPC = AMDGPUISD::TC_RETURN;
4751 switch (CallConv) {
4753 OPC = AMDGPUISD::TC_RETURN_GFX;
4754 break;
4757 OPC = UsesDynamicVGPRs ? AMDGPUISD::TC_RETURN_CHAIN_DVGPR
4758 : AMDGPUISD::TC_RETURN_CHAIN;
4759 break;
4760 }
4761
4762 // If the caller is a whole wave function, we need to use a special opcode
4763 // so we can patch up EXEC.
4764 if (Info->isWholeWaveFunction())
4765 OPC = AMDGPUISD::TC_RETURN_GFX_WholeWave;
4766
4767 SDValue Ret = DAG.getNode(OPC, DL, MVT::Other, Ops);
4768 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
4769 return Ret;
4770 }
4771
4772 // Returns a chain and a flag for retval copy to use.
4773 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, {MVT::Other, MVT::Glue}, Ops);
4774 DAG.addNoMergeSiteInfo(Call.getNode(), CLI.NoMerge);
4775 Chain = Call.getValue(0);
4776 InGlue = Call.getValue(1);
4777
4778 uint64_t CalleePopBytes = NumBytes;
4779 Chain = DAG.getCALLSEQ_END(Chain, 0, CalleePopBytes, InGlue, DL);
4780 if (!Ins.empty())
4781 InGlue = Chain.getValue(1);
4782
4783 // Handle result values, copying them out of physregs into vregs that we
4784 // return.
4785 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
4786 InVals, /*IsThisReturn=*/false, SDValue());
4787}
4788
4789// This is similar to the default implementation in ExpandDYNAMIC_STACKALLOC,
4790// except for:
4791// 1. Stack growth direction(default: downwards, AMDGPU: upwards), and
4792// 2. Scale size where, scale = wave-reduction(alloca-size) * wave-size
4794 SelectionDAG &DAG) const {
4795 const MachineFunction &MF = DAG.getMachineFunction();
4797
4798 SDLoc dl(Op);
4799 EVT VT = Op.getValueType();
4800 SDValue Chain = Op.getOperand(0);
4801 Register SPReg = Info->getStackPtrOffsetReg();
4802
4803 // Chain the dynamic stack allocation so that it doesn't modify the stack
4804 // pointer when other instructions are using the stack.
4805 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
4806
4807 SDValue Size = Op.getOperand(1);
4808 SDValue BaseAddr = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
4809 Align Alignment = cast<ConstantSDNode>(Op.getOperand(2))->getAlignValue();
4810
4811 const TargetFrameLowering *TFL = Subtarget->getFrameLowering();
4813 "Stack grows upwards for AMDGPU");
4814
4815 Chain = BaseAddr.getValue(1);
4816 // When using flat-scratch, the stack offset is unscaled.
4817 const bool HasFlatScratch = Subtarget->hasFlatScratchEnabled();
4818 const unsigned WavefrontSizeLog2 = Subtarget->getWavefrontSizeLog2();
4819
4820 Align StackAlign = TFL->getStackAlign();
4821 if (Alignment > StackAlign) {
4822 uint64_t ScaledAlignment = Alignment.value()
4823 << (HasFlatScratch ? 0 : WavefrontSizeLog2);
4824 uint64_t StackAlignMask = ScaledAlignment - 1;
4825 SDValue TmpAddr = DAG.getNode(ISD::ADD, dl, VT, BaseAddr,
4826 DAG.getConstant(StackAlignMask, dl, VT));
4827 BaseAddr = DAG.getNode(ISD::AND, dl, VT, TmpAddr,
4828 DAG.getSignedConstant(-ScaledAlignment, dl, VT));
4829 }
4830
4831 assert(Size.getValueType() == MVT::i32 && "Size must be 32-bit");
4832 SDValue NewSP;
4834 // Increase the stack pointer by the size of the alloca.
4835 // If not using flat-scratch, we have to scale the size by the wave-size.
4836 SDValue ScaledSize =
4837 HasFlatScratch
4838 ? Size
4839 : DAG.getNode(ISD::SHL, dl, VT, Size,
4840 DAG.getConstant(WavefrontSizeLog2, dl, MVT::i32));
4841 NewSP = DAG.getNode(ISD::ADD, dl, VT, BaseAddr, ScaledSize); // Value
4842 } else {
4843 // For dynamic sized alloca, perform wave-wide reduction to get max of
4844 // alloca size(divergent), and then scale it (when not using flat-scratch)
4845 // by wave-size.
4846 SDValue WaveReduction =
4847 DAG.getTargetConstant(Intrinsic::amdgcn_wave_reduce_umax, dl, MVT::i32);
4848 Size = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, WaveReduction,
4849 Size, DAG.getTargetConstant(0, dl, MVT::i32));
4850 SDValue ScaledSize = Size;
4851 if (!HasFlatScratch) {
4852 ScaledSize =
4853 DAG.getNode(ISD::SHL, dl, VT, Size,
4854 DAG.getConstant(WavefrontSizeLog2, dl, MVT::i32));
4855 }
4856 NewSP =
4857 DAG.getNode(ISD::ADD, dl, VT, BaseAddr, ScaledSize); // Value in vgpr.
4858 SDValue ReadFirstLaneID =
4859 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, dl, MVT::i32);
4860 NewSP = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, ReadFirstLaneID,
4861 NewSP);
4862 }
4863
4864 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP); // Output chain
4865 SDValue CallSeqEnd = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
4866
4867 return DAG.getMergeValues({BaseAddr, CallSeqEnd}, dl);
4868}
4869
4871 if (Op.getValueType() != MVT::i32)
4872 return Op; // Defer to cannot select error.
4873
4875 SDLoc SL(Op);
4876
4877 SDValue CopyFromSP = DAG.getCopyFromReg(Op->getOperand(0), SL, SP, MVT::i32);
4878
4879 // Convert from wave uniform to swizzled vector address. This should protect
4880 // from any edge cases where the stacksave result isn't directly used with
4881 // stackrestore.
4882 SDValue VectorAddress =
4883 DAG.getNode(AMDGPUISD::WAVE_ADDRESS, SL, MVT::i32, CopyFromSP);
4884 return DAG.getMergeValues({VectorAddress, CopyFromSP.getValue(1)}, SL);
4885}
4886
4888 SelectionDAG &DAG) const {
4889 SDLoc SL(Op);
4890 assert(Op.getValueType() == MVT::i32);
4891
4892 uint32_t BothRoundHwReg =
4894 SDValue GetRoundBothImm = DAG.getTargetConstant(BothRoundHwReg, SL, MVT::i32);
4895
4896 SDValue IntrinID =
4897 DAG.getTargetConstant(Intrinsic::amdgcn_s_getreg, SL, MVT::i32);
4898 SDValue GetReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, Op->getVTList(),
4899 Op.getOperand(0), IntrinID, GetRoundBothImm);
4900
4901 // There are two rounding modes, one for f32 and one for f64/f16. We only
4902 // report in the standard value range if both are the same.
4903 //
4904 // The raw values also differ from the expected FLT_ROUNDS values. Nearest
4905 // ties away from zero is not supported, and the other values are rotated by
4906 // 1.
4907 //
4908 // If the two rounding modes are not the same, report a target defined value.
4909
4910 // Mode register rounding mode fields:
4911 //
4912 // [1:0] Single-precision round mode.
4913 // [3:2] Double/Half-precision round mode.
4914 //
4915 // 0=nearest even; 1= +infinity; 2= -infinity, 3= toward zero.
4916 //
4917 // Hardware Spec
4918 // Toward-0 3 0
4919 // Nearest Even 0 1
4920 // +Inf 1 2
4921 // -Inf 2 3
4922 // NearestAway0 N/A 4
4923 //
4924 // We have to handle 16 permutations of a 4-bit value, so we create a 64-bit
4925 // table we can index by the raw hardware mode.
4926 //
4927 // (trunc (FltRoundConversionTable >> MODE.fp_round)) & 0xf
4928
4929 SDValue BitTable =
4931
4932 SDValue Two = DAG.getConstant(2, SL, MVT::i32);
4933 SDValue RoundModeTimesNumBits =
4934 DAG.getNode(ISD::SHL, SL, MVT::i32, GetReg, Two);
4935
4936 // TODO: We could possibly avoid a 64-bit shift and use a simpler table if we
4937 // knew only one mode was demanded.
4938 SDValue TableValue =
4939 DAG.getNode(ISD::SRL, SL, MVT::i64, BitTable, RoundModeTimesNumBits);
4940 SDValue TruncTable = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, TableValue);
4941
4942 SDValue EntryMask = DAG.getConstant(0xf, SL, MVT::i32);
4943 SDValue TableEntry =
4944 DAG.getNode(ISD::AND, SL, MVT::i32, TruncTable, EntryMask);
4945
4946 // There's a gap in the 4-bit encoded table and actual enum values, so offset
4947 // if it's an extended value.
4948 SDValue Four = DAG.getConstant(4, SL, MVT::i32);
4949 SDValue IsStandardValue =
4950 DAG.getSetCC(SL, MVT::i1, TableEntry, Four, ISD::SETULT);
4951 SDValue EnumOffset = DAG.getNode(ISD::ADD, SL, MVT::i32, TableEntry, Four);
4952 SDValue Result = DAG.getNode(ISD::SELECT, SL, MVT::i32, IsStandardValue,
4953 TableEntry, EnumOffset);
4954
4955 return DAG.getMergeValues({Result, GetReg.getValue(1)}, SL);
4956}
4957
4959 SelectionDAG &DAG) const {
4960 SDLoc SL(Op);
4961
4962 SDValue NewMode = Op.getOperand(1);
4963 assert(NewMode.getValueType() == MVT::i32);
4964
4965 // Index a table of 4-bit entries mapping from the C FLT_ROUNDS values to the
4966 // hardware MODE.fp_round values.
4967 if (auto *ConstMode = dyn_cast<ConstantSDNode>(NewMode)) {
4968 uint32_t ClampedVal = std::min(
4969 static_cast<uint32_t>(ConstMode->getZExtValue()),
4971 NewMode = DAG.getConstant(
4972 AMDGPU::decodeFltRoundToHWConversionTable(ClampedVal), SL, MVT::i32);
4973 } else {
4974 // If we know the input can only be one of the supported standard modes in
4975 // the range 0-3, we can use a simplified mapping to hardware values.
4976 KnownBits KB = DAG.computeKnownBits(NewMode);
4977 const bool UseReducedTable = KB.countMinLeadingZeros() >= 30;
4978 // The supported standard values are 0-3. The extended values start at 8. We
4979 // need to offset by 4 if the value is in the extended range.
4980
4981 if (UseReducedTable) {
4982 // Truncate to the low 32-bits.
4983 SDValue BitTable = DAG.getConstant(
4984 AMDGPU::FltRoundToHWConversionTable & 0xffff, SL, MVT::i32);
4985
4986 SDValue Two = DAG.getConstant(2, SL, MVT::i32);
4987 SDValue RoundModeTimesNumBits =
4988 DAG.getNode(ISD::SHL, SL, MVT::i32, NewMode, Two);
4989
4990 NewMode =
4991 DAG.getNode(ISD::SRL, SL, MVT::i32, BitTable, RoundModeTimesNumBits);
4992
4993 // TODO: SimplifyDemandedBits on the setreg source here can likely reduce
4994 // the table extracted bits into inline immediates.
4995 } else {
4996 // table_index = umin(value, value - 4)
4997 // MODE.fp_round = (bit_table >> (table_index << 2)) & 0xf
4998 SDValue BitTable =
5000
5001 SDValue Four = DAG.getConstant(4, SL, MVT::i32);
5002 SDValue OffsetEnum = DAG.getNode(ISD::SUB, SL, MVT::i32, NewMode, Four);
5003 SDValue IndexVal =
5004 DAG.getNode(ISD::UMIN, SL, MVT::i32, NewMode, OffsetEnum);
5005
5006 SDValue Two = DAG.getConstant(2, SL, MVT::i32);
5007 SDValue RoundModeTimesNumBits =
5008 DAG.getNode(ISD::SHL, SL, MVT::i32, IndexVal, Two);
5009
5010 SDValue TableValue =
5011 DAG.getNode(ISD::SRL, SL, MVT::i64, BitTable, RoundModeTimesNumBits);
5012 SDValue TruncTable = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, TableValue);
5013
5014 // No need to mask out the high bits since the setreg will ignore them
5015 // anyway.
5016 NewMode = TruncTable;
5017 }
5018
5019 // Insert a readfirstlane in case the value is a VGPR. We could do this
5020 // earlier and keep more operations scalar, but that interferes with
5021 // combining the source.
5022 SDValue ReadFirstLaneID =
5023 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, SL, MVT::i32);
5024 NewMode = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
5025 ReadFirstLaneID, NewMode);
5026 }
5027
5028 // N.B. The setreg will be later folded into s_round_mode on supported
5029 // targets.
5030 SDValue IntrinID =
5031 DAG.getTargetConstant(Intrinsic::amdgcn_s_setreg, SL, MVT::i32);
5032 uint32_t BothRoundHwReg =
5034 SDValue RoundBothImm = DAG.getTargetConstant(BothRoundHwReg, SL, MVT::i32);
5035
5036 SDValue SetReg =
5037 DAG.getNode(ISD::INTRINSIC_VOID, SL, Op->getVTList(), Op.getOperand(0),
5038 IntrinID, RoundBothImm, NewMode);
5039
5040 return SetReg;
5041}
5042
5044 unsigned AS = cast<MemSDNode>(Op)->getAddressSpace();
5045 if (AS == AMDGPUAS::BUFFER_RESOURCE)
5046 return Op.getOperand(0);
5048 return SDValue();
5049
5050 // I$ prefetch
5051 if (!Subtarget->hasSafeSmemPrefetch() && !Op.getConstantOperandVal(4))
5052 return SDValue();
5053
5054 // Prefetch the 64-bit address that a 32-bit constant pointer is cast to, as
5055 // a load does.
5056 SDValue Ptr = Op.getOperand(1);
5057 if (Ptr.getValueType() != MVT::i32)
5058 return Op;
5060 Ops[1] = DAG.getAddrSpaceCast(SDLoc(Op), MVT::i64, Ptr,
5063 return SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops), 0);
5064}
5065
5066// Work around DAG legality rules only based on the result type.
5068 bool IsStrict = Op.getOpcode() == ISD::STRICT_FP_EXTEND;
5069 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
5070 EVT SrcVT = Src.getValueType();
5071
5072 if (SrcVT.getScalarType() != MVT::bf16)
5073 return Op;
5074
5075 SDLoc SL(Op);
5076 SDValue BitCast =
5077 DAG.getNode(ISD::BITCAST, SL, SrcVT.changeTypeToInteger(), Src);
5078
5079 EVT DstVT = Op.getValueType();
5080 if (IsStrict)
5081 llvm_unreachable("Need STRICT_BF16_TO_FP");
5082
5083 return DAG.getNode(ISD::BF16_TO_FP, SL, DstVT, BitCast);
5084}
5085
5087 SDLoc SL(Op);
5088 if (Op.getValueType() != MVT::i64)
5089 return Op;
5090
5091 uint32_t ModeHwReg =
5093 SDValue ModeHwRegImm = DAG.getTargetConstant(ModeHwReg, SL, MVT::i32);
5094 uint32_t TrapHwReg =
5096 SDValue TrapHwRegImm = DAG.getTargetConstant(TrapHwReg, SL, MVT::i32);
5097
5098 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::Other);
5099 SDValue IntrinID =
5100 DAG.getTargetConstant(Intrinsic::amdgcn_s_getreg, SL, MVT::i32);
5101 SDValue GetModeReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, VTList,
5102 Op.getOperand(0), IntrinID, ModeHwRegImm);
5103 SDValue GetTrapReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, VTList,
5104 Op.getOperand(0), IntrinID, TrapHwRegImm);
5105 SDValue TokenReg =
5106 DAG.getNode(ISD::TokenFactor, SL, MVT::Other, GetModeReg.getValue(1),
5107 GetTrapReg.getValue(1));
5108
5109 SDValue CvtPtr =
5110 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, GetModeReg, GetTrapReg);
5111 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5112
5113 return DAG.getMergeValues({Result, TokenReg}, SL);
5114}
5115
5117 SDLoc SL(Op);
5118 if (Op.getOperand(1).getValueType() != MVT::i64)
5119 return Op;
5120
5121 SDValue Input = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op.getOperand(1));
5122 SDValue NewModeReg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Input,
5123 DAG.getConstant(0, SL, MVT::i32));
5124 SDValue NewTrapReg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Input,
5125 DAG.getConstant(1, SL, MVT::i32));
5126
5127 SDValue ReadFirstLaneID =
5128 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, SL, MVT::i32);
5129 NewModeReg = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
5130 ReadFirstLaneID, NewModeReg);
5131 NewTrapReg = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
5132 ReadFirstLaneID, NewTrapReg);
5133
5134 unsigned ModeHwReg =
5136 SDValue ModeHwRegImm = DAG.getTargetConstant(ModeHwReg, SL, MVT::i32);
5137 unsigned TrapHwReg =
5139 SDValue TrapHwRegImm = DAG.getTargetConstant(TrapHwReg, SL, MVT::i32);
5140
5141 SDValue IntrinID =
5142 DAG.getTargetConstant(Intrinsic::amdgcn_s_setreg, SL, MVT::i32);
5143 SDValue SetModeReg =
5144 DAG.getNode(ISD::INTRINSIC_VOID, SL, MVT::Other, Op.getOperand(0),
5145 IntrinID, ModeHwRegImm, NewModeReg);
5146 SDValue SetTrapReg =
5147 DAG.getNode(ISD::INTRINSIC_VOID, SL, MVT::Other, Op.getOperand(0),
5148 IntrinID, TrapHwRegImm, NewTrapReg);
5149 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, SetTrapReg, SetModeReg);
5150}
5151
5153 const MachineFunction &MF) const {
5154 Register Reg =
5156 .Case("m0", AMDGPU::M0)
5157 .Case("exec", AMDGPU::EXEC)
5158 .Case("exec_lo", AMDGPU::EXEC_LO)
5159 .Case("exec_hi", AMDGPU::EXEC_HI)
5160 .Case("flat_scratch", AMDGPU::FLAT_SCR)
5161 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
5162 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
5163 .Case("src_flat_scratch_base", AMDGPU::SRC_FLAT_SCRATCH_BASE)
5164 .Case("src_flat_scratch_base_lo", AMDGPU::SRC_FLAT_SCRATCH_BASE_LO)
5165 .Case("src_flat_scratch_base_hi", AMDGPU::SRC_FLAT_SCRATCH_BASE_HI)
5166 .Default(Register());
5167 if (!Reg)
5168 return Reg;
5169
5170 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
5171 if (!Subtarget->hasFlatScrRegister() &&
5172 TRI->regsOverlap(Reg, AMDGPU::FLAT_SCR))
5173 return Register();
5174
5175 if (!Subtarget->hasGloballyAddressableScratch() &&
5176 TRI->regsOverlap(Reg, AMDGPU::SRC_FLAT_SCRATCH_BASE))
5177 return Register();
5178
5179 switch (Reg) {
5180 case AMDGPU::M0:
5181 case AMDGPU::EXEC_LO:
5182 case AMDGPU::EXEC_HI:
5183 case AMDGPU::FLAT_SCR_LO:
5184 case AMDGPU::FLAT_SCR_HI:
5185 case AMDGPU::SRC_FLAT_SCRATCH_BASE_LO:
5186 case AMDGPU::SRC_FLAT_SCRATCH_BASE_HI:
5187 if (VT.getSizeInBits() == 32)
5188 return Reg;
5189 break;
5190 case AMDGPU::EXEC:
5191 case AMDGPU::FLAT_SCR:
5192 case AMDGPU::SRC_FLAT_SCRATCH_BASE:
5193 if (VT.getSizeInBits() == 64)
5194 return Reg;
5195 break;
5196 default:
5197 llvm_unreachable("missing register type checking");
5198 }
5199
5201 Twine("invalid type for register \"" + StringRef(RegName) + "\"."));
5202}
5203
5204// If kill is not the last instruction, split the block so kill is always a
5205// proper terminator.
5208 MachineBasicBlock *BB) const {
5209 MachineBasicBlock *SplitBB = BB->splitAt(MI, /*UpdateLiveIns=*/true);
5211 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
5212 return SplitBB;
5213}
5214
5215// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
5216// \p MI will be the only instruction in the loop body block. Otherwise, it will
5217// be the first instruction in the remainder block.
5218//
5219/// \returns { LoopBody, Remainder }
5220static std::pair<MachineBasicBlock *, MachineBasicBlock *>
5222 MachineFunction *MF = MBB.getParent();
5224
5225 // To insert the loop we need to split the block. Move everything after this
5226 // point to a new block, and insert a new empty block between the two.
5228 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
5230 ++MBBI;
5231
5232 MF->insert(MBBI, LoopBB);
5233 MF->insert(MBBI, RemainderBB);
5234
5235 LoopBB->addSuccessor(LoopBB);
5236 LoopBB->addSuccessor(RemainderBB);
5237
5238 // Move the rest of the block into a new block.
5239 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
5240
5241 if (InstInLoop) {
5242 auto Next = std::next(I);
5243
5244 // Move instruction to loop body.
5245 LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
5246
5247 // Move the rest of the block.
5248 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
5249 } else {
5250 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
5251 }
5252
5253 MBB.addSuccessor(LoopBB);
5254
5255 return std::pair(LoopBB, RemainderBB);
5256}
5257
5258/// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
5260 MachineBasicBlock *MBB = MI.getParent();
5262 auto I = MI.getIterator();
5263 auto E = std::next(I);
5264
5265 // clang-format off
5266 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
5267 .addImm(0);
5268 // clang-format on
5269
5270 MIBundleBuilder Bundler(*MBB, I, E);
5271 finalizeBundle(*MBB, Bundler.begin());
5272}
5273
5276 MachineBasicBlock *BB) const {
5277 const DebugLoc &DL = MI.getDebugLoc();
5278
5280
5282
5283 // Apparently kill flags are only valid if the def is in the same block?
5284 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
5285 Src->setIsKill(false);
5286
5287 auto [LoopBB, RemainderBB] = splitBlockForLoop(MI, *BB, true);
5288
5289 MachineBasicBlock::iterator I = LoopBB->end();
5290
5291 const unsigned EncodedReg = AMDGPU::Hwreg::HwregEncoding::encode(
5293
5294 // Clear TRAP_STS.MEM_VIOL
5295 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
5296 .addImm(0)
5297 .addImm(EncodedReg);
5298
5300
5301 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5302
5303 // Load and check TRAP_STS.MEM_VIOL
5304 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
5305 .addImm(EncodedReg);
5306
5307 // clang-format off
5308 // FIXME: Do we need to use an isel pseudo that may clobber scc?
5309 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
5310 .addReg(Reg)
5311 .addImm(0);
5312 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
5313 .addMBB(LoopBB);
5314 // clang-format on
5315
5316 return RemainderBB;
5317}
5318
5319// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
5320// wavefront. If the value is uniform and just happens to be in a VGPR, this
5321// will only do one iteration. In the worst case, this will loop 64 times.
5322//
5323// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
5326 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
5327 const DebugLoc &DL, const MachineOperand &Idx,
5328 unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
5329 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
5330 Register &SGPRIdxReg) {
5331
5332 MachineFunction *MF = OrigBB.getParent();
5333 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5334 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5337
5338 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
5339 Register PhiExec = MRI.createVirtualRegister(BoolRC);
5340 Register NewExec = MRI.createVirtualRegister(BoolRC);
5341 Register CurrentIdxReg =
5342 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5343 Register CondReg = MRI.createVirtualRegister(BoolRC);
5344
5345 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
5346 .addReg(InitReg)
5347 .addMBB(&OrigBB)
5348 .addReg(ResultReg)
5349 .addMBB(&LoopBB);
5350
5351 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
5352 .addReg(InitSaveExecReg)
5353 .addMBB(&OrigBB)
5354 .addReg(NewExec)
5355 .addMBB(&LoopBB);
5356
5357 // Read the next variant <- also loop target.
5358 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
5359 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
5360
5361 // Compare the just read M0 value to all possible Idx values.
5362 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
5363 .addReg(CurrentIdxReg)
5364 .addReg(Idx.getReg(), {}, Idx.getSubReg());
5365
5366 // Update EXEC, save the original EXEC value to VCC.
5367 BuildMI(LoopBB, I, DL, TII->get(LMC.AndSaveExecOpc), NewExec)
5368 .addReg(CondReg)
5369 .setOperandDead(3); // Dead scc
5370
5371 MRI.setSimpleHint(NewExec, CondReg);
5372
5373 if (UseGPRIdxMode) {
5374 if (Offset == 0) {
5375 SGPRIdxReg = CurrentIdxReg;
5376 } else {
5377 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5378 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
5379 .addReg(CurrentIdxReg)
5380 .addImm(Offset)
5381 .setOperandDead(3); // Dead scc
5382 }
5383 } else {
5384 // Move index from VCC into M0
5385 if (Offset == 0) {
5386 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::COPY), AMDGPU::M0)
5387 .addReg(CurrentIdxReg);
5388 } else {
5389 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
5390 .addReg(CurrentIdxReg)
5391 .addImm(Offset)
5392 .setOperandDead(3); // Dead scc
5393 }
5394 }
5395
5396 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
5397 MachineInstr *InsertPt =
5398 BuildMI(LoopBB, I, DL, TII->get(LMC.XorTermOpc), LMC.ExecReg)
5399 .addReg(LMC.ExecReg)
5400 .addReg(NewExec)
5401 .setOperandDead(3); // Dead scc
5402
5403 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
5404 // s_cbranch_scc0?
5405
5406 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
5407 // clang-format off
5408 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
5409 .addMBB(&LoopBB);
5410 // clang-format on
5411
5412 return InsertPt->getIterator();
5413}
5414
5415// This has slightly sub-optimal regalloc when the source vector is killed by
5416// the read. The register allocator does not understand that the kill is
5417// per-workitem, so is kept alive for the whole loop so we end up not re-using a
5418// subregister from it, using 1 more VGPR than necessary. This was saved when
5419// this was expanded after register allocation.
5422 unsigned InitResultReg, unsigned PhiReg, int Offset,
5423 bool UseGPRIdxMode, Register &SGPRIdxReg) {
5424 MachineFunction *MF = MBB.getParent();
5425 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5426 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5428 const DebugLoc &DL = MI.getDebugLoc();
5430
5431 const auto *BoolXExecRC = TRI->getWaveMaskRegClass();
5432 Register DstReg = MI.getOperand(0).getReg();
5433 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5434 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
5436
5437 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
5438
5439 // Save the EXEC mask
5440 // clang-format off
5441 BuildMI(MBB, I, DL, TII->get(LMC.MovOpc), SaveExec)
5442 .addReg(LMC.ExecReg);
5443 // clang-format on
5444
5445 auto [LoopBB, RemainderBB] = splitBlockForLoop(MI, MBB, false);
5446
5447 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5448
5449 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
5450 InitResultReg, DstReg, PhiReg, TmpExec,
5451 Offset, UseGPRIdxMode, SGPRIdxReg);
5452
5453 MachineBasicBlock *LandingPad = MF->CreateMachineBasicBlock();
5455 ++MBBI;
5456 MF->insert(MBBI, LandingPad);
5457 LoopBB->removeSuccessor(RemainderBB);
5458 LandingPad->addSuccessor(RemainderBB);
5459 LoopBB->addSuccessor(LandingPad);
5460 MachineBasicBlock::iterator First = LandingPad->begin();
5461 // clang-format off
5462 BuildMI(*LandingPad, First, DL, TII->get(LMC.MovOpc), LMC.ExecReg)
5463 .addReg(SaveExec);
5464 // clang-format on
5465
5466 return InsPt;
5467}
5468
5469// Returns subreg index, offset
5470static std::pair<unsigned, int>
5472 const TargetRegisterClass *SuperRC, unsigned VecReg,
5473 int Offset) {
5474 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
5475
5476 // Skip out of bounds offsets, or else we would end up using an undefined
5477 // register.
5478 if (Offset >= NumElts || Offset < 0)
5479 return std::pair(AMDGPU::sub0, Offset);
5480
5481 return std::pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
5482}
5483
5486 int Offset) {
5487 MachineBasicBlock *MBB = MI.getParent();
5488 const DebugLoc &DL = MI.getDebugLoc();
5490
5491 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5492
5493 assert(Idx->getReg() != AMDGPU::NoRegister);
5494
5495 if (Offset == 0) {
5496 // clang-format off
5497 BuildMI(*MBB, I, DL, TII->get(AMDGPU::COPY), AMDGPU::M0)
5498 .add(*Idx);
5499 // clang-format on
5500 } else {
5501 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
5502 .add(*Idx)
5503 .addImm(Offset)
5504 .setOperandDead(3); // Dead scc
5505 }
5506}
5507
5510 int Offset) {
5511 MachineBasicBlock *MBB = MI.getParent();
5512 const DebugLoc &DL = MI.getDebugLoc();
5514
5515 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5516
5517 if (Offset == 0)
5518 return Idx->getReg();
5519
5520 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5521 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
5522 .add(*Idx)
5523 .addImm(Offset)
5524 .setOperandDead(3); // Dead scc
5525 return Tmp;
5526}
5527
5530 const GCNSubtarget &ST) {
5531 const SIInstrInfo *TII = ST.getInstrInfo();
5532 const SIRegisterInfo &TRI = TII->getRegisterInfo();
5533 MachineFunction *MF = MBB.getParent();
5535
5536 Register Dst = MI.getOperand(0).getReg();
5537 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5538 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
5539 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
5540
5541 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
5542 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
5543
5544 unsigned SubReg;
5545 std::tie(SubReg, Offset) =
5546 computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
5547
5548 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
5549
5550 // Check for a SGPR index.
5551 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
5553 const DebugLoc &DL = MI.getDebugLoc();
5554
5555 if (UseGPRIdxMode) {
5556 // TODO: Look at the uses to avoid the copy. This may require rescheduling
5557 // to avoid interfering with other uses, so probably requires a new
5558 // optimization pass.
5560
5561 const MCInstrDesc &GPRIDXDesc =
5562 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
5563 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
5564 .addReg(SrcReg)
5565 .addReg(Idx)
5566 .addImm(SubReg);
5567 } else {
5569
5570 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
5571 .addReg(SrcReg, {}, SubReg)
5572 .addReg(SrcReg, RegState::Implicit);
5573 }
5574
5575 MI.eraseFromParent();
5576
5577 return &MBB;
5578 }
5579
5580 // Control flow needs to be inserted if indexing with a VGPR.
5581 const DebugLoc &DL = MI.getDebugLoc();
5583
5584 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5585 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5586
5587 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
5588
5589 Register SGPRIdxReg;
5590 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
5591 UseGPRIdxMode, SGPRIdxReg);
5592
5593 MachineBasicBlock *LoopBB = InsPt->getParent();
5594
5595 if (UseGPRIdxMode) {
5596 const MCInstrDesc &GPRIDXDesc =
5597 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
5598
5599 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
5600 .addReg(SrcReg)
5601 .addReg(SGPRIdxReg)
5602 .addImm(SubReg);
5603 } else {
5604 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
5605 .addReg(SrcReg, {}, SubReg)
5606 .addReg(SrcReg, RegState::Implicit);
5607 }
5608
5609 MI.eraseFromParent();
5610
5611 return LoopBB;
5612}
5613
5616 const GCNSubtarget &ST) {
5617 const SIInstrInfo *TII = ST.getInstrInfo();
5618 const SIRegisterInfo &TRI = TII->getRegisterInfo();
5619 MachineFunction *MF = MBB.getParent();
5621
5622 Register Dst = MI.getOperand(0).getReg();
5623 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
5624 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5625 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
5626 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
5627 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
5628 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
5629
5630 // This can be an immediate, but will be folded later.
5631 assert(Val->getReg());
5632
5633 unsigned SubReg;
5634 std::tie(SubReg, Offset) =
5635 computeIndirectRegAndOffset(TRI, VecRC, SrcVec->getReg(), Offset);
5636 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
5637
5638 if (Idx->getReg() == AMDGPU::NoRegister) {
5640 const DebugLoc &DL = MI.getDebugLoc();
5641
5642 assert(Offset == 0);
5643
5644 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
5645 .add(*SrcVec)
5646 .add(*Val)
5647 .addImm(SubReg);
5648
5649 MI.eraseFromParent();
5650 return &MBB;
5651 }
5652
5653 // Check for a SGPR index.
5654 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
5656 const DebugLoc &DL = MI.getDebugLoc();
5657
5658 if (UseGPRIdxMode) {
5660
5661 const MCInstrDesc &GPRIDXDesc =
5662 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
5663 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
5664 .addReg(SrcVec->getReg())
5665 .add(*Val)
5666 .addReg(Idx)
5667 .addImm(SubReg);
5668 } else {
5670
5671 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
5672 TRI.getRegSizeInBits(*VecRC), 32, false);
5673 BuildMI(MBB, I, DL, MovRelDesc, Dst)
5674 .addReg(SrcVec->getReg())
5675 .add(*Val)
5676 .addImm(SubReg);
5677 }
5678 MI.eraseFromParent();
5679 return &MBB;
5680 }
5681
5682 // Control flow needs to be inserted if indexing with a VGPR.
5683 const DebugLoc &DL = MI.getDebugLoc();
5684
5685 Register PhiReg = MRI.createVirtualRegister(VecRC);
5686
5687 Register SGPRIdxReg;
5688 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
5689 UseGPRIdxMode, SGPRIdxReg);
5690 MachineBasicBlock *LoopBB = InsPt->getParent();
5691
5692 if (UseGPRIdxMode) {
5693 const MCInstrDesc &GPRIDXDesc =
5694 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
5695
5696 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
5697 .addReg(PhiReg)
5698 .add(*Val)
5699 .addReg(SGPRIdxReg)
5700 .addImm(SubReg);
5701 } else {
5702 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
5703 TRI.getRegSizeInBits(*VecRC), 32, false);
5704 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
5705 .addReg(PhiReg)
5706 .add(*Val)
5707 .addImm(SubReg);
5708 }
5709
5710 MI.eraseFromParent();
5711 return LoopBB;
5712}
5713
5715 MachineBasicBlock *BB) {
5716 // For targets older than GFX12, we emit a sequence of 32-bit operations.
5717 // For GFX12, we emit s_add_u64 and s_sub_u64.
5718 MachineFunction *MF = BB->getParent();
5719 const SIInstrInfo *TII = MF->getSubtarget<GCNSubtarget>().getInstrInfo();
5720 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5722 const DebugLoc &DL = MI.getDebugLoc();
5723 MachineOperand &Dest = MI.getOperand(0);
5724 MachineOperand &Src0 = MI.getOperand(1);
5725 MachineOperand &Src1 = MI.getOperand(2);
5726 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
5727 if (ST.hasScalarAddSub64()) {
5728 // FIXME: If scc is used, this deletes the def
5729 unsigned Opc = IsAdd ? AMDGPU::S_ADD_U64 : AMDGPU::S_SUB_U64;
5730 // clang-format off
5731 BuildMI(*BB, MI, DL, TII->get(Opc), Dest.getReg())
5732 .add(Src0)
5733 .add(Src1);
5734 // clang-format on
5735 } else {
5736 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5737 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
5738
5739 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5740 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5741
5742 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
5743 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
5744 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
5745 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
5746
5747 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
5748 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
5749 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
5750 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
5751
5752 const MachineOperand &ImpDefSCC = MI.getOperand(3);
5753 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
5754
5755 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
5756 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
5757 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
5758 auto Hi = BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
5759 .add(Src0Sub1)
5760 .add(Src1Sub1);
5761 if (ImpDefSCC.isDead())
5762 Hi.setOperandDead(3);
5763 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
5764 .addReg(DestSub0)
5765 .addImm(AMDGPU::sub0)
5766 .addReg(DestSub1)
5767 .addImm(AMDGPU::sub1);
5768 }
5769 MI.eraseFromParent();
5770 return BB;
5771}
5772
5774 MachineFunction *MF = BB->getParent();
5775 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5776 const SIInstrInfo *TII = ST.getInstrInfo();
5777 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5779 const DebugLoc &DL = MI.getDebugLoc();
5780 Register Dst = MI.getOperand(0).getReg();
5781 const MachineOperand &Src0 = MI.getOperand(1);
5782 const MachineOperand &Src1 = MI.getOperand(2);
5783 Register SrcCond = MI.getOperand(3).getReg();
5784
5785 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5786 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5787 const TargetRegisterClass *CondRC = TRI->getWaveMaskRegClass();
5788 Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
5789
5790 int Src0Idx =
5791 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
5792 int Src1Idx =
5793 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src1);
5794 const TargetRegisterClass *Src0RC =
5795 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), Src0Idx));
5796 const TargetRegisterClass *Src1RC =
5797 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), Src1Idx));
5798
5799 const TargetRegisterClass *Src0SubRC =
5800 TRI->getSubRegisterClass(Src0RC, AMDGPU::sub0);
5801 const TargetRegisterClass *Src1SubRC =
5802 TRI->getSubRegisterClass(Src1RC, AMDGPU::sub1);
5803
5804 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
5805 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
5806 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
5807 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
5808
5809 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
5810 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
5811 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
5812 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
5813
5814 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy).addReg(SrcCond);
5815 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
5816 .addImm(0)
5817 .add(Src0Sub0)
5818 .addImm(0)
5819 .add(Src1Sub0)
5820 .addReg(SrcCondCopy);
5821
5822 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
5823 .addImm(0)
5824 .add(Src0Sub1)
5825 .addImm(0)
5826 .add(Src1Sub1)
5827 .addReg(SrcCondCopy);
5828
5829 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
5830 .addReg(DstLo)
5831 .addImm(AMDGPU::sub0)
5832 .addReg(DstHi)
5833 .addImm(AMDGPU::sub1);
5834 MI.eraseFromParent();
5835}
5836
5838 switch (Opc) {
5839 case AMDGPU::S_MIN_U32:
5840 return std::numeric_limits<uint32_t>::max();
5841 case AMDGPU::S_MIN_I32:
5842 return std::numeric_limits<int32_t>::max();
5843 case AMDGPU::S_MAX_U32:
5844 return std::numeric_limits<uint32_t>::min();
5845 case AMDGPU::S_MAX_I32:
5846 return std::numeric_limits<int32_t>::min();
5847 case AMDGPU::V_ADD_F32_e64: // -0.0
5848 return 0x80000000;
5849 case AMDGPU::V_SUB_F32_e64: // +0.0
5850 return 0x0;
5851 case AMDGPU::S_ADD_I32:
5852 case AMDGPU::S_SUB_I32:
5853 case AMDGPU::S_OR_B32:
5854 case AMDGPU::S_XOR_B32:
5855 return std::numeric_limits<uint32_t>::min();
5856 case AMDGPU::S_AND_B32:
5857 return std::numeric_limits<uint32_t>::max();
5858 case AMDGPU::V_MIN_F32_e64:
5859 case AMDGPU::V_MAX_F32_e64:
5860 return 0x7fc00000; // qNAN
5861 case AMDGPU::V_CMP_LT_U64_e64: // umin.u64
5862 return std::numeric_limits<uint64_t>::max();
5863 case AMDGPU::V_CMP_LT_I64_e64: // min.i64
5864 return std::numeric_limits<int64_t>::max();
5865 case AMDGPU::V_CMP_GT_U64_e64: // umax.u64
5866 return std::numeric_limits<uint64_t>::min();
5867 case AMDGPU::V_CMP_GT_I64_e64: // max.i64
5868 return std::numeric_limits<int64_t>::min();
5869 case AMDGPU::V_MIN_F64_e64:
5870 case AMDGPU::V_MAX_F64_e64:
5871 case AMDGPU::V_MIN_NUM_F64_e64:
5872 case AMDGPU::V_MAX_NUM_F64_e64:
5873 return 0x7FF8000000000000; // qNAN
5874 case AMDGPU::S_ADD_U64_PSEUDO:
5875 case AMDGPU::S_SUB_U64_PSEUDO:
5876 case AMDGPU::S_OR_B64:
5877 case AMDGPU::S_XOR_B64:
5878 return std::numeric_limits<uint64_t>::min();
5879 case AMDGPU::S_AND_B64:
5880 return std::numeric_limits<uint64_t>::max();
5881 case AMDGPU::V_ADD_F64_e64:
5882 case AMDGPU::V_ADD_F64_pseudo_e64:
5883 return 0x8000000000000000; // -0.0
5884 default:
5885 llvm_unreachable("Unexpected opcode in getIdentityValueForWaveReduction");
5886 }
5887}
5888
5889static bool is32bitWaveReduceOperation(unsigned Opc) {
5890 return Opc == AMDGPU::S_MIN_U32 || Opc == AMDGPU::S_MIN_I32 ||
5891 Opc == AMDGPU::S_MAX_U32 || Opc == AMDGPU::S_MAX_I32 ||
5892 Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32 ||
5893 Opc == AMDGPU::S_AND_B32 || Opc == AMDGPU::S_OR_B32 ||
5894 Opc == AMDGPU::S_XOR_B32 || Opc == AMDGPU::V_MIN_F32_e64 ||
5895 Opc == AMDGPU::V_MAX_F32_e64 || Opc == AMDGPU::V_ADD_F32_e64 ||
5896 Opc == AMDGPU::V_SUB_F32_e64;
5897}
5898
5900 return Opc == AMDGPU::V_MIN_F32_e64 || Opc == AMDGPU::V_MAX_F32_e64 ||
5901 Opc == AMDGPU::V_ADD_F32_e64 || Opc == AMDGPU::V_SUB_F32_e64 ||
5902 Opc == AMDGPU::V_MIN_F64_e64 || Opc == AMDGPU::V_MAX_F64_e64 ||
5903 Opc == AMDGPU::V_MIN_NUM_F64_e64 || Opc == AMDGPU::V_MAX_NUM_F64_e64 ||
5904 Opc == AMDGPU::V_ADD_F64_e64 || Opc == AMDGPU::V_ADD_F64_pseudo_e64;
5905}
5906
5907static std::tuple<unsigned, unsigned>
5909 unsigned DPPOpc;
5910 switch (Opc) {
5911 case AMDGPU::S_MIN_U32:
5912 DPPOpc = AMDGPU::V_MIN_U32_dpp;
5913 break;
5914 case AMDGPU::S_MIN_I32:
5915 DPPOpc = AMDGPU::V_MIN_I32_dpp;
5916 break;
5917 case AMDGPU::S_MAX_U32:
5918 DPPOpc = AMDGPU::V_MAX_U32_dpp;
5919 break;
5920 case AMDGPU::S_MAX_I32:
5921 DPPOpc = AMDGPU::V_MAX_I32_dpp;
5922 break;
5923 case AMDGPU::S_ADD_I32:
5924 case AMDGPU::S_SUB_I32:
5925 DPPOpc = ST.hasAddNoCarryInsts() ? AMDGPU::V_ADD_U32_dpp
5926 : AMDGPU::V_ADD_CO_U32_dpp;
5927 break;
5928 case AMDGPU::S_AND_B32:
5929 DPPOpc = AMDGPU::V_AND_B32_dpp;
5930 break;
5931 case AMDGPU::S_OR_B32:
5932 DPPOpc = AMDGPU::V_OR_B32_dpp;
5933 break;
5934 case AMDGPU::S_XOR_B32:
5935 DPPOpc = AMDGPU::V_XOR_B32_dpp;
5936 break;
5937 case AMDGPU::V_ADD_F32_e64:
5938 case AMDGPU::V_SUB_F32_e64:
5939 DPPOpc = AMDGPU::V_ADD_F32_dpp;
5940 break;
5941 case AMDGPU::V_MIN_F32_e64:
5942 DPPOpc = AMDGPU::V_MIN_F32_dpp;
5943 break;
5944 case AMDGPU::V_MAX_F32_e64:
5945 DPPOpc = AMDGPU::V_MAX_F32_dpp;
5946 break;
5947 case AMDGPU::V_CMP_LT_U64_e64: // umin.u64
5948 case AMDGPU::V_CMP_LT_I64_e64: // min.i64
5949 case AMDGPU::V_CMP_GT_U64_e64: // umax.u64
5950 case AMDGPU::V_CMP_GT_I64_e64: // max.i64
5951 case AMDGPU::S_ADD_U64_PSEUDO:
5952 case AMDGPU::S_SUB_U64_PSEUDO:
5953 case AMDGPU::S_AND_B64:
5954 case AMDGPU::S_OR_B64:
5955 case AMDGPU::S_XOR_B64:
5956 case AMDGPU::V_MIN_NUM_F64_e64:
5957 case AMDGPU::V_MIN_F64_e64:
5958 case AMDGPU::V_MAX_NUM_F64_e64:
5959 case AMDGPU::V_MAX_F64_e64:
5960 case AMDGPU::V_ADD_F64_pseudo_e64:
5961 case AMDGPU::V_ADD_F64_e64:
5962 DPPOpc = AMDGPU::V_MOV_B64_DPP_PSEUDO;
5963 break;
5964 default:
5965 llvm_unreachable("unhandled lane op");
5966 }
5967 unsigned ClampOpc = Opc;
5968 if (Opc == AMDGPU::V_SUB_F32_e64)
5969 ClampOpc = AMDGPU::V_ADD_F32_e64;
5970 if (!ST.getInstrInfo()->isVALU(Opc, /*AllowLDSDMA=*/true)) {
5971 if (Opc == AMDGPU::S_SUB_I32)
5972 ClampOpc = AMDGPU::S_ADD_I32;
5973 if (Opc == AMDGPU::S_ADD_U64_PSEUDO || Opc == AMDGPU::S_SUB_U64_PSEUDO)
5974 ClampOpc = AMDGPU::V_ADD_CO_U32_e64;
5975 else if (Opc == AMDGPU::S_AND_B64)
5976 ClampOpc = AMDGPU::V_AND_B32_e64;
5977 else if (Opc == AMDGPU::S_OR_B64)
5978 ClampOpc = AMDGPU::V_OR_B32_e64;
5979 else if (Opc == AMDGPU::S_XOR_B64)
5980 ClampOpc = AMDGPU::V_XOR_B32_e64;
5981 else
5982 ClampOpc = ST.getInstrInfo()->getVALUOp(ClampOpc);
5983 }
5984 return {DPPOpc, ClampOpc};
5985}
5986
5987static std::pair<Register, Register>
5989 const TargetRegisterClass *SrcRC, const GCNSubtarget &ST,
5991 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5992 const SIInstrInfo *TII = ST.getInstrInfo();
5993 const TargetRegisterClass *SrcSubRC =
5994 TRI->getSubRegisterClass(SrcRC, AMDGPU::sub0);
5995 Register Op1L =
5996 TII->buildExtractSubReg(MI, MRI, Op, SrcRC, AMDGPU::sub0, SrcSubRC);
5997 Register Op1H =
5998 TII->buildExtractSubReg(MI, MRI, Op, SrcRC, AMDGPU::sub1, SrcSubRC);
5999 return {Op1L, Op1H};
6000}
6001
6004 const GCNSubtarget &ST,
6005 unsigned Opc) {
6007 const SIRegisterInfo *TRI = ST.getRegisterInfo();
6008 const DebugLoc &DL = MI.getDebugLoc();
6009 const SIInstrInfo *TII = ST.getInstrInfo();
6010
6011 // Reduction operations depend on whether the input operand is SGPR or VGPR.
6012 Register SrcReg = MI.getOperand(1).getReg();
6013 bool isSGPR = TRI->isSGPRClass(MRI.getRegClass(SrcReg));
6014 Register DstReg = MI.getOperand(0).getReg();
6015 unsigned Stratergy = static_cast<unsigned>(MI.getOperand(2).getImm());
6016 enum WAVE_REDUCE_STRATEGY : unsigned { DEFAULT = 0, ITERATIVE = 1, DPP = 2 };
6017 MachineBasicBlock *RetBB = nullptr;
6018 unsigned MIOpc = MI.getOpcode();
6019 auto BuildRegSequence = [&](MachineBasicBlock &BB,
6021 Register Src0, Register Src1) {
6022 auto RegSequence =
6023 BuildMI(BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dst)
6024 .addReg(Src0)
6025 .addImm(AMDGPU::sub0)
6026 .addReg(Src1)
6027 .addImm(AMDGPU::sub1);
6028 return RegSequence;
6029 };
6030 if (isSGPR) {
6031 switch (Opc) {
6032 case AMDGPU::S_MIN_U32:
6033 case AMDGPU::S_MIN_I32:
6034 case AMDGPU::V_MIN_F32_e64:
6035 case AMDGPU::S_MAX_U32:
6036 case AMDGPU::S_MAX_I32:
6037 case AMDGPU::V_MAX_F32_e64:
6038 case AMDGPU::S_AND_B32:
6039 case AMDGPU::S_OR_B32: {
6040 // Idempotent operations.
6041 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstReg).addReg(SrcReg);
6042 RetBB = &BB;
6043 break;
6044 }
6045 case AMDGPU::V_CMP_LT_U64_e64: // umin
6046 case AMDGPU::V_CMP_LT_I64_e64: // min
6047 case AMDGPU::V_CMP_GT_U64_e64: // umax
6048 case AMDGPU::V_CMP_GT_I64_e64: // max
6049 case AMDGPU::V_MIN_F64_e64:
6050 case AMDGPU::V_MIN_NUM_F64_e64:
6051 case AMDGPU::V_MAX_F64_e64:
6052 case AMDGPU::V_MAX_NUM_F64_e64:
6053 case AMDGPU::S_AND_B64:
6054 case AMDGPU::S_OR_B64: {
6055 // Idempotent operations.
6056 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B64), DstReg).addReg(SrcReg);
6057 RetBB = &BB;
6058 break;
6059 }
6060 case AMDGPU::S_XOR_B32:
6061 case AMDGPU::S_XOR_B64:
6062 case AMDGPU::S_ADD_I32:
6063 case AMDGPU::S_ADD_U64_PSEUDO:
6064 case AMDGPU::V_ADD_F32_e64:
6065 case AMDGPU::V_ADD_F64_e64:
6066 case AMDGPU::V_ADD_F64_pseudo_e64:
6067 case AMDGPU::S_SUB_I32:
6068 case AMDGPU::S_SUB_U64_PSEUDO:
6069 case AMDGPU::V_SUB_F32_e64: {
6070 const TargetRegisterClass *WaveMaskRegClass = TRI->getWaveMaskRegClass();
6071 const TargetRegisterClass *DstRegClass = MRI.getRegClass(DstReg);
6072 Register ExecMask = MRI.createVirtualRegister(WaveMaskRegClass);
6073 Register NumActiveLanes =
6074 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6075
6076 bool IsWave32 = ST.isWave32();
6077 unsigned MovOpc = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
6078 MCRegister ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
6079 unsigned BitCountOpc =
6080 IsWave32 ? AMDGPU::S_BCNT1_I32_B32 : AMDGPU::S_BCNT1_I32_B64;
6081
6082 BuildMI(BB, MI, DL, TII->get(MovOpc), ExecMask).addReg(ExecReg);
6083
6084 auto NewAccumulator =
6085 BuildMI(BB, MI, DL, TII->get(BitCountOpc), NumActiveLanes)
6086 .addReg(ExecMask)
6087 .setOperandDead(2); // Dead scc
6088
6089 switch (Opc) {
6090 case AMDGPU::S_XOR_B32:
6091 case AMDGPU::S_XOR_B64: {
6092 // Performing an XOR operation on a uniform value
6093 // depends on the parity of the number of active lanes.
6094 // For even parity, the result will be 0, for odd
6095 // parity the result will be the same as the input value.
6096 Register ParityRegister =
6097 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6098 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_AND_B32), ParityRegister)
6099 .addReg(NewAccumulator->getOperand(0).getReg())
6100 .addImm(1)
6101 .setOperandDead(3); // Dead scc
6102 // Check if Src is a known identity constant.
6103 if (TII->getImmOrMaterializedImm(MRI, SrcReg) == 1) {
6104 // 1 * parity(exec) = parity(exec)
6105 if (Opc == AMDGPU::S_XOR_B32) {
6106 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstReg)
6107 .addReg(ParityRegister);
6108 } else {
6109 Register DstHi =
6110 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6111 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstHi).addImm(0);
6112 BuildRegSequence(BB, MI, DstReg, ParityRegister, DstHi);
6113 }
6114 break;
6115 }
6116 if (Opc == AMDGPU::S_XOR_B32) {
6117 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DstReg)
6118 .addReg(SrcReg)
6119 .addReg(ParityRegister);
6120 } else {
6121 Register DestSub0 =
6122 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6123 Register DestSub1 =
6124 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6125 auto [Op1L, Op1H] = ExtractSubRegs(MI, MI.getOperand(1),
6126 MRI.getRegClass(SrcReg), ST, MRI);
6127 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DestSub0)
6128 .addReg(Op1L)
6129 .addReg(ParityRegister);
6130 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DestSub1)
6131 .addReg(Op1H)
6132 .addReg(ParityRegister);
6133 BuildRegSequence(BB, MI, DstReg, DestSub0, DestSub1);
6134 }
6135 break;
6136 }
6137 case AMDGPU::S_SUB_I32: {
6138 Register NegatedVal = MRI.createVirtualRegister(DstRegClass);
6139 // Take the negation of the source operand.
6140 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_SUB_I32), NegatedVal)
6141 .addImm(0)
6142 .addReg(SrcReg)
6143 .setOperandDead(3); // Dead scc
6144 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DstReg)
6145 .addReg(NegatedVal)
6146 .addReg(NewAccumulator->getOperand(0).getReg());
6147 break;
6148 }
6149 case AMDGPU::S_ADD_I32: {
6150 // Check if Src is a known identity constant.
6151 if (TII->getImmOrMaterializedImm(MRI, SrcReg) == 1) {
6152 // 1 * bitcount(exec) = bitcount(exec)
6153 BuildMI(BB, MI, DL, TII->get(AMDGPU::COPY), DstReg)
6154 .addReg(NewAccumulator->getOperand(0).getReg());
6155 break;
6156 }
6157 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DstReg)
6158 .addReg(SrcReg)
6159 .addReg(NewAccumulator->getOperand(0).getReg());
6160 break;
6161 }
6162 case AMDGPU::S_ADD_U64_PSEUDO:
6163 case AMDGPU::S_SUB_U64_PSEUDO: {
6164 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6165 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6166 Register Op1H_Op0L_Reg =
6167 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6168 Register Op1L_Op0H_Reg =
6169 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6170 Register CarryReg =
6171 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6172 Register AddReg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6173 Register NegatedValLo =
6174 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6175 Register NegatedValHi =
6176 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6177 auto [Op1L, Op1H] = ExtractSubRegs(MI, MI.getOperand(1),
6178 MRI.getRegClass(SrcReg), ST, MRI);
6179 // Check if Src is a known identity constant.
6180 if (Opc == AMDGPU::S_ADD_U64_PSEUDO &&
6181 TII->getImmOrMaterializedImm(MRI, SrcReg) == 1) {
6182 // 1 * bitcount(exec) = bitcount(exec)
6183 Register DstHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6184 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstHi).addImm(0);
6185 BuildRegSequence(BB, MI, DstReg,
6186 NewAccumulator->getOperand(0).getReg(), DstHi);
6187 break;
6188 }
6189 if (Opc == AMDGPU::S_SUB_U64_PSEUDO) {
6190 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_SUB_I32), NegatedValLo)
6191 .addImm(0)
6192 .addReg(NewAccumulator->getOperand(0).getReg())
6193 .setOperandDead(3); // Dead scc
6194 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_ASHR_I32), NegatedValHi)
6195 .addReg(NegatedValLo)
6196 .addImm(31)
6197 .setOperandDead(3); // Dead scc
6198 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), Op1L_Op0H_Reg)
6199 .addReg(Op1L)
6200 .addReg(NegatedValHi);
6201 }
6202 Register LowOpcode = Opc == AMDGPU::S_SUB_U64_PSEUDO
6203 ? NegatedValLo
6204 : NewAccumulator->getOperand(0).getReg();
6205 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DestSub0)
6206 .addReg(Op1L)
6207 .addReg(LowOpcode);
6208 if (ST.hasScalarMulHiInsts()) {
6209 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_HI_U32), CarryReg)
6210 .addReg(Op1L)
6211 .addReg(LowOpcode);
6212 } else {
6213 Register VCarryReg =
6214 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6215 Register LowOpVGPR =
6216 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6217 BuildMI(BB, MI, DL, TII->get(AMDGPU::COPY), LowOpVGPR)
6218 .addReg(LowOpcode);
6219 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_MUL_HI_U32_e64), VCarryReg)
6220 .addReg(Op1L)
6221 .addReg(LowOpVGPR);
6222 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CarryReg)
6223 .addReg(VCarryReg);
6224 }
6225 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), Op1H_Op0L_Reg)
6226 .addReg(Op1H)
6227 .addReg(LowOpcode);
6228
6229 Register HiVal = Opc == AMDGPU::S_SUB_U64_PSEUDO ? AddReg : DestSub1;
6230 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_ADD_U32), HiVal)
6231 .addReg(CarryReg)
6232 .addReg(Op1H_Op0L_Reg)
6233 .setOperandDead(3); // Dead scc
6234
6235 if (Opc == AMDGPU::S_SUB_U64_PSEUDO) {
6236 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_ADD_U32), DestSub1)
6237 .addReg(HiVal)
6238 .addReg(Op1L_Op0H_Reg)
6239 .setOperandDead(3); // Dead scc
6240 }
6241 BuildRegSequence(BB, MI, DstReg, DestSub0, DestSub1);
6242 break;
6243 }
6244 case AMDGPU::V_ADD_F32_e64:
6245 case AMDGPU::V_ADD_F64_e64:
6246 case AMDGPU::V_ADD_F64_pseudo_e64:
6247 case AMDGPU::V_SUB_F32_e64: {
6248 bool is32BitOpc = is32bitWaveReduceOperation(Opc);
6249 const TargetRegisterClass *VregRC = TII->getRegClass(TII->get(Opc), 0);
6250 Register ActiveLanesVreg = MRI.createVirtualRegister(VregRC);
6251 Register DstVreg = MRI.createVirtualRegister(VregRC);
6252 // Get number of active lanes as a float val.
6253 BuildMI(BB, MI, DL,
6254 TII->get(is32BitOpc ? AMDGPU::V_CVT_F32_I32_e64
6255 : AMDGPU::V_CVT_F64_I32_e64),
6256 ActiveLanesVreg)
6257 .addReg(NewAccumulator->getOperand(0).getReg())
6258 .addImm(0) // clamp
6259 .addImm(0); // output-modifier
6260
6261 // Take negation of input for SUB reduction
6262 unsigned srcMod = (MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F32 ||
6263 MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64)
6266 unsigned MulOpc = is32BitOpc ? AMDGPU::V_MUL_F32_e64
6267 : ST.getGeneration() >= AMDGPUSubtarget::GFX12
6268 ? AMDGPU::V_MUL_F64_pseudo_e64
6269 : AMDGPU::V_MUL_F64_e64;
6270 auto DestVregInst = BuildMI(BB, MI, DL, TII->get(MulOpc),
6271 DstVreg)
6272 .addImm(srcMod) // src0 modifier
6273 .addReg(SrcReg)
6274 .addImm(SISrcMods::NONE) // src1 modifier
6275 .addReg(ActiveLanesVreg)
6276 .addImm(SISrcMods::NONE) // clamp
6277 .addImm(SISrcMods::NONE); // output-mod
6278 if (is32BitOpc) {
6279 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
6280 .addReg(DstVreg);
6281 } else {
6282 Register LaneValueLoReg =
6283 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6284 Register LaneValueHiReg =
6285 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6286 auto [Op1L, Op1H] =
6287 ExtractSubRegs(MI, DestVregInst->getOperand(0), VregRC, ST, MRI);
6288 // lane value input should be in an sgpr
6289 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
6290 LaneValueLoReg)
6291 .addReg(Op1L);
6292 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
6293 LaneValueHiReg)
6294 .addReg(Op1H);
6295 NewAccumulator =
6296 BuildRegSequence(BB, MI, DstReg, LaneValueLoReg, LaneValueHiReg);
6297 }
6298 }
6299 }
6300 RetBB = &BB;
6301 }
6302 }
6303 } else {
6305 Register SrcReg = MI.getOperand(1).getReg();
6306 bool is32BitOpc = is32bitWaveReduceOperation(Opc);
6308 bool NeedsMovDPP = !is32BitOpc;
6309 // Create virtual registers required for lowering.
6310 const TargetRegisterClass *WaveMaskRegClass = TRI->getWaveMaskRegClass();
6311 const TargetRegisterClass *DstRegClass = MRI.getRegClass(DstReg);
6312 const TargetRegisterClass *SrcRegClass = MRI.getRegClass(SrcReg);
6313 bool IsWave32 = ST.isWave32();
6314 unsigned MovOpcForExec = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
6315 unsigned ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
6316 if (Stratergy == WAVE_REDUCE_STRATEGY::ITERATIVE ||
6317 !ST.hasDPP()) { // If target doesn't support DPP operations, default to
6318 // iterative stratergy
6319
6320 // To reduce the VGPR using iterative approach, we need to iterate
6321 // over all the active lanes. Lowering consists of ComputeLoop,
6322 // which iterate over only active lanes. We use copy of EXEC register
6323 // as induction variable and every active lane modifies it using bitset0
6324 // so that we will get the next active lane for next iteration.
6325
6326 // Create Control flow for loop
6327 // Split MI's Machine Basic block into For loop
6328 auto [ComputeLoop, ComputeEnd] = splitBlockForLoop(MI, BB, true);
6329
6330 Register LoopIterator = MRI.createVirtualRegister(WaveMaskRegClass);
6331 Register IdentityValReg = MRI.createVirtualRegister(DstRegClass);
6332 Register AccumulatorReg = MRI.createVirtualRegister(DstRegClass);
6333 Register ActiveBitsReg = MRI.createVirtualRegister(WaveMaskRegClass);
6334 Register NewActiveBitsReg = MRI.createVirtualRegister(WaveMaskRegClass);
6335 Register FF1Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6336 Register LaneValueReg = MRI.createVirtualRegister(DstRegClass);
6337
6338 // Create initial values of induction variable from Exec, Accumulator and
6339 // insert branch instr to newly created ComputeBlock
6340 BuildMI(BB, I, DL, TII->get(MovOpcForExec), LoopIterator).addReg(ExecReg);
6341 uint64_t IdentityValue =
6342 MI.getOpcode() == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64
6343 ? 0x0 // +0.0 for double sub reduction
6345 BuildMI(BB, I, DL,
6346 TII->get(is32BitOpc ? AMDGPU::S_MOV_B32
6347 : AMDGPU::S_MOV_B64_IMM_PSEUDO),
6348 IdentityValReg)
6349 .addImm(IdentityValue);
6350 // clang-format off
6351 BuildMI(BB, I, DL, TII->get(AMDGPU::S_BRANCH))
6352 .addMBB(ComputeLoop);
6353 // clang-format on
6354
6355 // Start constructing ComputeLoop
6356 I = ComputeLoop->begin();
6357 auto Accumulator =
6358 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::PHI), AccumulatorReg)
6359 .addReg(IdentityValReg)
6360 .addMBB(&BB);
6361 auto ActiveBits =
6362 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::PHI), ActiveBitsReg)
6363 .addReg(LoopIterator)
6364 .addMBB(&BB);
6365
6366 I = ComputeLoop->end();
6367 MachineInstr *NewAccumulator;
6368 // Perform the computations
6369 unsigned SFFOpc =
6370 IsWave32 ? AMDGPU::S_FF1_I32_B32 : AMDGPU::S_FF1_I32_B64;
6371 BuildMI(*ComputeLoop, I, DL, TII->get(SFFOpc), FF1Reg)
6372 .addReg(ActiveBitsReg);
6373 if (is32BitOpc) {
6374 Register OpDstReg = DstReg;
6375 bool hasSrc0Modifier = AMDGPU::getNamedOperandIdx(
6376 Opc, AMDGPU::OpName::src0_modifiers) != -1;
6377 bool hasSrc1Modifier = AMDGPU::getNamedOperandIdx(
6378 Opc, AMDGPU::OpName::src1_modifiers) != -1;
6379 bool hasClamp =
6380 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp) != -1;
6381 bool hasOpSel =
6382 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel) != -1;
6383 bool hasOMod =
6384 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod) != -1;
6385 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READLANE_B32),
6386 LaneValueReg)
6387 .addReg(SrcReg)
6388 .addReg(FF1Reg);
6389 if (ST.getInstrInfo()->isVALU(Opc, /*AllowLDSDMA=*/true)) {
6390 // Get the Lane Value in VGPR to avoid the Constant Bus Restriction
6391 Register LaneValVgpr = MRI.createVirtualRegister(SrcRegClass);
6392 Register VgprResultReg = MRI.createVirtualRegister(SrcRegClass);
6393 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::COPY), LaneValVgpr)
6394 .addReg(LaneValueReg);
6395 OpDstReg = VgprResultReg;
6396 LaneValueReg = LaneValVgpr;
6397 }
6398 auto OpInstr = BuildMI(*ComputeLoop, I, DL, TII->get(Opc), OpDstReg);
6399 if (hasSrc0Modifier)
6400 OpInstr.addImm(SISrcMods::NONE); // src0 modifier
6401 OpInstr.addReg(AccumulatorReg); // src0
6402 if (hasSrc1Modifier)
6403 OpInstr.addImm(SISrcMods::NONE); // src1 modifier
6404 OpInstr.addReg(LaneValueReg); // src1
6405 if (hasClamp)
6406 OpInstr.addImm(0); // clamp
6407 if (hasOpSel)
6408 OpInstr.addImm(0); // opsel
6409 if (hasOMod)
6410 OpInstr.addImm(0); // omod
6411 if (TII->isSALU(Opc))
6412 OpInstr.setOperandDead(3); // Dead scc
6413 if (ST.getInstrInfo()->isVALU(Opc, /*AllowLDSDMA=*/true)) {
6414 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
6415 DstReg)
6416 .addReg(OpDstReg);
6417 }
6418 } else {
6419 Register LaneValueLoReg =
6420 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6421 Register LaneValueHiReg =
6422 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6423 Register LaneValReg =
6424 MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6425 auto [Op1L, Op1H] = ExtractSubRegs(MI, MI.getOperand(1),
6426 MRI.getRegClass(SrcReg), ST, MRI);
6427 // lane value input should be in an sgpr
6428 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READLANE_B32),
6429 LaneValueLoReg)
6430 .addReg(Op1L)
6431 .addReg(FF1Reg);
6432 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READLANE_B32),
6433 LaneValueHiReg)
6434 .addReg(Op1H)
6435 .addReg(FF1Reg);
6436 auto LaneValue = BuildRegSequence(*ComputeLoop, I, LaneValReg,
6437 LaneValueLoReg, LaneValueHiReg);
6438 switch (Opc) {
6439 case AMDGPU::S_OR_B64:
6440 case AMDGPU::S_AND_B64:
6441 case AMDGPU::S_XOR_B64: {
6442 NewAccumulator = BuildMI(*ComputeLoop, I, DL, TII->get(Opc), DstReg)
6443 .addReg(Accumulator->getOperand(0).getReg())
6444 .addReg(LaneValue->getOperand(0).getReg())
6445 .setOperandDead(3); // Dead scc
6446 break;
6447 }
6448 case AMDGPU::V_CMP_GT_I64_e64:
6449 case AMDGPU::V_CMP_GT_U64_e64:
6450 case AMDGPU::V_CMP_LT_I64_e64:
6451 case AMDGPU::V_CMP_LT_U64_e64: {
6452 Register LaneMaskReg = MRI.createVirtualRegister(WaveMaskRegClass);
6453 Register ComparisonResultReg =
6454 MRI.createVirtualRegister(WaveMaskRegClass);
6455 int SrcIdx =
6456 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src);
6457 const TargetRegisterClass *VregClass =
6458 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), SrcIdx));
6459 Register AccumulatorVReg = MRI.createVirtualRegister(VregClass);
6460 auto [SrcReg0Sub0, SrcReg0Sub1] = ExtractSubRegs(
6461 MI, Accumulator->getOperand(0), VregClass, ST, MRI);
6462 BuildRegSequence(*ComputeLoop, I, AccumulatorVReg, SrcReg0Sub0,
6463 SrcReg0Sub1);
6464 BuildMI(*ComputeLoop, I, DL, TII->get(Opc), LaneMaskReg)
6465 .addReg(LaneValue->getOperand(0).getReg())
6466 .addReg(AccumulatorVReg);
6467
6468 unsigned AndOpc = IsWave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
6469 BuildMI(*ComputeLoop, I, DL, TII->get(AndOpc), ComparisonResultReg)
6470 .addReg(LaneMaskReg)
6471 .addReg(ActiveBitsReg);
6472
6473 NewAccumulator = BuildMI(*ComputeLoop, I, DL,
6474 TII->get(AMDGPU::S_CSELECT_B64), DstReg)
6475 .addReg(LaneValue->getOperand(0).getReg())
6476 .addReg(Accumulator->getOperand(0).getReg());
6477 break;
6478 }
6479 case AMDGPU::V_MIN_F64_e64:
6480 case AMDGPU::V_MIN_NUM_F64_e64:
6481 case AMDGPU::V_MAX_F64_e64:
6482 case AMDGPU::V_MAX_NUM_F64_e64:
6483 case AMDGPU::V_ADD_F64_e64:
6484 case AMDGPU::V_ADD_F64_pseudo_e64: {
6485 int SrcIdx =
6486 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src);
6487 const TargetRegisterClass *VregRC =
6488 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), SrcIdx));
6489 Register AccumulatorVReg = MRI.createVirtualRegister(VregRC);
6490 Register DstVreg = MRI.createVirtualRegister(VregRC);
6491 Register LaneValLo =
6492 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6493 Register LaneValHi =
6494 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6495 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::COPY), AccumulatorVReg)
6496 .addReg(Accumulator->getOperand(0).getReg());
6497 unsigned Modifier =
6498 MI.getOpcode() == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64
6501 auto DstVregInst =
6502 BuildMI(*ComputeLoop, I, DL, TII->get(Opc), DstVreg)
6503 .addImm(Modifier) // src0 modifiers
6504 .addReg(LaneValue->getOperand(0).getReg())
6505 .addImm(SISrcMods::NONE) // src1 modifiers
6506 .addReg(AccumulatorVReg)
6507 .addImm(SISrcMods::NONE) // clamp
6508 .addImm(SISrcMods::NONE); // omod
6509 auto ReadLaneLo =
6510 BuildMI(*ComputeLoop, I, DL,
6511 TII->get(AMDGPU::V_READFIRSTLANE_B32), LaneValLo);
6512 auto ReadLaneHi =
6513 BuildMI(*ComputeLoop, I, DL,
6514 TII->get(AMDGPU::V_READFIRSTLANE_B32), LaneValHi);
6515 MachineBasicBlock::iterator Iters = *ReadLaneLo;
6516 auto [Op1L, Op1H] = ExtractSubRegs(*Iters, DstVregInst->getOperand(0),
6517 VregRC, ST, MRI);
6518 ReadLaneLo.addReg(Op1L);
6519 ReadLaneHi.addReg(Op1H);
6520 NewAccumulator =
6521 BuildRegSequence(*ComputeLoop, I, DstReg, LaneValLo, LaneValHi);
6522 break;
6523 }
6524 case AMDGPU::S_ADD_U64_PSEUDO:
6525 case AMDGPU::S_SUB_U64_PSEUDO: {
6526 NewAccumulator = BuildMI(*ComputeLoop, I, DL, TII->get(Opc), DstReg)
6527 .addReg(Accumulator->getOperand(0).getReg())
6528 .addReg(LaneValue->getOperand(0).getReg())
6529 .setOperandDead(3); // Dead scc
6530 ComputeLoop =
6531 expand64BitScalarArithmetic(*NewAccumulator, ComputeLoop);
6532 break;
6533 }
6534 }
6535 }
6536 // Manipulate the iterator to get the next active lane
6537 unsigned BITSETOpc =
6538 IsWave32 ? AMDGPU::S_BITSET0_B32 : AMDGPU::S_BITSET0_B64;
6539 BuildMI(*ComputeLoop, I, DL, TII->get(BITSETOpc), NewActiveBitsReg)
6540 .addReg(FF1Reg)
6541 .addReg(ActiveBitsReg);
6542
6543 // Add phi nodes
6544 Accumulator.addReg(DstReg).addMBB(ComputeLoop);
6545 ActiveBits.addReg(NewActiveBitsReg).addMBB(ComputeLoop);
6546
6547 // Creating branching
6548 MachineInstrBuilder SetSCCInstr;
6549 if (!ST.hasScalarCompareEq64()) {
6550 // For targets <= gfx7, use an S_OR_B32/B64 instruction to set SCC.
6551 Register LaneMaskReg = MRI.createVirtualRegister(WaveMaskRegClass);
6552 unsigned CMPOpc = IsWave32 ? AMDGPU::S_OR_B32 : AMDGPU::S_OR_B64;
6553 SetSCCInstr =
6554 BuildMI(*ComputeLoop, I, DL, TII->get(CMPOpc), LaneMaskReg);
6555 } else {
6556 unsigned CMPOpc =
6557 IsWave32 ? AMDGPU::S_CMP_LG_U32 : AMDGPU::S_CMP_LG_U64;
6558 SetSCCInstr = BuildMI(*ComputeLoop, I, DL, TII->get(CMPOpc));
6559 }
6560 SetSCCInstr.addReg(NewActiveBitsReg);
6561 if (ST.hasScalarCompareEq64())
6562 SetSCCInstr.addImm(0);
6563 else
6564 SetSCCInstr.addReg(NewActiveBitsReg);
6565 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
6566 .addMBB(ComputeLoop);
6567
6568 RetBB = ComputeEnd;
6569 } else {
6570 assert(ST.hasDPP() && "Sub Target does not support DPP Operations");
6571 MachineBasicBlock *CurrBB = &BB;
6572 Register SrcWithIdentity = MRI.createVirtualRegister(SrcRegClass);
6573 Register IdentityVGPR = MRI.createVirtualRegister(SrcRegClass);
6574 Register IdentitySGPR = MRI.createVirtualRegister(DstRegClass);
6575 Register DPPRowShr1 = MRI.createVirtualRegister(SrcRegClass);
6576 Register DPPRowShr2 = MRI.createVirtualRegister(SrcRegClass);
6577 Register DPPRowShr4 = MRI.createVirtualRegister(SrcRegClass);
6578 Register DPPRowShr8 = MRI.createVirtualRegister(SrcRegClass);
6579 Register RowBcast15 = MRI.createVirtualRegister(SrcRegClass);
6580 Register ReducedValSGPR = MRI.createVirtualRegister(DstRegClass);
6581 Register NegatedReducedVal = MRI.createVirtualRegister(DstRegClass);
6582 Register RowBcast31 = MRI.createVirtualRegister(SrcRegClass);
6583 Register UndefExec = MRI.createVirtualRegister(WaveMaskRegClass);
6584 Register FinalDPPResult;
6585 MachineInstr *SrcWithIdentityInstr;
6586 MachineInstr *LastBcastInstr;
6587 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), UndefExec);
6588
6590 BuildMI(*CurrBB, MI, DL,
6591 TII->get(is32BitOpc ? AMDGPU::S_MOV_B32
6592 : AMDGPU::S_MOV_B64_IMM_PSEUDO),
6593 IdentitySGPR)
6594 .addImm(IdentityValue);
6595 auto IdentityCopyInstr =
6596 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::COPY), IdentityVGPR)
6597 .addReg(IdentitySGPR);
6598 unsigned DPPOpc, ClampOpc;
6599 std::tie(DPPOpc, ClampOpc) = getDPPOpcForWaveReduction(Opc, ST);
6600 auto BuildSetInactiveInstr = [&](Register Dst, Register Src0,
6601 Register Src1) {
6602 return BuildMI(BB, MI, DL, TII->get(AMDGPU::V_SET_INACTIVE_B32),
6603 Dst)
6604 .addImm(0) // src0 modifiers
6605 .addReg(Src0) // src0
6606 .addImm(0) // src1 modifiers
6607 .addReg(Src1) // identity value for inactive lanes
6608 .addReg(UndefExec); // bool i1
6609 };
6610 auto BuildDPPMachineInstr = [&](Register Dst, Register Src,
6611 unsigned DPPCtrl) {
6612 auto DPPInstr =
6613 BuildMI(*CurrBB, MI, DL, TII->get(DPPOpc), Dst).addReg(Src); // old
6614 if (isFPOp && !NeedsMovDPP)
6615 DPPInstr.addImm(SISrcMods::NONE); // src0 modifier
6616 DPPInstr.addReg(Src); // src0
6617 if (isFPOp && !NeedsMovDPP)
6618 DPPInstr.addImm(SISrcMods::NONE); // src1 modifier
6619 if (!NeedsMovDPP)
6620 DPPInstr.addReg(Src); // src1
6621 if (AMDGPU::getNamedOperandIdx(DPPOpc, AMDGPU::OpName::clamp) >= 0)
6622 DPPInstr.addImm(0); // clamp
6623 DPPInstr
6624 .addImm(DPPCtrl) // dpp-ctrl
6625 .addImm(0xf) // row-mask
6626 .addImm(0xf) // bank-mask
6627 .addImm(0); // bound-control
6628 };
6629 auto BuildClampInstr = [&](Register Dst, Register Src0, Register Src1,
6630 bool isAddSub = false,
6631 bool needsCarryIn = false,
6632 Register CarryIn = Register()) {
6633 unsigned InstrOpc = ClampOpc;
6634 Register CarryOutReg = MRI.createVirtualRegister(WaveMaskRegClass);
6635 if (needsCarryIn)
6636 InstrOpc = AMDGPU::V_ADDC_U32_e64;
6637 auto ClampInstr = BuildMI(*CurrBB, MI, DL, TII->get(InstrOpc), Dst);
6638 if (isFPOp)
6639 ClampInstr.addImm(SISrcMods::NONE); // src0 mod
6640 if (isAddSub) {
6641 if (needsCarryIn)
6642 ClampInstr.addReg(CarryOutReg,
6644 RegState::Dead); // killed carry-out reg
6645 else
6646 ClampInstr.addReg(CarryOutReg, RegState::Define); // carry-out reg
6647 }
6648 ClampInstr.addReg(Src0); // src0
6649 if (isFPOp)
6650 ClampInstr.addImm(SISrcMods::NONE); // src1 mod
6651 ClampInstr.addReg(Src1); // src1
6652 if (needsCarryIn)
6653 ClampInstr.addReg(CarryIn); // carry-in reg
6654 if (AMDGPU::getNamedOperandIdx(InstrOpc, AMDGPU::OpName::clamp) >= 0)
6655 ClampInstr.addImm(0); // clamp
6656 if (isFPOp)
6657 ClampInstr.addImm(0); // omod
6658 LastBcastInstr = ClampInstr;
6659 return CarryOutReg;
6660 };
6661 auto BuildPostDPPInstr = [&](Register Src0, Register Src1) {
6662 bool isAddSubOpc =
6663 Opc == AMDGPU::S_ADD_U64_PSEUDO || Opc == AMDGPU::S_SUB_U64_PSEUDO;
6664 bool isBitWiseOpc = Opc == AMDGPU::S_AND_B64 ||
6665 Opc == AMDGPU::S_OR_B64 || Opc == AMDGPU::S_XOR_B64;
6666 Register ReturnReg = MRI.createVirtualRegister(SrcRegClass);
6667 if (isAddSubOpc || isBitWiseOpc) {
6668 Register ResLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6669 Register ResHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6670 MachineOperand Src0Operand =
6671 MachineOperand::CreateReg(Src0, /*isDef=*/false);
6672 MachineOperand Src1Operand =
6673 MachineOperand::CreateReg(Src1, /*isDef=*/false);
6674 auto [Src0Lo, Src0Hi] =
6675 ExtractSubRegs(MI, Src0Operand, SrcRegClass, ST, MRI);
6676 auto [Src1Lo, Src1Hi] =
6677 ExtractSubRegs(MI, Src1Operand, SrcRegClass, ST, MRI);
6678 Register CarryReg = BuildClampInstr(
6679 ResLo, Src0Lo, Src1Lo, isAddSubOpc, /*needsCarryIn*/ false);
6680 BuildClampInstr(ResHi, Src0Hi, Src1Hi, isAddSubOpc,
6681 /*needsCarryIn*/ isAddSubOpc, CarryReg);
6682 BuildRegSequence(*CurrBB, MI, ReturnReg, ResLo, ResHi);
6683 } else {
6684 if (isFPOp) {
6685 BuildMI(*CurrBB, MI, DL, TII->get(Opc), ReturnReg)
6686 .addImm(SISrcMods::NONE) // src0 modifiers
6687 .addReg(Src0)
6688 .addImm(SISrcMods::NONE) // src1 modifiers
6689 .addReg(Src1)
6690 .addImm(SISrcMods::NONE) // clamp
6691 .addImm(SISrcMods::NONE); // omod
6692 } else {
6693 Register CmpMaskReg = MRI.createVirtualRegister(WaveMaskRegClass);
6694 BuildMI(*CurrBB, MI, DL, TII->get(Opc), CmpMaskReg)
6695 .addReg(Src0) // src0
6696 .addReg(Src1); // src1
6697 LastBcastInstr =
6698 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B64_PSEUDO),
6699 ReturnReg)
6700 .addReg(Src1) // src0
6701 .addReg(Src0) // src1
6702 .addReg(CmpMaskReg); // src2
6703 expand64BitV_CNDMASK(*LastBcastInstr, CurrBB);
6704 }
6705 }
6706 return ReturnReg;
6707 };
6708
6709 // Set inactive lanes to the identity value.
6710 if (is32BitOpc) {
6711 SrcWithIdentityInstr =
6712 BuildSetInactiveInstr(SrcWithIdentity, SrcReg, IdentityVGPR);
6713 } else {
6714 Register SrcWithIdentitylo =
6715 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6716 Register SrcWithIdentityhi =
6717 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6718 auto [Reg0Sub0, Reg0Sub1] = ExtractSubRegs(
6719 MI, IdentityCopyInstr->getOperand(0), SrcRegClass, ST, MRI);
6720 auto [SrcReg0Sub0, SrcReg0Sub1] =
6721 ExtractSubRegs(MI, MI.getOperand(1), SrcRegClass, ST, MRI);
6722 MachineInstr *SetInactiveLoInstr =
6723 BuildSetInactiveInstr(SrcWithIdentitylo, SrcReg0Sub0, Reg0Sub0);
6724 MachineInstr *SetInactiveHiInstr =
6725 BuildSetInactiveInstr(SrcWithIdentityhi, SrcReg0Sub1, Reg0Sub1);
6726 SrcWithIdentityInstr =
6727 BuildRegSequence(*CurrBB, MI, SrcWithIdentity,
6728 SetInactiveLoInstr->getOperand(0).getReg(),
6729 SetInactiveHiInstr->getOperand(0).getReg());
6730 }
6731 // DPP reduction
6732 Register SrcWithIdentityReg =
6733 SrcWithIdentityInstr->getOperand(0).getReg();
6734 BuildDPPMachineInstr(DPPRowShr1, SrcWithIdentityReg,
6736 if (NeedsMovDPP)
6737 DPPRowShr1 = BuildPostDPPInstr(SrcWithIdentityReg, DPPRowShr1);
6738
6739 BuildDPPMachineInstr(DPPRowShr2, DPPRowShr1,
6741 if (NeedsMovDPP)
6742 DPPRowShr2 = BuildPostDPPInstr(DPPRowShr1, DPPRowShr2);
6743
6744 BuildDPPMachineInstr(DPPRowShr4, DPPRowShr2,
6746 if (NeedsMovDPP)
6747 DPPRowShr4 = BuildPostDPPInstr(DPPRowShr2, DPPRowShr4);
6748
6749 BuildDPPMachineInstr(DPPRowShr8, DPPRowShr4,
6751 if (NeedsMovDPP)
6752 DPPRowShr8 = BuildPostDPPInstr(DPPRowShr4, DPPRowShr8);
6753
6754 if (ST.hasDPPBroadcasts()) {
6755 BuildDPPMachineInstr(RowBcast15, DPPRowShr8, AMDGPU::DPP::BCAST15);
6756 if (NeedsMovDPP)
6757 RowBcast15 = BuildPostDPPInstr(DPPRowShr8, RowBcast15);
6758 } else {
6759 // magic constant: 0x1E0
6760 // To Set BIT_MODE : bit 15 = 0
6761 // XOR mask : bit [14:10] = 0
6762 // OR mask : bit [9:5] = 15
6763 // AND mask : bit [4:0] = 0
6764 if (is32BitOpc) {
6765 Register SwizzledValue =
6766 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6767 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_SWIZZLE_B32),
6768 SwizzledValue)
6769 .addReg(DPPRowShr8) // addr
6770 .addImm(0x1E0) // swizzle offset (i16)
6771 .addImm(0x0); // gds (i1)
6772 BuildClampInstr(RowBcast15, DPPRowShr8, SwizzledValue);
6773 } else {
6774 Register SwizzledValuelo =
6775 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6776 Register SwizzledValuehi =
6777 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6778 Register SwizzledValue64 = MRI.createVirtualRegister(SrcRegClass);
6779 MachineOperand DPPRowShr8Op =
6780 MachineOperand::CreateReg(DPPRowShr8, /*isDef=*/false);
6781 auto [Op1L, Op1H] =
6782 ExtractSubRegs(MI, DPPRowShr8Op, SrcRegClass, ST, MRI);
6783 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_SWIZZLE_B32),
6784 SwizzledValuelo)
6785 .addReg(Op1L) // addr
6786 .addImm(0x1E0) // swizzle offset (i16)
6787 .addImm(0x0); // gds (i1)
6788 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_SWIZZLE_B32),
6789 SwizzledValuehi)
6790 .addReg(Op1H) // addr
6791 .addImm(0x1E0) // swizzle offset (i16)
6792 .addImm(0x0); // gds (i1)
6793 BuildRegSequence(*CurrBB, MI, SwizzledValue64, SwizzledValuelo,
6794 SwizzledValuehi);
6795 if (NeedsMovDPP)
6796 RowBcast15 = BuildPostDPPInstr(DPPRowShr8, SwizzledValue64);
6797 else
6798 BuildClampInstr(RowBcast15, DPPRowShr8, SwizzledValue64);
6799 }
6800 }
6801 FinalDPPResult = RowBcast15;
6802 if (!IsWave32) {
6803 if (ST.hasDPPBroadcasts()) {
6804 BuildDPPMachineInstr(RowBcast31, RowBcast15, AMDGPU::DPP::BCAST31);
6805 if (NeedsMovDPP)
6806 RowBcast31 = BuildPostDPPInstr(RowBcast15, RowBcast31);
6807 } else {
6808 Register ShiftedThreadID =
6809 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6810 Register PermuteByteOffset =
6811 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6812 Register PermutedValue = MRI.createVirtualRegister(SrcRegClass);
6813 Register Lane32Offset =
6814 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6815 Register WordSizeConst =
6816 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6817 Register ThreadIDRegLo =
6818 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6819 Register ThreadIDReg =
6820 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6821 // Get the thread ID.
6822 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
6823 ThreadIDRegLo)
6824 .addImm(-1)
6825 .addImm(0);
6826 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_MBCNT_HI_U32_B32_e64),
6827 ThreadIDReg)
6828 .addImm(-1)
6829 .addReg(ThreadIDRegLo);
6830 // shift each lane over by 32 positions, so value in 31st lane is
6831 // present in 63rd lane.
6832 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::S_MOV_B32), Lane32Offset)
6833 .addImm(0x20);
6834 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_ADD_U32_e64),
6835 ShiftedThreadID)
6836 .addReg(ThreadIDReg)
6837 .addReg(Lane32Offset)
6838 .addImm(0); // clamp
6839 // multiply by reg size.
6840 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::S_MOV_B32), WordSizeConst)
6841 .addImm(0x4);
6842 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_MUL_LO_U32_e64),
6843 PermuteByteOffset)
6844 .addReg(WordSizeConst)
6845 .addReg(ShiftedThreadID);
6846 // Permute the lanes
6847 if (is32BitOpc) {
6848 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_PERMUTE_B32),
6849 PermutedValue)
6850 .addReg(PermuteByteOffset) // addr
6851 .addReg(RowBcast15) // data
6852 .addImm(0); // offset
6853 } else {
6854 Register PermutedValuelo =
6855 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6856 Register PermutedValuehi =
6857 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6858 MachineOperand RowBcast15Op =
6859 MachineOperand::CreateReg(RowBcast15, /*isDef=*/false);
6860 auto [RowBcast15Lo, RowBcast15Hi] =
6861 ExtractSubRegs(MI, RowBcast15Op, SrcRegClass, ST, MRI);
6862 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_PERMUTE_B32),
6863 PermutedValuelo)
6864 .addReg(PermuteByteOffset) // addr
6865 .addReg(RowBcast15Lo) // swizzle offset (i16)
6866 .addImm(0x0); // gds (i1)
6867 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_PERMUTE_B32),
6868 PermutedValuehi)
6869 .addReg(PermuteByteOffset) // addr
6870 .addReg(RowBcast15Hi) // swizzle offset (i16)
6871 .addImm(0x0); // gds (i1)
6872 BuildRegSequence(*CurrBB, MI, PermutedValue, PermutedValuelo,
6873 PermutedValuehi);
6874 }
6875 if (NeedsMovDPP)
6876 RowBcast31 = BuildPostDPPInstr(RowBcast15, PermutedValue);
6877 else
6878 BuildClampInstr(RowBcast31, RowBcast15, PermutedValue);
6879 }
6880 FinalDPPResult = RowBcast31;
6881 }
6882 if (MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F32 ||
6883 MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64) {
6884 Register NegatedValVGPR = MRI.createVirtualRegister(SrcRegClass);
6885 // Opc for f32 reduction is V_SUB_F32.
6886 // For f64, there is no equivalent V_SUB_F64 opcode, so use
6887 // V_ADD_F64/V_ADD_F64_pseudo, and negate the second operand.
6888 BuildMI(*CurrBB, MI, DL, TII->get(Opc),
6889 NegatedValVGPR)
6890 .addImm(SISrcMods::NONE) // src0 mods
6891 .addReg(IdentityVGPR) // src0
6892 .addImm(is32BitOpc ? SISrcMods::NONE : SISrcMods::NEG) // src1 mods
6893 .addReg(IsWave32 ? RowBcast15 : RowBcast31) // src1
6894 .addImm(SISrcMods::NONE) // clamp
6895 .addImm(SISrcMods::NONE); // omod
6896 FinalDPPResult = NegatedValVGPR;
6897 }
6898 // The final reduced value is in the last lane.
6899 if (is32BitOpc) {
6900 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_READLANE_B32),
6901 ReducedValSGPR)
6902 .addReg(FinalDPPResult)
6903 .addImm(ST.getWavefrontSize() - 1);
6904 } else {
6905 Register LaneValueLoReg =
6906 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6907 Register LaneValueHiReg =
6908 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6909 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
6910 MachineOperand FinalDPPResultOperand =
6911 MachineOperand::CreateReg(FinalDPPResult, /*isDef=*/false);
6912 auto [Op1L, Op1H] =
6913 ExtractSubRegs(MI, FinalDPPResultOperand, SrcRC, ST, MRI);
6914 // lane value input should be in an sgpr
6915 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_READLANE_B32),
6916 LaneValueLoReg)
6917 .addReg(Op1L)
6918 .addImm(ST.getWavefrontSize() - 1);
6919 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_READLANE_B32),
6920 LaneValueHiReg)
6921 .addReg(Op1H)
6922 .addImm(ST.getWavefrontSize() - 1);
6923 BuildRegSequence(*CurrBB, MI, ReducedValSGPR, LaneValueLoReg,
6924 LaneValueHiReg);
6925 }
6926 if (Opc == AMDGPU::S_SUB_I32) {
6927 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::S_SUB_I32), NegatedReducedVal)
6928 .addImm(0)
6929 .addReg(ReducedValSGPR)
6930 .setOperandDead(3); // Dead scc
6931 } else if (Opc == AMDGPU::S_SUB_U64_PSEUDO) {
6932 auto NegatedValInstr =
6933 BuildMI(*CurrBB, MI, DL, TII->get(Opc), NegatedReducedVal)
6934 .addImm(0)
6935 .addReg(ReducedValSGPR)
6936 .setOperandDead(3); // Dead scc
6937 CurrBB = expand64BitScalarArithmetic(*NegatedValInstr, CurrBB);
6938 }
6939 // Mark the final result as a whole-wave-mode calculation.
6940 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::STRICT_WWM), DstReg)
6941 .addReg(Opc == AMDGPU::S_SUB_I32 || Opc == AMDGPU::S_SUB_U64_PSEUDO
6942 ? NegatedReducedVal
6943 : ReducedValSGPR);
6944 RetBB = CurrBB;
6945 }
6946 }
6947 MI.eraseFromParent();
6948 return RetBB;
6949}
6950
6953 MachineBasicBlock *BB) const {
6954 MachineFunction *MF = BB->getParent();
6956 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
6958 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
6960 const DebugLoc &DL = MI.getDebugLoc();
6961
6962 switch (MI.getOpcode()) {
6963 case AMDGPU::WAVE_REDUCE_UMIN_PSEUDO_U32:
6964 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MIN_U32);
6965 case AMDGPU::WAVE_REDUCE_UMIN_PSEUDO_U64:
6966 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_LT_U64_e64);
6967 case AMDGPU::WAVE_REDUCE_MIN_PSEUDO_I32:
6968 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MIN_I32);
6969 case AMDGPU::WAVE_REDUCE_MIN_PSEUDO_I64:
6970 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_LT_I64_e64);
6971 case AMDGPU::WAVE_REDUCE_FMIN_PSEUDO_F32:
6972 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_MIN_F32_e64);
6973 case AMDGPU::WAVE_REDUCE_FMIN_PSEUDO_F64:
6974 return lowerWaveReduce(MI, *BB, *getSubtarget(),
6975 ST.getGeneration() >= AMDGPUSubtarget::GFX12
6976 ? AMDGPU::V_MIN_NUM_F64_e64
6977 : AMDGPU::V_MIN_F64_e64);
6978 case AMDGPU::WAVE_REDUCE_UMAX_PSEUDO_U32:
6979 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MAX_U32);
6980 case AMDGPU::WAVE_REDUCE_UMAX_PSEUDO_U64:
6981 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_GT_U64_e64);
6982 case AMDGPU::WAVE_REDUCE_MAX_PSEUDO_I32:
6983 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MAX_I32);
6984 case AMDGPU::WAVE_REDUCE_MAX_PSEUDO_I64:
6985 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_GT_I64_e64);
6986 case AMDGPU::WAVE_REDUCE_FMAX_PSEUDO_F32:
6987 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_MAX_F32_e64);
6988 case AMDGPU::WAVE_REDUCE_FMAX_PSEUDO_F64:
6989 return lowerWaveReduce(MI, *BB, *getSubtarget(),
6990 ST.getGeneration() >= AMDGPUSubtarget::GFX12
6991 ? AMDGPU::V_MAX_NUM_F64_e64
6992 : AMDGPU::V_MAX_F64_e64);
6993 case AMDGPU::WAVE_REDUCE_ADD_PSEUDO_I32:
6994 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_ADD_I32);
6995 case AMDGPU::WAVE_REDUCE_ADD_PSEUDO_U64:
6996 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_ADD_U64_PSEUDO);
6997 case AMDGPU::WAVE_REDUCE_FADD_PSEUDO_F32:
6998 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_ADD_F32_e64);
6999 case AMDGPU::WAVE_REDUCE_FADD_PSEUDO_F64:
7000 return lowerWaveReduce(MI, *BB, *getSubtarget(),
7001 ST.getGeneration() >= AMDGPUSubtarget::GFX12
7002 ? AMDGPU::V_ADD_F64_pseudo_e64
7003 : AMDGPU::V_ADD_F64_e64);
7004 case AMDGPU::WAVE_REDUCE_SUB_PSEUDO_I32:
7005 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_SUB_I32);
7006 case AMDGPU::WAVE_REDUCE_SUB_PSEUDO_U64:
7007 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_SUB_U64_PSEUDO);
7008 case AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F32:
7009 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_SUB_F32_e64);
7010 case AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64:
7011 // There is no S/V_SUB_F64 opcode. Double type subtraction is expanded as
7012 // fadd + neg, by setting the NEG bit in the instruction.
7013 return lowerWaveReduce(MI, *BB, *getSubtarget(),
7014 ST.getGeneration() >= AMDGPUSubtarget::GFX12
7015 ? AMDGPU::V_ADD_F64_pseudo_e64
7016 : AMDGPU::V_ADD_F64_e64);
7017 case AMDGPU::WAVE_REDUCE_AND_PSEUDO_B32:
7018 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_AND_B32);
7019 case AMDGPU::WAVE_REDUCE_AND_PSEUDO_B64:
7020 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_AND_B64);
7021 case AMDGPU::WAVE_REDUCE_OR_PSEUDO_B32:
7022 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_OR_B32);
7023 case AMDGPU::WAVE_REDUCE_OR_PSEUDO_B64:
7024 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_OR_B64);
7025 case AMDGPU::WAVE_REDUCE_XOR_PSEUDO_B32:
7026 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_XOR_B32);
7027 case AMDGPU::WAVE_REDUCE_XOR_PSEUDO_B64:
7028 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_XOR_B64);
7029 case AMDGPU::S_UADDO_PSEUDO:
7030 case AMDGPU::S_USUBO_PSEUDO: {
7031 MachineOperand &Dest0 = MI.getOperand(0);
7032 MachineOperand &Dest1 = MI.getOperand(1);
7033 MachineOperand &Src0 = MI.getOperand(2);
7034 MachineOperand &Src1 = MI.getOperand(3);
7035
7036 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
7037 ? AMDGPU::S_ADD_U32
7038 : AMDGPU::S_SUB_U32;
7039 // clang-format off
7040 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg())
7041 .add(Src0)
7042 .add(Src1);
7043 // clang-format on
7044
7045 unsigned SelOpc =
7046 Subtarget->isWave64() ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
7047 BuildMI(*BB, MI, DL, TII->get(SelOpc), Dest1.getReg()).addImm(-1).addImm(0);
7048
7049 MI.eraseFromParent();
7050 return BB;
7051 }
7052 case AMDGPU::S_ADD_U64_PSEUDO:
7053 case AMDGPU::S_SUB_U64_PSEUDO: {
7054 return expand64BitScalarArithmetic(MI, BB);
7055 }
7056 case AMDGPU::V_ADD_U64_PSEUDO:
7057 case AMDGPU::V_SUB_U64_PSEUDO: {
7058 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
7059
7060 MachineOperand &Dest = MI.getOperand(0);
7061 MachineOperand &Src0 = MI.getOperand(1);
7062 MachineOperand &Src1 = MI.getOperand(2);
7063
7064 if (ST.hasAddSubU64Insts()) {
7065 auto I = BuildMI(*BB, MI, DL,
7066 TII->get(IsAdd ? AMDGPU::V_ADD_U64_e64
7067 : AMDGPU::V_SUB_U64_e64),
7068 Dest.getReg())
7069 .add(Src0)
7070 .add(Src1)
7071 .addImm(0); // clamp
7072 TII->legalizeOperands(*I);
7073 MI.eraseFromParent();
7074 return BB;
7075 }
7076
7077 if (IsAdd && ST.hasLshlAddU64Inst()) {
7078 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
7079 Dest.getReg())
7080 .add(Src0)
7081 .addImm(0)
7082 .add(Src1);
7083 TII->legalizeOperands(*Add);
7084 MI.eraseFromParent();
7085 return BB;
7086 }
7087
7088 const auto *CarryRC = TRI->getWaveMaskRegClass();
7089
7090 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7091 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7092
7093 Register CarryReg = MRI.createVirtualRegister(CarryRC);
7094 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
7095
7096 const TargetRegisterClass *Src0RC = Src0.isReg()
7097 ? MRI.getRegClass(Src0.getReg())
7098 : &AMDGPU::VReg_64RegClass;
7099 const TargetRegisterClass *Src1RC = Src1.isReg()
7100 ? MRI.getRegClass(Src1.getReg())
7101 : &AMDGPU::VReg_64RegClass;
7102
7103 const TargetRegisterClass *Src0SubRC =
7104 TRI->getSubRegisterClass(Src0RC, AMDGPU::sub0);
7105 const TargetRegisterClass *Src1SubRC =
7106 TRI->getSubRegisterClass(Src1RC, AMDGPU::sub1);
7107
7108 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
7109 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
7110 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
7111 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
7112
7113 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
7114 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
7115 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
7116 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
7117
7118 unsigned LoOpc =
7119 IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
7120 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
7121 .addReg(CarryReg, RegState::Define)
7122 .add(SrcReg0Sub0)
7123 .add(SrcReg1Sub0)
7124 .addImm(0); // clamp bit
7125
7126 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
7127 MachineInstr *HiHalf =
7128 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
7129 .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
7130 .add(SrcReg0Sub1)
7131 .add(SrcReg1Sub1)
7132 .addReg(CarryReg)
7133 .addImm(0); // clamp bit
7134
7135 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
7136 .addReg(DestSub0)
7137 .addImm(AMDGPU::sub0)
7138 .addReg(DestSub1)
7139 .addImm(AMDGPU::sub1);
7140 TII->legalizeOperands(*LoHalf);
7141 TII->legalizeOperands(*HiHalf);
7142 MI.eraseFromParent();
7143 return BB;
7144 }
7145 case AMDGPU::S_ADD_CO_PSEUDO:
7146 case AMDGPU::S_SUB_CO_PSEUDO: {
7147 // This pseudo has a chance to be selected
7148 // only from uniform add/subcarry node. All the VGPR operands
7149 // therefore assumed to be splat vectors.
7151 MachineOperand &Dest = MI.getOperand(0);
7152 MachineOperand &CarryDest = MI.getOperand(1);
7153 MachineOperand &Src0 = MI.getOperand(2);
7154 MachineOperand &Src1 = MI.getOperand(3);
7155 MachineOperand &Src2 = MI.getOperand(4);
7156 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
7157 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7158 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
7159 .addReg(Src0.getReg());
7160 Src0.setReg(RegOp0);
7161 }
7162 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
7163 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7164 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
7165 .addReg(Src1.getReg());
7166 Src1.setReg(RegOp1);
7167 }
7168 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7169 if (TRI->isVectorRegister(MRI, Src2.getReg())) {
7170 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
7171 .addReg(Src2.getReg());
7172 Src2.setReg(RegOp2);
7173 }
7174
7175 if (ST.isWave64()) {
7176 if (ST.hasScalarCompareEq64()) {
7177 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
7178 .addReg(Src2.getReg())
7179 .addImm(0);
7180 } else {
7181 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
7182 const TargetRegisterClass *SubRC =
7183 TRI->getSubRegisterClass(Src2RC, AMDGPU::sub0);
7184 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
7185 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
7186 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
7187 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
7188 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7189
7190 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
7191 .add(Src2Sub0)
7192 .add(Src2Sub1);
7193
7194 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
7195 .addReg(Src2_32)
7196 .addImm(0);
7197 }
7198 } else {
7199 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
7200 .addReg(Src2.getReg())
7201 .addImm(0);
7202 }
7203
7204 unsigned Opc = MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO
7205 ? AMDGPU::S_ADDC_U32
7206 : AMDGPU::S_SUBB_U32;
7207
7208 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
7209
7210 unsigned SelOpc =
7211 ST.isWave64() ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
7212
7213 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
7214 .addImm(-1)
7215 .addImm(0);
7216
7217 MI.eraseFromParent();
7218 return BB;
7219 }
7220 case AMDGPU::SI_INIT_M0: {
7221 MachineOperand &M0Init = MI.getOperand(0);
7222 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
7223 TII->get(M0Init.isReg() ? AMDGPU::COPY : AMDGPU::S_MOV_B32),
7224 AMDGPU::M0)
7225 .add(M0Init);
7226 MI.eraseFromParent();
7227 return BB;
7228 }
7229 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM: {
7230 // Set SCC to true, in case the barrier instruction gets converted to a NOP.
7231 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
7232 TII->get(AMDGPU::S_CMP_EQ_U32))
7233 .addImm(0)
7234 .addImm(0);
7235 return BB;
7236 }
7237 case AMDGPU::GET_GROUPSTATICSIZE: {
7238 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
7239 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
7240 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
7241 .add(MI.getOperand(0))
7242 .addImm(MFI->getLDSSize());
7243 MI.eraseFromParent();
7244 return BB;
7245 }
7246 case AMDGPU::GET_SHADERCYCLESHILO: {
7247 assert(MF->getSubtarget<GCNSubtarget>().hasShaderCyclesHiLoRegisters());
7248 // The algorithm is:
7249 //
7250 // hi1 = getreg(SHADER_CYCLES_HI)
7251 // lo1 = getreg(SHADER_CYCLES_LO)
7252 // hi2 = getreg(SHADER_CYCLES_HI)
7253 //
7254 // If hi1 == hi2 then there was no overflow and the result is hi2:lo1.
7255 // Otherwise there was overflow and the result is hi2:0. In both cases the
7256 // result should represent the actual time at some point during the sequence
7257 // of three getregs.
7258 using namespace AMDGPU::Hwreg;
7259 Register RegHi1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7260 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegHi1)
7261 .addImm(HwregEncoding::encode(ID_SHADER_CYCLES_HI, 0, 32));
7262 Register RegLo1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7263 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegLo1)
7264 .addImm(HwregEncoding::encode(ID_SHADER_CYCLES, 0, 32));
7265 Register RegHi2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7266 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegHi2)
7267 .addImm(HwregEncoding::encode(ID_SHADER_CYCLES_HI, 0, 32));
7268 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CMP_EQ_U32))
7269 .addReg(RegHi1)
7270 .addReg(RegHi2);
7271 Register RegLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7272 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B32), RegLo)
7273 .addReg(RegLo1)
7274 .addImm(0);
7275 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE))
7276 .add(MI.getOperand(0))
7277 .addReg(RegLo)
7278 .addImm(AMDGPU::sub0)
7279 .addReg(RegHi2)
7280 .addImm(AMDGPU::sub1);
7281 MI.eraseFromParent();
7282 return BB;
7283 }
7284 case AMDGPU::SI_INDIRECT_SRC_V1:
7285 case AMDGPU::SI_INDIRECT_SRC_V2:
7286 case AMDGPU::SI_INDIRECT_SRC_V3:
7287 case AMDGPU::SI_INDIRECT_SRC_V4:
7288 case AMDGPU::SI_INDIRECT_SRC_V5:
7289 case AMDGPU::SI_INDIRECT_SRC_V6:
7290 case AMDGPU::SI_INDIRECT_SRC_V7:
7291 case AMDGPU::SI_INDIRECT_SRC_V8:
7292 case AMDGPU::SI_INDIRECT_SRC_V9:
7293 case AMDGPU::SI_INDIRECT_SRC_V10:
7294 case AMDGPU::SI_INDIRECT_SRC_V11:
7295 case AMDGPU::SI_INDIRECT_SRC_V12:
7296 case AMDGPU::SI_INDIRECT_SRC_V16:
7297 case AMDGPU::SI_INDIRECT_SRC_V32:
7298 return emitIndirectSrc(MI, *BB, *getSubtarget());
7299 case AMDGPU::SI_INDIRECT_DST_V1:
7300 case AMDGPU::SI_INDIRECT_DST_V2:
7301 case AMDGPU::SI_INDIRECT_DST_V3:
7302 case AMDGPU::SI_INDIRECT_DST_V4:
7303 case AMDGPU::SI_INDIRECT_DST_V5:
7304 case AMDGPU::SI_INDIRECT_DST_V6:
7305 case AMDGPU::SI_INDIRECT_DST_V7:
7306 case AMDGPU::SI_INDIRECT_DST_V8:
7307 case AMDGPU::SI_INDIRECT_DST_V9:
7308 case AMDGPU::SI_INDIRECT_DST_V10:
7309 case AMDGPU::SI_INDIRECT_DST_V11:
7310 case AMDGPU::SI_INDIRECT_DST_V12:
7311 case AMDGPU::SI_INDIRECT_DST_V16:
7312 case AMDGPU::SI_INDIRECT_DST_V32:
7313 return emitIndirectDst(MI, *BB, *getSubtarget());
7314 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
7315 case AMDGPU::SI_KILL_I1_PSEUDO:
7316 return splitKillBlock(MI, BB);
7317 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
7319 return BB;
7320 }
7321 case AMDGPU::SI_BR_UNDEF: {
7322 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
7323 .add(MI.getOperand(0));
7324 Br->getOperand(1).setIsUndef(); // read undef SCC
7325 MI.eraseFromParent();
7326 return BB;
7327 }
7328 case AMDGPU::ADJCALLSTACKUP:
7329 case AMDGPU::ADJCALLSTACKDOWN: {
7331 MachineInstrBuilder MIB(*MF, &MI);
7332 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
7333 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
7334 return BB;
7335 }
7336 case AMDGPU::SI_CALL_ISEL: {
7337 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
7338
7340 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL))
7341 .addDef(ReturnAddrReg, RegState::Dead);
7342
7343 for (const MachineOperand &MO : MI.operands())
7344 MIB.add(MO);
7345
7346 MIB.cloneMemRefs(MI);
7347 MIB.setMIFlags(MI.getFlags());
7348 MI.eraseFromParent();
7349 return BB;
7350 }
7351 case AMDGPU::V_ADDC_U32_e32:
7352 case AMDGPU::V_SUBB_U32_e32:
7353 case AMDGPU::V_SUBBREV_U32_e32:
7354 // These instructions have an implicit use of vcc which counts towards the
7355 // constant bus limit.
7356 TII->legalizeOperands(MI);
7357 return BB;
7358 case AMDGPU::DS_GWS_INIT:
7359 case AMDGPU::DS_GWS_SEMA_BR:
7360 case AMDGPU::DS_GWS_BARRIER:
7361 case AMDGPU::DS_GWS_SEMA_V:
7362 case AMDGPU::DS_GWS_SEMA_P:
7363 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
7364 // A s_waitcnt 0 is required to be the instruction immediately following.
7365 if (getSubtarget()->hasGWSAutoReplay()) {
7367 return BB;
7368 }
7369
7370 return emitGWSMemViolTestLoop(MI, BB);
7371 case AMDGPU::S_SETREG_B32: {
7372 // Try to optimize cases that only set the denormal mode or rounding mode.
7373 //
7374 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
7375 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
7376 // instead.
7377 //
7378 // FIXME: This could be predicates on the immediate, but tablegen doesn't
7379 // allow you to have a no side effect instruction in the output of a
7380 // sideeffecting pattern.
7381 auto [ID, Offset, Width] =
7382 AMDGPU::Hwreg::HwregEncoding::decode(MI.getOperand(1).getImm());
7383 if (ID != AMDGPU::Hwreg::ID_MODE)
7384 return BB;
7385
7386 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
7387 const unsigned SetMask = WidthMask << Offset;
7388
7389 if (getSubtarget()->hasDenormModeInst()) {
7390 unsigned SetDenormOp = 0;
7391 unsigned SetRoundOp = 0;
7392
7393 // The dedicated instructions can only set the whole denorm or round mode
7394 // at once, not a subset of bits in either.
7395 if (SetMask ==
7397 // If this fully sets both the round and denorm mode, emit the two
7398 // dedicated instructions for these.
7399 SetRoundOp = AMDGPU::S_ROUND_MODE;
7400 SetDenormOp = AMDGPU::S_DENORM_MODE;
7401 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
7402 SetRoundOp = AMDGPU::S_ROUND_MODE;
7403 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
7404 SetDenormOp = AMDGPU::S_DENORM_MODE;
7405 }
7406
7407 if (SetRoundOp || SetDenormOp) {
7408 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
7409 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
7410 unsigned ImmVal = Def->getOperand(1).getImm();
7411 if (SetRoundOp) {
7412 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
7413 .addImm(ImmVal & 0xf);
7414
7415 // If we also have the denorm mode, get just the denorm mode bits.
7416 ImmVal >>= 4;
7417 }
7418
7419 if (SetDenormOp) {
7420 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
7421 .addImm(ImmVal & 0xf);
7422 }
7423
7424 MI.eraseFromParent();
7425 return BB;
7426 }
7427 }
7428 }
7429
7430 // If only FP bits are touched, used the no side effects pseudo.
7431 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
7432 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
7433 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
7434
7435 return BB;
7436 }
7437 case AMDGPU::S_INVERSE_BALLOT_U32:
7438 case AMDGPU::S_INVERSE_BALLOT_U64:
7439 // These opcodes only exist to let SIFixSGPRCopies insert a readfirstlane if
7440 // necessary. After that they are equivalent to a COPY.
7441 MI.setDesc(TII->get(AMDGPU::COPY));
7442 return BB;
7443 case AMDGPU::ENDPGM_TRAP: {
7444 if (BB->succ_empty() && std::next(MI.getIterator()) == BB->end()) {
7445 MI.setDesc(TII->get(AMDGPU::S_ENDPGM));
7446 MI.addOperand(MachineOperand::CreateImm(0));
7447 return BB;
7448 }
7449
7450 // We need a block split to make the real endpgm a terminator. We also don't
7451 // want to break phis in successor blocks, so we can't just delete to the
7452 // end of the block.
7453
7454 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
7456 MF->push_back(TrapBB);
7457 // clang-format off
7458 BuildMI(*TrapBB, TrapBB->end(), DL, TII->get(AMDGPU::S_ENDPGM))
7459 .addImm(0);
7460 BuildMI(*BB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
7461 .addMBB(TrapBB);
7462 // clang-format on
7463
7464 BB->addSuccessor(TrapBB);
7465 MI.eraseFromParent();
7466 return SplitBB;
7467 }
7468 case AMDGPU::SIMULATED_TRAP: {
7469 assert(Subtarget->hasPrivEnabledTrap2NopBug());
7470 MachineBasicBlock *SplitBB =
7471 TII->insertSimulatedTrap(MRI, *BB, MI, MI.getDebugLoc());
7472 MI.eraseFromParent();
7473 return SplitBB;
7474 }
7475 case AMDGPU::SI_TCRETURN_GFX_WholeWave:
7476 case AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN: {
7478
7479 // During ISel, it's difficult to propagate the original EXEC mask to use as
7480 // an input to SI_WHOLE_WAVE_FUNC_RETURN. Set it up here instead.
7481 MachineInstr *Setup = TII->getWholeWaveFunctionSetup(*BB->getParent());
7482 assert(Setup && "Couldn't find SI_SETUP_WHOLE_WAVE_FUNC");
7483 Register OriginalExec = Setup->getOperand(0).getReg();
7484 MI.getOperand(0).setReg(OriginalExec);
7485 return BB;
7486 }
7487 case AMDGPU::V_DOT2_F32_F16:
7488 case AMDGPU::V_DOT2_F32_BF16: {
7489 // Hint RA to assign dst and src2 the same physical register.
7490 // For targets without VOP2, but with VOPD, variant of the instruction this
7491 // is one of the conditions to attempt converting VOP3P to VOPD.
7492 MRI.setSimpleHint(MI.getOperand(0).getReg(), MI.getOperand(6).getReg());
7493 return BB;
7494 }
7495 case AMDGPU::SCHED_BARRIER:
7496 case AMDGPU::SCHED_GROUP_BARRIER:
7497 MI.getOperand(0).setImm(MI.getOperand(0).getImm() &
7498 static_cast<unsigned>(AMDGPU::SchedGroupMask::ALL));
7499 return BB;
7500 default:
7501 if (TII->isImage(MI) || TII->isMUBUF(MI)) {
7502 if (!MI.mayStore())
7504 return BB;
7505 }
7507 }
7508}
7509
7511 // This currently forces unfolding various combinations of fsub into fma with
7512 // free fneg'd operands. As long as we have fast FMA (controlled by
7513 // isFMAFasterThanFMulAndFAdd), we should perform these.
7514
7515 // When fma is quarter rate, for f64 where add / sub are at best half rate,
7516 // most of these combines appear to be cycle neutral but save on instruction
7517 // count / code size.
7518 return true;
7519}
7520
7522
7524 EVT VT) const {
7525 if (!VT.isVector()) {
7526 return MVT::i1;
7527 }
7528 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
7529}
7530
7532 // TODO: Should i16 be used always if legal? For now it would force VALU
7533 // shifts.
7534 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
7535}
7536
7538 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
7539 ? Ty.changeElementSize(16)
7540 : Ty.changeElementSize(32);
7541}
7542
7543// Answering this is somewhat tricky and depends on the specific device which
7544// have different rates for fma or all f64 operations.
7545//
7546// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
7547// regardless of which device (although the number of cycles differs between
7548// devices), so it is always profitable for f64.
7549//
7550// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
7551// only on full rate devices. Normally, we should prefer selecting v_mad_f32
7552// which we can always do even without fused FP ops since it returns the same
7553// result as the separate operations and since it is always full
7554// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
7555// however does not support denormals, so we do report fma as faster if we have
7556// a fast fma device and require denormals.
7557//
7559 DenormalFPEnv FPEnv) const {
7560 VT = VT.getScalarType();
7561 if (!VT.isSimple())
7562 return false;
7563
7564 switch (VT.getSimpleVT().SimpleTy) {
7565 case MVT::f32: {
7566 // If mad is not available this depends only on if f32 fma is full rate.
7567 if (!Subtarget->hasMadMacF32Insts())
7568 return Subtarget->hasFastFMAF32();
7569
7570 // Otherwise f32 mad is always full rate and returns the same result as
7571 // the separate operations so should be preferred over fma.
7572 // However does not support denormals.
7574 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
7575
7576 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
7577 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
7578 }
7579 case MVT::f64:
7580 return true;
7581 case MVT::f16:
7582 case MVT::bf16:
7583 return Subtarget->has16BitInsts() &&
7585 default:
7586 break;
7587 }
7588
7589 return false;
7590}
7591
7596
7598 Type *Ty) const {
7600 getValueType(F.getDataLayout(), Ty, /*AllowUnknown=*/true),
7601 F.getDenormalFPEnv());
7602}
7603
7605 LLT Ty) const {
7606 switch (Ty.getScalarSizeInBits()) {
7607 case 16:
7608 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
7609 case 32:
7610 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
7611 case 64:
7612 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
7613 default:
7614 break;
7615 }
7616
7617 return false;
7618}
7619
7621 // TODO: Check future ftz flag
7622 // v_mad_f32/v_mac_f32 do not support denormals.
7623 if (VT == MVT::f32)
7624 return Subtarget->hasMadMacF32Insts() &&
7626 if (VT == MVT::f16)
7627 return Subtarget->hasMadF16() &&
7629
7630 return false;
7631}
7632
7634 if (!Ty.isScalar())
7635 return false;
7636
7637 DenormalFPEnv FPEnv = getDenormalFPEnv(*MI.getMF());
7638 if (Ty.getScalarSizeInBits() == 16)
7639 return isFMADLegal(MVT::f16, FPEnv);
7640 if (Ty.getScalarSizeInBits() == 32)
7641 return isFMADLegal(MVT::f32, FPEnv);
7642
7643 return false;
7644}
7645
7647 const SDNode *N) const {
7648 return isFMADLegal(N->getValueType(0),
7650}
7651
7653 return isFMADLegal(getValueType(F.getDataLayout(), Ty->getScalarType(),
7654 /*AllowUnknown=*/true),
7655 F.getDenormalFPEnv());
7656}
7657
7658//===----------------------------------------------------------------------===//
7659// Custom DAG Lowering Operations
7660//===----------------------------------------------------------------------===//
7661
7662// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
7663// wider vector type is legal.
7665 SelectionDAG &DAG) const {
7666 unsigned Opc = Op.getOpcode();
7667 EVT VT = Op.getValueType();
7669
7670 auto [Lo, Hi] = DAG.SplitVectorOperand(Op.getNode(), 0);
7671 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
7672
7673 SDLoc SL(Op);
7674
7675 // Forward any trailing scalar operands unchanged to both halves.
7676 SmallVector<SDValue, 2> LoOps = {Lo};
7677 SmallVector<SDValue, 2> HiOps = {Hi};
7678 auto TrailingOps = drop_begin(Op->ops());
7679 LoOps.append(TrailingOps.begin(), TrailingOps.end());
7680 HiOps.append(TrailingOps.begin(), TrailingOps.end());
7681
7682 SDValue OpLo = DAG.getNode(Opc, SL, LoVT, LoOps, Op->getFlags());
7683 SDValue OpHi = DAG.getNode(Opc, SL, HiVT, HiOps, Op->getFlags());
7684
7685 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
7686}
7687
7688// Enable lowering of ROTR for vxi32 types. This is a workaround for a
7689// regression whereby extra unnecessary instructions were added to codegen
7690// for rotr operations, casued by legalising v2i32 or. This resulted in extra
7691// instructions to extract the result from the vector.
7693 [[maybe_unused]] EVT VT = Op.getValueType();
7694
7695 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v8i32 ||
7696 VT == MVT::v16i32) &&
7697 "Unexpected ValueType.");
7698
7699 return DAG.UnrollVectorOp(Op.getNode());
7700}
7701
7702// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
7703// wider vector type is legal.
7705 SelectionDAG &DAG) const {
7706 unsigned Opc = Op.getOpcode();
7707 EVT VT = Op.getValueType();
7709
7710 auto [Lo0, Hi0] = DAG.SplitVectorOperand(Op.getNode(), 0);
7711 auto [Lo1, Hi1] = DAG.SplitVectorOperand(Op.getNode(), 1);
7712
7713 SDLoc SL(Op);
7714
7715 SDValue OpLo =
7716 DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Op->getFlags());
7717 SDValue OpHi =
7718 DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Op->getFlags());
7719
7720 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
7721}
7722
7724 SelectionDAG &DAG) const {
7725 unsigned Opc = Op.getOpcode();
7726 EVT VT = Op.getValueType();
7728
7729 SDValue Op0 = Op.getOperand(0);
7730 SDValue Lo0, Hi0;
7731 if (Op0.getValueType().isVector())
7732 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
7733 else
7734 Lo0 = Hi0 = DAG.getFreeze(Op0);
7735
7736 auto [Lo1, Hi1] = DAG.SplitVectorOperand(Op.getNode(), 1);
7737 auto [Lo2, Hi2] = DAG.SplitVectorOperand(Op.getNode(), 2);
7738
7739 SDLoc SL(Op);
7740 auto ResVT = DAG.GetSplitDestVTs(VT);
7741
7742 SDValue OpLo =
7743 DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, Op->getFlags());
7744 SDValue OpHi =
7745 DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, Op->getFlags());
7746
7747 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
7748}
7749
7751 switch (Op.getOpcode()) {
7752 default:
7754 case ISD::BRCOND:
7755 return LowerBRCOND(Op, DAG);
7756 case ISD::RETURNADDR:
7757 return LowerRETURNADDR(Op, DAG);
7758 case ISD::SPONENTRY:
7759 return LowerSPONENTRY(Op, DAG);
7760 case ISD::LOAD: {
7761 SDValue Result = LowerLOAD(Op, DAG);
7762 assert((!Result.getNode() || Result.getNode()->getNumValues() == 2) &&
7763 "Load should return a value and a chain");
7764 return Result;
7765 }
7766 case ISD::FSQRT: {
7767 EVT VT = Op.getValueType();
7768 if (VT == MVT::f32)
7769 return lowerFSQRTF32(Op, DAG);
7770 if (VT == MVT::f64)
7771 return lowerFSQRTF64(Op, DAG);
7772 return SDValue();
7773 }
7774 case ISD::FSIN:
7775 case ISD::FCOS:
7776 return LowerTrig(Op, DAG);
7777 case ISD::SELECT:
7778 return LowerSELECT(Op, DAG);
7779 case ISD::FDIV:
7780 return LowerFDIV(Op, DAG);
7781 case ISD::FFREXP:
7782 return LowerFFREXP(Op, DAG);
7784 return LowerATOMIC_CMP_SWAP(Op, DAG);
7785 case ISD::STORE:
7786 return LowerSTORE(Op, DAG);
7787 case ISD::GlobalAddress: {
7790 return LowerGlobalAddress(MFI, Op, DAG);
7791 }
7792 case ISD::BlockAddress:
7793 return LowerBlockAddress(Op, DAG);
7795 return LowerExternalSymbol(Op, DAG);
7797 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7799 return LowerCONVERT_FROM_ARBITRARY_FP(Op, DAG);
7801 return LowerCONVERT_TO_ARBITRARY_FP(Op, DAG);
7803 return LowerINTRINSIC_W_CHAIN(Op, DAG);
7805 return LowerINTRINSIC_VOID(Op, DAG);
7806 case ISD::ADDRSPACECAST:
7807 return lowerADDRSPACECAST(Op, DAG);
7809 return lowerINSERT_SUBVECTOR(Op, DAG);
7811 return lowerINSERT_VECTOR_ELT(Op, DAG);
7813 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
7815 return lowerVECTOR_SHUFFLE(Op, DAG);
7817 return lowerSCALAR_TO_VECTOR(Op, DAG);
7818 case ISD::BUILD_VECTOR:
7819 return lowerBUILD_VECTOR(Op, DAG);
7820 case ISD::FP_ROUND:
7822 return lowerFP_ROUND(Op, DAG);
7823 case ISD::TRAP:
7824 return lowerTRAP(Op, DAG);
7825 case ISD::DEBUGTRAP:
7826 return lowerDEBUGTRAP(Op, DAG);
7827 case ISD::ABS:
7828 case ISD::FABS:
7829 case ISD::FNEG:
7830 case ISD::FCANONICALIZE:
7831 case ISD::BSWAP:
7832 return splitUnaryVectorOp(Op, DAG);
7835 if (Op.getValueType().isVector() && Op.getValueType() != MVT::v2i16 &&
7836 Op.getOperand(0).getValueType().getScalarType() == MVT::f32)
7837 return splitUnaryVectorOp(Op, DAG);
7838 return LowerFP_TO_INT_SAT(Op, DAG);
7839 case ISD::FSUB:
7840 if (Op.getValueType() == MVT::bf16) {
7841 // Custom expansion:
7842 // fsub bf16 %a, %b -> fadd v2bf16(widen %a), fneg v2bf16(widen %b)
7843 // Then extract back to bf16.
7844 //
7845 // We create fneg on v2bf16 (not bf16) so the instruction selector can
7846 // fold the negation into the packed add's neg_lo/neg_hi modifiers,
7847 // generating a single v_pk_add_bf16 instruction. If we negate bf16 first,
7848 // it becomes a separate v_xor instruction before widening.
7849 SDLoc DL(Op);
7850 SDValue Op0 = Op.getOperand(0);
7851 SDValue Op1 = Op.getOperand(1);
7852
7853 // Widen both operands to v2bf16
7854 SDValue Vec0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2bf16, Op0);
7855 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2bf16, Op1);
7856
7857 // Create FNEG v2bf16 for the second operand
7858 SDValue NegVec1 = DAG.getNode(ISD::FNEG, DL, MVT::v2bf16, Vec1);
7859
7860 // Perform FADD v2bf16
7861 SDValue Result = DAG.getNode(ISD::FADD, DL, MVT::v2bf16, Vec0, NegVec1);
7862
7863 // Extract element 0 back to bf16
7864 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::bf16, Result,
7865 DAG.getConstant(0, DL, MVT::i32));
7866 }
7867 return SDValue();
7868 case ISD::FMINNUM:
7869 case ISD::FMAXNUM:
7870 return lowerFMINNUM_FMAXNUM(Op, DAG);
7871 case ISD::FMINIMUMNUM:
7872 case ISD::FMAXIMUMNUM:
7873 return lowerFMINIMUMNUM_FMAXIMUMNUM(Op, DAG);
7874 case ISD::FLDEXP:
7875 case ISD::STRICT_FLDEXP:
7876 return lowerFLDEXP(Op, DAG);
7877 case ISD::FMA:
7878 return splitTernaryVectorOp(Op, DAG);
7879 case ISD::FP_TO_SINT:
7880 case ISD::FP_TO_UINT:
7881 if (Subtarget->hasVCvtPkIU16F32() && Op.getValueType() == MVT::i16 &&
7882 Op.getOperand(0).getValueType() == MVT::f32) {
7883 // Make f32->i16 legal so we can select V_CVT_PK_[IU]16_F32.
7884 return Op;
7885 }
7886 return LowerFP_TO_INT(Op, DAG);
7887 case ISD::SHL:
7888 case ISD::SRA:
7889 case ISD::SRL:
7890 case ISD::ADD:
7891 case ISD::SUB:
7892 case ISD::SMIN:
7893 case ISD::SMAX:
7894 case ISD::UMIN:
7895 case ISD::UMAX:
7896 case ISD::FMINNUM_IEEE:
7897 case ISD::FMAXNUM_IEEE:
7898 case ISD::FMINIMUM:
7899 case ISD::FMAXIMUM:
7900 case ISD::UADDSAT:
7901 case ISD::USUBSAT:
7902 case ISD::SADDSAT:
7903 case ISD::SSUBSAT:
7904 case ISD::FADD:
7905 case ISD::FMUL:
7906 return splitBinaryVectorOp(Op, DAG);
7907 case ISD::FCOPYSIGN:
7908 return lowerFCOPYSIGN(Op, DAG);
7909 case ISD::MUL:
7910 return lowerMUL(Op, DAG);
7911 case ISD::SMULO:
7912 case ISD::UMULO:
7913 return lowerXMULO(Op, DAG);
7914 case ISD::SMUL_LOHI:
7915 case ISD::UMUL_LOHI:
7916 return lowerXMUL_LOHI(Op, DAG);
7918 return LowerDYNAMIC_STACKALLOC(Op, DAG);
7919 case ISD::STACKSAVE:
7920 return LowerSTACKSAVE(Op, DAG);
7921 case ISD::GET_ROUNDING:
7922 return lowerGET_ROUNDING(Op, DAG);
7923 case ISD::SET_ROUNDING:
7924 return lowerSET_ROUNDING(Op, DAG);
7925 case ISD::PREFETCH:
7926 return lowerPREFETCH(Op, DAG);
7927 case ISD::FP_EXTEND:
7929 return lowerFP_EXTEND(Op, DAG);
7930 case ISD::GET_FPENV:
7931 return lowerGET_FPENV(Op, DAG);
7932 case ISD::SET_FPENV:
7933 return lowerSET_FPENV(Op, DAG);
7934 case ISD::ROTR:
7935 return lowerROTR(Op, DAG);
7936 case ISD::INLINEASM:
7937 return LowerINLINEASM(Op, DAG);
7938 }
7939 return SDValue();
7940}
7941
7942// TFE results are dword granular: value dwords followed by one status dword.
7943static std::pair<SDValue, SDValue>
7945 LLVMContext &C = *DAG.getContext();
7946 unsigned NumValueDWords = divideCeil(VT.getSizeInBits(), 32);
7948 DAG.getVectorIdxConstant(NumValueDWords, DL));
7949 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
7950 SDValue ValueDWords =
7951 NumValueDWords == 1
7952 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op, ZeroIdx)
7954 EVT::getVectorVT(C, MVT::i32, NumValueDWords), Op,
7955 ZeroIdx);
7956 if (!VT.isVector() && VT.getSizeInBits() < 32)
7957 ValueDWords =
7958 DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), ValueDWords);
7959 return {DAG.getNode(ISD::BITCAST, DL, VT, ValueDWords), Status};
7960}
7961
7962// Used for D16: Casts the result of an instruction into the right vector,
7963// packs values if loads return unpacked values.
7965 const SDLoc &DL, SelectionDAG &DAG,
7966 bool Unpacked) {
7967 if (!LoadVT.isVector())
7968 return Result;
7969
7970 // Cast back to the original packed type or to a larger type that is a
7971 // multiple of 32 bit for D16. Widening the return type is a required for
7972 // legalization.
7973 EVT FittingLoadVT = LoadVT;
7974 if ((LoadVT.getVectorNumElements() % 2) == 1) {
7975 FittingLoadVT =
7977 LoadVT.getVectorNumElements() + 1);
7978 }
7979
7980 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
7981 // Truncate to v2i16/v4i16.
7982 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
7983
7984 // Workaround legalizer not scalarizing truncate after vector op
7985 // legalization but not creating intermediate vector trunc.
7987 DAG.ExtractVectorElements(Result, Elts);
7988 for (SDValue &Elt : Elts)
7989 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
7990
7991 // Pad illegal v1i16/v3fi6 to v4i16
7992 if ((LoadVT.getVectorNumElements() % 2) == 1)
7993 Elts.push_back(DAG.getPOISON(MVT::i16));
7994
7995 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
7996
7997 // Bitcast to original type (v2f16/v4f16).
7998 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
7999 }
8000
8001 // Cast back to the original packed type.
8002 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
8003}
8004
8005SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, MemSDNode *M,
8006 SelectionDAG &DAG,
8008 bool IsIntrinsic) const {
8009 SDLoc DL(M);
8010
8011 bool IsTFE = M->getNumValues() == 3;
8012 bool Unpacked = Subtarget->hasUnpackedD16VMem();
8013 EVT LoadVT = M->getValueType(0);
8014
8015 EVT EquivLoadVT = LoadVT;
8016 if (LoadVT.isVector()) {
8017 if (Unpacked) {
8018 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8019 LoadVT.getVectorNumElements());
8020 } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
8021 // Widen v3f16 to legal type
8022 EquivLoadVT =
8024 LoadVT.getVectorNumElements() + 1);
8025 }
8026 }
8027
8028 if (IsTFE) {
8029 unsigned NumValueDWords = divideCeil(EquivLoadVT.getSizeInBits(), 32);
8030 EVT LoadDWordsVT =
8031 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumValueDWords + 1);
8032 SDVTList VTList = DAG.getVTList(LoadDWordsVT, MVT::Other);
8034 Opcode, DL, VTList, Ops, M->getMemoryVT(), M->getMemOperand());
8035 auto [Value, Status] = splitTFEValueAndStatus(Load, EquivLoadVT, DL, DAG);
8036 SDValue Adjusted =
8037 adjustLoadValueTypeImpl(Value, LoadVT, DL, DAG, Unpacked);
8038 return DAG.getMergeValues({Adjusted, Status, Load.getValue(1)}, DL);
8039 }
8040
8041 // Change from v4f16/v2f16 to EquivLoadVT.
8042 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
8043
8045 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, VTList, Ops,
8046 M->getMemoryVT(), M->getMemOperand());
8047
8048 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
8049
8050 return DAG.getMergeValues({Adjusted, Load.getValue(1)}, DL);
8051}
8052
8053SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
8054 SelectionDAG &DAG,
8055 ArrayRef<SDValue> Ops) const {
8056 SDLoc DL(M);
8057 EVT LoadVT = M->getValueType(0);
8058 EVT EltType = LoadVT.getScalarType();
8059 EVT IntVT = LoadVT.changeTypeToInteger();
8060
8061 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8062
8063 if (IsFormat && !IsD16 && EltType.getSizeInBits() < 32) {
8064 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
8066 "unsupported sub-dword format buffer load", DL.getDebugLoc()));
8067 return DAG.getMergeValues({DAG.getPOISON(LoadVT), M->getOperand(0)}, DL);
8068 }
8069
8070 assert(M->getNumValues() == 2 || M->getNumValues() == 3);
8071 bool IsTFE = M->getNumValues() == 3;
8072
8073 if (IsD16 && IsTFE && !Subtarget->hasBufferTFEFormatD16()) {
8074 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
8076 "TFE D16 format buffer load is not supported on this GPU",
8077 DL.getDebugLoc()));
8078 return DAG.getErrorMergeValues({M->value_begin(), M->value_end()},
8079 M->getOperand(0), DL);
8080 }
8081
8082 unsigned Opc = IsD16 ? (IsTFE ? AMDGPUISD::BUFFER_LOAD_FORMAT_D16_TFE
8083 : AMDGPUISD::BUFFER_LOAD_FORMAT_D16)
8084 : IsFormat ? (IsTFE ? AMDGPUISD::BUFFER_LOAD_FORMAT_TFE
8085 : AMDGPUISD::BUFFER_LOAD_FORMAT)
8086 : IsTFE ? AMDGPUISD::BUFFER_LOAD_TFE
8087 : AMDGPUISD::BUFFER_LOAD;
8088
8089 if (IsD16)
8090 return adjustLoadValueType(Opc, M, DAG, Ops);
8091
8092 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
8093 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
8094 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M->getMemOperand(),
8095 IsTFE);
8096
8097 if (isTypeLegal(LoadVT)) {
8098 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
8099 M->getMemOperand(), DAG);
8100 }
8101
8102 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
8103 SDVTList VTList = IsTFE ? DAG.getVTList(CastVT, MVT::i32, MVT::Other)
8104 : DAG.getVTList(CastVT, MVT::Other);
8105 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
8106 M->getMemOperand(), DAG);
8107 SDValue Data = DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode);
8108 if (IsTFE)
8109 return DAG.getMergeValues({Data, MemNode.getValue(1), MemNode.getValue(2)},
8110 DL);
8111 return DAG.getMergeValues({Data, MemNode.getValue(1)}, DL);
8112}
8113
8115 SelectionDAG &DAG) {
8116 EVT VT = N->getValueType(0);
8117 SDValue Src = N->getOperand(1);
8118 SDLoc SL(N);
8119
8120 if (Src.getOpcode() == ISD::SETCC) {
8121 SDValue Op0 = Src.getOperand(0);
8122 SDValue Op1 = Src.getOperand(1);
8123 // Need to expand bfloat to float for comparison (setcc).
8124 if (Op0.getValueType() == MVT::bf16) {
8125 Op0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Op0);
8126 Op1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Op1);
8127 }
8128 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
8129 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Op0, Op1, Src.getOperand(2));
8130 }
8131 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
8132 // (ballot 0) -> 0
8133 if (Arg->isZero())
8134 return DAG.getConstant(0, SL, VT);
8135
8136 // (ballot 1) -> EXEC/EXEC_LO
8137 if (Arg->isOne()) {
8138 Register Exec;
8139 if (VT.getScalarSizeInBits() == 32)
8140 Exec = AMDGPU::EXEC_LO;
8141 else if (VT.getScalarSizeInBits() == 64)
8142 Exec = AMDGPU::EXEC;
8143 else
8144 return SDValue();
8145
8146 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
8147 }
8148 }
8149
8150 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
8151 // ISD::SETNE)
8152 return DAG.getNode(
8153 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
8154 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
8155}
8156
8158 Intrinsic::ID IntrinsicID) {
8159 bool Signed = IntrinsicID == Intrinsic::amdgcn_sbfe;
8160 SDLoc DL(Op);
8161 EVT VT = Op.getValueType();
8162 SDValue Src = Op.getOperand(1);
8163 SDValue Offset = Op.getOperand(2);
8164 SDValue Width = Op.getOperand(3);
8165
8166 if (VT != MVT::i32) {
8169 Twine(Intrinsic::getBaseName(IntrinsicID)) + " only supports i32",
8170 DL.getDebugLoc()));
8171 return DAG.getPOISON(VT);
8172 }
8173
8174 return DAG.getNode(Signed ? AMDGPUISD::BFE_I32 : AMDGPUISD::BFE_U32, DL, VT,
8175 Src, Offset, Width);
8176}
8177
8179 EVT VT);
8180
8182 SelectionDAG &DAG) {
8183 EVT VT = N->getValueType(0);
8184 unsigned ValSize = VT.getSizeInBits();
8185 unsigned IID = N->getConstantOperandVal(0);
8186 bool IsPermLane16 = IID == Intrinsic::amdgcn_permlane16 ||
8187 IID == Intrinsic::amdgcn_permlanex16;
8188 bool IsSetInactive = IID == Intrinsic::amdgcn_set_inactive ||
8189 IID == Intrinsic::amdgcn_set_inactive_chain_arg;
8190 bool IsPermlaneShuffle = IID == Intrinsic::amdgcn_permlane_bcast ||
8191 IID == Intrinsic::amdgcn_permlane_up ||
8192 IID == Intrinsic::amdgcn_permlane_down ||
8193 IID == Intrinsic::amdgcn_permlane_xor;
8194 SDLoc SL(N);
8195 MVT IntVT = MVT::getIntegerVT(ValSize);
8196 const GCNSubtarget *ST = TLI.getSubtarget();
8197
8198 unsigned SplitSize = 32;
8199 if (IID == Intrinsic::amdgcn_update_dpp && (ValSize % 64 == 0) &&
8200 ST->hasDPALU_DPP() &&
8201 AMDGPU::isLegalDPALU_DPPControl(*ST, N->getConstantOperandVal(3)))
8202 SplitSize = 64;
8203
8204 auto createLaneOp = [&DAG, &SL, N, IID](SDValue Src0, SDValue Src1,
8205 SDValue Src2, MVT ValT) -> SDValue {
8207 switch (IID) {
8208 case Intrinsic::amdgcn_permlane16:
8209 case Intrinsic::amdgcn_permlanex16:
8210 case Intrinsic::amdgcn_update_dpp:
8211 Operands.push_back(N->getOperand(6));
8212 Operands.push_back(N->getOperand(5));
8213 Operands.push_back(N->getOperand(4));
8214 [[fallthrough]];
8215 case Intrinsic::amdgcn_writelane:
8216 case Intrinsic::amdgcn_permlane_bcast:
8217 case Intrinsic::amdgcn_permlane_up:
8218 case Intrinsic::amdgcn_permlane_down:
8219 case Intrinsic::amdgcn_permlane_xor:
8220 Operands.push_back(Src2);
8221 [[fallthrough]];
8222 case Intrinsic::amdgcn_readlane:
8223 case Intrinsic::amdgcn_set_inactive:
8224 case Intrinsic::amdgcn_set_inactive_chain_arg:
8225 case Intrinsic::amdgcn_mov_dpp8:
8226 Operands.push_back(Src1);
8227 [[fallthrough]];
8228 case Intrinsic::amdgcn_readfirstlane:
8229 case Intrinsic::amdgcn_permlane64:
8230 Operands.push_back(Src0);
8231 break;
8232 default:
8233 llvm_unreachable("unhandled lane op");
8234 }
8235
8236 Operands.push_back(DAG.getTargetConstant(IID, SL, MVT::i32));
8237 std::reverse(Operands.begin(), Operands.end());
8238
8239 if (SDNode *GL = N->getGluedNode()) {
8240 assert(GL->getOpcode() == ISD::CONVERGENCECTRL_GLUE);
8241 GL = GL->getOperand(0).getNode();
8242 Operands.push_back(DAG.getNode(ISD::CONVERGENCECTRL_GLUE, SL, MVT::Glue,
8243 SDValue(GL, 0)));
8244 }
8245
8246 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, ValT, Operands);
8247 };
8248
8249 SDValue Src0 = N->getOperand(1);
8250 SDValue Src1, Src2;
8251 if (IID == Intrinsic::amdgcn_readlane || IID == Intrinsic::amdgcn_writelane ||
8252 IID == Intrinsic::amdgcn_mov_dpp8 ||
8253 IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16 ||
8254 IsPermlaneShuffle) {
8255 Src1 = N->getOperand(2);
8256 if (IID == Intrinsic::amdgcn_writelane ||
8257 IID == Intrinsic::amdgcn_update_dpp || IsPermLane16 ||
8258 IsPermlaneShuffle)
8259 Src2 = N->getOperand(3);
8260 }
8261
8262 if (ValSize == SplitSize) {
8263 // Already legal
8264 return SDValue();
8265 }
8266
8267 if (ValSize < 32) {
8268 bool IsFloat = VT.isFloatingPoint();
8269 Src0 = DAG.getAnyExtOrTrunc(IsFloat ? DAG.getBitcast(IntVT, Src0) : Src0,
8270 SL, MVT::i32);
8271
8272 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16) {
8273 Src1 = DAG.getAnyExtOrTrunc(IsFloat ? DAG.getBitcast(IntVT, Src1) : Src1,
8274 SL, MVT::i32);
8275 }
8276
8277 if (IID == Intrinsic::amdgcn_writelane) {
8278 Src2 = DAG.getAnyExtOrTrunc(IsFloat ? DAG.getBitcast(IntVT, Src2) : Src2,
8279 SL, MVT::i32);
8280 }
8281
8282 SDValue LaneOp = createLaneOp(Src0, Src1, Src2, MVT::i32);
8283 SDValue Trunc = DAG.getAnyExtOrTrunc(LaneOp, SL, IntVT);
8284 return IsFloat ? DAG.getBitcast(VT, Trunc) : Trunc;
8285 }
8286
8287 if (ValSize % SplitSize != 0)
8288 return SDValue();
8289
8290 auto unrollLaneOp = [&DAG, &SL](SDNode *N) -> SDValue {
8291 EVT VT = N->getValueType(0);
8292 unsigned NE = VT.getVectorNumElements();
8293 EVT EltVT = VT.getVectorElementType();
8295 unsigned NumOperands = N->getNumOperands();
8296 SmallVector<SDValue, 4> Operands(NumOperands);
8297 SDNode *GL = N->getGluedNode();
8298
8299 // only handle convergencectrl_glue
8301
8302 for (unsigned i = 0; i != NE; ++i) {
8303 for (unsigned j = 0, e = GL ? NumOperands - 1 : NumOperands; j != e;
8304 ++j) {
8305 SDValue Operand = N->getOperand(j);
8306 EVT OperandVT = Operand.getValueType();
8307 if (OperandVT.isVector()) {
8308 // A vector operand; extract a single element.
8309 EVT OperandEltVT = OperandVT.getVectorElementType();
8310 Operands[j] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, OperandEltVT,
8311 Operand, DAG.getVectorIdxConstant(i, SL));
8312 } else {
8313 // A scalar operand; just use it as is.
8314 Operands[j] = Operand;
8315 }
8316 }
8317
8318 if (GL)
8319 Operands[NumOperands - 1] =
8320 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, SL, MVT::Glue,
8321 SDValue(GL->getOperand(0).getNode(), 0));
8322
8323 Scalars.push_back(DAG.getNode(N->getOpcode(), SL, EltVT, Operands));
8324 }
8325
8326 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NE);
8327 return DAG.getBuildVector(VecVT, SL, Scalars);
8328 };
8329
8330 if (VT.isVector()) {
8331 switch (MVT::SimpleValueType EltTy =
8333 case MVT::i32:
8334 case MVT::f32:
8335 if (SplitSize == 32) {
8336 SDValue LaneOp = createLaneOp(Src0, Src1, Src2, VT.getSimpleVT());
8337 return unrollLaneOp(LaneOp.getNode());
8338 }
8339 [[fallthrough]];
8340 case MVT::i16:
8341 case MVT::f16:
8342 case MVT::bf16: {
8343 unsigned SubVecNumElt =
8344 SplitSize / VT.getVectorElementType().getSizeInBits();
8345 MVT SubVecVT = MVT::getVectorVT(EltTy, SubVecNumElt);
8347 SDValue Src0SubVec, Src1SubVec, Src2SubVec;
8348 for (unsigned i = 0, EltIdx = 0; i < ValSize / SplitSize; i++) {
8349 Src0SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, SubVecVT, Src0,
8350 DAG.getConstant(EltIdx, SL, MVT::i32));
8351
8352 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive ||
8353 IsPermLane16) {
8354 Src1SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, SubVecVT, Src1,
8355 DAG.getConstant(EltIdx, SL, MVT::i32));
8356
8357 Pieces.push_back(
8358 createLaneOp(Src0SubVec, Src1SubVec, Src2, SubVecVT));
8359 } else if (IID == Intrinsic::amdgcn_writelane) {
8360 Src2SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, SubVecVT, Src2,
8361 DAG.getConstant(EltIdx, SL, MVT::i32));
8362 Pieces.push_back(
8363 createLaneOp(Src0SubVec, Src1, Src2SubVec, SubVecVT));
8364 } else {
8365 Pieces.push_back(createLaneOp(Src0SubVec, Src1, Src2, SubVecVT));
8366 }
8367
8368 EltIdx += SubVecNumElt;
8369 }
8370 return DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, Pieces);
8371 }
8372 default:
8373 // Handle all other cases by bitcasting to i32 vectors
8374 break;
8375 }
8376 }
8377
8378 MVT VecVT =
8379 MVT::getVectorVT(MVT::getIntegerVT(SplitSize), ValSize / SplitSize);
8380 Src0 = DAG.getBitcast(VecVT, Src0);
8381
8382 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16)
8383 Src1 = DAG.getBitcast(VecVT, Src1);
8384
8385 if (IID == Intrinsic::amdgcn_writelane)
8386 Src2 = DAG.getBitcast(VecVT, Src2);
8387
8388 SDValue LaneOp = createLaneOp(Src0, Src1, Src2, VecVT);
8389 SDValue UnrolledLaneOp = unrollLaneOp(LaneOp.getNode());
8390 return DAG.getBitcast(VT, UnrolledLaneOp);
8391}
8392
8394 SelectionDAG &DAG) {
8395 EVT VT = N->getValueType(0);
8396
8397 if (VT.getSizeInBits() != 32)
8398 return SDValue();
8399
8400 SDLoc SL(N);
8401
8402 SDValue Value = N->getOperand(1);
8403 SDValue Index = N->getOperand(2);
8404
8405 // ds_bpermute requires index to be multiplied by 4
8406 SDValue ShiftAmount = DAG.getShiftAmountConstant(2, MVT::i32, SL);
8407 SDValue ShiftedIndex =
8408 DAG.getNode(ISD::SHL, SL, Index.getValueType(), Index, ShiftAmount);
8409
8410 // Intrinsics will require i32 to operate on
8411 SDValue ValueI32 = DAG.getBitcast(MVT::i32, Value);
8412
8413 auto MakeIntrinsic = [&DAG, &SL](unsigned IID, MVT RetVT,
8414 SmallVector<SDValue> IntrinArgs) -> SDValue {
8416 Operands[0] = DAG.getTargetConstant(IID, SL, MVT::i32);
8417 Operands.append(IntrinArgs);
8418 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, RetVT, Operands);
8419 };
8420
8421 // If we can bpermute across the whole wave, then just do that
8422 if (TLI.getSubtarget()->supportsWaveWideBPermute()) {
8423 SDValue BPermute = MakeIntrinsic(Intrinsic::amdgcn_ds_bpermute, MVT::i32,
8424 {ShiftedIndex, ValueI32});
8425 return DAG.getBitcast(VT, BPermute);
8426 }
8427
8428 assert(TLI.getSubtarget()->isWave64());
8429
8430 // Otherwise, we need to make use of whole wave mode
8431 SDValue PoisonVal = DAG.getPOISON(ValueI32->getValueType(0));
8432
8433 // Set inactive lanes to poison
8434 SDValue WWMValue = MakeIntrinsic(Intrinsic::amdgcn_set_inactive, MVT::i32,
8435 {ValueI32, PoisonVal});
8436 SDValue WWMIndex = MakeIntrinsic(Intrinsic::amdgcn_set_inactive, MVT::i32,
8437 {ShiftedIndex, PoisonVal});
8438
8439 SDValue Swapped =
8440 MakeIntrinsic(Intrinsic::amdgcn_permlane64, MVT::i32, {WWMValue});
8441
8442 // Get permutation of each half, then we'll select which one to use
8443 SDValue BPermSameHalf = MakeIntrinsic(Intrinsic::amdgcn_ds_bpermute, MVT::i32,
8444 {WWMIndex, WWMValue});
8445 SDValue BPermOtherHalf = MakeIntrinsic(Intrinsic::amdgcn_ds_bpermute,
8446 MVT::i32, {WWMIndex, Swapped});
8447 SDValue BPermOtherHalfWWM =
8448 MakeIntrinsic(Intrinsic::amdgcn_wwm, MVT::i32, {BPermOtherHalf});
8449
8450 // Select which side to take the permute from
8451 SDValue ThreadIDMask = DAG.getAllOnesConstant(SL, MVT::i32);
8452 // We can get away with only using mbcnt_lo here since we're only
8453 // trying to detect which side of 32 each lane is on, and mbcnt_lo
8454 // returns 32 for lanes 32-63.
8455 SDValue ThreadID =
8456 MakeIntrinsic(Intrinsic::amdgcn_mbcnt_lo, MVT::i32,
8457 {ThreadIDMask, DAG.getTargetConstant(0, SL, MVT::i32)});
8458
8459 SDValue SameOrOtherHalf =
8460 DAG.getNode(ISD::AND, SL, MVT::i32,
8461 DAG.getNode(ISD::XOR, SL, MVT::i32, ThreadID, Index),
8462 DAG.getTargetConstant(32, SL, MVT::i32));
8463 SDValue UseSameHalf =
8464 DAG.getSetCC(SL, MVT::i1, SameOrOtherHalf,
8465 DAG.getConstant(0, SL, MVT::i32), ISD::SETEQ);
8466 SDValue Result = DAG.getSelect(SL, MVT::i32, UseSameHalf, BPermSameHalf,
8467 BPermOtherHalfWWM);
8468 return DAG.getBitcast(VT, Result);
8469}
8470
8473 SelectionDAG &DAG) const {
8474 switch (N->getOpcode()) {
8476 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
8477 Results.push_back(Res);
8478 return;
8479 }
8481 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
8482 Results.push_back(Res);
8483 return;
8484 }
8486 if (SDValue Res = LowerCONVERT_TO_ARBITRARY_FP(SDValue(N, 0), DAG))
8487 Results.push_back(Res);
8488 return;
8489 }
8491 unsigned IID = N->getConstantOperandVal(0);
8492 switch (IID) {
8493 case Intrinsic::amdgcn_wave_reduce_min:
8494 case Intrinsic::amdgcn_wave_reduce_umin:
8495 case Intrinsic::amdgcn_wave_reduce_max:
8496 case Intrinsic::amdgcn_wave_reduce_umax:
8497 case Intrinsic::amdgcn_wave_reduce_add:
8498 case Intrinsic::amdgcn_wave_reduce_sub:
8499 case Intrinsic::amdgcn_wave_reduce_and:
8500 case Intrinsic::amdgcn_wave_reduce_or:
8501 case Intrinsic::amdgcn_wave_reduce_xor: {
8502 EVT VT = N->getValueType(0);
8503 if (isTypeLegal(VT))
8504 return;
8505 SDLoc SL(N);
8506 bool NeedsSignExt = IID == Intrinsic::amdgcn_wave_reduce_min ||
8507 IID == Intrinsic::amdgcn_wave_reduce_max ||
8508 IID == Intrinsic::amdgcn_wave_reduce_add ||
8509 IID == Intrinsic::amdgcn_wave_reduce_sub;
8510 unsigned ExtOpc = NeedsSignExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8511 SDValue ExtSrc = DAG.getNode(ExtOpc, SL, MVT::i32, N->getOperand(1));
8512 SDValue Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
8513 N->getOperand(0), ExtSrc, N->getOperand(2));
8514 Results.push_back(DAG.getNode(ISD::TRUNCATE, SL, VT, Result));
8515 return;
8516 }
8517 case Intrinsic::amdgcn_make_buffer_rsrc:
8518 Results.push_back(lowerPointerAsRsrcIntrin(N, DAG));
8519 return;
8520 case Intrinsic::amdgcn_cvt_pkrtz: {
8521 SDValue Src0 = N->getOperand(1);
8522 SDValue Src1 = N->getOperand(2);
8523 SDLoc SL(N);
8524 SDValue Cvt =
8525 DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, Src0, Src1);
8526 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
8527 return;
8528 }
8529 case Intrinsic::amdgcn_cvt_pknorm_i16:
8530 case Intrinsic::amdgcn_cvt_pknorm_u16:
8531 case Intrinsic::amdgcn_cvt_pk_i16:
8532 case Intrinsic::amdgcn_cvt_pk_u16: {
8533 SDValue Src0 = N->getOperand(1);
8534 SDValue Src1 = N->getOperand(2);
8535 SDLoc SL(N);
8536 unsigned Opcode;
8537
8538 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
8539 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
8540 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
8541 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
8542 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
8543 Opcode = AMDGPUISD::CVT_PK_I16_I32;
8544 else
8545 Opcode = AMDGPUISD::CVT_PK_U16_U32;
8546
8547 EVT VT = N->getValueType(0);
8548 if (isTypeLegal(VT))
8549 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
8550 else {
8551 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
8552 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
8553 }
8554 return;
8555 }
8556 case Intrinsic::amdgcn_s_buffer_load: {
8557 SDValue Op = SDValue(N, 0);
8558 EVT VT = Op.getValueType();
8559 Results.push_back(lowerSBuffer(VT, VT, SDLoc(Op), DAG.getEntryNode(),
8560 Op.getOperand(1), Op.getOperand(2),
8561 Op.getOperand(3), DAG));
8562 return;
8563 }
8564 case Intrinsic::amdgcn_dead: {
8565 for (unsigned I = 0, E = N->getNumValues(); I < E; ++I)
8566 Results.push_back(DAG.getPOISON(N->getValueType(I)));
8567 return;
8568 }
8569 }
8570 break;
8571 }
8573 if (N->getConstantOperandVal(1) != Intrinsic::amdgcn_ptr_s_buffer_load &&
8574 N->getValueType(0).isSimple() &&
8575 SBufferLoadDiagnosticVTs[N->getSimpleValueType(0).SimpleTy])
8576 break;
8577 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
8578 if (Res.getOpcode() == ISD::MERGE_VALUES) {
8579 // FIXME: Hacky
8580 for (unsigned I = 0; I < Res.getNumOperands(); I++) {
8581 Results.push_back(Res.getOperand(I));
8582 }
8583 } else {
8584 for (unsigned I = 0; I < N->getNumValues(); ++I)
8585 Results.push_back(Res.getValue(I));
8586 }
8587 return;
8588 }
8589
8590 break;
8591 }
8592 case ISD::SELECT: {
8593 SDLoc SL(N);
8594 EVT VT = N->getValueType(0);
8595 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
8596 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
8597 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
8598
8599 EVT SelectVT = NewVT;
8600 if (NewVT.bitsLT(MVT::i32)) {
8601 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
8602 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
8603 SelectVT = MVT::i32;
8604 }
8605
8606 SDValue NewSelect =
8607 DAG.getNode(ISD::SELECT, SL, SelectVT, N->getOperand(0), LHS, RHS);
8608
8609 if (NewVT != SelectVT)
8610 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
8611 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
8612 return;
8613 }
8614 case ISD::FNEG: {
8615 if (N->getValueType(0) != MVT::v2f16)
8616 break;
8617
8618 SDLoc SL(N);
8619 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
8620
8621 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, BC,
8622 DAG.getConstant(0x80008000, SL, MVT::i32));
8623 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
8624 return;
8625 }
8626 case ISD::FABS: {
8627 if (N->getValueType(0) != MVT::v2f16)
8628 break;
8629
8630 SDLoc SL(N);
8631 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
8632
8633 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, BC,
8634 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
8635 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
8636 return;
8637 }
8638 case ISD::FSQRT: {
8639 if (N->getValueType(0) != MVT::f16)
8640 break;
8641 Results.push_back(lowerFSQRTF16(SDValue(N, 0), DAG));
8642 break;
8643 }
8644 default:
8646 break;
8647 }
8648}
8649
8650/// Helper function for LowerBRCOND
8651static SDNode *findUser(SDValue Value, unsigned Opcode) {
8652
8653 for (SDUse &U : Value->uses()) {
8654 if (U.get() != Value)
8655 continue;
8656
8657 if (U.getUser()->getOpcode() == Opcode)
8658 return U.getUser();
8659 }
8660 return nullptr;
8661}
8662
8663unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
8664 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8665 switch (Intr->getConstantOperandVal(1)) {
8666 case Intrinsic::amdgcn_if:
8667 return AMDGPUISD::IF;
8668 case Intrinsic::amdgcn_else:
8669 return AMDGPUISD::ELSE;
8670 case Intrinsic::amdgcn_loop:
8671 return AMDGPUISD::LOOP;
8672 case Intrinsic::amdgcn_end_cf:
8673 llvm_unreachable("should not occur");
8674 default:
8675 return 0;
8676 }
8677 }
8678
8679 // break, if_break, else_break are all only used as inputs to loop, not
8680 // directly as branch conditions.
8681 return 0;
8682}
8683
8690
8692 if (Subtarget->isAmdPalOS() || Subtarget->isMesa3DOS())
8693 return false;
8694
8695 // FIXME: Either avoid relying on address space here or change the default
8696 // address space for functions to avoid the explicit check.
8697 return (GV->getValueType()->isFunctionTy() ||
8700}
8701
8703 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
8704}
8705
8707 if (!GV->hasExternalLinkage())
8708 return true;
8709
8710 // With object linking, external LDS declarations need relocations so the
8711 // linker can assign their offsets.
8713 if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
8714 if (GVar->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
8715 GVar->getAddressSpace() == AMDGPUAS::BARRIER) {
8716 assert(GVar->isDeclaration() &&
8717 "AS 3 & 13 GVs should be declaration here "
8718 "when object linking is enabled");
8719 return false;
8720 }
8721 }
8722 }
8723
8724 const auto OS = getTargetMachine().getTargetTriple().getOS();
8725 return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
8726}
8727
8728/// This transforms the control flow intrinsics to get the branch destination as
8729/// last parameter, also switches branch target with BR if the need arise
8730SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, SelectionDAG &DAG) const {
8731 SDLoc DL(BRCOND);
8732
8733 SDNode *Intr = BRCOND.getOperand(1).getNode();
8734 SDValue Target = BRCOND.getOperand(2);
8735 SDNode *BR = nullptr;
8736 SDNode *SetCC = nullptr;
8737
8738 switch (Intr->getOpcode()) {
8739 case ISD::SETCC: {
8740 // As long as we negate the condition everything is fine
8741 SetCC = Intr;
8742 Intr = SetCC->getOperand(0).getNode();
8743 break;
8744 }
8745 case ISD::XOR: {
8746 // Similar to SETCC, if we have (xor c, -1), we will be fine.
8747 SDValue LHS = Intr->getOperand(0);
8748 SDValue RHS = Intr->getOperand(1);
8749 if (auto *C = dyn_cast<ConstantSDNode>(RHS); C && C->getZExtValue()) {
8750 Intr = LHS.getNode();
8751 break;
8752 }
8753 [[fallthrough]];
8754 }
8755 default: {
8756 // Get the target from BR if we don't negate the condition
8757 BR = findUser(BRCOND, ISD::BR);
8758 assert(BR && "brcond missing unconditional branch user");
8759 Target = BR->getOperand(1);
8760 }
8761 }
8762
8763 unsigned CFNode = isCFIntrinsic(Intr);
8764 if (CFNode == 0) {
8765 // This is a uniform branch so we don't need to legalize.
8766 return BRCOND;
8767 }
8768
8769 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
8771
8772 assert(!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
8773 SetCC->getOperandCondCode(2) == ISD::SETNE));
8774
8775 // operands of the new intrinsic call
8777 if (HaveChain)
8778 Ops.push_back(BRCOND.getOperand(0));
8779
8780 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
8781 Ops.push_back(Target);
8782
8783 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
8784
8785 // build the new intrinsic call
8786 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
8787
8788 if (!HaveChain) {
8789 SDValue Ops[] = {SDValue(Result, 0), BRCOND.getOperand(0)};
8790
8792 }
8793
8794 if (BR) {
8795 // Give the branch instruction our target
8796 SDValue Ops[] = {BR->getOperand(0), BRCOND.getOperand(2)};
8797 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
8798 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
8799 }
8800
8801 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
8802
8803 // Copy the intrinsic results to registers
8804 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
8805 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
8806 if (!CopyToReg)
8807 continue;
8808
8809 Chain = DAG.getCopyToReg(Chain, DL, CopyToReg->getOperand(1),
8810 SDValue(Result, i - 1), SDValue());
8811
8812 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
8813 }
8814
8815 // Remove the old intrinsic from the chain
8816 DAG.ReplaceAllUsesOfValueWith(SDValue(Intr, Intr->getNumValues() - 1),
8817 Intr->getOperand(0));
8818
8819 return Chain;
8820}
8821
8822SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
8823 MVT VT = Op.getSimpleValueType();
8824 SDLoc DL(Op);
8825 // Checking the depth
8826 if (Op.getConstantOperandVal(0) != 0)
8827 return DAG.getConstant(0, DL, VT);
8828
8830 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8831 // Check for kernel and shader functions
8832 if (Info->isEntryFunction())
8833 return DAG.getConstant(0, DL, VT);
8834
8835 MachineFrameInfo &MFI = MF.getFrameInfo();
8836 // There is a call to @llvm.returnaddress in this function
8837 MFI.setReturnAddressIsTaken(true);
8838
8839 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
8840 // Get the return address reg and mark it as an implicit live-in
8841 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF),
8842 getRegClassFor(VT, Op.getNode()->isDivergent()));
8843
8844 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
8845}
8846
8847SDValue SITargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
8849 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8850
8851 // For functions that set up their own stack, select the GET_STACK_BASE
8852 // pseudo.
8853 if (MFI->isBottomOfStack())
8854 return Op;
8855
8856 // For everything else, create a dummy stack object.
8857 int FI = MF.getFrameInfo().CreateFixedObject(1, 0, /*IsImmutable=*/false);
8858 return DAG.getFrameIndex(FI, Op.getValueType());
8859}
8860
8861SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, SDValue Op,
8862 const SDLoc &DL, EVT VT) const {
8863 return Op.getValueType().bitsLE(VT)
8864 ? DAG.getNode(ISD::FP_EXTEND, DL, VT, Op)
8865 : DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
8866 DAG.getTargetConstant(0, DL, MVT::i32));
8867}
8868
8869SDValue SITargetLowering::splitFP_ROUNDVectorOp(SDValue Op,
8870 SelectionDAG &DAG) const {
8871 EVT DstVT = Op.getValueType();
8872 unsigned NumElts = DstVT.getVectorNumElements();
8873 assert(NumElts > 2 && isPowerOf2_32(NumElts));
8874
8875 auto [Lo, Hi] = DAG.SplitVectorOperand(Op.getNode(), 0);
8876
8877 SDLoc DL(Op);
8878 unsigned Opc = Op.getOpcode();
8879 SDValue Flags = Op.getOperand(1);
8880 EVT HalfDstVT =
8881 EVT::getVectorVT(*DAG.getContext(), DstVT.getScalarType(), NumElts / 2);
8882 SDValue OpLo = DAG.getNode(Opc, DL, HalfDstVT, Lo, Flags);
8883 SDValue OpHi = DAG.getNode(Opc, DL, HalfDstVT, Hi, Flags);
8884
8885 return DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, OpLo, OpHi);
8886}
8887
8888SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
8889 bool IsStrict = Op->isStrictFPOpcode();
8890 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8891 EVT SrcVT = Src.getValueType();
8892 EVT DstVT = Op.getValueType();
8893
8894 if (DstVT.isVectorOf(MVT::f16)) {
8895 assert(Subtarget->hasCvtPkF16F32Inst() && "support v_cvt_pk_f16_f32");
8896 if (SrcVT.getScalarType() != MVT::f32)
8897 return SDValue();
8898 return SrcVT == MVT::v2f32 ? Op : splitFP_ROUNDVectorOp(Op, DAG);
8899 }
8900
8901 if (SrcVT.getScalarType() != MVT::f64)
8902 return Op;
8903
8904 SDLoc DL(Op);
8905 if (DstVT == MVT::f16) {
8906 // TODO: Handle strictfp
8907 if (Op.getOpcode() != ISD::FP_ROUND)
8908 return Op;
8909
8910 if (!Subtarget->has16BitInsts()) {
8911 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
8912 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
8913 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
8914 }
8915 if (Op->getFlags().hasApproximateFuncs()) {
8916 SDValue Flags = Op.getOperand(1);
8917 SDValue Src32 = DAG.getNode(ISD::FP_ROUND, DL, MVT::f32, Src, Flags);
8918 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Src32, Flags);
8919 }
8920 SDValue FpToFp16 = LowerF64ToF16Safe(Src, DL, DAG);
8921 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
8922 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
8923 }
8924
8925 assert(DstVT.getScalarType() == MVT::bf16 &&
8926 "custom lower FP_ROUND for f16 or bf16");
8927 assert(Subtarget->hasBF16ConversionInsts() && "f32 -> bf16 is legal");
8928
8929 // Round-inexact-to-odd f64 to f32, then do the final rounding using the
8930 // hardware f32 -> bf16 instruction.
8931 EVT F32VT = SrcVT.changeElementType(*DAG.getContext(), MVT::f32);
8932 SDValue Rod = expandRoundInexactToOdd(F32VT, Src, DL, DAG);
8933 if (IsStrict) {
8934 return DAG.getNode(
8935 ISD::STRICT_FP_ROUND, DL, {DstVT, MVT::Other},
8936 {Op.getOperand(0), Rod, DAG.getTargetConstant(0, DL, MVT::i32)});
8937 }
8938 return DAG.getNode(ISD::FP_ROUND, DL, DstVT, Rod,
8939 DAG.getTargetConstant(0, DL, MVT::i32));
8940}
8941
8942SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
8943 SelectionDAG &DAG) const {
8944 EVT VT = Op.getValueType();
8945 const MachineFunction &MF = DAG.getMachineFunction();
8946 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8947 bool IsIEEEMode = Info->getMode().IEEE;
8948
8949 // FIXME: Assert during selection that this is only selected for
8950 // ieee_mode. Currently a combine can produce the ieee version for non-ieee
8951 // mode functions, but this happens to be OK since it's only done in cases
8952 // where there is known no sNaN.
8953 if (IsIEEEMode && !Subtarget->hasIEEEMinimumMaximumInsts())
8954 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
8955
8956 if (VT == MVT::v4f16 || VT == MVT::v8f16 || VT == MVT::v16f16 ||
8957 VT == MVT::v32f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16 ||
8958 VT == MVT::v16bf16 || VT == MVT::v32bf16 || VT == MVT::v4f64 ||
8959 VT == MVT::v8f64 || VT == MVT::v16f64 || VT == MVT::v32f64)
8960 return splitBinaryVectorOp(Op, DAG);
8961 return Op;
8962}
8963
8964SDValue
8965SITargetLowering::lowerFMINIMUMNUM_FMAXIMUMNUM(SDValue Op,
8966 SelectionDAG &DAG) const {
8967 EVT VT = Op.getValueType();
8968 const MachineFunction &MF = DAG.getMachineFunction();
8969 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8970 bool IsIEEEMode = Info->getMode().IEEE;
8971
8972 if (IsIEEEMode && !Subtarget->hasIEEEMinimumMaximumInsts())
8973 return expandFMINIMUMNUM_FMAXIMUMNUM(Op.getNode(), DAG);
8974
8975 if (VT == MVT::v4f16 || VT == MVT::v8f16 || VT == MVT::v16f16 ||
8976 VT == MVT::v32f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16 ||
8977 VT == MVT::v16bf16 || VT == MVT::v32bf16 || VT == MVT::v4f64 ||
8978 VT == MVT::v8f64 || VT == MVT::v16f64 || VT == MVT::v32f64)
8979 return splitBinaryVectorOp(Op, DAG);
8980 return Op;
8981}
8982
8983SDValue SITargetLowering::lowerFLDEXP(SDValue Op, SelectionDAG &DAG) const {
8984 bool IsStrict = Op.getOpcode() == ISD::STRICT_FLDEXP;
8985 EVT VT = Op.getValueType();
8986 assert(VT == MVT::f16);
8987
8988 SDValue Exp = Op.getOperand(IsStrict ? 2 : 1);
8989 EVT ExpVT = Exp.getValueType();
8990 if (ExpVT == MVT::i16)
8991 return Op;
8992
8993 SDLoc DL(Op);
8994
8995 // Correct the exponent type for f16 to i16.
8996 // Clamp the range of the exponent to the instruction's range.
8997
8998 // TODO: This should be a generic narrowing legalization, and can easily be
8999 // for GlobalISel.
9000
9001 SDValue MinExp = DAG.getSignedConstant(minIntN(16), DL, ExpVT);
9002 SDValue ClampMin = DAG.getNode(ISD::SMAX, DL, ExpVT, Exp, MinExp);
9003
9004 SDValue MaxExp = DAG.getSignedConstant(maxIntN(16), DL, ExpVT);
9005 SDValue Clamp = DAG.getNode(ISD::SMIN, DL, ExpVT, ClampMin, MaxExp);
9006
9007 SDValue TruncExp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Clamp);
9008
9009 if (IsStrict) {
9010 return DAG.getNode(ISD::STRICT_FLDEXP, DL, {VT, MVT::Other},
9011 {Op.getOperand(0), Op.getOperand(1), TruncExp});
9012 }
9013
9014 return DAG.getNode(ISD::FLDEXP, DL, VT, Op.getOperand(0), TruncExp);
9015}
9016
9018 switch (Op->getOpcode()) {
9019 case ISD::ABS:
9020 case ISD::SRA:
9021 case ISD::SMIN:
9022 case ISD::SMAX:
9023 return ISD::SIGN_EXTEND;
9024 case ISD::SRL:
9025 case ISD::UMIN:
9026 case ISD::UMAX:
9027 case ISD::USUBSAT:
9028 case ISD::UADDSAT:
9029 return ISD::ZERO_EXTEND;
9030 case ISD::ADD:
9031 case ISD::SUB:
9032 case ISD::AND:
9033 case ISD::OR:
9034 case ISD::XOR:
9035 case ISD::SHL:
9036 case ISD::SELECT:
9037 case ISD::MUL:
9038 // operation result won't be influenced by garbage high bits.
9039 // TODO: are all of those cases correct, and are there more?
9040 return ISD::ANY_EXTEND;
9041 case ISD::SETCC: {
9042 ISD::CondCode CC = Op.getOperandCondCode(2);
9044 }
9045 default:
9046 llvm_unreachable("unexpected opcode!");
9047 }
9048}
9049
9050SDValue
9051SITargetLowering::promoteUniformUnaryOpToI32(SDValue Op,
9052 DAGCombinerInfo &DCI) const {
9053 EVT OpTy = Op.getValueType();
9054 SelectionDAG &DAG = DCI.DAG;
9055 EVT ExtTy = OpTy.changeElementType(*DAG.getContext(), MVT::i32);
9056
9057 if (isNarrowingProfitable(Op.getNode(), ExtTy, OpTy))
9058 return SDValue();
9059
9060 SDLoc DL(Op);
9061 SDValue Input = Op.getOperand(0);
9062 const unsigned ExtOp = getExtOpcodeForPromotedOp(Op);
9063 Input = DAG.getNode(ExtOp, DL, ExtTy, Input);
9064
9065 SDValue NewVal = DAG.getNode(Op.getOpcode(), DL, ExtTy, Input);
9066
9067 return DAG.getNode(ISD::TRUNCATE, DL, OpTy, NewVal);
9068}
9069
9070SDValue SITargetLowering::promoteUniformOpToI32(SDValue Op,
9071 DAGCombinerInfo &DCI) const {
9072 const unsigned Opc = Op.getOpcode();
9073 assert(Opc == ISD::ADD || Opc == ISD::SUB || Opc == ISD::SHL ||
9074 Opc == ISD::SRL || Opc == ISD::SRA || Opc == ISD::AND ||
9075 Opc == ISD::OR || Opc == ISD::XOR || Opc == ISD::MUL ||
9076 Opc == ISD::SETCC || Opc == ISD::SELECT || Opc == ISD::SMIN ||
9077 Opc == ISD::SMAX || Opc == ISD::UMIN || Opc == ISD::UMAX ||
9078 Opc == ISD::USUBSAT || Opc == ISD::UADDSAT);
9079
9080 EVT OpTy = (Opc != ISD::SETCC) ? Op.getValueType()
9081 : Op->getOperand(0).getValueType();
9082 auto &DAG = DCI.DAG;
9083 auto ExtTy = OpTy.changeElementType(*DAG.getContext(), MVT::i32);
9084
9085 if (DCI.isBeforeLegalizeOps() ||
9086 isNarrowingProfitable(Op.getNode(), ExtTy, OpTy))
9087 return SDValue();
9088
9089 SDLoc DL(Op);
9090 SDValue LHS;
9091 SDValue RHS;
9092 if (Opc == ISD::SELECT) {
9093 LHS = Op->getOperand(1);
9094 RHS = Op->getOperand(2);
9095 } else {
9096 LHS = Op->getOperand(0);
9097 RHS = Op->getOperand(1);
9098 }
9099
9100 const unsigned ExtOp = getExtOpcodeForPromotedOp(Op);
9101 LHS = DAG.getNode(ExtOp, DL, ExtTy, {LHS});
9102
9103 // Special case: for shifts, the RHS always needs a zext.
9104 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
9105 RHS = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtTy, {RHS});
9106 else
9107 RHS = DAG.getNode(ExtOp, DL, ExtTy, {RHS});
9108
9109 // setcc always return i1/i1 vec so no need to truncate after.
9110 if (Opc == ISD::SETCC) {
9111 ISD::CondCode CC = Op.getOperandCondCode(2);
9112 return DAG.getSetCC(DL, Op.getValueType(), LHS, RHS, CC);
9113 }
9114
9115 // For other ops, we extend the operation's return type as well so we need to
9116 // truncate back to the original type.
9117 SDValue NewVal;
9118 if (Opc == ISD::SELECT)
9119 NewVal = DAG.getNode(ISD::SELECT, DL, ExtTy, {Op->getOperand(0), LHS, RHS});
9120 else if (Opc == ISD::UADDSAT) {
9121 SDValue Sum = DAG.getNode(ISD::ADD, DL, ExtTy, LHS, RHS);
9122 SDValue MaxVal = DAG.getConstant(
9123 APInt::getMaxValue(OpTy.getScalarSizeInBits()).zext(32), DL, ExtTy);
9124 NewVal = DAG.getNode(ISD::UMIN, DL, ExtTy, Sum, MaxVal);
9125 } else
9126 NewVal = DAG.getNode(Opc, DL, ExtTy, {LHS, RHS});
9127
9128 return DAG.getZExtOrTrunc(NewVal, DL, OpTy);
9129}
9130
9131SDValue SITargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9132 SDValue Mag = Op.getOperand(0);
9133 EVT MagVT = Mag.getValueType();
9134
9135 if (MagVT.getVectorNumElements() > 2)
9136 return splitBinaryVectorOp(Op, DAG);
9137
9138 SDValue Sign = Op.getOperand(1);
9139 EVT SignVT = Sign.getValueType();
9140
9141 if (MagVT == SignVT)
9142 return Op;
9143
9144 // fcopysign v2f16:mag, v2f32:sign ->
9145 // fcopysign v2f16:mag,
9146 // bitcast (trunc (srl (bitcast sign to v2i32), 16) to v2i16)
9147
9148 SDLoc SL(Op);
9149 SDValue SignAsInt32 = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Sign);
9150 SDValue ShiftAmt = DAG.getShiftAmountConstant(16, MVT::v2i32, SL);
9151 SDValue SignShifted =
9152 DAG.getNode(ISD::SRL, SL, MVT::v2i32, SignAsInt32, ShiftAmt);
9153 SDValue SignAsInt16 = DAG.getNode(ISD::TRUNCATE, SL, MVT::v2i16, SignShifted);
9154
9155 SDValue SignAsHalf16 = DAG.getNode(ISD::BITCAST, SL, MagVT, SignAsInt16);
9156
9157 return DAG.getNode(ISD::FCOPYSIGN, SL, MagVT, Mag, SignAsHalf16);
9158}
9159
9160// Custom lowering for vector multiplications and s_mul_u64.
9161SDValue SITargetLowering::lowerMUL(SDValue Op, SelectionDAG &DAG) const {
9162 EVT VT = Op.getValueType();
9163
9164 // Split vector operands.
9165 if (VT.isVector())
9166 return splitBinaryVectorOp(Op, DAG);
9167
9168 assert(VT == MVT::i64 && "The following code is a special for s_mul_u64");
9169
9170 // There are four ways to lower s_mul_u64:
9171 //
9172 // 1. If all the operands are uniform, then we lower it as it is.
9173 //
9174 // 2. If the operands are divergent, then we have to split s_mul_u64 in 32-bit
9175 // multiplications because there is not a vector equivalent of s_mul_u64.
9176 //
9177 // 3. If the cost model decides that it is more efficient to use vector
9178 // registers, then we have to split s_mul_u64 in 32-bit multiplications.
9179 // This happens in splitScalarSMULU64() in SIInstrInfo.cpp .
9180 //
9181 // 4. If the cost model decides to use vector registers and both of the
9182 // operands are zero-extended/sign-extended from 32-bits, then we split the
9183 // s_mul_u64 in two 32-bit multiplications. The problem is that it is not
9184 // possible to check if the operands are zero-extended or sign-extended in
9185 // SIInstrInfo.cpp. For this reason, here, we replace s_mul_u64 with
9186 // s_mul_u64_u32_pseudo if both operands are zero-extended and we replace
9187 // s_mul_u64 with s_mul_i64_i32_pseudo if both operands are sign-extended.
9188 // If the cost model decides that we have to use vector registers, then
9189 // splitScalarSMulPseudo() (in SIInstrInfo.cpp) split s_mul_u64_u32/
9190 // s_mul_i64_i32_pseudo in two vector multiplications. If the cost model
9191 // decides that we should use scalar registers, then s_mul_u64_u32_pseudo/
9192 // s_mul_i64_i32_pseudo is lowered as s_mul_u64 in expandPostRAPseudo() in
9193 // SIInstrInfo.cpp .
9194
9195 if (Op->isDivergent())
9196 return SDValue();
9197
9198 SDValue Op0 = Op.getOperand(0);
9199 SDValue Op1 = Op.getOperand(1);
9200 // If all the operands are zero-enteted to 32-bits, then we replace s_mul_u64
9201 // with s_mul_u64_u32_pseudo. If all the operands are sign-extended to
9202 // 32-bits, then we replace s_mul_u64 with s_mul_i64_i32_pseudo.
9203 KnownBits Op0KnownBits = DAG.computeKnownBits(Op0);
9204 unsigned Op0LeadingZeros = Op0KnownBits.countMinLeadingZeros();
9205 KnownBits Op1KnownBits = DAG.computeKnownBits(Op1);
9206 unsigned Op1LeadingZeros = Op1KnownBits.countMinLeadingZeros();
9207 SDLoc SL(Op);
9208 if (Op0LeadingZeros >= 32 && Op1LeadingZeros >= 32)
9209 return SDValue(
9210 DAG.getMachineNode(AMDGPU::S_MUL_U64_U32_PSEUDO, SL, VT, Op0, Op1), 0);
9211 unsigned Op0SignBits = DAG.ComputeNumSignBits(Op0);
9212 unsigned Op1SignBits = DAG.ComputeNumSignBits(Op1);
9213 if (Op0SignBits >= 33 && Op1SignBits >= 33)
9214 return SDValue(
9215 DAG.getMachineNode(AMDGPU::S_MUL_I64_I32_PSEUDO, SL, VT, Op0, Op1), 0);
9216 // If all the operands are uniform, then we lower s_mul_u64 as it is.
9217 return Op;
9218}
9219
9220SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
9221 EVT VT = Op.getValueType();
9222 SDLoc SL(Op);
9223 SDValue LHS = Op.getOperand(0);
9224 SDValue RHS = Op.getOperand(1);
9225 bool isSigned = Op.getOpcode() == ISD::SMULO;
9226
9227 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
9228 const APInt &C = RHSC->getAPIntValue();
9229 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
9230 if (C.isPowerOf2()) {
9231 // smulo(x, signed_min) is same as umulo(x, signed_min).
9232 bool UseArithShift = isSigned && !C.isMinSignedValue();
9233 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
9234 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
9235 SDValue Overflow =
9236 DAG.getSetCC(SL, MVT::i1,
9237 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, SL, VT,
9238 Result, ShiftAmt),
9239 LHS, ISD::SETNE);
9240 return DAG.getMergeValues({Result, Overflow}, SL);
9241 }
9242 }
9243
9244 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
9245 SDValue Top =
9246 DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, SL, VT, LHS, RHS);
9247
9249 ? DAG.getNode(ISD::SRA, SL, VT, Result,
9250 DAG.getConstant(VT.getScalarSizeInBits() - 1,
9251 SL, MVT::i32))
9252 : DAG.getConstant(0, SL, VT);
9253 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
9254
9255 return DAG.getMergeValues({Result, Overflow}, SL);
9256}
9257
9258SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
9259 if (Op->isDivergent()) {
9260 // Select to V_MAD_[IU]64_[IU]32.
9261 return Op;
9262 }
9263 if (Subtarget->hasSMulHi()) {
9264 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
9265 return SDValue();
9266 }
9267 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
9268 // calculate the high part, so we might as well do the whole thing with
9269 // V_MAD_[IU]64_[IU]32.
9270 return Op;
9271}
9272
9273SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
9274 if (!Subtarget->hasTrapHandler() ||
9275 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
9276 return lowerTrapEndpgm(Op, DAG);
9277
9278 return Subtarget->supportsGetDoorbellID() ? lowerTrapHsa(Op, DAG)
9279 : lowerTrapHsaQueuePtr(Op, DAG);
9280}
9281
9282SDValue SITargetLowering::lowerTrapEndpgm(SDValue Op, SelectionDAG &DAG) const {
9283 SDLoc SL(Op);
9284 SDValue Chain = Op.getOperand(0);
9285 return DAG.getNode(AMDGPUISD::ENDPGM_TRAP, SL, MVT::Other, Chain);
9286}
9287
9288SDValue
9289SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
9290 const SDLoc &DL, Align Alignment,
9291 ImplicitParameter Param) const {
9294 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
9295 MachinePointerInfo PtrInfo =
9297 return DAG.getLoad(
9298 VT, DL, DAG.getEntryNode(), Ptr, PtrInfo.getWithOffset(Offset), Alignment,
9300}
9301
9302SDValue SITargetLowering::lowerTrapHsaQueuePtr(SDValue Op,
9303 SelectionDAG &DAG) const {
9304 SDLoc SL(Op);
9305 SDValue Chain = Op.getOperand(0);
9306
9307 SDValue QueuePtr;
9308 // For code object version 5, QueuePtr is passed through implicit kernarg.
9309 const Module *M = DAG.getMachineFunction().getFunction().getParent();
9311 QueuePtr =
9312 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
9313 } else {
9315 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9316 Register UserSGPR = Info->getQueuePtrUserSGPR();
9317
9318 if (UserSGPR == AMDGPU::NoRegister) {
9319 // We probably are in a function incorrectly marked with
9320 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
9321 // trap, so just use a null pointer.
9322 QueuePtr = DAG.getConstant(0, SL, MVT::i64);
9323 } else {
9324 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
9325 MVT::i64);
9326 }
9327 }
9328
9329 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
9330 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, QueuePtr, SDValue());
9331
9333 SDValue Ops[] = {ToReg, DAG.getTargetConstant(TrapID, SL, MVT::i16), SGPR01,
9334 ToReg.getValue(1)};
9335 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
9336}
9337
9338SDValue SITargetLowering::lowerTrapHsa(SDValue Op, SelectionDAG &DAG) const {
9339 SDLoc SL(Op);
9340 SDValue Chain = Op.getOperand(0);
9341
9342 // We need to simulate the 's_trap 2' instruction on targets that run in
9343 // PRIV=1 (where it is treated as a nop).
9344 if (Subtarget->hasPrivEnabledTrap2NopBug())
9345 return DAG.getNode(AMDGPUISD::SIMULATED_TRAP, SL, MVT::Other, Chain);
9346
9348 SDValue Ops[] = {Chain, DAG.getTargetConstant(TrapID, SL, MVT::i16)};
9349 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
9350}
9351
9352SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
9353 SDLoc SL(Op);
9354 SDValue Chain = Op.getOperand(0);
9356
9357 if (!Subtarget->hasTrapHandler() ||
9358 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
9359 LLVMContext &Ctx = MF.getFunction().getContext();
9360 Ctx.diagnose(DiagnosticInfoUnsupported(MF.getFunction(),
9361 "debugtrap handler not supported",
9362 Op.getDebugLoc(), DS_Warning));
9363 return Chain;
9364 }
9365
9366 uint64_t TrapID =
9368 SDValue Ops[] = {Chain, DAG.getTargetConstant(TrapID, SL, MVT::i16)};
9369 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
9370}
9371
9372/// When a divergent value (in VGPR) is passed to an inline asm with an SGPR
9373/// constraint ('s'), we need to insert v_readfirstlane to move the value from
9374/// VGPR to SGPR. This is done by modifying the CopyToReg nodes in the glue
9375/// chain that feed into the INLINEASM node.
9376SDValue SITargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
9377 unsigned NumOps = Op.getNumOperands();
9378
9379 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
9380 SmallSet<Register, 8> SGPRInputRegs;
9381
9382 unsigned NumVals = 0;
9383 for (unsigned I = InlineAsm::Op_FirstOperand; I < NumOps - 1;
9384 I += 1 + NumVals) {
9385 const InlineAsm::Flag Flags(Op.getConstantOperandVal(I));
9386 NumVals = Flags.getNumOperandRegisters();
9387
9388 unsigned RCID;
9389 bool IsSGPRInput = Flags.getKind() == InlineAsm::Kind::RegUse &&
9390 NumVals > 0 && Flags.hasRegClassConstraint(RCID) &&
9391 TRI->isSGPRClass(TRI->getRegClass(RCID));
9392
9393 for (unsigned J = 0; J < NumVals; ++J) {
9394 SDValue Val = Op.getOperand(I + 1 + J);
9395 if (const RegisterSDNode *RegNode =
9397 Register Reg = RegNode->getReg();
9398 if (IsSGPRInput || (Reg.isPhysical() && TRI->isSGPRPhysReg(Reg)))
9399 SGPRInputRegs.insert(Reg);
9400 }
9401 }
9402 }
9403
9404 if (SGPRInputRegs.empty())
9405 return Op;
9406
9407 // Walk the glue chain and insert readfirstlane for divergent SGPR inputs.
9408 SDLoc DL(Op);
9409 SDNode *N = Op.getOperand(NumOps - 1).getNode();
9410
9411 while (N && N->getOpcode() == ISD::CopyToReg) {
9412 Register Reg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
9413 SDValue SrcVal = N->getOperand(2);
9414
9415 // Insert readfirstlane if copying a divergent value to an SGPR input.
9416 if (SrcVal->isDivergent() && SGPRInputRegs.count(Reg)) {
9417 SDValue ReadFirstLaneID =
9418 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
9419 SDValue ReadFirstLane =
9421 ReadFirstLaneID, SrcVal);
9422
9423 SmallVector<SDValue, 4> Ops = {N->getOperand(0), N->getOperand(1),
9424 ReadFirstLane};
9425 if (N->getNumOperands() > 3)
9426 Ops.push_back(N->getOperand(3)); // Glue input
9427
9428 DAG.UpdateNodeOperands(N, Ops);
9429 }
9430
9431 // Follow glue chain to next CopyToReg.
9432 SDNode *Next = nullptr;
9433 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I) {
9434 if (N->getOperand(I).getValueType() == MVT::Glue) {
9435 Next = N->getOperand(I).getNode();
9436 break;
9437 }
9438 }
9439 N = Next;
9440 }
9441
9442 return Op;
9443}
9444
9445SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
9446 SelectionDAG &DAG) const {
9447 unsigned BaseAS = AS;
9448 unsigned SANum = AMDGPU::getSyntheticApertureNumber(AS);
9450 BaseAS = AMDGPUAS::LOCAL_ADDRESS;
9451
9452 SDValue Aperture = getBaseSegmentAperture(BaseAS, DL, DAG);
9453
9454 if (SANum != AMDGPU::SyntheticAperture::None) {
9455 SDValue Tag = DAG.getConstant(SANum, DL, MVT::i32);
9456 return DAG.getNode(ISD::OR, DL, MVT::i32, Aperture, Tag);
9457 }
9458
9459 return Aperture;
9460}
9461
9462SDValue SITargetLowering::getBaseSegmentAperture(unsigned AS, const SDLoc &DL,
9463 SelectionDAG &DAG) const {
9464 const bool IsLDS = (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::BARRIER);
9465
9466 if (Subtarget->hasApertureRegs()) {
9467 const unsigned ApertureRegNo =
9468 IsLDS ? AMDGPU::SRC_SHARED_BASE : AMDGPU::SRC_PRIVATE_BASE;
9469 assert((ApertureRegNo != AMDGPU::SRC_PRIVATE_BASE ||
9470 !Subtarget->hasGloballyAddressableScratch()) &&
9471 "Cannot use src_private_base with globally addressable scratch!");
9472 // Note: this feature (register) is broken. When used as a 32-bit operand,
9473 // it returns a wrong value (all zeroes?). The real value is in the upper 32
9474 // bits.
9475 //
9476 // To work around the issue, emit a 64 bit copy from this register
9477 // then extract the high bits. Note that this shouldn't even result in a
9478 // shift being emitted and simply become a pair of registers (e.g.):
9479 // s_mov_b64 s[6:7], src_shared_base
9480 // v_mov_b32_e32 v1, s7
9481 SDValue Copy =
9482 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ApertureRegNo, MVT::v2i32);
9483 return DAG.getExtractVectorElt(DL, MVT::i32, Copy, 1);
9484 }
9485
9486 // For code object version 5, private_base and shared_base are passed through
9487 // implicit kernargs.
9488 const Module *M = DAG.getMachineFunction().getFunction().getParent();
9491 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
9492 }
9493
9495 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9496 Register UserSGPR = Info->getQueuePtrUserSGPR();
9497 if (UserSGPR == AMDGPU::NoRegister) {
9498 // We probably are in a function incorrectly marked with
9499 // amdgpu-no-queue-ptr. This is undefined.
9500 return DAG.getPOISON(MVT::i32);
9501 }
9502
9503 SDValue QueuePtr =
9504 CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
9505
9506 // Offset into amd_queue_t for group_segment_aperture_base_hi /
9507 // private_segment_aperture_base_hi.
9508 uint32_t StructOffset = IsLDS ? 0x40 : 0x44;
9509
9510 SDValue Ptr =
9511 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::getFixed(StructOffset));
9512
9513 // TODO: Use custom target PseudoSourceValue.
9514 // TODO: We should use the value from the IR intrinsic call, but it might not
9515 // be available and how do we get it?
9516 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
9517 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
9518 commonAlignment(Align(64), StructOffset),
9521}
9522
9523/// Return true if the value is a known valid address, such that a null check is
9524/// not necessary.
9526 const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
9528 return true;
9529
9530 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
9531 return ConstVal->getSExtValue() != AMDGPU::getNullPointerValue(AddrSpace);
9532
9533 // TODO: Search through arithmetic, handle arguments and loads
9534 // marked nonnull.
9535 return false;
9536}
9537
9538SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
9539 SelectionDAG &DAG) const {
9540 SDLoc SL(Op);
9541
9542 const AMDGPUTargetMachine &TM =
9543 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
9544
9545 const auto *ASC = cast<AddrSpaceCastSDNode>(Op);
9546 unsigned SrcAS = ASC->getSrcAddressSpace();
9547 SDValue Src = ASC->getOperand(0);
9548 unsigned DestAS = ASC->getDestAddressSpace();
9549 bool IsNonNull = ASC->getFlags().hasNonNull();
9550
9551 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
9552
9553 // flat -> local/private/barrier
9554 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
9555 if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
9556 DestAS == AMDGPUAS::PRIVATE_ADDRESS || DestAS == AMDGPUAS::BARRIER) {
9557 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
9558
9559 if (DestAS == AMDGPUAS::PRIVATE_ADDRESS &&
9560 Subtarget->hasGloballyAddressableScratch()) {
9561 // flat -> private with globally addressable scratch: subtract
9562 // src_flat_scratch_base_lo.
9563 SDValue FlatScratchBaseLo(
9564 DAG.getMachineNode(
9565 AMDGPU::S_MOV_B32, SL, MVT::i32,
9566 DAG.getRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE_LO, MVT::i32)),
9567 0);
9568 Ptr = DAG.getNode(ISD::SUB, SL, MVT::i32, Ptr, FlatScratchBaseLo);
9569 }
9570
9571 if (IsNonNull || isKnownNonNull(Op, DAG, TM, SrcAS))
9572 return Ptr;
9573
9574 unsigned NullVal = AMDGPU::getNullPointerValue(DestAS);
9575 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
9576 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
9577
9578 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
9579 SegmentNullPtr);
9580 }
9581 }
9582
9583 // local/private/barrier -> flat
9584 if (DestAS == AMDGPUAS::FLAT_ADDRESS) {
9585 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
9586 SrcAS == AMDGPUAS::PRIVATE_ADDRESS || SrcAS == AMDGPUAS::BARRIER) {
9587 SDValue CvtPtr;
9588 if (SrcAS == AMDGPUAS::PRIVATE_ADDRESS &&
9589 Subtarget->hasGloballyAddressableScratch()) {
9590 // For wave32: Addr = (TID[4:0] << 52) + FLAT_SCRATCH_BASE + privateAddr
9591 // For wave64: Addr = (TID[5:0] << 51) + FLAT_SCRATCH_BASE + privateAddr
9592 SDValue AllOnes = DAG.getSignedTargetConstant(-1, SL, MVT::i32);
9593 SDValue ThreadID = DAG.getConstant(0, SL, MVT::i32);
9594 ThreadID = DAG.getNode(
9595 ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
9596 DAG.getTargetConstant(Intrinsic::amdgcn_mbcnt_lo, SL, MVT::i32),
9597 AllOnes, ThreadID);
9598 if (Subtarget->isWave64())
9599 ThreadID = DAG.getNode(
9600 ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
9601 DAG.getTargetConstant(Intrinsic::amdgcn_mbcnt_hi, SL, MVT::i32),
9602 AllOnes, ThreadID);
9603 SDValue ShAmt = DAG.getShiftAmountConstant(
9604 57 - 32 - Subtarget->getWavefrontSizeLog2(), MVT::i32, SL);
9605 SDValue SrcHi = DAG.getNode(ISD::SHL, SL, MVT::i32, ThreadID, ShAmt);
9606 CvtPtr = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, SrcHi);
9607 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
9608 // Accessing src_flat_scratch_base_lo as a 64-bit operand gives the full
9609 // 64-bit hi:lo value.
9610 SDValue FlatScratchBase = {
9611 DAG.getMachineNode(
9612 AMDGPU::S_MOV_B64, SL, MVT::i64,
9613 DAG.getRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE, MVT::i64)),
9614 0};
9615 CvtPtr = DAG.getNode(ISD::ADD, SL, MVT::i64, CvtPtr, FlatScratchBase);
9616 } else {
9617 SDValue Aperture = getSegmentAperture(SrcAS, SL, DAG);
9618
9619 CvtPtr = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
9620 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
9621 }
9622
9623 if (IsNonNull || isKnownNonNull(Op, DAG, TM, SrcAS))
9624 return CvtPtr;
9625
9626 unsigned NullVal = AMDGPU::getNullPointerValue(SrcAS);
9627 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
9628
9629 SDValue NonNull =
9630 DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
9631
9632 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
9633 FlatNullPtr);
9634 }
9635 }
9636
9637 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
9638 Op.getValueType() == MVT::i64) {
9639 const SIMachineFunctionInfo *Info =
9640 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
9641 if (Info->get32BitAddressHighBits() == 0)
9642 return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, Src);
9643
9644 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
9645 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
9646 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9647 }
9648
9649 if (DestAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
9650 Src.getValueType() == MVT::i64)
9651 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
9652
9653 // global <-> flat are no-ops and never emitted.
9654
9655 // Invalid casts are poison.
9656 return DAG.getPOISON(Op->getValueType(0));
9657}
9658
9659// This lowers an INSERT_SUBVECTOR by extracting the individual elements from
9660// the small vector and inserting them into the big vector. That is better than
9661// the default expansion of doing it via a stack slot. Even though the use of
9662// the stack slot would be optimized away afterwards, the stack slot itself
9663// remains.
9664SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
9665 SelectionDAG &DAG) const {
9666 SDValue Vec = Op.getOperand(0);
9667 SDValue Ins = Op.getOperand(1);
9668 SDValue Idx = Op.getOperand(2);
9669 EVT VecVT = Vec.getValueType();
9670 EVT InsVT = Ins.getValueType();
9671 EVT EltVT = VecVT.getVectorElementType();
9672 unsigned InsNumElts = InsVT.getVectorNumElements();
9673 unsigned IdxVal = Idx->getAsZExtVal();
9674 SDLoc SL(Op);
9675
9676 if (EltVT.getScalarSizeInBits() == 16 && IdxVal % 2 == 0) {
9677 // Insert 32-bit registers at a time.
9678 assert(InsNumElts % 2 == 0 && "expect legal vector types");
9679
9680 unsigned VecNumElts = VecVT.getVectorNumElements();
9681 EVT NewVecVT =
9682 EVT::getVectorVT(*DAG.getContext(), MVT::i32, VecNumElts / 2);
9683 EVT NewInsVT = InsNumElts == 2 ? MVT::i32
9685 MVT::i32, InsNumElts / 2);
9686
9687 Vec = DAG.getNode(ISD::BITCAST, SL, NewVecVT, Vec);
9688 Ins = DAG.getNode(ISD::BITCAST, SL, NewInsVT, Ins);
9689
9690 for (unsigned I = 0; I != InsNumElts / 2; ++I) {
9691 SDValue Elt;
9692 if (InsNumElts == 2) {
9693 Elt = Ins;
9694 } else {
9695 Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Ins,
9696 DAG.getConstant(I, SL, MVT::i32));
9697 }
9698 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NewVecVT, Vec, Elt,
9699 DAG.getConstant(IdxVal / 2 + I, SL, MVT::i32));
9700 }
9701
9702 return DAG.getNode(ISD::BITCAST, SL, VecVT, Vec);
9703 }
9704
9705 for (unsigned I = 0; I != InsNumElts; ++I) {
9706 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
9707 DAG.getConstant(I, SL, MVT::i32));
9708 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
9709 DAG.getConstant(IdxVal + I, SL, MVT::i32));
9710 }
9711 return Vec;
9712}
9713
9714SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
9715 SelectionDAG &DAG) const {
9716 SDValue Vec = Op.getOperand(0);
9717 SDValue InsVal = Op.getOperand(1);
9718 SDValue Idx = Op.getOperand(2);
9719 EVT VecVT = Vec.getValueType();
9720 EVT EltVT = VecVT.getVectorElementType();
9721 unsigned VecSize = VecVT.getSizeInBits();
9722 unsigned EltSize = EltVT.getSizeInBits();
9723 SDLoc SL(Op);
9724
9725 // Specially handle the case of v4i16 with static indexing.
9726 unsigned NumElts = VecVT.getVectorNumElements();
9727 auto *KIdx = dyn_cast<ConstantSDNode>(Idx);
9728 if (NumElts == 4 && EltSize == 16 && KIdx) {
9729 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
9730
9731 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
9732 DAG.getConstant(0, SL, MVT::i32));
9733 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
9734 DAG.getConstant(1, SL, MVT::i32));
9735
9736 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
9737 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
9738
9739 unsigned Idx = KIdx->getZExtValue();
9740 bool InsertLo = Idx < 2;
9741 SDValue InsHalf = DAG.getNode(
9742 ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, InsertLo ? LoVec : HiVec,
9743 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
9744 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
9745
9746 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
9747
9748 SDValue Concat =
9749 InsertLo ? DAG.getBuildVector(MVT::v2i32, SL, {InsHalf, HiHalf})
9750 : DAG.getBuildVector(MVT::v2i32, SL, {LoHalf, InsHalf});
9751
9752 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
9753 }
9754
9755 // Static indexing does not lower to stack access, and hence there is no need
9756 // for special custom lowering to avoid stack access.
9757 if (isa<ConstantSDNode>(Idx))
9758 return SDValue();
9759
9760 // Avoid stack access for dynamic indexing by custom lowering to
9761 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
9762 // Vectors wider than 64 bits do this on each 64-bit piece.
9763 assert(isPowerOf2_32(EltSize));
9764 unsigned PieceSize = std::min(VecSize, 64u);
9765 unsigned NumPieces = VecSize / PieceSize;
9766 unsigned EltsPerPiece = PieceSize / EltSize;
9767 MVT IntVT = MVT::getIntegerVT(PieceSize);
9768 EVT PieceVT = EVT::getVectorVT(*DAG.getContext(), EltVT, EltsPerPiece);
9769
9770 // Convert vector index to bit-index within its piece and get the required
9771 // bit mask. Using the index within the piece keeps the shift below 64.
9772 SDValue PieceIdx = Idx;
9773 if (NumPieces > 1)
9774 PieceIdx = DAG.getNode(ISD::AND, SL, MVT::i32, Idx,
9775 DAG.getConstant(EltsPerPiece - 1, SL, MVT::i32));
9776 const auto EltMask = maskTrailingOnes<uint64_t>(EltSize);
9777 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
9778 SDValue ScaledIdx =
9779 DAG.getNode(ISD::SHL, SL, MVT::i32, PieceIdx, ScaleFactor);
9780 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
9781 DAG.getConstant(EltMask, SL, IntVT), ScaledIdx);
9782
9783 // 1. Create a congruent vector with the target value in each element.
9784 SDValue ExtVal =
9785 DAG.getBitcast(IntVT, DAG.getSplatBuildVector(PieceVT, SL, InsVal));
9786
9787 auto InsertIntoPiece = [&](SDValue Piece, SDValue Mask) {
9788 // 2. Mask off all other indices except the required index within (1).
9789 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, Mask, ExtVal);
9790
9791 // 3. Mask off the required index within the target vector.
9792 SDValue RHS =
9793 DAG.getNode(ISD::AND, SL, IntVT, DAG.getNOT(SL, Mask, IntVT), Piece);
9794
9795 // 4. Get (2) and (3) ORed into the target vector.
9796 return DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS, SDNodeFlags::Disjoint);
9797 };
9798
9799 if (NumPieces == 1)
9800 return DAG.getBitcast(VecVT,
9801 InsertIntoPiece(DAG.getBitcast(IntVT, Vec), BFM));
9802
9803 // 5. Apply (2)-(4) to each 64-bit piece, with the mask cleared in every
9804 // piece except the one that holds the index, and rebuild the vector.
9805 MVT PiecesVT = MVT::getVectorVT(IntVT, NumPieces);
9806 SDValue BCVec = DAG.getBitcast(PiecesVT, Vec);
9807 SDValue PieceNo =
9808 DAG.getNode(ISD::SRL, SL, MVT::i32, Idx,
9809 DAG.getConstant(Log2_32(EltsPerPiece), SL, MVT::i32));
9810 SDValue Zero = DAG.getConstant(0, SL, IntVT);
9812 Pieces.reserve(NumPieces);
9813 for (unsigned I = 0; I != NumPieces; ++I) {
9814 SDValue CurPieceNo = DAG.getConstant(I, SL, MVT::i32);
9815 SDValue Piece =
9816 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, IntVT, BCVec, CurPieceNo);
9817 SDValue Mask =
9818 DAG.getSelectCC(SL, PieceNo, CurPieceNo, BFM, Zero, ISD::SETEQ);
9819 Pieces.push_back(InsertIntoPiece(Piece, Mask));
9820 }
9821
9822 return DAG.getBitcast(VecVT, DAG.getBuildVector(PiecesVT, SL, Pieces));
9823}
9824
9825SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
9826 SelectionDAG &DAG) const {
9827 SDLoc SL(Op);
9828
9829 EVT ResultVT = Op.getValueType();
9830 SDValue Vec = Op.getOperand(0);
9831 SDValue Idx = Op.getOperand(1);
9832 EVT VecVT = Vec.getValueType();
9833 unsigned VecSize = VecVT.getSizeInBits();
9834 EVT EltVT = VecVT.getVectorElementType();
9835
9836 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
9837
9838 // Make sure we do any optimizations that will make it easier to fold
9839 // source modifiers before obscuring it with bit operations.
9840
9841 // XXX - Why doesn't this get called when vector_shuffle is expanded?
9842 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
9843 return Combined;
9844
9845 if (VecSize == 128 || VecSize == 256 || VecSize == 512) {
9846 SDValue Lo, Hi;
9847 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VecVT);
9848
9849 if (VecSize == 128) {
9850 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
9851 Lo = DAG.getBitcast(LoVT,
9852 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9853 DAG.getConstant(0, SL, MVT::i32)));
9854 Hi = DAG.getBitcast(HiVT,
9855 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9856 DAG.getConstant(1, SL, MVT::i32)));
9857 } else if (VecSize == 256) {
9858 SDValue V2 = DAG.getBitcast(MVT::v4i64, Vec);
9859 SDValue Parts[4];
9860 for (unsigned P = 0; P < 4; ++P) {
9861 Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9862 DAG.getConstant(P, SL, MVT::i32));
9863 }
9864
9865 Lo = DAG.getBitcast(LoVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
9866 Parts[0], Parts[1]));
9867 Hi = DAG.getBitcast(HiVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
9868 Parts[2], Parts[3]));
9869 } else {
9870 assert(VecSize == 512);
9871
9872 SDValue V2 = DAG.getBitcast(MVT::v8i64, Vec);
9873 SDValue Parts[8];
9874 for (unsigned P = 0; P < 8; ++P) {
9875 Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9876 DAG.getConstant(P, SL, MVT::i32));
9877 }
9878
9879 Lo = DAG.getBitcast(LoVT,
9880 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v4i64,
9881 Parts[0], Parts[1], Parts[2], Parts[3]));
9882 Hi = DAG.getBitcast(HiVT,
9883 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v4i64,
9884 Parts[4], Parts[5], Parts[6], Parts[7]));
9885 }
9886
9887 EVT IdxVT = Idx.getValueType();
9888 unsigned NElem = VecVT.getVectorNumElements();
9889 assert(isPowerOf2_32(NElem));
9890 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
9891 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
9892 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
9893 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
9894 }
9895
9896 assert(VecSize <= 64);
9897
9898 MVT IntVT = MVT::getIntegerVT(VecSize);
9899
9900 // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly.
9901 SDValue VecBC = peekThroughBitcasts(Vec);
9902 if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9903 SDValue Src = VecBC.getOperand(0);
9904 Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src);
9905 Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT);
9906 }
9907
9908 unsigned EltSize = EltVT.getSizeInBits();
9909 assert(isPowerOf2_32(EltSize));
9910
9911 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
9912
9913 // Convert vector index to bit-index (* EltSize)
9914 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
9915
9916 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
9917 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
9918
9919 if (ResultVT == MVT::f16 || ResultVT == MVT::bf16) {
9920 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
9921 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
9922 }
9923
9924 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
9925}
9926
9927static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
9928 assert(Elt % 2 == 0);
9929 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
9930}
9931
9932static bool elementPairIsOddToEven(ArrayRef<int> Mask, int Elt) {
9933 assert(Elt % 2 == 0);
9934 return Mask[Elt] >= 0 && Mask[Elt + 1] >= 0 && (Mask[Elt] & 1) &&
9935 !(Mask[Elt + 1] & 1);
9936}
9937
9938SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
9939 SelectionDAG &DAG) const {
9940 SDLoc SL(Op);
9941 EVT ResultVT = Op.getValueType();
9942 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
9943 MVT EltVT = ResultVT.getVectorElementType().getSimpleVT();
9944 const int NewSrcNumElts = 2;
9945 MVT PackVT = MVT::getVectorVT(EltVT, NewSrcNumElts);
9946 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
9947
9948 // Break up the shuffle into registers sized pieces.
9949 //
9950 // We're trying to form sub-shuffles that the register allocation pipeline
9951 // won't be able to figure out, like how to use v_pk_mov_b32 to do a register
9952 // blend or 16-bit op_sel. It should be able to figure out how to reassemble a
9953 // pair of copies into a consecutive register copy, so use the ordinary
9954 // extract_vector_elt lowering unless we can use the shuffle.
9955 //
9956 // TODO: This is a bit of hack, and we should probably always use
9957 // extract_subvector for the largest possible subvector we can (or at least
9958 // use it for PackVT aligned pieces). However we have worse support for
9959 // combines on them don't directly treat extract_subvector / insert_subvector
9960 // as legal. The DAG scheduler also ends up doing a worse job with the
9961 // extract_subvectors.
9962 const bool ShouldUseConsecutiveExtract = EltVT.getSizeInBits() == 16;
9963
9964 // vector_shuffle <0,1,6,7> lhs, rhs
9965 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
9966 //
9967 // vector_shuffle <6,7,2,3> lhs, rhs
9968 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
9969 //
9970 // vector_shuffle <6,7,0,1> lhs, rhs
9971 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
9972
9973 // Avoid scalarizing when both halves are reading from consecutive elements.
9974
9975 // If we're treating 2 element shuffles as legal, also create odd-to-even
9976 // shuffles of neighboring pairs.
9977 //
9978 // vector_shuffle <3,2,7,6> lhs, rhs
9979 // -> concat_vectors vector_shuffle <1, 0> (extract_subvector lhs, 0)
9980 // vector_shuffle <1, 0> (extract_subvector rhs, 2)
9981
9983 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
9984 if (ShouldUseConsecutiveExtract &&
9986 const int Idx = SVN->getMaskElt(I);
9987 int VecIdx = Idx < SrcNumElts ? 0 : 1;
9988 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
9989 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, PackVT,
9990 SVN->getOperand(VecIdx),
9991 DAG.getConstant(EltIdx, SL, MVT::i32));
9992 Pieces.push_back(SubVec);
9993 } else if (elementPairIsOddToEven(SVN->getMask(), I) &&
9995 int Idx0 = SVN->getMaskElt(I);
9996 int Idx1 = SVN->getMaskElt(I + 1);
9997
9998 SDValue SrcOp0 = SVN->getOperand(0);
9999 SDValue SrcOp1 = SrcOp0;
10000 if (Idx0 >= SrcNumElts) {
10001 SrcOp0 = SVN->getOperand(1);
10002 Idx0 -= SrcNumElts;
10003 }
10004
10005 if (Idx1 >= SrcNumElts) {
10006 SrcOp1 = SVN->getOperand(1);
10007 Idx1 -= SrcNumElts;
10008 }
10009
10010 int AlignedIdx0 = Idx0 & ~(NewSrcNumElts - 1);
10011 int AlignedIdx1 = Idx1 & ~(NewSrcNumElts - 1);
10012
10013 // Extract nearest even aligned piece.
10014 SDValue SubVec0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, PackVT, SrcOp0,
10015 DAG.getConstant(AlignedIdx0, SL, MVT::i32));
10016 SDValue SubVec1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, PackVT, SrcOp1,
10017 DAG.getConstant(AlignedIdx1, SL, MVT::i32));
10018
10019 int NewMaskIdx0 = Idx0 - AlignedIdx0;
10020 int NewMaskIdx1 = Idx1 - AlignedIdx1;
10021
10022 SDValue Result0 = SubVec0;
10023 SDValue Result1 = SubVec0;
10024
10025 if (SubVec0 != SubVec1) {
10026 NewMaskIdx1 += NewSrcNumElts;
10027 Result1 = SubVec1;
10028 } else {
10029 Result1 = DAG.getPOISON(PackVT);
10030 }
10031
10032 SDValue Shuf = DAG.getVectorShuffle(PackVT, SL, Result0, Result1,
10033 {NewMaskIdx0, NewMaskIdx1});
10034 Pieces.push_back(Shuf);
10035 } else {
10036 const int Idx0 = SVN->getMaskElt(I);
10037 const int Idx1 = SVN->getMaskElt(I + 1);
10038 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
10039 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
10040 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
10041 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
10042
10043 SDValue Vec0 = SVN->getOperand(VecIdx0);
10044 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec0,
10045 DAG.getSignedConstant(EltIdx0, SL, MVT::i32));
10046
10047 SDValue Vec1 = SVN->getOperand(VecIdx1);
10048 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec1,
10049 DAG.getSignedConstant(EltIdx1, SL, MVT::i32));
10050 Pieces.push_back(DAG.getBuildVector(PackVT, SL, {Elt0, Elt1}));
10051 }
10052 }
10053
10054 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
10055}
10056
10057SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
10058 SelectionDAG &DAG) const {
10059 SDValue SVal = Op.getOperand(0);
10060 EVT ResultVT = Op.getValueType();
10061 EVT SValVT = SVal.getValueType();
10062 SDValue UndefVal = DAG.getPOISON(SValVT);
10063 SDLoc SL(Op);
10064
10066 VElts.push_back(SVal);
10067 for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
10068 VElts.push_back(UndefVal);
10069
10070 return DAG.getBuildVector(ResultVT, SL, VElts);
10071}
10072
10073SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
10074 SelectionDAG &DAG) const {
10075 SDLoc SL(Op);
10076 EVT VT = Op.getValueType();
10077
10078 if (VT == MVT::v2f16 || VT == MVT::v2i16 || VT == MVT::v2bf16) {
10079 assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
10080
10081 SDValue Lo = Op.getOperand(0);
10082 SDValue Hi = Op.getOperand(1);
10083
10084 // Avoid adding defined bits with the zero_extend.
10085 if (Hi.isUndef()) {
10086 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
10087 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
10088 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
10089 }
10090
10091 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
10092 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
10093
10094 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
10095 DAG.getConstant(16, SL, MVT::i32));
10096 if (Lo.isUndef())
10097 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
10098
10099 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
10100 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
10101
10102 SDValue Or =
10103 DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi, SDNodeFlags::Disjoint);
10104 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
10105 }
10106
10107 // Split into 2-element chunks.
10108 const unsigned NumParts = VT.getVectorNumElements() / 2;
10109 EVT PartVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
10110 MVT PartIntVT = MVT::getIntegerVT(PartVT.getSizeInBits());
10111
10113 for (unsigned P = 0; P < NumParts; ++P) {
10114 SDValue Vec = DAG.getBuildVector(
10115 PartVT, SL, {Op.getOperand(P * 2), Op.getOperand(P * 2 + 1)});
10116 Casts.push_back(DAG.getNode(ISD::BITCAST, SL, PartIntVT, Vec));
10117 }
10118
10119 SDValue Blend =
10120 DAG.getBuildVector(MVT::getVectorVT(PartIntVT, NumParts), SL, Casts);
10121 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
10122}
10123
10125 const GlobalAddressSDNode *GA) const {
10126 // Named barriers have fixed, non-relocated LDS addresses, so a constant
10127 // offset into an array of them can be folded into the address.
10129 const auto *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
10130 return GV && AMDGPU::isNamedBarrier(*GV);
10131 }
10132
10133 // OSes that use ELF REL relocations (instead of RELA) can only store a
10134 // 32-bit addend in the instruction, so it is not safe to allow offset folding
10135 // which can create arbitrary 64-bit addends. (This is only a problem for
10136 // R_AMDGPU_*32_HI relocations since other relocation types are unaffected by
10137 // the high 32 bits of the addend.)
10138 //
10139 // This should be kept in sync with how HasRelocationAddend is initialized in
10140 // the constructor of ELFAMDGPUAsmBackend.
10141 if (!Subtarget->isAmdHsaOS())
10142 return false;
10143
10144 // We can fold offsets for anything that doesn't require a GOT relocation.
10145 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
10149}
10150
10151static SDValue
10153 const SDLoc &DL, int64_t Offset, EVT PtrVT,
10154 unsigned GAFlags = SIInstrInfo::MO_NONE) {
10155 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
10156 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
10157 // lowered to the following code sequence:
10158 //
10159 // For constant address space:
10160 // s_getpc_b64 s[0:1]
10161 // s_add_u32 s0, s0, $symbol
10162 // s_addc_u32 s1, s1, 0
10163 //
10164 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
10165 // a fixup or relocation is emitted to replace $symbol with a literal
10166 // constant, which is a pc-relative offset from the encoding of the $symbol
10167 // operand to the global variable.
10168 //
10169 // For global address space:
10170 // s_getpc_b64 s[0:1]
10171 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
10172 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
10173 //
10174 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
10175 // fixups or relocations are emitted to replace $symbol@*@lo and
10176 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
10177 // which is a 64-bit pc-relative offset from the encoding of the $symbol
10178 // operand to the global variable.
10179 if (((const GCNSubtarget &)DAG.getSubtarget()).has64BitLiterals()) {
10180 assert(GAFlags != SIInstrInfo::MO_NONE);
10181
10182 SDValue Ptr =
10183 DAG.getTargetGlobalAddress(GV, DL, MVT::i64, Offset, GAFlags + 2);
10184 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET64, DL, PtrVT, Ptr);
10185 }
10186
10187 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset, GAFlags);
10188 SDValue PtrHi;
10189 if (GAFlags == SIInstrInfo::MO_NONE)
10190 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
10191 else
10192 PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset, GAFlags + 1);
10193 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
10194}
10195
10196SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunctionInfo *MFI,
10197 SDValue Op,
10198 SelectionDAG &DAG) const {
10199 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
10200 SDLoc DL(GSD);
10201 EVT PtrVT = Op.getValueType();
10202
10203 const GlobalValue *GV = GSD->getGlobal();
10204 const unsigned AS = GSD->getAddressSpace();
10205 if (((AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::BARRIER) &&
10208 if (AS == AMDGPUAS::LOCAL_ADDRESS && GV->hasExternalLinkage()) {
10209 const GlobalVariable &GVar = *cast<GlobalVariable>(GV);
10210 // HIP uses an unsized array `extern __shared__ T s[]` or similar
10211 // zero-sized type in other languages to declare the dynamic shared
10212 // memory which size is not known at the compile time. They will be
10213 // allocated by the runtime and placed directly after the static
10214 // allocated ones. They all share the same offset.
10215 if (GVar.getGlobalSize(GVar.getDataLayout()) == 0) {
10216 assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
10217 // Adjust alignment for that dynamic shared memory array.
10219 MFI->setDynLDSAlign(F, GVar);
10220 MFI->setUsesDynamicLDS(true);
10221 return SDValue(
10222 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
10223 }
10224 }
10226 }
10227
10228 if (AS == AMDGPUAS::BARRIER) {
10229 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
10231 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0);
10232 }
10233
10234 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
10235 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
10237 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
10238 }
10239
10240 if (Subtarget->isAmdPalOS() || Subtarget->isMesa3DOS()) {
10241 if (Subtarget->has64BitLiterals()) {
10243 GV, DL, MVT::i64, GSD->getOffset(), SIInstrInfo::MO_ABS64);
10244 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Addr),
10245 0);
10246 }
10247
10248 SDValue AddrLo = DAG.getTargetGlobalAddress(
10249 GV, DL, MVT::i32, GSD->getOffset(), SIInstrInfo::MO_ABS32_LO);
10250 AddrLo = {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, AddrLo), 0};
10251
10252 SDValue AddrHi = DAG.getTargetGlobalAddress(
10253 GV, DL, MVT::i32, GSD->getOffset(), SIInstrInfo::MO_ABS32_HI);
10254 AddrHi = {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, AddrHi), 0};
10255
10256 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, AddrLo, AddrHi);
10257 }
10258
10259 if (shouldEmitFixup(GV))
10260 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
10261
10262 if (shouldEmitPCReloc(GV))
10263 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
10265
10266 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
10268 PointerType *PtrTy =
10270 const DataLayout &DataLayout = DAG.getDataLayout();
10271 Align Alignment = DataLayout.getABITypeAlign(PtrTy);
10272 MachinePointerInfo PtrInfo =
10274
10275 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
10278}
10279
10280SDValue SITargetLowering::LowerExternalSymbol(SDValue Op,
10281 SelectionDAG &DAG) const {
10282 // TODO: Handle this. It should be mostly the same as LowerGlobalAddress.
10283 const Function &Fn = DAG.getMachineFunction().getFunction();
10284 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10285 Fn, "unsupported external symbol", Op.getDebugLoc()));
10286 return DAG.getPOISON(Op.getValueType());
10287}
10288
10290 const SDLoc &DL, SDValue V) const {
10291 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
10292 // the destination register.
10293 //
10294 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
10295 // so we will end up with redundant moves to m0.
10296 //
10297 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
10298
10299 // A Null SDValue creates a glue result.
10300 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
10301 V, Chain);
10302 return SDValue(M0, 0);
10303}
10304
10305SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, SDValue Op,
10306 MVT VT,
10307 unsigned Offset) const {
10308 SDLoc SL(Op);
10309 SDValue Param = lowerKernargMemParameter(
10310 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
10311 // The local size values will have the hi 16-bits as zero.
10312 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
10313 DAG.getValueType(VT));
10314}
10315
10317 EVT VT) {
10320 "non-hsa intrinsic with hsa target", DL.getDebugLoc()));
10321 return DAG.getPOISON(VT);
10322}
10323
10325 EVT VT) {
10328 "intrinsic not supported on subtarget", DL.getDebugLoc()));
10329 return DAG.getPOISON(VT);
10330}
10331
10333 ArrayRef<SDValue> Elts) {
10334 assert(!Elts.empty());
10335 MVT Type;
10336 unsigned NumElts = Elts.size();
10337
10338 if (NumElts <= 12) {
10339 Type = MVT::getVectorVT(MVT::f32, NumElts);
10340 } else {
10341 assert(Elts.size() <= 16);
10342 Type = MVT::v16f32;
10343 NumElts = 16;
10344 }
10345
10346 SmallVector<SDValue, 16> VecElts(NumElts);
10347 for (unsigned i = 0; i < Elts.size(); ++i) {
10348 SDValue Elt = Elts[i];
10349 if (Elt.getValueType() != MVT::f32)
10350 Elt = DAG.getBitcast(MVT::f32, Elt);
10351 VecElts[i] = Elt;
10352 }
10353 for (unsigned i = Elts.size(); i < NumElts; ++i)
10354 VecElts[i] = DAG.getPOISON(MVT::f32);
10355
10356 if (NumElts == 1)
10357 return VecElts[0];
10358 return DAG.getBuildVector(Type, DL, VecElts);
10359}
10360
10361static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
10362 SDValue Src, int ExtraElts) {
10363 EVT SrcVT = Src.getValueType();
10364
10366
10367 if (SrcVT.isVector())
10368 DAG.ExtractVectorElements(Src, Elts);
10369 else
10370 Elts.push_back(Src);
10371
10372 SDValue Undef = DAG.getPOISON(SrcVT.getScalarType());
10373 while (ExtraElts--)
10374 Elts.push_back(Undef);
10375
10376 return DAG.getBuildVector(CastVT, DL, Elts);
10377}
10378
10379// Re-construct the required return value for a image load intrinsic.
10380// This is more complicated due to the optional use TexFailCtrl which means the
10381// required return type is an aggregate
10383 ArrayRef<EVT> ResultTypes, bool IsTexFail,
10384 bool Unpacked, bool IsD16, int DMaskPop,
10385 int NumVDataDwords, bool IsAtomicPacked16Bit,
10386 const SDLoc &DL) {
10387 // Determine the required return type. This is the same regardless of
10388 // IsTexFail flag
10389 EVT ReqRetVT = ResultTypes[0];
10390 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
10391 int NumDataDwords = ((IsD16 && !Unpacked) || IsAtomicPacked16Bit)
10392 ? (ReqRetNumElts + 1) / 2
10393 : ReqRetNumElts;
10394
10395 int MaskPopDwords = (!IsD16 || Unpacked) ? DMaskPop : (DMaskPop + 1) / 2;
10396
10397 MVT DataDwordVT =
10398 NumDataDwords == 1 ? MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
10399
10400 MVT MaskPopVT =
10401 MaskPopDwords == 1 ? MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
10402
10403 SDValue Data(Result, 0);
10404 SDValue TexFail;
10405
10406 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
10407 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
10408 if (MaskPopVT.isVector()) {
10409 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
10410 SDValue(Result, 0), ZeroIdx);
10411 } else {
10412 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
10413 SDValue(Result, 0), ZeroIdx);
10414 }
10415 }
10416
10417 if (DataDwordVT.isVector() && !IsAtomicPacked16Bit)
10418 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
10419 NumDataDwords - MaskPopDwords);
10420
10421 if (IsD16)
10422 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
10423
10424 EVT LegalReqRetVT = ReqRetVT;
10425 if (!ReqRetVT.isVector()) {
10426 if (!Data.getValueType().isInteger())
10427 Data = DAG.getNode(ISD::BITCAST, DL,
10428 Data.getValueType().changeTypeToInteger(), Data);
10429 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
10430 } else {
10431 // We need to widen the return vector to a legal type
10432 if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
10433 ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
10434 LegalReqRetVT =
10436 ReqRetVT.getVectorNumElements() + 1);
10437 }
10438 }
10439 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
10440
10441 if (IsTexFail) {
10442 TexFail =
10443 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
10444 DAG.getConstant(MaskPopDwords, DL, MVT::i32));
10445
10446 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
10447 }
10448
10449 if (Result->getNumValues() == 1)
10450 return Data;
10451
10452 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
10453}
10454
10455static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
10456 SDValue *LWE, bool &IsTexFail) {
10457 auto *TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
10458
10459 uint64_t Value = TexFailCtrlConst->getZExtValue();
10460 if (Value) {
10461 IsTexFail = true;
10462 }
10463
10464 SDLoc DL(TexFailCtrlConst);
10465 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
10466 Value &= ~(uint64_t)0x1;
10467 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
10468 Value &= ~(uint64_t)0x2;
10469
10470 return Value == 0;
10471}
10472
10474 MVT PackVectorVT,
10475 SmallVectorImpl<SDValue> &PackedAddrs,
10476 unsigned DimIdx, unsigned EndIdx,
10477 unsigned NumGradients) {
10478 SDLoc DL(Op);
10479 for (unsigned I = DimIdx; I < EndIdx; I++) {
10480 SDValue Addr = Op.getOperand(I);
10481
10482 // Gradients are packed with undef for each coordinate.
10483 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
10484 // 1D: undef,dx/dh; undef,dx/dv
10485 // 2D: dy/dh,dx/dh; dy/dv,dx/dv
10486 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
10487 if (((I + 1) >= EndIdx) ||
10488 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
10489 I == DimIdx + NumGradients - 1))) {
10490 if (Addr.getValueType() != MVT::i16)
10491 Addr = DAG.getBitcast(MVT::i16, Addr);
10492 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
10493 } else {
10494 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
10495 I++;
10496 }
10497 Addr = DAG.getBitcast(MVT::f32, Addr);
10498 PackedAddrs.push_back(Addr);
10499 }
10500}
10501
10502/// Emit a DiagnosticInfoUnsupported for an unsupported image intrinsic and
10503/// return poison values of \p ResultTypes, preserving the chain if present.
10505 ArrayRef<EVT> ResultTypes,
10506 const SDLoc &DL, const Twine &Msg) {
10508 DAG.getMachineFunction().getFunction(), Msg, DL.getDebugLoc()));
10509 return DAG.getErrorMergeValues(ResultTypes, Op.getOperand(0), DL);
10510}
10511
10512SDValue SITargetLowering::lowerImage(SDValue Op,
10514 SelectionDAG &DAG, bool WithChain) const {
10515 SDLoc DL(Op);
10517 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
10518 unsigned IntrOpcode = Intr->BaseOpcode;
10519 // For image atomic: use no-return opcode if result is unused.
10520 if (Intr->AtomicNoRetBaseOpcode != Intr->BaseOpcode &&
10521 !Op.getNode()->hasAnyUseOfValue(0))
10522 IntrOpcode = Intr->AtomicNoRetBaseOpcode;
10523 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
10525 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
10526 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
10527 bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
10528 bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
10529 bool IsGFX13 = AMDGPU::isGFX13(*Subtarget);
10530
10531 SmallVector<EVT, 3> ResultTypes(Op->values());
10532 SmallVector<EVT, 3> OrigResultTypes(Op->values());
10533 if (BaseOpcode->NoReturn && BaseOpcode->Atomic)
10534 ResultTypes.erase(&ResultTypes[0]);
10535
10536 bool IsD16 = false;
10537 bool IsG16 = false;
10538 bool IsA16 = false;
10539 SDValue VData;
10540 int NumVDataDwords = 0;
10541 bool AdjustRetType = false;
10542 bool IsAtomicPacked16Bit = false;
10543
10544 // Offset of intrinsic arguments
10545 const unsigned ArgOffset = WithChain ? 2 : 1;
10546
10547 unsigned DMask;
10548 unsigned DMaskLanes = 0;
10549
10550 if (BaseOpcode->Atomic) {
10551 VData = Op.getOperand(2);
10552
10553 IsAtomicPacked16Bit =
10554 (IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_F16 ||
10555 IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_F16_NORTN ||
10556 IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_BF16 ||
10557 IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_BF16_NORTN);
10558
10559 if (!IsAtomicPacked16Bit && VData.getValueSizeInBits() != 32 &&
10560 VData.getValueSizeInBits() != 64) {
10561 return diagnoseUnsupportedImage(DAG, Op, OrigResultTypes, DL,
10562 "unsupported image atomic data type");
10563 }
10564
10565 bool Is64Bit = VData.getValueSizeInBits() == 64;
10566 if (BaseOpcode->AtomicX2) {
10567 SDValue VData2 = Op.getOperand(3);
10568 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
10569 {VData, VData2});
10570 if (Is64Bit)
10571 VData = DAG.getBitcast(MVT::v4i32, VData);
10572
10573 if (!BaseOpcode->NoReturn)
10574 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
10575
10576 DMask = Is64Bit ? 0xf : 0x3;
10577 NumVDataDwords = Is64Bit ? 4 : 2;
10578 } else {
10579 DMask = Is64Bit ? 0x3 : 0x1;
10580 NumVDataDwords = Is64Bit ? 2 : 1;
10581 }
10582 } else {
10583 DMask = Op->getConstantOperandVal(ArgOffset + Intr->DMaskIndex);
10584 DMaskLanes = BaseOpcode->Gather4 ? 4 : llvm::popcount(DMask);
10585
10586 if (BaseOpcode->Store) {
10587 VData = Op.getOperand(2);
10588
10589 MVT StoreVT = VData.getSimpleValueType();
10590 MVT StoreScalarVT = StoreVT.getScalarType();
10591 if (StoreScalarVT != MVT::f16 && StoreScalarVT.getSizeInBits() != 32 &&
10592 StoreScalarVT.getSizeInBits() != 64) {
10593 return diagnoseUnsupportedImage(DAG, Op, OrigResultTypes, DL,
10594 "unsupported image store data type");
10595 }
10596 if (StoreScalarVT == MVT::f16) {
10597 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
10598 return Op; // D16 is unsupported for this instruction
10599
10600 IsD16 = true;
10601 VData = handleD16VData(VData, DAG, true);
10602 }
10603
10604 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
10605 } else if (!BaseOpcode->NoReturn) {
10606 // Work out the num dwords based on the dmask popcount and underlying type
10607 // and whether packing is supported.
10608 MVT LoadVT = ResultTypes[0].getSimpleVT();
10609 MVT LoadScalarVT = LoadVT.getScalarType();
10610 if (LoadScalarVT != MVT::f16 && LoadScalarVT.getSizeInBits() != 32 &&
10611 LoadScalarVT.getSizeInBits() != 64) {
10612 return diagnoseUnsupportedImage(DAG, Op, OrigResultTypes, DL,
10613 "unsupported image load data type");
10614 }
10615 if (LoadScalarVT == MVT::f16) {
10616 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
10617 return Op; // D16 is unsupported for this instruction
10618
10619 IsD16 = true;
10620 }
10621
10622 // Confirm that the return type is large enough for the dmask specified
10623 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
10624 (!LoadVT.isVector() && DMaskLanes > 1))
10625 return Op;
10626
10627 // The sq block of gfx8 and gfx9 do not estimate register use correctly
10628 // for d16 image_gather4, image_gather4_l, and image_gather4_lz
10629 // instructions.
10630 if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
10631 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
10632 NumVDataDwords = (DMaskLanes + 1) / 2;
10633 else
10634 NumVDataDwords = DMaskLanes;
10635
10636 AdjustRetType = true;
10637 }
10638 }
10639
10640 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
10642
10643 // Check for 16 bit addresses or derivatives and pack if true.
10644 MVT VAddrVT =
10645 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
10646 MVT VAddrScalarVT = VAddrVT.getScalarType();
10647 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
10648 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
10649
10650 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
10651 VAddrScalarVT = VAddrVT.getScalarType();
10652 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
10653 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
10654
10655 // Push back extra arguments.
10656 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
10657 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
10658 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
10659 // Special handling of bias when A16 is on. Bias is of type half but
10660 // occupies full 32-bit.
10661 SDValue Bias = DAG.getBuildVector(
10662 MVT::v2f16, DL,
10663 {Op.getOperand(ArgOffset + I), DAG.getPOISON(MVT::f16)});
10664 VAddrs.push_back(Bias);
10665 } else {
10666 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
10667 "Bias needs to be converted to 16 bit in A16 mode");
10668 VAddrs.push_back(Op.getOperand(ArgOffset + I));
10669 }
10670 }
10671
10672 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
10673 // 16 bit gradients are supported, but are tied to the A16 control
10674 // so both gradients and addresses must be 16 bit
10675 LLVM_DEBUG(
10676 dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
10677 "require 16 bit args for both gradients and addresses");
10678 return Op;
10679 }
10680
10681 if (IsA16) {
10682 if (!ST->hasA16()) {
10683 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
10684 "support 16 bit addresses\n");
10685 return Op;
10686 }
10687 }
10688
10689 // We've dealt with incorrect input so we know that if IsA16, IsG16
10690 // are set then we have to compress/pack operands (either address,
10691 // gradient or both)
10692 // In the case where a16 and gradients are tied (no G16 support) then we
10693 // have already verified that both IsA16 and IsG16 are true
10694 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
10695 // Activate g16
10696 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
10698 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
10699 }
10700
10701 // Add gradients (packed or unpacked)
10702 if (IsG16) {
10703 // Pack the gradients
10704 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
10705 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
10706 ArgOffset + Intr->GradientStart,
10707 ArgOffset + Intr->CoordStart, Intr->NumGradients);
10708 } else {
10709 for (unsigned I = ArgOffset + Intr->GradientStart;
10710 I < ArgOffset + Intr->CoordStart; I++)
10711 VAddrs.push_back(Op.getOperand(I));
10712 }
10713
10714 // Add addresses (packed or unpacked)
10715 if (IsA16) {
10716 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
10717 ArgOffset + Intr->CoordStart, VAddrEnd,
10718 0 /* No gradients */);
10719 } else {
10720 // Add uncompressed address
10721 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
10722 VAddrs.push_back(Op.getOperand(I));
10723 }
10724
10725 // If the register allocator cannot place the address registers contiguously
10726 // without introducing moves, then using the non-sequential address encoding
10727 // is always preferable, since it saves VALU instructions and is usually a
10728 // wash in terms of code size or even better.
10729 //
10730 // However, we currently have no way of hinting to the register allocator that
10731 // MIMG addresses should be placed contiguously when it is possible to do so,
10732 // so force non-NSA for the common 2-address case as a heuristic.
10733 //
10734 // SIShrinkInstructions will convert NSA encodings to non-NSA after register
10735 // allocation when possible.
10736 //
10737 // Partial NSA is allowed on GFX11+ where the final register is a contiguous
10738 // set of the remaining addresses.
10739 const unsigned NSAMaxSize = ST->getNSAMaxSize(BaseOpcode->Sampler);
10740 const bool HasPartialNSAEncoding = ST->hasPartialNSAEncoding();
10741 const bool UseNSA = ST->hasNSAEncoding() &&
10742 VAddrs.size() >= ST->getNSAThreshold(MF) &&
10743 (VAddrs.size() <= NSAMaxSize || HasPartialNSAEncoding);
10744 const bool UsePartialNSA =
10745 UseNSA && HasPartialNSAEncoding && VAddrs.size() > NSAMaxSize;
10746
10747 SDValue VAddr;
10748 if (UsePartialNSA) {
10749 VAddr = getBuildDwordsVector(DAG, DL,
10750 ArrayRef(VAddrs).drop_front(NSAMaxSize - 1));
10751 } else if (!UseNSA) {
10752 VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
10753 }
10754
10755 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
10756 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
10757 SDValue Unorm;
10758 if (!BaseOpcode->Sampler) {
10759 Unorm = True;
10760 } else {
10761 uint64_t UnormConst =
10762 Op.getConstantOperandVal(ArgOffset + Intr->UnormIndex);
10763
10764 Unorm = UnormConst ? True : False;
10765 }
10766
10767 SDValue TFE;
10768 SDValue LWE;
10769 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
10770 bool IsTexFail = false;
10771 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
10772 return Op;
10773
10774 if (IsTexFail) {
10775 if (!DMaskLanes) {
10776 // Expecting to get an error flag since TFC is on - and dmask is 0
10777 // Force dmask to be at least 1 otherwise the instruction will fail
10778 DMask = 0x1;
10779 DMaskLanes = 1;
10780 NumVDataDwords = 1;
10781 }
10782 NumVDataDwords += 1;
10783 AdjustRetType = true;
10784 }
10785
10786 // Has something earlier tagged that the return type needs adjusting
10787 // This happens if the instruction is a load or has set TexFailCtrl flags
10788 if (AdjustRetType) {
10789 // NumVDataDwords reflects the true number of dwords required in the return
10790 // type
10791 if (DMaskLanes == 0 && !BaseOpcode->Store) {
10792 // This is a no-op load. This can be eliminated
10793 SDValue Undef = DAG.getPOISON(Op.getValueType());
10794 if (isa<MemSDNode>(Op))
10795 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
10796 return Undef;
10797 }
10798
10799 EVT NewVT = NumVDataDwords > 1 ? EVT::getVectorVT(*DAG.getContext(),
10800 MVT::i32, NumVDataDwords)
10801 : MVT::i32;
10802
10803 ResultTypes[0] = NewVT;
10804 if (ResultTypes.size() == 3) {
10805 // Original result was aggregate type used for TexFailCtrl results
10806 // The actual instruction returns as a vector type which has now been
10807 // created. Remove the aggregate result.
10808 ResultTypes.erase(&ResultTypes[1]);
10809 }
10810 }
10811
10812 unsigned CPol = Op.getConstantOperandVal(ArgOffset + Intr->CachePolicyIndex);
10813 // Keep GLC only when the atomic's result is actually used.
10814 if (BaseOpcode->Atomic && !BaseOpcode->NoReturn)
10816 if (CPol & ~((IsGFX12Plus ? AMDGPU::CPol::ALL : AMDGPU::CPol::ALL_pregfx12) |
10818 return Op;
10819
10821 if (BaseOpcode->Store || BaseOpcode->Atomic)
10822 Ops.push_back(VData); // vdata
10823 if (UsePartialNSA) {
10824 append_range(Ops, ArrayRef(VAddrs).take_front(NSAMaxSize - 1));
10825 Ops.push_back(VAddr);
10826 } else if (UseNSA)
10827 append_range(Ops, VAddrs);
10828 else
10829 Ops.push_back(VAddr);
10830 SDValue Rsrc = Op.getOperand(ArgOffset + Intr->RsrcIndex);
10831 EVT RsrcVT = Rsrc.getValueType();
10832 bool IndexedRsrc = IsGFX13 && RsrcVT == MVT::i32;
10833 if (RsrcVT != MVT::v4i32 && RsrcVT != MVT::v8i32 && !IndexedRsrc)
10834 return Op;
10835 Ops.push_back(Rsrc);
10836 bool IsSampIndexed = false;
10837 if (BaseOpcode->Sampler) {
10838 SDValue Samp = Op.getOperand(ArgOffset + Intr->SampIndex);
10839 EVT SampVT = Samp.getValueType();
10840 IsSampIndexed = IsGFX13 && SampVT == MVT::i32;
10841 if (SampVT != MVT::v4i32 && !IsSampIndexed)
10842 return Op;
10843 Ops.push_back(Samp);
10844 }
10845 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
10846 if (IsGFX10Plus)
10847 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
10848 if (!IsGFX12Plus || BaseOpcode->Sampler || BaseOpcode->MSAA)
10849 Ops.push_back(Unorm);
10850 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
10851 Ops.push_back(IsA16 && // r128, a16 for gfx9
10852 ST->hasFeature(AMDGPU::FeatureR128A16)
10853 ? True
10854 : False);
10855 if (IsGFX10Plus)
10856 Ops.push_back(IsA16 ? True : False);
10857
10858 if (!Subtarget->hasGFX90AInsts())
10859 Ops.push_back(TFE); // tfe
10860 else if (TFE->getAsZExtVal()) {
10861 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10863 "TFE is not supported on this GPU", DL.getDebugLoc()));
10864 }
10865
10866 if (!IsGFX12Plus || BaseOpcode->Sampler || BaseOpcode->MSAA)
10867 Ops.push_back(LWE); // lwe
10868 if (!IsGFX10Plus)
10869 Ops.push_back(DimInfo->DA ? True : False);
10870 if (BaseOpcode->HasD16)
10871 Ops.push_back(IsD16 ? True : False);
10872 if (isa<MemSDNode>(Op))
10873 Ops.push_back(Op.getOperand(0)); // chain
10874
10875 int NumVAddrDwords =
10876 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
10877 int Opcode = -1;
10878
10879 if (IsGFX13) {
10880 Opcode =
10881 AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx13, NumVDataDwords,
10882 NumVAddrDwords, IndexedRsrc, IsSampIndexed);
10883 } else if (IsGFX12Plus) {
10884 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx12,
10885 NumVDataDwords, NumVAddrDwords);
10886 } else if (IsGFX11Plus) {
10887 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
10888 UseNSA ? AMDGPU::MIMGEncGfx11NSA
10889 : AMDGPU::MIMGEncGfx11Default,
10890 NumVDataDwords, NumVAddrDwords);
10891 } else if (IsGFX10Plus) {
10892 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
10893 UseNSA ? AMDGPU::MIMGEncGfx10NSA
10894 : AMDGPU::MIMGEncGfx10Default,
10895 NumVDataDwords, NumVAddrDwords);
10896 } else {
10897 if (Subtarget->hasGFX90AInsts()) {
10898 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
10899 NumVDataDwords, NumVAddrDwords);
10900 if (Opcode == -1) {
10902 DAG, Op, OrigResultTypes, DL,
10903 "requested image instruction is not supported on this GPU");
10904 }
10905 }
10906 if (Opcode == -1 &&
10907 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
10908 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
10909 NumVDataDwords, NumVAddrDwords);
10910 if (Opcode == -1)
10911 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
10912 NumVDataDwords, NumVAddrDwords);
10913 }
10914 if (Opcode == -1)
10915 return Op;
10916
10917 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
10918 if (auto *MemOp = dyn_cast<MemSDNode>(Op)) {
10919 MachineMemOperand *MemRef = MemOp->getMemOperand();
10920 DAG.setNodeMemRefs(NewNode, {MemRef});
10921 }
10922
10923 if (BaseOpcode->NoReturn) {
10924 if (BaseOpcode->Atomic)
10925 return DAG.getMergeValues(
10926 {DAG.getPOISON(OrigResultTypes[0]), SDValue(NewNode, 0)}, DL);
10927
10928 return SDValue(NewNode, 0);
10929 }
10930
10931 if (BaseOpcode->AtomicX2) {
10933 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
10934 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
10935 }
10936
10937 return constructRetValue(DAG, NewNode, OrigResultTypes, IsTexFail,
10938 Subtarget->hasUnpackedD16VMem(), IsD16, DMaskLanes,
10939 NumVDataDwords, IsAtomicPacked16Bit, DL);
10940}
10941
10942SDValue SITargetLowering::lowerSBuffer(EVT VT, EVT MemVT, SDLoc DL,
10943 SDValue Chain, SDValue Rsrc,
10944 SDValue Offset, SDValue CachePolicy,
10945 SelectionDAG &DAG,
10946 MachineMemOperand *MMO) const {
10948 bool HasChainResult = MMO != nullptr;
10949
10950 // SBUFFER_LOAD only produces values that fill whole SGPRs, apart from the
10951 // subword loads below.
10952 bool IsSubwordLoad = (MemVT == MVT::i8 || MemVT == MVT::i16) &&
10953 Subtarget->hasScalarSubwordLoads();
10954 if ((!isTypeLegal(VT) || VT.getSizeInBits() % 32 != 0) && !IsSubwordLoad) {
10955 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10956 MF.getFunction(), "unsupported s_buffer_load result type",
10957 DL.getDebugLoc()));
10958 EVT ResultTypes[] = {VT, MVT::Other};
10959 return DAG.getErrorMergeValues(
10960 ArrayRef(ResultTypes, HasChainResult ? 2 : 1), Chain, DL);
10961 }
10962
10963 if (!HasChainResult) {
10964 const DataLayout &DataLayout = DAG.getDataLayout();
10966 DataLayout.getABITypeAlign(MemVT.getTypeForEVT(*DAG.getContext()));
10967
10968 MMO = MF.getMachineMemOperand(MachinePointerInfo(),
10972 MemVT.getStoreSize(), Alignment);
10973 }
10974
10975 if (!Offset->isDivergent()) {
10976 SDValue Ops[] = {Chain, Rsrc, Offset, CachePolicy};
10977
10978 // Lower llvm.amdgcn.*s.buffer.load.{i,u}N intrinsics. First, generate
10979 // s_buffer_load_u* for signed and unsigned load instructions. Next, DAG
10980 // combiner tries to merge the s_buffer_load_uN with a sext instruction
10981 // (performSignExtendInRegCombine()) and it replaces s_buffer_load_uN with
10982 // s_buffer_load_iN.
10983 auto HandleScalarSubwordLoads = [&](unsigned Opcode) -> SDValue {
10984 SDValue BufferLoad = DAG.getMemIntrinsicNode(
10985 Opcode, DL, DAG.getVTList(MVT::i32, MVT::Other), Ops, MemVT, MMO);
10986 SDValue LoadVal = DAG.getAnyExtOrTrunc(
10987 DAG.getNode(ISD::TRUNCATE, DL, MemVT, BufferLoad), DL, VT);
10988 if (HasChainResult)
10989 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
10990 return LoadVal;
10991 };
10992 if (MemVT == MVT::i8 && Subtarget->hasScalarSubwordLoads())
10993 return HandleScalarSubwordLoads(AMDGPUISD::SBUFFER_LOAD_UBYTE);
10994
10995 if (MemVT == MVT::i16 && Subtarget->hasScalarSubwordLoads())
10996 return HandleScalarSubwordLoads(AMDGPUISD::SBUFFER_LOAD_USHORT);
10997
10998 // Widen vec3 load to vec4. Only 32-bit elements have a vec4 pattern.
10999 if (VT.isVector() && VT.getVectorNumElements() == 3 &&
11000 VT.getVectorElementType().getSizeInBits() == 32 &&
11001 !Subtarget->hasScalarDwordx3Loads()) {
11002 EVT WidenedVT =
11004 auto WidenedOp = DAG.getMemIntrinsicNode(
11005 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT, MVT::Other),
11006 Ops, WidenedVT,
11007 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
11008 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
11009 DAG.getVectorIdxConstant(0, DL));
11010 if (HasChainResult)
11011 return DAG.getMergeValues({Subvector, WidenedOp.getValue(1)}, DL);
11012 return Subvector;
11013 }
11014
11015 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
11016 DAG.getVTList(VT, MVT::Other), Ops, MemVT,
11017 MMO);
11018 }
11019
11020 // We have a divergent offset. Emit a MUBUF buffer load instead. We can
11021 // assume that the buffer is unswizzled.
11022 SDValue Ops[] = {
11023 Chain, // Chain
11024 Rsrc, // rsrc
11025 DAG.getConstant(0, DL, MVT::i32), // vindex
11026 {}, // voffset
11027 {}, // soffset
11028 {}, // offset
11029 CachePolicy, // cachepolicy
11030 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
11031 };
11032 if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
11033 Subtarget->hasScalarSubwordLoads()) {
11034 setBufferOffsets(Offset, DAG, &Ops[3], Align(4));
11035 SDValue Load = handleByteShortBufferLoads(DAG, MemVT, DL, Ops, MMO);
11036 SDValue LoadVal = DAG.getAnyExtOrTrunc(Load.getOperand(0), DL, VT);
11037 if (HasChainResult)
11038 return DAG.getMergeValues({LoadVal, Load.getOperand(1)}, DL);
11039 return LoadVal;
11040 }
11041
11043 unsigned NumLoads = 1;
11044 MVT LoadVT = VT.getSimpleVT();
11045 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
11046 assert((LoadVT.getScalarType() == MVT::i32 ||
11047 LoadVT.getScalarType() == MVT::f32));
11048
11049 if (NumElts == 8 || NumElts == 16) {
11050 NumLoads = NumElts / 4;
11051 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
11052 }
11053
11054 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Other});
11055
11056 // Use the alignment to ensure that the required offsets will fit into the
11057 // immediate offsets.
11058 setBufferOffsets(Offset, DAG, &Ops[3],
11059 NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
11060
11061 uint64_t InstOffset = Ops[5]->getAsZExtVal();
11062 unsigned LoadSize = LoadVT.getStoreSize();
11063 for (unsigned i = 0; i < NumLoads; ++i) {
11064 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
11065 MachineMemOperand *LoadMMO = MF.getMachineMemOperand(MMO, 16 * i, LoadSize);
11066 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
11067 LoadVT, LoadMMO, DAG));
11068 }
11069
11070 if (NumElts == 8 || NumElts == 16) {
11071 SDValue LoadVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
11072 if (HasChainResult) {
11073 SmallVector<SDValue, 4> LoadChains;
11074 for (SDValue Load : Loads)
11075 LoadChains.push_back(Load.getValue(1));
11076 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, LoadChains);
11077 return DAG.getMergeValues({LoadVal, Chain}, DL);
11078 }
11079 return LoadVal;
11080 }
11081
11082 return Loads[0];
11083}
11084
11085SDValue SITargetLowering::lowerWaveID(SelectionDAG &DAG, SDValue Op) const {
11086 // With architected SGPRs, waveIDinGroup is in TTMP8[29:25].
11087 if (!Subtarget->hasArchitectedSGPRs())
11088 return {};
11089 SDLoc SL(Op);
11090 MVT VT = MVT::i32;
11091 SDValue TTMP8 = DAG.getCopyFromReg(DAG.getEntryNode(), SL, AMDGPU::TTMP8, VT);
11092 return DAG.getNode(AMDGPUISD::BFE_U32, SL, VT, TTMP8,
11093 DAG.getConstant(25, SL, VT), DAG.getConstant(5, SL, VT));
11094}
11095
11096SDValue SITargetLowering::lowerConstHwRegRead(SelectionDAG &DAG, SDValue Op,
11097 AMDGPU::Hwreg::Id HwReg,
11098 unsigned LowBit,
11099 unsigned Width) const {
11100 SDLoc SL(Op);
11101 using namespace AMDGPU::Hwreg;
11102 return {DAG.getMachineNode(
11103 AMDGPU::S_GETREG_B32_const, SL, MVT::i32,
11104 DAG.getTargetConstant(HwregEncoding::encode(HwReg, LowBit, Width),
11105 SL, MVT::i32)),
11106 0};
11107}
11108
11109SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
11110 unsigned Dim,
11111 const ArgDescriptor &Arg) const {
11112 SDLoc SL(Op);
11114 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
11115 if (MaxID == 0)
11116 return DAG.getConstant(0, SL, MVT::i32);
11117
11118 // It's undefined behavior if a function marked with the amdgpu-no-*
11119 // attributes uses the corresponding intrinsic.
11120 if (!Arg)
11121 return DAG.getPOISON(Op->getValueType(0));
11122
11123 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
11124 SDLoc(DAG.getEntryNode()), Arg);
11125
11126 // Don't bother inserting AssertZext for packed IDs since we're emitting the
11127 // masking operations anyway.
11128 //
11129 // TODO: We could assert the top bit is 0 for the source copy.
11130 if (Arg.isMasked())
11131 return Val;
11132
11133 // Preserve the known bits after expansion to a copy.
11134 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_width(MaxID));
11135 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
11136 DAG.getValueType(SmallVT));
11137}
11138
11139SDValue SITargetLowering::lowerFromFP8(SDValue Op, bool IsBF8,
11140 SelectionDAG &DAG) const {
11141 SDLoc SL(Op);
11142 SDValue Src = Op.getOperand(0);
11143 EVT DstVT = Op.getValueType();
11144 bool IsF16 = DstVT.getVectorElementType() == MVT::f16;
11145 assert((!IsF16 || Subtarget->hasFP8F16ConversionInsts()) &&
11146 "fp8/bf8 -> f16 conversion requires FP8F16ConversionInsts");
11147
11148 unsigned Opc;
11149 if (IsF16)
11150 Opc = IsBF8 ? AMDGPUISD::CVT_PK_F16_BF8 : AMDGPUISD::CVT_PK_F16_FP8;
11151 else
11152 Opc = IsBF8 ? AMDGPUISD::CVT_PK_F32_BF8 : AMDGPUISD::CVT_PK_F32_FP8;
11153
11154 // Pack the two i8 lanes into the integer type the packed HW node reads. The
11155 // f16 form takes i16 and the f32 form takes i32. v2i8 bitcasts to i16
11156 // directly and the f32 node reads the low half of an any-extended i32.
11157 EVT PackedVT =
11159 SDValue AsI16 = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11160 SDValue Packed = DAG.getAnyExtOrTrunc(AsI16, SL, PackedVT);
11161 return DAG.getNode(Opc, SL, DstVT, Packed);
11162}
11163
11164SDValue
11165SITargetLowering::LowerCONVERT_FROM_ARBITRARY_FP(SDValue Op,
11166 SelectionDAG &DAG) const {
11167 // Handle the OCP FP8 formats (E4M3FN, E5M2) and unsigned E5M3 on subtargets
11168 // with matching HW conversions. Other formats use the generic expansion.
11169 APFloatBase::Semantics FPSemantic =
11170 static_cast<APFloatBase::Semantics>(Op.getConstantOperandVal(1));
11171 const bool IsFP8 = FPSemantic == APFloatBase::S_Float8E4M3FN;
11172 const bool IsBF8 = FPSemantic == APFloatBase::S_Float8E5M2;
11173 const bool IsE5M3 = FPSemantic == APFloatBase::S_Float8E5M3FNU;
11174 const bool HasE5M3ConversionInsts =
11175 Subtarget->hasFP8ConversionInsts() && Subtarget->hasFP8E5M3Insts();
11176 const bool IsSupported = IsFP8 || IsBF8 || (IsE5M3 && HasE5M3ConversionInsts);
11177 if (!IsSupported)
11178 return SDValue();
11179
11180 EVT DstVT = Op.getValueType();
11181 // The custom action for a v2i8 source also reaches half conversions on
11182 // targets which only have FP8-to-f32 instructions.
11183 if (DstVT.getScalarType() == MVT::f16 &&
11184 !Subtarget->hasFP8F16ConversionInsts())
11185 return SDValue();
11186
11187 if (IsE5M3) {
11188 if (DstVT.getScalarType() != MVT::f32)
11189 return SDValue();
11190
11191 SDLoc SL(Op);
11192 SDValue Src = Op.getOperand(0);
11193 assert((!DstVT.isVector() || DstVT == MVT::v2f32) &&
11194 "only the v2f32 vector result is custom lowered");
11195
11196 if (DstVT.isVector())
11197 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11198 Src = DAG.getAnyExtOrTrunc(Src, SL, MVT::i32);
11199
11200 auto ConvertByte = [&](unsigned ByteSel) {
11201 return DAG.getNode(AMDGPUISD::CVT_F32_FP8_E5M3, SL, MVT::f32, Src,
11202 DAG.getTargetConstant(ByteSel, SL, MVT::i32));
11203 };
11204
11205 if (!DstVT.isVector())
11206 return ConvertByte(0);
11207 return DAG.getBuildVector(DstVT, SL, {ConvertByte(0), ConvertByte(1)});
11208 }
11209
11210 if (!DstVT.isVector()) {
11211 SDValue Src = Op.getOperand(0);
11212 if (Src.getValueType() != MVT::i32) {
11213 SDLoc SL(Op);
11214 SDValue SrcI32 = DAG.getAnyExtOrTrunc(Src, SL, MVT::i32);
11215 return DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, SL, DstVT, SrcI32,
11216 Op.getOperand(1));
11217 }
11218 return Op;
11219 }
11220
11221 EVT EltVT = DstVT.getVectorElementType();
11222 if (EltVT == MVT::f16 || EltVT == MVT::f32)
11223 return lowerFromFP8(Op, IsBF8, DAG);
11224 return SDValue();
11225}
11226
11227SDValue SITargetLowering::lowerToFP8(SDValue Op, bool IsBF8, bool IsE5M3,
11228 SelectionDAG &DAG) const {
11229 SDLoc SL(Op);
11230 SDValue Src = Op.getOperand(0);
11231 EVT ResVT = Op.getValueType();
11232 bool IsF16 = Src.getValueType().getScalarType() == MVT::f16;
11233 assert((!IsF16 || Subtarget->hasF16FP8ConversionInsts()) &&
11234 "f16 -> fp8/bf8 conversion requires F16FP8ConversionInsts");
11235 assert((!ResVT.isVector() || ResVT == MVT::v2i8) &&
11236 "only the v2i8 vector result is custom lowered");
11237
11238 if (IsF16) {
11239 unsigned Opc =
11240 IsBF8 ? AMDGPUISD::CVT_PK_BF8_F16 : AMDGPUISD::CVT_PK_FP8_F16;
11241 SDValue Bytes = DAG.getNode(Opc, SL, MVT::i16, Src);
11242 return DAG.getNode(ISD::BITCAST, SL, ResVT, Bytes);
11243 }
11244
11245 unsigned Opc = IsBF8 ? AMDGPUISD::CVT_PK_BF8_F32
11246 : IsE5M3 ? AMDGPUISD::CVT_PK_FP8_F32_E5M3
11247 : AMDGPUISD::CVT_PK_FP8_F32;
11248 SDValue PoisonI32 = DAG.getPOISON(MVT::i32);
11249 SDValue WordSel = DAG.getTargetConstant(0, SL, MVT::i1);
11250
11251 if (!ResVT.isVector()) {
11252 // Convert one lane, the second is unused. Feed it the same source so the
11253 // instruction does not read an undefined register.
11254 SDValue Packed =
11255 DAG.getNode(Opc, SL, MVT::i32, Src, Src, PoisonI32, WordSel);
11256 return DAG.getAnyExtOrTrunc(Packed, SL, ResVT);
11257 }
11258
11259 SDValue A = DAG.getExtractVectorElt(SL, MVT::f32, Src, 0);
11260 SDValue B = DAG.getExtractVectorElt(SL, MVT::f32, Src, 1);
11261 SDValue Packed = DAG.getNode(Opc, SL, MVT::i32, A, B, PoisonI32, WordSel);
11262 SDValue Bytes = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Packed);
11263 return DAG.getNode(ISD::BITCAST, SL, ResVT, Bytes);
11264}
11265
11266SDValue
11267SITargetLowering::LowerCONVERT_TO_ARBITRARY_FP(SDValue Op,
11268 SelectionDAG &DAG) const {
11269 // The OCP FP8 formats (E4M3FN, E5M2) and unsigned E5M3 map to HW conversions
11270 // on subtargets that support them. Everything else uses generic expansion.
11272 static_cast<APFloatBase::Semantics>(Op.getConstantOperandVal(1));
11273 const bool IsFP8 = Sem == APFloatBase::S_Float8E4M3FN;
11274 const bool IsBF8 = Sem == APFloatBase::S_Float8E5M2;
11275 const bool IsE5M3 = Sem == APFloatBase::S_Float8E5M3FNU;
11276 const bool HasE5M3ConversionInsts =
11277 Subtarget->hasFP8ConversionInsts() && Subtarget->hasFP8E5M3Insts();
11278 const bool IsSupported = IsFP8 || IsBF8 || (IsE5M3 && HasE5M3ConversionInsts);
11279 if (!IsSupported)
11280 return SDValue();
11281
11282 // The HW conversions only support nearest-even. The OCP conversions do not
11283 // saturate. The unsigned E5M3 conversion always clamps out-of-range inputs,
11284 // which also refines the non-saturating form where those inputs are poison.
11285 if (static_cast<RoundingMode>(Op.getConstantOperandVal(2)) !=
11287 return SDValue();
11288 if (!IsE5M3 && Op.getConstantOperandVal(3) != 0)
11289 return SDValue();
11290
11291 EVT SrcEltVT = Op.getOperand(0).getValueType().getScalarType();
11292 // The f32 form is built here rather than by a tablegen pattern because the
11293 // HW result is i32 while the node result is i16 after the i8 promotion.
11294 if (SrcEltVT == MVT::f32)
11295 return lowerToFP8(Op, IsBF8, IsE5M3, DAG);
11296 if (!IsE5M3 && SrcEltVT == MVT::f16 &&
11297 Subtarget->hasF16FP8ConversionInsts()) {
11298 // A scalar conversion is selected from the generic node by tablegen, only
11299 // the illegal v2i8 result type needs lowering here.
11300 if (!Op.getValueType().isVector())
11301 return Op;
11302 return lowerToFP8(Op, IsBF8, false, DAG);
11303 }
11304 return SDValue();
11305}
11306
11307SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
11308 SelectionDAG &DAG) const {
11310 auto *MFI = MF.getInfo<SIMachineFunctionInfo>();
11311
11312 EVT VT = Op.getValueType();
11313 SDLoc DL(Op);
11314 unsigned IntrinsicID = Op.getConstantOperandVal(0);
11315
11316 // TODO: Should this propagate fast-math-flags?
11317
11318 switch (IntrinsicID) {
11319 case Intrinsic::amdgcn_wave_reduce_min:
11320 case Intrinsic::amdgcn_wave_reduce_umin:
11321 case Intrinsic::amdgcn_wave_reduce_fmin:
11322 case Intrinsic::amdgcn_wave_reduce_max:
11323 case Intrinsic::amdgcn_wave_reduce_umax:
11324 case Intrinsic::amdgcn_wave_reduce_fmax:
11325 case Intrinsic::amdgcn_wave_reduce_add:
11326 case Intrinsic::amdgcn_wave_reduce_fadd:
11327 case Intrinsic::amdgcn_wave_reduce_sub:
11328 case Intrinsic::amdgcn_wave_reduce_fsub:
11329 case Intrinsic::amdgcn_wave_reduce_and:
11330 case Intrinsic::amdgcn_wave_reduce_or:
11331 case Intrinsic::amdgcn_wave_reduce_xor: {
11332 EVT SrcVT = Op.getOperand(1).getValueType();
11333 if (SrcVT.getFixedSizeInBits() == 16) {
11334 bool IsFPOp = SrcVT.isFloatingPoint();
11335 bool NeedsSignExt = IntrinsicID == Intrinsic::amdgcn_wave_reduce_min ||
11336 IntrinsicID == Intrinsic::amdgcn_wave_reduce_max ||
11337 IntrinsicID == Intrinsic::amdgcn_wave_reduce_add ||
11338 IntrinsicID == Intrinsic::amdgcn_wave_reduce_sub;
11339 unsigned ExtOpc = IsFPOp ? ISD::FP_EXTEND
11340 : NeedsSignExt ? ISD::SIGN_EXTEND
11342 auto SrcType = IsFPOp ? MVT::f16 : MVT::i16;
11343 auto ExtType = IsFPOp ? MVT::f32 : MVT::i32;
11344 SDValue ExtendedSrc = DAG.getNode(ExtOpc, DL, ExtType, Op.getOperand(1));
11345 SDValue Strategy = Op.getOperand(2);
11347 Op.getOperand(0), ExtendedSrc, Strategy);
11348 if (IsFPOp)
11349 return DAG.getNode(ISD::FP_ROUND, DL, SrcType, Result,
11350 DAG.getTargetConstant(1, DL, MVT::i32));
11351 else
11352 return DAG.getNode(ISD::TRUNCATE, DL, SrcType, Result);
11353 }
11354 return SDValue();
11355 }
11356 case Intrinsic::amdgcn_implicit_buffer_ptr: {
11357 if (!MFI->getUserSGPRInfo().hasImplicitBufferPtr()) {
11358 const char *Error =
11359 Subtarget->hasArchitectedFlatScratch()
11360 ? "intrinsic not supported on subtarget"
11361 : !Subtarget->isMesa3DOS()
11362 ? "intrinsic not supported for OS"
11363 : "intrinsic not supported for calling convention";
11364 DAG.getContext()->diagnose(
11365 DiagnosticInfoUnsupported(MF.getFunction(), Error, DL.getDebugLoc()));
11366 return DAG.getPOISON(VT);
11367 }
11368
11369 return getPreloadedValue(DAG, *MFI, VT,
11371 }
11372 case Intrinsic::amdgcn_dispatch_ptr:
11373 case Intrinsic::amdgcn_queue_ptr: {
11374 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
11375 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
11376 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
11377 DL.getDebugLoc()));
11378 return DAG.getPOISON(VT);
11379 }
11380
11381 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr
11384 return getPreloadedValue(DAG, *MFI, VT, RegID);
11385 }
11386 case Intrinsic::amdgcn_implicitarg_ptr: {
11387 if (MFI->isEntryFunction())
11388 return getImplicitArgPtr(DAG, DL);
11389 return getPreloadedValue(DAG, *MFI, VT,
11391 }
11392 case Intrinsic::amdgcn_kernarg_segment_ptr: {
11393 if (!AMDGPU::isKernel(MF.getFunction())) {
11394 // This only makes sense to call in a kernel, so just lower to null.
11395 return DAG.getConstant(0, DL, VT);
11396 }
11397
11398 return getPreloadedValue(DAG, *MFI, VT,
11400 }
11401 case Intrinsic::amdgcn_dispatch_id: {
11402 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
11403 }
11404 case Intrinsic::amdgcn_rcp:
11405 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
11406 case Intrinsic::amdgcn_rsq:
11407 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
11408 case Intrinsic::amdgcn_rsq_legacy:
11409 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
11410 return emitRemovedIntrinsicError(DAG, DL, VT);
11411 return SDValue();
11412 case Intrinsic::amdgcn_rcp_legacy:
11413 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
11414 return emitRemovedIntrinsicError(DAG, DL, VT);
11415 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
11416 case Intrinsic::amdgcn_fma_legacy:
11417 case Intrinsic::amdgcn_sudot4:
11418 case Intrinsic::amdgcn_sudot8:
11419 case Intrinsic::amdgcn_tanh:
11420 return SDValue();
11421 case Intrinsic::amdgcn_rsq_clamp: {
11422 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
11423 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
11424
11425 Type *Type = VT.getTypeForEVT(*DAG.getContext());
11426 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
11427 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
11428
11429 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
11430 SDValue Tmp =
11431 DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, DAG.getConstantFP(Max, DL, VT));
11432 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
11433 DAG.getConstantFP(Min, DL, VT));
11434 }
11435 case Intrinsic::r600_read_ngroups_x:
11436 if (Subtarget->isAmdHsaOS())
11437 return emitNonHSAIntrinsicError(DAG, DL, VT);
11438
11439 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
11441 false);
11442 case Intrinsic::r600_read_ngroups_y:
11443 if (Subtarget->isAmdHsaOS())
11444 return emitNonHSAIntrinsicError(DAG, DL, VT);
11445
11446 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
11448 false);
11449 case Intrinsic::r600_read_ngroups_z:
11450 if (Subtarget->isAmdHsaOS())
11451 return emitNonHSAIntrinsicError(DAG, DL, VT);
11452
11453 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
11455 false);
11456 case Intrinsic::r600_read_local_size_x:
11457 if (Subtarget->isAmdHsaOS())
11458 return emitNonHSAIntrinsicError(DAG, DL, VT);
11459
11460 return lowerImplicitZextParam(DAG, Op, MVT::i16,
11462 case Intrinsic::r600_read_local_size_y:
11463 if (Subtarget->isAmdHsaOS())
11464 return emitNonHSAIntrinsicError(DAG, DL, VT);
11465
11466 return lowerImplicitZextParam(DAG, Op, MVT::i16,
11468 case Intrinsic::r600_read_local_size_z:
11469 if (Subtarget->isAmdHsaOS())
11470 return emitNonHSAIntrinsicError(DAG, DL, VT);
11471
11472 return lowerImplicitZextParam(DAG, Op, MVT::i16,
11474 case Intrinsic::amdgcn_workgroup_id_x:
11475 return lowerWorkGroupId(DAG, *MFI, VT,
11479 case Intrinsic::amdgcn_workgroup_id_y:
11480 return lowerWorkGroupId(DAG, *MFI, VT,
11484 case Intrinsic::amdgcn_workgroup_id_z:
11485 return lowerWorkGroupId(DAG, *MFI, VT,
11489 case Intrinsic::amdgcn_cluster_id_x:
11490 return Subtarget->hasClusters()
11491 ? getPreloadedValue(DAG, *MFI, VT,
11493 : DAG.getPOISON(VT);
11494 case Intrinsic::amdgcn_cluster_id_y:
11495 return Subtarget->hasClusters()
11496 ? getPreloadedValue(DAG, *MFI, VT,
11498 : DAG.getPOISON(VT);
11499 case Intrinsic::amdgcn_cluster_id_z:
11500 return Subtarget->hasClusters()
11501 ? getPreloadedValue(DAG, *MFI, VT,
11503 : DAG.getPOISON(VT);
11504 case Intrinsic::amdgcn_cluster_workgroup_id_x:
11505 return Subtarget->hasClusters()
11506 ? getPreloadedValue(
11507 DAG, *MFI, VT,
11509 : DAG.getPOISON(VT);
11510 case Intrinsic::amdgcn_cluster_workgroup_id_y:
11511 return Subtarget->hasClusters()
11512 ? getPreloadedValue(
11513 DAG, *MFI, VT,
11515 : DAG.getPOISON(VT);
11516 case Intrinsic::amdgcn_cluster_workgroup_id_z:
11517 return Subtarget->hasClusters()
11518 ? getPreloadedValue(
11519 DAG, *MFI, VT,
11521 : DAG.getPOISON(VT);
11522 case Intrinsic::amdgcn_cluster_workgroup_flat_id:
11523 return Subtarget->hasClusters()
11524 ? lowerConstHwRegRead(DAG, Op, AMDGPU::Hwreg::ID_IB_STS2, 21, 4)
11525 : SDValue();
11526 case Intrinsic::amdgcn_cluster_workgroup_max_id_x:
11527 return Subtarget->hasClusters()
11528 ? getPreloadedValue(
11529 DAG, *MFI, VT,
11531 : DAG.getPOISON(VT);
11532 case Intrinsic::amdgcn_cluster_workgroup_max_id_y:
11533 return Subtarget->hasClusters()
11534 ? getPreloadedValue(
11535 DAG, *MFI, VT,
11537 : DAG.getPOISON(VT);
11538 case Intrinsic::amdgcn_cluster_workgroup_max_id_z:
11539 return Subtarget->hasClusters()
11540 ? getPreloadedValue(
11541 DAG, *MFI, VT,
11543 : DAG.getPOISON(VT);
11544 case Intrinsic::amdgcn_cluster_workgroup_max_flat_id:
11545 return Subtarget->hasClusters()
11546 ? getPreloadedValue(
11547 DAG, *MFI, VT,
11549 : DAG.getPOISON(VT);
11550 case Intrinsic::amdgcn_wave_id:
11551 return lowerWaveID(DAG, Op);
11552 case Intrinsic::amdgcn_lds_kernel_id: {
11553 if (MFI->isEntryFunction())
11554 return getLDSKernelId(DAG, DL);
11555 return getPreloadedValue(DAG, *MFI, VT,
11557 }
11558 case Intrinsic::amdgcn_workitem_id_x:
11559 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
11560 case Intrinsic::amdgcn_workitem_id_y:
11561 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
11562 case Intrinsic::amdgcn_workitem_id_z:
11563 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
11564 case Intrinsic::amdgcn_wavefrontsize:
11565 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
11566 SDLoc(Op), MVT::i32);
11567 case Intrinsic::amdgcn_s_buffer_load: {
11568 unsigned CPol = Op.getConstantOperandVal(3);
11569 // s_buffer_load, because of how it's optimized, can't be volatile
11570 // so reject ones with the volatile bit set.
11571 if (CPol & ~((Subtarget->getGeneration() >= AMDGPUSubtarget::GFX12)
11574 return Op;
11575 return lowerSBuffer(VT, VT, DL, DAG.getEntryNode(), Op.getOperand(1),
11576 Op.getOperand(2), Op.getOperand(3), DAG);
11577 }
11578 case Intrinsic::amdgcn_fdiv_fast:
11579 return lowerFDIV_FAST(Op, DAG);
11580 case Intrinsic::amdgcn_sin:
11581 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
11582
11583 case Intrinsic::amdgcn_cos:
11584 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
11585
11586 case Intrinsic::amdgcn_mul_u24:
11587 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1),
11588 Op.getOperand(2));
11589 case Intrinsic::amdgcn_mul_i24:
11590 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1),
11591 Op.getOperand(2));
11592
11593 case Intrinsic::amdgcn_log_clamp: {
11594 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
11595 return SDValue();
11596
11597 return emitRemovedIntrinsicError(DAG, DL, VT);
11598 }
11599 case Intrinsic::amdgcn_fract:
11600 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
11601
11602 case Intrinsic::amdgcn_class: {
11603 SDValue Src = Op.getOperand(1);
11604 EVT SrcVT = Src.getValueType();
11605 bool IsLegal = SrcVT == MVT::f32 || SrcVT == MVT::f64 ||
11606 (SrcVT == MVT::f16 && Subtarget->has16BitInsts());
11607 if (!IsLegal) {
11608 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
11610 "llvm.amdgcn.class only supports f16, f32, and f64",
11611 DL.getDebugLoc()));
11612 return DAG.getPOISON(VT);
11613 }
11614 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, Src, Op.getOperand(2));
11615 }
11616 case Intrinsic::amdgcn_div_fmas:
11617 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, Op.getOperand(1),
11618 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
11619
11620 case Intrinsic::amdgcn_div_fixup:
11621 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, Op.getOperand(1),
11622 Op.getOperand(2), Op.getOperand(3));
11623
11624 case Intrinsic::amdgcn_div_scale: {
11625 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
11626
11627 // Translate to the operands expected by the machine instruction. The
11628 // first parameter must be the same as the first instruction.
11629 SDValue Numerator = Op.getOperand(1);
11630 SDValue Denominator = Op.getOperand(2);
11631
11632 // Note this order is opposite of the machine instruction's operations,
11633 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
11634 // intrinsic has the numerator as the first operand to match a normal
11635 // division operation.
11636
11637 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
11638
11639 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
11640 Denominator, Numerator);
11641 }
11642 case Intrinsic::amdgcn_ballot:
11643 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
11644 case Intrinsic::amdgcn_fmed3:
11645 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, Op.getOperand(1),
11646 Op.getOperand(2), Op.getOperand(3), Op->getFlags());
11647 case Intrinsic::amdgcn_fdot2:
11648 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, Op.getOperand(1),
11649 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
11650 case Intrinsic::amdgcn_fmul_legacy:
11651 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, Op.getOperand(1),
11652 Op.getOperand(2));
11653 case Intrinsic::amdgcn_sbfe:
11654 case Intrinsic::amdgcn_ubfe:
11655 return lowerBFEIntrinsic(Op, DAG, IntrinsicID);
11656 case Intrinsic::amdgcn_cvt_pkrtz:
11657 case Intrinsic::amdgcn_cvt_pknorm_i16:
11658 case Intrinsic::amdgcn_cvt_pknorm_u16:
11659 case Intrinsic::amdgcn_cvt_pk_i16:
11660 case Intrinsic::amdgcn_cvt_pk_u16: {
11661 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
11662 EVT VT = Op.getValueType();
11663 unsigned Opcode;
11664
11665 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
11666 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
11667 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
11668 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
11669 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
11670 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
11671 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
11672 Opcode = AMDGPUISD::CVT_PK_I16_I32;
11673 else
11674 Opcode = AMDGPUISD::CVT_PK_U16_U32;
11675
11676 if (isTypeLegal(VT))
11677 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
11678
11679 SDValue Node =
11680 DAG.getNode(Opcode, DL, MVT::i32, Op.getOperand(1), Op.getOperand(2));
11681 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
11682 }
11683 case Intrinsic::amdgcn_fmad_ftz:
11684 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
11685 Op.getOperand(2), Op.getOperand(3));
11686
11687 case Intrinsic::amdgcn_if_break:
11688 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
11689 Op->getOperand(1), Op->getOperand(2)),
11690 0);
11691
11692 case Intrinsic::amdgcn_groupstaticsize: {
11694 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
11695 return Op;
11696
11697 const Module *M = MF.getFunction().getParent();
11698 const GlobalValue *GV =
11699 Intrinsic::getDeclarationIfExists(M, Intrinsic::amdgcn_groupstaticsize);
11700 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
11702 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
11703 }
11704 case Intrinsic::amdgcn_is_shared:
11705 case Intrinsic::amdgcn_is_private: {
11706 SDLoc SL(Op);
11707 SDValue SrcVec =
11708 DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
11709 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
11710 DAG.getConstant(1, SL, MVT::i32));
11711
11712 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared)
11714 : AMDGPUAS::PRIVATE_ADDRESS;
11715 if (AS == AMDGPUAS::PRIVATE_ADDRESS &&
11716 Subtarget->hasGloballyAddressableScratch()) {
11717 SDValue FlatScratchBaseHi(
11718 DAG.getMachineNode(
11719 AMDGPU::S_MOV_B32, DL, MVT::i32,
11720 DAG.getRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE_HI, MVT::i32)),
11721 0);
11722 // Test bits 63..58 against the aperture address.
11723 return DAG.getSetCC(
11724 SL, MVT::i1,
11725 DAG.getNode(ISD::XOR, SL, MVT::i32, SrcHi, FlatScratchBaseHi),
11726 DAG.getConstant(1u << 26, SL, MVT::i32), ISD::SETULT);
11727 }
11728
11729 SDValue Aperture = getSegmentAperture(AS, SL, DAG);
11730 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
11731 }
11732 case Intrinsic::amdgcn_perm:
11733 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
11734 Op.getOperand(2), Op.getOperand(3));
11735 case Intrinsic::amdgcn_reloc_constant: {
11736 Module *M = MF.getFunction().getParent();
11737 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
11738 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
11739 auto *RelocSymbol = cast<GlobalVariable>(
11740 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
11741 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
11743 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
11744 }
11745 case Intrinsic::amdgcn_swmmac_f16_16x16x32_f16:
11746 case Intrinsic::amdgcn_swmmac_bf16_16x16x32_bf16:
11747 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf16:
11748 case Intrinsic::amdgcn_swmmac_f32_16x16x32_f16:
11749 case Intrinsic::amdgcn_swmmac_f32_16x16x32_fp8_fp8:
11750 case Intrinsic::amdgcn_swmmac_f32_16x16x32_fp8_bf8:
11751 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf8_fp8:
11752 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf8_bf8: {
11753 if (Op.getOperand(4).getValueType() == MVT::i32)
11754 return SDValue();
11755
11756 SDLoc SL(Op);
11757 auto IndexKeyi32 = DAG.getAnyExtOrTrunc(Op.getOperand(4), SL, MVT::i32);
11758 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(),
11759 Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11760 Op.getOperand(3), IndexKeyi32);
11761 }
11762 case Intrinsic::amdgcn_swmmac_f32_16x16x128_fp8_fp8:
11763 case Intrinsic::amdgcn_swmmac_f32_16x16x128_fp8_bf8:
11764 case Intrinsic::amdgcn_swmmac_f32_16x16x128_bf8_fp8:
11765 case Intrinsic::amdgcn_swmmac_f32_16x16x128_bf8_bf8:
11766 case Intrinsic::amdgcn_swmmac_f16_16x16x128_fp8_fp8:
11767 case Intrinsic::amdgcn_swmmac_f16_16x16x128_fp8_bf8:
11768 case Intrinsic::amdgcn_swmmac_f16_16x16x128_bf8_fp8:
11769 case Intrinsic::amdgcn_swmmac_f16_16x16x128_bf8_bf8: {
11770 if (Op.getOperand(4).getValueType() == MVT::i64)
11771 return SDValue();
11772
11773 SDLoc SL(Op);
11774 auto IndexKeyi64 =
11775 Op.getOperand(4).getValueType() == MVT::v2i32
11776 ? DAG.getBitcast(MVT::i64, Op.getOperand(4))
11777 : DAG.getAnyExtOrTrunc(Op.getOperand(4), SL, MVT::i64);
11778 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(),
11779 {Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11780 Op.getOperand(3), IndexKeyi64, Op.getOperand(5),
11781 Op.getOperand(6)});
11782 }
11783 case Intrinsic::amdgcn_swmmac_f16_16x16x64_f16:
11784 case Intrinsic::amdgcn_swmmac_bf16_16x16x64_bf16:
11785 case Intrinsic::amdgcn_swmmac_f32_16x16x64_bf16:
11786 case Intrinsic::amdgcn_swmmac_bf16f32_16x16x64_bf16:
11787 case Intrinsic::amdgcn_swmmac_f32_16x16x64_f16:
11788 case Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8: {
11789 EVT IndexKeyTy = IntrinsicID == Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8
11790 ? MVT::i64
11791 : MVT::i32;
11792 if (Op.getOperand(6).getValueType() == IndexKeyTy)
11793 return SDValue();
11794
11795 SDLoc SL(Op);
11796 auto IndexKey =
11797 Op.getOperand(6).getValueType().isVector()
11798 ? DAG.getBitcast(IndexKeyTy, Op.getOperand(6))
11799 : DAG.getAnyExtOrTrunc(Op.getOperand(6), SL, IndexKeyTy);
11801 Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11802 Op.getOperand(3), Op.getOperand(4), Op.getOperand(5),
11803 IndexKey, Op.getOperand(7), Op.getOperand(8)};
11804 if (IntrinsicID == Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8)
11805 Args.push_back(Op.getOperand(9));
11806 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(), Args);
11807 }
11808 case Intrinsic::amdgcn_swmmac_i32_16x16x32_iu4:
11809 case Intrinsic::amdgcn_swmmac_i32_16x16x32_iu8:
11810 case Intrinsic::amdgcn_swmmac_i32_16x16x64_iu4: {
11811 if (Op.getOperand(6).getValueType() == MVT::i32)
11812 return SDValue();
11813
11814 SDLoc SL(Op);
11815 auto IndexKeyi32 = DAG.getAnyExtOrTrunc(Op.getOperand(6), SL, MVT::i32);
11816 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(),
11817 {Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11818 Op.getOperand(3), Op.getOperand(4), Op.getOperand(5),
11819 IndexKeyi32, Op.getOperand(7)});
11820 }
11821 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
11822 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
11823 unsigned AFmt = (unsigned)Op.getConstantOperandVal(1);
11824 unsigned BFmt = (unsigned)Op.getConstantOperandVal(3);
11825 unsigned AScaleFmt = (unsigned)Op.getConstantOperandVal(8);
11826 unsigned BScaleFmt = (unsigned)Op.getConstantOperandVal(11);
11827 if (!AMDGPU::isValidWMMAScaleFmtCombination(AFmt, AScaleFmt, BFmt,
11828 BScaleFmt)) {
11830 "invalid matrix and scale format combination in wmma call");
11831 Op->print(errs());
11832 errs() << '\n';
11833 }
11834 return SDValue();
11835 }
11836 case Intrinsic::amdgcn_readlane:
11837 case Intrinsic::amdgcn_readfirstlane:
11838 case Intrinsic::amdgcn_writelane:
11839 case Intrinsic::amdgcn_permlane16:
11840 case Intrinsic::amdgcn_permlanex16:
11841 case Intrinsic::amdgcn_permlane64:
11842 case Intrinsic::amdgcn_set_inactive:
11843 case Intrinsic::amdgcn_set_inactive_chain_arg:
11844 case Intrinsic::amdgcn_mov_dpp8:
11845 case Intrinsic::amdgcn_update_dpp:
11846 case Intrinsic::amdgcn_permlane_bcast:
11847 case Intrinsic::amdgcn_permlane_up:
11848 case Intrinsic::amdgcn_permlane_down:
11849 case Intrinsic::amdgcn_permlane_xor:
11850 return lowerLaneOp(*this, Op.getNode(), DAG);
11851 case Intrinsic::amdgcn_dead: {
11853 for (const EVT ValTy : Op.getNode()->values())
11854 Poisons.push_back(DAG.getPOISON(ValTy));
11855 return DAG.getMergeValues(Poisons, SDLoc(Op));
11856 }
11857 case Intrinsic::amdgcn_wave_shuffle:
11858 return lowerWaveShuffle(*this, Op.getNode(), DAG);
11859 default:
11860 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
11862 return lowerImage(Op, ImageDimIntr, DAG, false);
11863
11864 return Op;
11865 }
11866}
11867
11868// On targets not supporting constant in soffset field, turn zero to
11869// SGPR_NULL to avoid generating an extra s_mov with zero.
11871 const GCNSubtarget *Subtarget) {
11872 if (Subtarget->hasRestrictedSOffset() && isNullConstant(SOffset))
11873 return DAG.getRegister(AMDGPU::SGPR_NULL, MVT::i32);
11874 return SOffset;
11875}
11876
11877SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
11878 SelectionDAG &DAG,
11879 unsigned NewOpcode) const {
11880 SDLoc DL(Op);
11881
11882 SDValue VData = Op.getOperand(2);
11883 if (VData.getValueSizeInBits() != 32 && VData.getValueSizeInBits() != 64) {
11884 SmallVector<EVT, 2> ResultTypes(Op->values());
11885 return diagnoseUnsupportedImage(DAG, Op, ResultTypes, DL,
11886 "unsupported buffer atomic data type");
11887 }
11888 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
11889 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(4), DAG);
11890 auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
11891 SDValue Ops[] = {
11892 Op.getOperand(0), // Chain
11893 VData, // vdata
11894 Rsrc, // rsrc
11895 DAG.getConstant(0, DL, MVT::i32), // vindex
11896 VOffset, // voffset
11897 SOffset, // soffset
11898 Offset, // offset
11899 Op.getOperand(6), // cachepolicy
11900 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
11901 };
11902
11903 auto *M = cast<MemSDNode>(Op);
11904
11905 EVT MemVT = VData.getValueType();
11906 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
11907 M->getMemOperand());
11908}
11909
11910SDValue
11911SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
11912 unsigned NewOpcode) const {
11913 SDLoc DL(Op);
11914
11915 SDValue VData = Op.getOperand(2);
11916 if (VData.getValueSizeInBits() != 32 && VData.getValueSizeInBits() != 64) {
11917 SmallVector<EVT, 2> ResultTypes(Op->values());
11918 return diagnoseUnsupportedImage(DAG, Op, ResultTypes, DL,
11919 "unsupported buffer atomic data type");
11920 }
11921 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
11922 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(5), DAG);
11923 auto SOffset = selectSOffset(Op.getOperand(6), DAG, Subtarget);
11924 SDValue Ops[] = {
11925 Op.getOperand(0), // Chain
11926 VData, // vdata
11927 Rsrc, // rsrc
11928 Op.getOperand(4), // vindex
11929 VOffset, // voffset
11930 SOffset, // soffset
11931 Offset, // offset
11932 Op.getOperand(7), // cachepolicy
11933 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
11934 };
11935
11936 auto *M = cast<MemSDNode>(Op);
11937
11938 EVT MemVT = VData.getValueType();
11939 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
11940 M->getMemOperand());
11941}
11942
11944 SDLoc DL) {
11945 SDNode *N = Op.getNode();
11946 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
11947 unsigned NumOperands = N->getNumOperands();
11948 if (N->getOperand(NumOperands - 1) == Zero)
11949 return;
11951 Ops[NumOperands - 1] = Zero; // M0 = 0
11952 DAG.UpdateNodeOperands(N, Ops);
11953}
11954
11955SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
11956 SelectionDAG &DAG) const {
11957 unsigned IntrID = Op.getConstantOperandVal(1);
11958 SDLoc DL(Op);
11959
11960 switch (IntrID) {
11961 case Intrinsic::amdgcn_cluster_load_b32:
11962 case Intrinsic::amdgcn_cluster_load_b64:
11963 case Intrinsic::amdgcn_cluster_load_b128: {
11964 if (Subtarget->hasGFX1250_STRICT())
11966 return SDValue();
11967 }
11968 case Intrinsic::amdgcn_ds_ordered_add:
11969 case Intrinsic::amdgcn_ds_ordered_swap: {
11970 MemSDNode *M = cast<MemSDNode>(Op);
11971 SDValue Chain = M->getOperand(0);
11972 SDValue M0 = M->getOperand(2);
11973 SDValue Value = M->getOperand(3);
11974 unsigned IndexOperand = M->getConstantOperandVal(7);
11975 unsigned WaveRelease = M->getConstantOperandVal(8);
11976 unsigned WaveDone = M->getConstantOperandVal(9);
11977
11978 unsigned OrderedCountIndex = IndexOperand & 0x3f;
11979 IndexOperand &= ~0x3f;
11980 unsigned CountDw = 0;
11981
11982 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
11983 CountDw = (IndexOperand >> 24) & 0xf;
11984 IndexOperand &= ~(0xf << 24);
11985
11986 if (CountDw < 1 || CountDw > 4) {
11987 const Function &Fn = DAG.getMachineFunction().getFunction();
11988 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
11989 Fn, "ds_ordered_count: dword count must be between 1 and 4",
11990 DL.getDebugLoc()));
11991 CountDw = 1;
11992 }
11993 }
11994
11995 if (IndexOperand) {
11996 const Function &Fn = DAG.getMachineFunction().getFunction();
11997 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
11998 Fn, "ds_ordered_count: bad index operand", DL.getDebugLoc()));
11999 }
12000
12001 if (WaveDone && !WaveRelease) {
12002 // TODO: Move this to IR verifier
12003 const Function &Fn = DAG.getMachineFunction().getFunction();
12004 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12005 Fn, "ds_ordered_count: wave_done requires wave_release",
12006 DL.getDebugLoc()));
12007 }
12008
12009 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
12010 unsigned ShaderType =
12012 unsigned Offset0 = OrderedCountIndex << 2;
12013 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (Instruction << 4);
12014
12015 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
12016 Offset1 |= (CountDw - 1) << 6;
12017
12018 if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX11)
12019 Offset1 |= ShaderType << 2;
12020
12021 unsigned Offset = Offset0 | (Offset1 << 8);
12022
12023 SDValue Ops[] = {
12024 Chain, Value, DAG.getTargetConstant(Offset, DL, MVT::i16),
12025 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
12026 };
12027 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
12028 M->getVTList(), Ops, M->getMemoryVT(),
12029 M->getMemOperand());
12030 }
12031 case Intrinsic::amdgcn_ptr_s_buffer_load: {
12032 unsigned CPol = Op.getConstantOperandVal(4);
12033 if (CPol & ~((Subtarget->getGeneration() >= AMDGPUSubtarget::GFX12)
12036 return Op;
12037
12038 MemSDNode *M = cast<MemSDNode>(Op);
12039 return lowerSBuffer(
12040 Op.getValueType(), M->getMemoryVT(), DL, Op.getOperand(0),
12041 bufferRsrcPtrToVector(Op.getOperand(2), DAG), Op.getOperand(3),
12042 Op.getOperand(4), DAG, M->getMemOperand());
12043 }
12044 case Intrinsic::amdgcn_raw_buffer_load:
12045 case Intrinsic::amdgcn_raw_ptr_buffer_load:
12046 case Intrinsic::amdgcn_raw_atomic_buffer_load:
12047 case Intrinsic::amdgcn_raw_ptr_atomic_buffer_load:
12048 case Intrinsic::amdgcn_raw_buffer_load_format:
12049 case Intrinsic::amdgcn_raw_ptr_buffer_load_format: {
12050 const bool IsFormat =
12051 IntrID == Intrinsic::amdgcn_raw_buffer_load_format ||
12052 IntrID == Intrinsic::amdgcn_raw_ptr_buffer_load_format;
12053
12054 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(2), DAG);
12055 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(3), DAG);
12056 auto SOffset = selectSOffset(Op.getOperand(4), DAG, Subtarget);
12057 SDValue Ops[] = {
12058 Op.getOperand(0), // Chain
12059 Rsrc, // rsrc
12060 DAG.getConstant(0, DL, MVT::i32), // vindex
12061 VOffset, // voffset
12062 SOffset, // soffset
12063 Offset, // offset
12064 Op.getOperand(5), // cachepolicy, swizzled buffer
12065 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
12066 };
12067
12068 auto *M = cast<MemSDNode>(Op);
12069 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
12070 }
12071 case Intrinsic::amdgcn_struct_buffer_load:
12072 case Intrinsic::amdgcn_struct_ptr_buffer_load:
12073 case Intrinsic::amdgcn_struct_buffer_load_format:
12074 case Intrinsic::amdgcn_struct_ptr_buffer_load_format:
12075 case Intrinsic::amdgcn_struct_atomic_buffer_load:
12076 case Intrinsic::amdgcn_struct_ptr_atomic_buffer_load: {
12077 const bool IsFormat =
12078 IntrID == Intrinsic::amdgcn_struct_buffer_load_format ||
12079 IntrID == Intrinsic::amdgcn_struct_ptr_buffer_load_format;
12080
12081 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(2), DAG);
12082 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(4), DAG);
12083 auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
12084 SDValue Ops[] = {
12085 Op.getOperand(0), // Chain
12086 Rsrc, // rsrc
12087 Op.getOperand(3), // vindex
12088 VOffset, // voffset
12089 SOffset, // soffset
12090 Offset, // offset
12091 Op.getOperand(6), // cachepolicy, swizzled buffer
12092 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
12093 };
12094
12095 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
12096 }
12097 case Intrinsic::amdgcn_raw_tbuffer_load:
12098 case Intrinsic::amdgcn_raw_ptr_tbuffer_load: {
12099 MemSDNode *M = cast<MemSDNode>(Op);
12100 EVT LoadVT = Op.getValueType();
12101 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(2), DAG);
12102 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(3), DAG);
12103 auto SOffset = selectSOffset(Op.getOperand(4), DAG, Subtarget);
12104
12105 SDValue Ops[] = {
12106 Op.getOperand(0), // Chain
12107 Rsrc, // rsrc
12108 DAG.getConstant(0, DL, MVT::i32), // vindex
12109 VOffset, // voffset
12110 SOffset, // soffset
12111 Offset, // offset
12112 Op.getOperand(5), // format
12113 Op.getOperand(6), // cachepolicy, swizzled buffer
12114 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
12115 };
12116
12117 if (LoadVT.getScalarSizeInBits() == 16)
12118 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, M, DAG,
12119 Ops);
12120 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
12121 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
12122 DAG);
12123 }
12124 case Intrinsic::amdgcn_struct_tbuffer_load:
12125 case Intrinsic::amdgcn_struct_ptr_tbuffer_load: {
12126 MemSDNode *M = cast<MemSDNode>(Op);
12127 EVT LoadVT = Op.getValueType();
12128 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(2), DAG);
12129 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(4), DAG);
12130 auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
12131
12132 SDValue Ops[] = {
12133 Op.getOperand(0), // Chain
12134 Rsrc, // rsrc
12135 Op.getOperand(3), // vindex
12136 VOffset, // voffset
12137 SOffset, // soffset
12138 Offset, // offset
12139 Op.getOperand(6), // format
12140 Op.getOperand(7), // cachepolicy, swizzled buffer
12141 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
12142 };
12143
12144 if (LoadVT.getScalarSizeInBits() == 16)
12145 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, M, DAG,
12146 Ops);
12147 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
12148 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
12149 DAG);
12150 }
12151 case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
12152 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fadd:
12153 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
12154 case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
12155 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fadd:
12156 return lowerStructBufferAtomicIntrin(Op, DAG,
12157 AMDGPUISD::BUFFER_ATOMIC_FADD);
12158 case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
12159 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmin:
12160 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
12161 case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
12162 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmin:
12163 return lowerStructBufferAtomicIntrin(Op, DAG,
12164 AMDGPUISD::BUFFER_ATOMIC_FMIN);
12165 case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
12166 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmax:
12167 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
12168 case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
12169 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmax:
12170 return lowerStructBufferAtomicIntrin(Op, DAG,
12171 AMDGPUISD::BUFFER_ATOMIC_FMAX);
12172 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
12173 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_swap:
12174 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
12175 case Intrinsic::amdgcn_raw_buffer_atomic_add:
12176 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_add:
12177 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
12178 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
12179 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub:
12180 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
12181 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
12182 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smin:
12183 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
12184 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
12185 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umin:
12186 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
12187 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
12188 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smax:
12189 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
12190 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
12191 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umax:
12192 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
12193 case Intrinsic::amdgcn_raw_buffer_atomic_and:
12194 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_and:
12195 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
12196 case Intrinsic::amdgcn_raw_buffer_atomic_or:
12197 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_or:
12198 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
12199 case Intrinsic::amdgcn_raw_buffer_atomic_xor:
12200 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_xor:
12201 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
12202 case Intrinsic::amdgcn_raw_buffer_atomic_inc:
12203 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_inc:
12204 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
12205 case Intrinsic::amdgcn_raw_buffer_atomic_dec:
12206 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_dec:
12207 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
12208 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
12209 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_swap:
12210 return lowerStructBufferAtomicIntrin(Op, DAG,
12211 AMDGPUISD::BUFFER_ATOMIC_SWAP);
12212 case Intrinsic::amdgcn_struct_buffer_atomic_add:
12213 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_add:
12214 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
12215 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
12216 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub:
12217 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
12218 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
12219 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smin:
12220 return lowerStructBufferAtomicIntrin(Op, DAG,
12221 AMDGPUISD::BUFFER_ATOMIC_SMIN);
12222 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
12223 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umin:
12224 return lowerStructBufferAtomicIntrin(Op, DAG,
12225 AMDGPUISD::BUFFER_ATOMIC_UMIN);
12226 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
12227 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smax:
12228 return lowerStructBufferAtomicIntrin(Op, DAG,
12229 AMDGPUISD::BUFFER_ATOMIC_SMAX);
12230 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
12231 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umax:
12232 return lowerStructBufferAtomicIntrin(Op, DAG,
12233 AMDGPUISD::BUFFER_ATOMIC_UMAX);
12234 case Intrinsic::amdgcn_struct_buffer_atomic_and:
12235 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_and:
12236 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
12237 case Intrinsic::amdgcn_struct_buffer_atomic_or:
12238 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_or:
12239 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
12240 case Intrinsic::amdgcn_struct_buffer_atomic_xor:
12241 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_xor:
12242 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
12243 case Intrinsic::amdgcn_struct_buffer_atomic_inc:
12244 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_inc:
12245 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
12246 case Intrinsic::amdgcn_struct_buffer_atomic_dec:
12247 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_dec:
12248 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
12249 case Intrinsic::amdgcn_raw_buffer_atomic_sub_clamp_u32:
12250 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub_clamp_u32:
12251 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_CSUB);
12252 case Intrinsic::amdgcn_struct_buffer_atomic_sub_clamp_u32:
12253 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub_clamp_u32:
12254 return lowerStructBufferAtomicIntrin(Op, DAG,
12255 AMDGPUISD::BUFFER_ATOMIC_CSUB);
12256 case Intrinsic::amdgcn_raw_buffer_atomic_cond_sub_u32:
12257 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_cond_sub_u32:
12258 return lowerRawBufferAtomicIntrin(Op, DAG,
12259 AMDGPUISD::BUFFER_ATOMIC_COND_SUB_U32);
12260 case Intrinsic::amdgcn_struct_buffer_atomic_cond_sub_u32:
12261 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_cond_sub_u32:
12262 return lowerStructBufferAtomicIntrin(Op, DAG,
12263 AMDGPUISD::BUFFER_ATOMIC_COND_SUB_U32);
12264 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap:
12265 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_cmpswap: {
12266 SDValue Src = Op.getOperand(2);
12267 if (Src.getValueSizeInBits() != 32 && Src.getValueSizeInBits() != 64) {
12268 SmallVector<EVT, 2> ResultTypes(Op->values());
12269 return diagnoseUnsupportedImage(DAG, Op, ResultTypes, DL,
12270 "unsupported buffer atomic data type");
12271 }
12272 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(4), DAG);
12273 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(5), DAG);
12274 auto SOffset = selectSOffset(Op.getOperand(6), DAG, Subtarget);
12275 SDValue Ops[] = {
12276 Op.getOperand(0), // Chain
12277 Op.getOperand(2), // src
12278 Op.getOperand(3), // cmp
12279 Rsrc, // rsrc
12280 DAG.getConstant(0, DL, MVT::i32), // vindex
12281 VOffset, // voffset
12282 SOffset, // soffset
12283 Offset, // offset
12284 Op.getOperand(7), // cachepolicy
12285 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
12286 };
12287 EVT VT = Op.getValueType();
12288 auto *M = cast<MemSDNode>(Op);
12289
12290 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
12291 Op->getVTList(), Ops, VT,
12292 M->getMemOperand());
12293 }
12294 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap:
12295 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_cmpswap: {
12296 SDValue Src = Op.getOperand(2);
12297 if (Src.getValueSizeInBits() != 32 && Src.getValueSizeInBits() != 64) {
12298 SmallVector<EVT, 2> ResultTypes(Op->values());
12299 return diagnoseUnsupportedImage(DAG, Op, ResultTypes, DL,
12300 "unsupported buffer atomic data type");
12301 }
12302 SDValue Rsrc = bufferRsrcPtrToVector(Op->getOperand(4), DAG);
12303 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(6), DAG);
12304 auto SOffset = selectSOffset(Op.getOperand(7), DAG, Subtarget);
12305 SDValue Ops[] = {
12306 Op.getOperand(0), // Chain
12307 Op.getOperand(2), // src
12308 Op.getOperand(3), // cmp
12309 Rsrc, // rsrc
12310 Op.getOperand(5), // vindex
12311 VOffset, // voffset
12312 SOffset, // soffset
12313 Offset, // offset
12314 Op.getOperand(8), // cachepolicy
12315 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
12316 };
12317 EVT VT = Op.getValueType();
12318 auto *M = cast<MemSDNode>(Op);
12319
12320 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
12321 Op->getVTList(), Ops, VT,
12322 M->getMemOperand());
12323 }
12324 case Intrinsic::amdgcn_image_bvh_dual_intersect_ray:
12325 case Intrinsic::amdgcn_image_bvh8_intersect_ray: {
12326 MemSDNode *M = cast<MemSDNode>(Op);
12327 SDValue NodePtr = M->getOperand(2);
12328 SDValue RayExtent = M->getOperand(3);
12329 SDValue InstanceMask = M->getOperand(4);
12330 SDValue RayOrigin = M->getOperand(5);
12331 SDValue RayDir = M->getOperand(6);
12332 SDValue Offsets = M->getOperand(7);
12333 SDValue TDescr = M->getOperand(8);
12334
12335 assert(NodePtr.getValueType() == MVT::i64);
12336 assert(RayDir.getValueType() == MVT::v3f32);
12337
12338 bool IsBVH8 = IntrID == Intrinsic::amdgcn_image_bvh8_intersect_ray;
12339 const unsigned NumVDataDwords = 10;
12340 const unsigned NumVAddrDwords = IsBVH8 ? 11 : 12;
12341 int Opcode = AMDGPU::getMIMGOpcode(
12342 IsBVH8 ? AMDGPU::IMAGE_BVH8_INTERSECT_RAY
12343 : AMDGPU::IMAGE_BVH_DUAL_INTERSECT_RAY,
12344 AMDGPU::MIMGEncGfx12, NumVDataDwords, NumVAddrDwords);
12345 assert(Opcode != -1);
12346
12348 Ops.push_back(NodePtr);
12349 Ops.push_back(DAG.getBuildVector(
12350 MVT::v2i32, DL,
12351 {DAG.getBitcast(MVT::i32, RayExtent),
12352 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, InstanceMask)}));
12353 Ops.push_back(RayOrigin);
12354 Ops.push_back(RayDir);
12355 Ops.push_back(Offsets);
12356 Ops.push_back(TDescr);
12357 Ops.push_back(M->getChain());
12358
12359 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
12360 MachineMemOperand *MemRef = M->getMemOperand();
12361 DAG.setNodeMemRefs(NewNode, {MemRef});
12362 return SDValue(NewNode, 0);
12363 }
12364 case Intrinsic::amdgcn_image_bvh_intersect_ray: {
12365 MemSDNode *M = cast<MemSDNode>(Op);
12366 SDValue NodePtr = M->getOperand(2);
12367 SDValue RayExtent = M->getOperand(3);
12368 SDValue RayOrigin = M->getOperand(4);
12369 SDValue RayDir = M->getOperand(5);
12370 SDValue RayInvDir = M->getOperand(6);
12371 SDValue TDescr = M->getOperand(7);
12372
12373 assert(NodePtr.getValueType() == MVT::i32 ||
12374 NodePtr.getValueType() == MVT::i64);
12375 assert(RayDir.getValueType() == MVT::v3f16 ||
12376 RayDir.getValueType() == MVT::v3f32);
12377
12378 const bool IsGFX11 = AMDGPU::isGFX11(*Subtarget);
12379 const bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
12380 const bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
12381 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
12382 const bool Is64 = NodePtr.getValueType() == MVT::i64;
12383 const unsigned NumVDataDwords = 4;
12384 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
12385 const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords;
12386 const bool UseNSA = (Subtarget->hasNSAEncoding() &&
12387 NumVAddrs <= Subtarget->getNSAMaxSize()) ||
12388 IsGFX12Plus;
12389 const unsigned BaseOpcodes[2][2] = {
12390 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
12391 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
12392 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
12393 int Opcode;
12394 if (UseNSA) {
12395 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
12396 IsGFX12Plus ? AMDGPU::MIMGEncGfx12
12397 : IsGFX11 ? AMDGPU::MIMGEncGfx11NSA
12398 : AMDGPU::MIMGEncGfx10NSA,
12399 NumVDataDwords, NumVAddrDwords);
12400 } else {
12401 assert(!IsGFX12Plus);
12402 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
12403 IsGFX11 ? AMDGPU::MIMGEncGfx11Default
12404 : AMDGPU::MIMGEncGfx10Default,
12405 NumVDataDwords, NumVAddrDwords);
12406 }
12407 assert(Opcode != -1);
12408
12410
12411 auto packLanes = [&DAG, &Ops, &DL](SDValue Op, bool IsAligned) {
12413 DAG.ExtractVectorElements(Op, Lanes, 0, 3);
12414 if (Lanes[0].getValueSizeInBits() == 32) {
12415 for (unsigned I = 0; I < 3; ++I)
12416 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
12417 } else {
12418 if (IsAligned) {
12419 Ops.push_back(DAG.getBitcast(
12420 MVT::i32,
12421 DAG.getBuildVector(MVT::v2f16, DL, {Lanes[0], Lanes[1]})));
12422 Ops.push_back(Lanes[2]);
12423 } else {
12424 SDValue Elt0 = Ops.pop_back_val();
12425 Ops.push_back(DAG.getBitcast(
12426 MVT::i32, DAG.getBuildVector(MVT::v2f16, DL, {Elt0, Lanes[0]})));
12427 Ops.push_back(DAG.getBitcast(
12428 MVT::i32,
12429 DAG.getBuildVector(MVT::v2f16, DL, {Lanes[1], Lanes[2]})));
12430 }
12431 }
12432 };
12433
12434 if (UseNSA && IsGFX11Plus) {
12435 Ops.push_back(NodePtr);
12436 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
12437 Ops.push_back(RayOrigin);
12438 if (IsA16) {
12439 SmallVector<SDValue, 3> DirLanes, InvDirLanes, MergedLanes;
12440 DAG.ExtractVectorElements(RayDir, DirLanes, 0, 3);
12441 DAG.ExtractVectorElements(RayInvDir, InvDirLanes, 0, 3);
12442 for (unsigned I = 0; I < 3; ++I) {
12443 MergedLanes.push_back(DAG.getBitcast(
12444 MVT::i32, DAG.getBuildVector(MVT::v2f16, DL,
12445 {DirLanes[I], InvDirLanes[I]})));
12446 }
12447 Ops.push_back(DAG.getBuildVector(MVT::v3i32, DL, MergedLanes));
12448 } else {
12449 Ops.push_back(RayDir);
12450 Ops.push_back(RayInvDir);
12451 }
12452 } else {
12453 if (Is64)
12454 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0,
12455 2);
12456 else
12457 Ops.push_back(NodePtr);
12458
12459 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
12460 packLanes(RayOrigin, true);
12461 packLanes(RayDir, true);
12462 packLanes(RayInvDir, false);
12463 }
12464
12465 if (!UseNSA) {
12466 // Build a single vector containing all the operands so far prepared.
12467 if (NumVAddrDwords > 12) {
12468 SDValue Undef = DAG.getPOISON(MVT::i32);
12469 Ops.append(16 - Ops.size(), Undef);
12470 }
12471 assert(Ops.size() >= 8 && Ops.size() <= 12);
12472 SDValue MergedOps =
12473 DAG.getBuildVector(MVT::getVectorVT(MVT::i32, Ops.size()), DL, Ops);
12474 Ops.clear();
12475 Ops.push_back(MergedOps);
12476 }
12477
12478 Ops.push_back(TDescr);
12479 Ops.push_back(DAG.getTargetConstant(IsA16, DL, MVT::i1));
12480 Ops.push_back(M->getChain());
12481
12482 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
12483 MachineMemOperand *MemRef = M->getMemOperand();
12484 DAG.setNodeMemRefs(NewNode, {MemRef});
12485 return SDValue(NewNode, 0);
12486 }
12487 case Intrinsic::amdgcn_global_atomic_fmin_num:
12488 case Intrinsic::amdgcn_global_atomic_fmax_num:
12489 case Intrinsic::amdgcn_flat_atomic_fmin_num:
12490 case Intrinsic::amdgcn_flat_atomic_fmax_num: {
12491 MemSDNode *M = cast<MemSDNode>(Op);
12492 SDValue Ops[] = {
12493 M->getOperand(0), // Chain
12494 M->getOperand(2), // Ptr
12495 M->getOperand(3) // Value
12496 };
12497 unsigned Opcode = 0;
12498 switch (IntrID) {
12499 case Intrinsic::amdgcn_global_atomic_fmin_num:
12500 case Intrinsic::amdgcn_flat_atomic_fmin_num: {
12501 Opcode = ISD::ATOMIC_LOAD_FMIN;
12502 break;
12503 }
12504 case Intrinsic::amdgcn_global_atomic_fmax_num:
12505 case Intrinsic::amdgcn_flat_atomic_fmax_num: {
12506 Opcode = ISD::ATOMIC_LOAD_FMAX;
12507 break;
12508 }
12509 default:
12510 llvm_unreachable("unhandled atomic opcode");
12511 }
12512 return DAG.getAtomic(Opcode, SDLoc(Op), M->getMemoryVT(), M->getVTList(),
12513 Ops, M->getMemOperand());
12514 }
12515 case Intrinsic::amdgcn_s_alloc_vgpr: {
12516 SDValue NumVGPRs = Op.getOperand(2);
12517 if (!NumVGPRs->isDivergent())
12518 return Op;
12519
12520 SDValue ReadFirstLaneID =
12521 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
12522 NumVGPRs = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
12523 ReadFirstLaneID, NumVGPRs);
12524
12525 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, Op->getVTList(),
12526 Op.getOperand(0), Op.getOperand(1), NumVGPRs);
12527 }
12528 case Intrinsic::amdgcn_s_get_barrier_state:
12529 case Intrinsic::amdgcn_s_get_named_barrier_state: {
12530 SDValue Chain = Op->getOperand(0);
12532 unsigned Opc;
12533
12534 if (isa<ConstantSDNode>(Op->getOperand(2))) {
12535 uint64_t BarID = cast<ConstantSDNode>(Op->getOperand(2))->getZExtValue();
12536 if (IntrID == Intrinsic::amdgcn_s_get_named_barrier_state)
12537 BarID = BarID & 0x3F;
12538 Opc = AMDGPU::S_GET_BARRIER_STATE_IMM;
12539 SDValue K = DAG.getTargetConstant(BarID, DL, MVT::i32);
12540 Ops.push_back(K);
12541 Ops.push_back(Chain);
12542 } else {
12543 Opc = AMDGPU::S_GET_BARRIER_STATE_M0;
12544 if (IntrID == Intrinsic::amdgcn_s_get_named_barrier_state) {
12545 SDValue M0Val = DAG.getNode(ISD::AND, DL, MVT::i32, Op->getOperand(2),
12546 DAG.getConstant(0x3F, DL, MVT::i32));
12547 Ops.push_back(copyToM0(DAG, Chain, DL, M0Val).getValue(0));
12548 } else
12549 Ops.push_back(copyToM0(DAG, Chain, DL, Op->getOperand(2)).getValue(0));
12550 }
12551
12552 auto *NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
12553 return SDValue(NewMI, 0);
12554 }
12555 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
12556 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
12557 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B: {
12558 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12559 SDValue Chain = Op->getOperand(0);
12560 SDValue Ptr = Op->getOperand(2);
12561 EVT VT = Op->getValueType(0);
12562 return DAG.getAtomicLoad(ISD::NON_EXTLOAD, DL, MII->getMemoryVT(), VT,
12563 Chain, Ptr, MII->getMemOperand());
12564 }
12565 case Intrinsic::amdgcn_av_load_b8:
12566 case Intrinsic::amdgcn_av_load_b16:
12567 case Intrinsic::amdgcn_av_load_b32:
12568 case Intrinsic::amdgcn_av_load_b64:
12569 case Intrinsic::amdgcn_av_load_b128: {
12570 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12571 SDValue Chain = Op->getOperand(0);
12572 SDValue Ptr = Op->getOperand(2);
12573 EVT VT = Op->getValueType(0);
12574 // Lower to a regular ISD::LOAD. The MachineMemOperand carries Monotonic
12575 // ordering and syncscope so that SIMemoryLegalizer sets cache policy bits.
12576 // Address space filtering in the load_global/load_flat PatFrags selects
12577 // the correct GLOBAL vs FLAT instruction.
12578 return DAG.getLoad(VT, DL, Chain, Ptr, MII->getMemOperand());
12579 }
12580 case Intrinsic::amdgcn_flat_load_monitor_b32:
12581 case Intrinsic::amdgcn_flat_load_monitor_b64:
12582 case Intrinsic::amdgcn_flat_load_monitor_b128: {
12583 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12584 SDValue Chain = Op->getOperand(0);
12585 SDValue Ptr = Op->getOperand(2);
12586 return DAG.getMemIntrinsicNode(AMDGPUISD::FLAT_LOAD_MONITOR, DL,
12587 Op->getVTList(), {Chain, Ptr},
12588 MII->getMemoryVT(), MII->getMemOperand());
12589 }
12590 case Intrinsic::amdgcn_global_load_monitor_b32:
12591 case Intrinsic::amdgcn_global_load_monitor_b64:
12592 case Intrinsic::amdgcn_global_load_monitor_b128: {
12593 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12594 SDValue Chain = Op->getOperand(0);
12595 SDValue Ptr = Op->getOperand(2);
12596 return DAG.getMemIntrinsicNode(AMDGPUISD::GLOBAL_LOAD_MONITOR, DL,
12597 Op->getVTList(), {Chain, Ptr},
12598 MII->getMemoryVT(), MII->getMemOperand());
12599 }
12600 default:
12601
12602 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
12604 return lowerImage(Op, ImageDimIntr, DAG, true);
12605
12606 return SDValue();
12607 }
12608}
12609
12610// Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
12611// dwordx4 if on SI and handle TFE loads.
12612SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
12613 SDVTList VTList,
12614 ArrayRef<SDValue> Ops, EVT MemVT,
12615 MachineMemOperand *MMO,
12616 SelectionDAG &DAG) const {
12617 LLVMContext &C = *DAG.getContext();
12619 EVT VT = VTList.VTs[0];
12620
12621 assert(VTList.NumVTs == 2 || VTList.NumVTs == 3);
12622 bool IsTFE = VTList.NumVTs == 3;
12623 if (IsTFE) {
12624 unsigned NumValueDWords = divideCeil(VT.getSizeInBits(), 32);
12625 unsigned NumOpDWords = NumValueDWords + 1;
12626 EVT OpDWordsVT = EVT::getVectorVT(C, MVT::i32, NumOpDWords);
12627 SDVTList OpDWordsVTList = DAG.getVTList(OpDWordsVT, VTList.VTs[2]);
12628 MachineMemOperand *OpDWordsMMO =
12629 MF.getMachineMemOperand(MMO, 0, NumOpDWords * 4);
12630 SDValue Op = getMemIntrinsicNode(Opcode, DL, OpDWordsVTList, Ops,
12631 OpDWordsVT, OpDWordsMMO, DAG);
12632 auto [Value, Status] = splitTFEValueAndStatus(Op, VT, DL, DAG);
12633 return DAG.getMergeValues({Value, Status, SDValue(Op.getNode(), 1)}, DL);
12634 }
12635
12636 if (!Subtarget->hasDwordx3LoadStores() &&
12637 (VT == MVT::v3i32 || VT == MVT::v3f32)) {
12638 EVT WidenedVT = EVT::getVectorVT(C, VT.getVectorElementType(), 4);
12639 EVT WidenedMemVT = EVT::getVectorVT(C, MemVT.getVectorElementType(), 4);
12640 MachineMemOperand *WidenedMMO = MF.getMachineMemOperand(MMO, 0, 16);
12641 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
12642 SDValue Op = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
12643 WidenedMemVT, WidenedMMO);
12645 DAG.getVectorIdxConstant(0, DL));
12646 return DAG.getMergeValues({Value, SDValue(Op.getNode(), 1)}, DL);
12647 }
12648
12649 return DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops, MemVT, MMO);
12650}
12651
12652SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
12653 bool ImageStore) const {
12654 EVT StoreVT = VData.getValueType();
12655
12656 // No change for f16 and legal vector D16 types.
12657 if (!StoreVT.isVector())
12658 return VData;
12659
12660 SDLoc DL(VData);
12661 unsigned NumElements = StoreVT.getVectorNumElements();
12662
12663 if (Subtarget->hasUnpackedD16VMem()) {
12664 // We need to unpack the packed data to store.
12665 EVT IntStoreVT = StoreVT.changeTypeToInteger();
12666 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
12667
12668 EVT EquivStoreVT =
12669 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
12670 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
12671 return DAG.UnrollVectorOp(ZExt.getNode());
12672 }
12673
12674 // The sq block of gfx8.1 does not estimate register use correctly for d16
12675 // image store instructions. The data operand is computed as if it were not a
12676 // d16 image instruction.
12677 if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
12678 // Bitcast to i16
12679 EVT IntStoreVT = StoreVT.changeTypeToInteger();
12680 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
12681
12682 // Decompose into scalars
12684 DAG.ExtractVectorElements(IntVData, Elts);
12685
12686 // Group pairs of i16 into v2i16 and bitcast to i32
12687 SmallVector<SDValue, 4> PackedElts;
12688 for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
12689 SDValue Pair =
12690 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
12691 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
12692 PackedElts.push_back(IntPair);
12693 }
12694 if ((NumElements % 2) == 1) {
12695 // Handle v3i16
12696 unsigned I = Elts.size() / 2;
12697 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
12698 {Elts[I * 2], DAG.getPOISON(MVT::i16)});
12699 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
12700 PackedElts.push_back(IntPair);
12701 }
12702
12703 // Pad using UNDEF
12704 PackedElts.resize(Elts.size(), DAG.getPOISON(MVT::i32));
12705
12706 // Build final vector
12707 EVT VecVT =
12708 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
12709 return DAG.getBuildVector(VecVT, DL, PackedElts);
12710 }
12711
12712 if (NumElements == 3) {
12713 EVT IntStoreVT =
12715 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
12716
12717 EVT WidenedStoreVT = EVT::getVectorVT(
12718 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
12719 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
12720 WidenedStoreVT.getStoreSizeInBits());
12721 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
12722 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
12723 }
12724
12725 assert(isTypeLegal(StoreVT));
12726 return VData;
12727}
12728
12729static bool isAsyncLDSDMA(Intrinsic::ID Intr) {
12730 switch (Intr) {
12731 case Intrinsic::amdgcn_raw_buffer_load_async_lds:
12732 case Intrinsic::amdgcn_raw_ptr_buffer_load_async_lds:
12733 case Intrinsic::amdgcn_struct_buffer_load_async_lds:
12734 case Intrinsic::amdgcn_struct_ptr_buffer_load_async_lds:
12735 case Intrinsic::amdgcn_load_async_to_lds:
12736 case Intrinsic::amdgcn_global_load_async_lds:
12737 return true;
12738 }
12739 return false;
12740}
12741
12742SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
12743 SelectionDAG &DAG) const {
12744 SDLoc DL(Op);
12745 SDValue Chain = Op.getOperand(0);
12746 unsigned IntrinsicID = Op.getConstantOperandVal(1);
12747
12748 switch (IntrinsicID) {
12749 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
12750 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
12751 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
12752 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128: {
12753 if (Subtarget->hasGFX1250_STRICT())
12755 return SDValue();
12756 }
12757 case Intrinsic::amdgcn_exp_compr: {
12758 SDValue Src0 = Op.getOperand(4);
12759 SDValue Src1 = Op.getOperand(5);
12760 // Hack around illegal type on SI by directly selecting it.
12761 if (isTypeLegal(Src0.getValueType()))
12762 return SDValue();
12763
12764 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
12765 SDValue Undef = DAG.getPOISON(MVT::f32);
12766 const SDValue Ops[] = {
12767 Op.getOperand(2), // tgt
12768 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
12769 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
12770 Undef, // src2
12771 Undef, // src3
12772 Op.getOperand(7), // vm
12773 DAG.getTargetConstant(1, DL, MVT::i1), // compr
12774 Op.getOperand(3), // en
12775 Op.getOperand(0) // Chain
12776 };
12777
12778 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
12779 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
12780 }
12781
12782 case Intrinsic::amdgcn_struct_tbuffer_store:
12783 case Intrinsic::amdgcn_struct_ptr_tbuffer_store: {
12784 SDValue VData = Op.getOperand(2);
12785 bool IsD16 = (VData.getValueType().getScalarSizeInBits() == 16);
12786 if (IsD16)
12787 VData = handleD16VData(VData, DAG);
12788 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
12789 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(5), DAG);
12790 auto SOffset = selectSOffset(Op.getOperand(6), DAG, Subtarget);
12791 SDValue Ops[] = {
12792 Chain,
12793 VData, // vdata
12794 Rsrc, // rsrc
12795 Op.getOperand(4), // vindex
12796 VOffset, // voffset
12797 SOffset, // soffset
12798 Offset, // offset
12799 Op.getOperand(7), // format
12800 Op.getOperand(8), // cachepolicy, swizzled buffer
12801 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
12802 };
12803 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16
12804 : AMDGPUISD::TBUFFER_STORE_FORMAT;
12805 MemSDNode *M = cast<MemSDNode>(Op);
12806 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
12807 M->getMemoryVT(), M->getMemOperand());
12808 }
12809
12810 case Intrinsic::amdgcn_raw_tbuffer_store:
12811 case Intrinsic::amdgcn_raw_ptr_tbuffer_store: {
12812 SDValue VData = Op.getOperand(2);
12813 bool IsD16 = (VData.getValueType().getScalarSizeInBits() == 16);
12814 if (IsD16)
12815 VData = handleD16VData(VData, DAG);
12816 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
12817 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(4), DAG);
12818 auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
12819 SDValue Ops[] = {
12820 Chain,
12821 VData, // vdata
12822 Rsrc, // rsrc
12823 DAG.getConstant(0, DL, MVT::i32), // vindex
12824 VOffset, // voffset
12825 SOffset, // soffset
12826 Offset, // offset
12827 Op.getOperand(6), // format
12828 Op.getOperand(7), // cachepolicy, swizzled buffer
12829 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
12830 };
12831 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16
12832 : AMDGPUISD::TBUFFER_STORE_FORMAT;
12833 MemSDNode *M = cast<MemSDNode>(Op);
12834 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
12835 M->getMemoryVT(), M->getMemOperand());
12836 }
12837
12838 case Intrinsic::amdgcn_raw_buffer_store:
12839 case Intrinsic::amdgcn_raw_ptr_buffer_store:
12840 case Intrinsic::amdgcn_raw_buffer_store_format:
12841 case Intrinsic::amdgcn_raw_ptr_buffer_store_format: {
12842 const bool IsFormat =
12843 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format ||
12844 IntrinsicID == Intrinsic::amdgcn_raw_ptr_buffer_store_format;
12845
12846 SDValue VData = Op.getOperand(2);
12847 EVT VDataVT = VData.getValueType();
12848 EVT EltType = VDataVT.getScalarType();
12849 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
12850
12851 if (IsFormat && !IsD16 && EltType.getSizeInBits() < 32) {
12852 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12854 "unsupported sub-dword format buffer store", DL.getDebugLoc()));
12855 return Chain;
12856 }
12857
12858 if (IsD16) {
12859 VData = handleD16VData(VData, DAG);
12860 VDataVT = VData.getValueType();
12861 }
12862
12863 if (!isTypeLegal(VDataVT)) {
12864 VData =
12865 DAG.getNode(ISD::BITCAST, DL,
12866 getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
12867 }
12868
12869 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
12870 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(4), DAG);
12871 auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
12872 SDValue Ops[] = {
12873 Chain,
12874 VData,
12875 Rsrc,
12876 DAG.getConstant(0, DL, MVT::i32), // vindex
12877 VOffset, // voffset
12878 SOffset, // soffset
12879 Offset, // offset
12880 Op.getOperand(6), // cachepolicy, swizzled buffer
12881 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
12882 };
12883 unsigned Opc =
12884 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
12885 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
12886 MemSDNode *M = cast<MemSDNode>(Op);
12887
12888 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
12889 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
12890 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
12891
12892 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
12893 M->getMemoryVT(), M->getMemOperand());
12894 }
12895
12896 case Intrinsic::amdgcn_struct_buffer_store:
12897 case Intrinsic::amdgcn_struct_ptr_buffer_store:
12898 case Intrinsic::amdgcn_struct_buffer_store_format:
12899 case Intrinsic::amdgcn_struct_ptr_buffer_store_format: {
12900 const bool IsFormat =
12901 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format ||
12902 IntrinsicID == Intrinsic::amdgcn_struct_ptr_buffer_store_format;
12903
12904 SDValue VData = Op.getOperand(2);
12905 EVT VDataVT = VData.getValueType();
12906 EVT EltType = VDataVT.getScalarType();
12907 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
12908
12909 if (IsFormat && !IsD16 && EltType.getSizeInBits() < 32) {
12910 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12912 "unsupported sub-dword format buffer store", DL.getDebugLoc()));
12913 return Chain;
12914 }
12915
12916 if (IsD16) {
12917 VData = handleD16VData(VData, DAG);
12918 VDataVT = VData.getValueType();
12919 }
12920
12921 if (!isTypeLegal(VDataVT)) {
12922 VData =
12923 DAG.getNode(ISD::BITCAST, DL,
12924 getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
12925 }
12926
12927 auto Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
12928 auto [VOffset, Offset] = splitBufferOffsets(Op.getOperand(5), DAG);
12929 auto SOffset = selectSOffset(Op.getOperand(6), DAG, Subtarget);
12930 SDValue Ops[] = {
12931 Chain,
12932 VData,
12933 Rsrc,
12934 Op.getOperand(4), // vindex
12935 VOffset, // voffset
12936 SOffset, // soffset
12937 Offset, // offset
12938 Op.getOperand(7), // cachepolicy, swizzled buffer
12939 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
12940 };
12941 unsigned Opc =
12942 !IsFormat ? AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
12943 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
12944 MemSDNode *M = cast<MemSDNode>(Op);
12945
12946 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
12947 EVT VDataType = VData.getValueType().getScalarType();
12948 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
12949 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
12950
12951 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
12952 M->getMemoryVT(), M->getMemOperand());
12953 }
12954 case Intrinsic::amdgcn_raw_buffer_load_lds:
12955 case Intrinsic::amdgcn_raw_buffer_load_async_lds:
12956 case Intrinsic::amdgcn_raw_ptr_buffer_load_lds:
12957 case Intrinsic::amdgcn_raw_ptr_buffer_load_async_lds:
12958 case Intrinsic::amdgcn_struct_buffer_load_lds:
12959 case Intrinsic::amdgcn_struct_buffer_load_async_lds:
12960 case Intrinsic::amdgcn_struct_ptr_buffer_load_lds:
12961 case Intrinsic::amdgcn_struct_ptr_buffer_load_async_lds: {
12962 unsigned Opc;
12963 bool HasVIndex =
12964 IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds ||
12965 IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_async_lds ||
12966 IntrinsicID == Intrinsic::amdgcn_struct_ptr_buffer_load_lds ||
12967 IntrinsicID == Intrinsic::amdgcn_struct_ptr_buffer_load_async_lds;
12968 unsigned OpOffset = HasVIndex ? 1 : 0;
12969 SDValue VOffset = Op.getOperand(5 + OpOffset);
12970 bool HasVOffset = !isNullConstant(VOffset);
12971 unsigned Size = Op->getConstantOperandVal(4);
12972
12973 switch (Size) {
12974 default:
12975 return SDValue();
12976 case 1:
12977 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
12978 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
12979 : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
12980 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
12981 break;
12982 case 2:
12983 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
12984 : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
12985 : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
12986 : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
12987 break;
12988 case 4:
12989 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
12990 : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
12991 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
12992 : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
12993 break;
12994 case 12:
12995 if (!Subtarget->hasLDSLoadB96_B128())
12996 return SDValue();
12997 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX3_LDS_BOTHEN
12998 : AMDGPU::BUFFER_LOAD_DWORDX3_LDS_IDXEN
12999 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX3_LDS_OFFEN
13000 : AMDGPU::BUFFER_LOAD_DWORDX3_LDS_OFFSET;
13001 break;
13002 case 16:
13003 if (!Subtarget->hasLDSLoadB96_B128())
13004 return SDValue();
13005 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX4_LDS_BOTHEN
13006 : AMDGPU::BUFFER_LOAD_DWORDX4_LDS_IDXEN
13007 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX4_LDS_OFFEN
13008 : AMDGPU::BUFFER_LOAD_DWORDX4_LDS_OFFSET;
13009 break;
13010 }
13011
13012 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
13013
13015
13016 if (HasVIndex && HasVOffset)
13017 Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL,
13018 {Op.getOperand(5), // VIndex
13019 VOffset}));
13020 else if (HasVIndex)
13021 Ops.push_back(Op.getOperand(5));
13022 else if (HasVOffset)
13023 Ops.push_back(VOffset);
13024
13025 SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(2), DAG);
13026 Ops.push_back(Rsrc);
13027 Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset
13028 Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset
13029 bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
13030 unsigned Aux = Op.getConstantOperandVal(8 + OpOffset);
13031 Ops.push_back(DAG.getTargetConstant(
13032 Aux & (IsGFX12Plus ? AMDGPU::CPol::ALL : AMDGPU::CPol::ALL_pregfx12),
13033 DL, MVT::i16)); // cpol
13034 Ops.push_back(DAG.getTargetConstant(
13035 Aux & (IsGFX12Plus ? AMDGPU::CPol::SWZ : AMDGPU::CPol::SWZ_pregfx12)
13036 ? 1
13037 : 0,
13038 DL, MVT::i8)); // swz
13039 Ops.push_back(
13040 DAG.getTargetConstant(isAsyncLDSDMA(IntrinsicID), DL, MVT::i8));
13041 Ops.push_back(M0Val.getValue(0)); // Chain
13042 Ops.push_back(M0Val.getValue(1)); // Glue
13043
13044 auto *M = cast<MemSDNode>(Op);
13045 auto *Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops);
13046 DAG.setNodeMemRefs(Load, M->memoperands());
13047
13048 return SDValue(Load, 0);
13049 }
13050 // Buffers are handled by LowerBufferFatPointers, and we're going to go
13051 // for "trust me" that the remaining cases are global pointers until
13052 // such time as we can put two mem operands on an intrinsic.
13053 case Intrinsic::amdgcn_load_to_lds:
13054 case Intrinsic::amdgcn_load_async_to_lds:
13055 case Intrinsic::amdgcn_global_load_lds:
13056 case Intrinsic::amdgcn_global_load_async_lds: {
13057 if (!Subtarget->hasVMemToLDSLoad())
13058 return SDValue();
13059
13060 unsigned Opc;
13061 unsigned Size = Op->getConstantOperandVal(4);
13062 switch (Size) {
13063 default:
13064 return SDValue();
13065 case 1:
13066 Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
13067 break;
13068 case 2:
13069 Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
13070 break;
13071 case 4:
13072 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
13073 break;
13074 case 12:
13075 if (!Subtarget->hasLDSLoadB96_B128())
13076 return SDValue();
13077 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORDX3;
13078 break;
13079 case 16:
13080 if (!Subtarget->hasLDSLoadB96_B128())
13081 return SDValue();
13082 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORDX4;
13083 break;
13084 }
13085
13086 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
13087
13089
13090 SDValue Addr = Op.getOperand(2); // Global ptr
13091 SDValue VOffset;
13092 // Try to split SAddr and VOffset. Global and LDS pointers share the same
13093 // immediate offset, so we cannot use a regular SelectGlobalSAddr().
13094 if (Addr->isDivergent() && Addr->isAnyAdd()) {
13095 SDValue LHS = Addr.getOperand(0);
13096 SDValue RHS = Addr.getOperand(1);
13097
13098 if (LHS->isDivergent())
13099 std::swap(LHS, RHS);
13100
13101 if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND &&
13102 RHS.getOperand(0).getValueType() == MVT::i32) {
13103 // add (i64 sgpr), (zero_extend (i32 vgpr))
13104 Addr = LHS;
13105 VOffset = RHS.getOperand(0);
13106 }
13107 }
13108
13109 Ops.push_back(Addr);
13110 if (!Addr->isDivergent()) {
13112 if (!VOffset)
13113 VOffset =
13114 SDValue(DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
13115 DAG.getTargetConstant(0, DL, MVT::i32)),
13116 0);
13117 Ops.push_back(VOffset);
13118 }
13119
13120 Ops.push_back(Op.getOperand(5)); // Offset
13121
13122 unsigned Aux = Op.getConstantOperandVal(6);
13123 Ops.push_back(DAG.getTargetConstant(Aux & ~AMDGPU::CPol::VIRTUAL_BITS, DL,
13124 MVT::i32)); // CPol
13125 Ops.push_back(
13126 DAG.getTargetConstant(isAsyncLDSDMA(IntrinsicID), DL, MVT::i8));
13127
13128 Ops.push_back(M0Val.getValue(0)); // Chain
13129 Ops.push_back(M0Val.getValue(1)); // Glue
13130
13131 auto *M = cast<MemSDNode>(Op);
13132 auto *Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
13133 DAG.setNodeMemRefs(Load, M->memoperands());
13134
13135 return SDValue(Load, 0);
13136 }
13137 case Intrinsic::amdgcn_end_cf:
13138 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
13139 Op->getOperand(2), Chain),
13140 0);
13141 case Intrinsic::amdgcn_s_barrier_signal_var: {
13142 // Member count of 0 means to re-use a previous member count,
13143 // which, if the named barrier is statically chosen, means we can use
13144 // the immarg form. Otherwisee, fall through to constructiong M0 as for
13145 // s_barrier_init.
13146 SDValue CntOp = Op->getOperand(3);
13147 auto *CntC = dyn_cast<ConstantSDNode>(CntOp);
13148 if (CntC && CntC->isZero()) {
13149 SDValue Chain = Op->getOperand(0);
13150 SDValue BarOp = Op->getOperand(2);
13152
13153 std::optional<uint64_t> BarVal;
13154 if (auto *C = dyn_cast<ConstantSDNode>(BarOp))
13155 BarVal = C->getZExtValue();
13156 else if (auto *GA = dyn_cast<GlobalAddressSDNode>(BarOp))
13158 *GA->getGlobal(), AMDGPUAS::BARRIER))
13159 BarVal = *Addr + GA->getOffset();
13160
13161 if (BarVal) {
13162 unsigned BarID = *BarVal & 0x3F;
13163 Ops.push_back(DAG.getTargetConstant(BarID, DL, MVT::i32));
13164 Ops.push_back(Chain);
13165 auto *NewMI = DAG.getMachineNode(AMDGPU::S_BARRIER_SIGNAL_IMM, DL,
13166 Op->getVTList(), Ops);
13167 return SDValue(NewMI, 0);
13168 }
13169 }
13170 [[fallthrough]];
13171 }
13172 case Intrinsic::amdgcn_s_barrier_init: {
13173 // these two intrinsics have two operands: barrier pointer and member count
13174 SDValue Chain = Op->getOperand(0);
13176 SDValue BarOp = Op->getOperand(2);
13177 SDValue CntOp = Op->getOperand(3);
13178 SDValue M0Val;
13179 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_s_barrier_init
13180 ? AMDGPU::S_BARRIER_INIT_M0
13181 : AMDGPU::S_BARRIER_SIGNAL_M0;
13182 // extract the BarrierID from bits 0-5 of BarOp
13183 SDValue BarID = DAG.getNode(ISD::AND, DL, MVT::i32, BarOp,
13184 DAG.getConstant(0x3F, DL, MVT::i32));
13185 // Member count should be put into M0[ShAmt:+CntMask width]
13186 // Barrier ID should be put into M0[5:0]
13187 unsigned CntMask = AMDGPU::getBarrierMemberCountBitMask(
13188 AMDGPU::getIsaVersion(Subtarget->getCPU()));
13189 SDValue MemberCnt = DAG.getNode(ISD::AND, DL, MVT::i32, CntOp,
13190 DAG.getConstant(CntMask, DL, MVT::i32));
13191 constexpr unsigned ShAmt = 16;
13192 M0Val = DAG.getNode(ISD::SHL, DL, MVT::i32, MemberCnt,
13193 DAG.getShiftAmountConstant(ShAmt, MVT::i32, DL));
13194
13195 M0Val = DAG.getNode(ISD::OR, DL, MVT::i32, M0Val, BarID);
13196
13197 Ops.push_back(copyToM0(DAG, Chain, DL, M0Val).getValue(0));
13198
13199 auto *NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
13200 return SDValue(NewMI, 0);
13201 }
13202 case Intrinsic::amdgcn_s_wakeup_barrier: {
13203 if (!Subtarget->hasSWakeupBarrier())
13204 return SDValue();
13205 [[fallthrough]];
13206 }
13207 case Intrinsic::amdgcn_s_barrier_join: {
13208 // these three intrinsics have one operand: barrier pointer
13209 SDValue Chain = Op->getOperand(0);
13211 SDValue BarOp = Op->getOperand(2);
13212 unsigned Opc;
13213
13214 if (isa<ConstantSDNode>(BarOp)) {
13215 uint64_t BarVal = cast<ConstantSDNode>(BarOp)->getZExtValue();
13216 switch (IntrinsicID) {
13217 default:
13218 return SDValue();
13219 case Intrinsic::amdgcn_s_barrier_join:
13220 Opc = AMDGPU::S_BARRIER_JOIN_IMM;
13221 break;
13222 case Intrinsic::amdgcn_s_wakeup_barrier:
13223 Opc = AMDGPU::S_WAKEUP_BARRIER_IMM;
13224 break;
13225 }
13226 // extract the BarrierID from bits 0-5 of the immediate
13227 unsigned BarID = BarVal & 0x3F;
13228 SDValue K = DAG.getTargetConstant(BarID, DL, MVT::i32);
13229 Ops.push_back(K);
13230 Ops.push_back(Chain);
13231 } else {
13232 switch (IntrinsicID) {
13233 default:
13234 return SDValue();
13235 case Intrinsic::amdgcn_s_barrier_join:
13236 Opc = AMDGPU::S_BARRIER_JOIN_M0;
13237 break;
13238 case Intrinsic::amdgcn_s_wakeup_barrier:
13239 Opc = AMDGPU::S_WAKEUP_BARRIER_M0;
13240 break;
13241 }
13242 // extract the BarrierID from bits 0-5 of BarOp, copy to M0[5:0]
13243 SDValue M0Val = DAG.getNode(ISD::AND, DL, MVT::i32, BarOp,
13244 DAG.getConstant(0x3F, DL, MVT::i32));
13245 Ops.push_back(copyToM0(DAG, Chain, DL, M0Val).getValue(0));
13246 }
13247
13248 auto *NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
13249 return SDValue(NewMI, 0);
13250 }
13251 case Intrinsic::amdgcn_s_prefetch_data:
13252 case Intrinsic::amdgcn_s_prefetch_inst: {
13253 // For non-global address space preserve the chain and remove the call.
13255 return Op.getOperand(0);
13256 return Op;
13257 }
13258 case Intrinsic::amdgcn_s_buffer_prefetch_data: {
13259 SDValue Ops[] = {
13260 Chain, bufferRsrcPtrToVector(Op.getOperand(2), DAG),
13261 Op.getOperand(3), // offset
13262 Op.getOperand(4), // length
13263 };
13264
13265 MemSDNode *M = cast<MemSDNode>(Op);
13266 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_PREFETCH_DATA, DL,
13267 Op->getVTList(), Ops, M->getMemoryVT(),
13268 M->getMemOperand());
13269 }
13270 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
13271 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
13272 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
13273 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
13274 SDValue Chain = Op->getOperand(0);
13275 SDValue Ptr = Op->getOperand(2);
13276 SDValue Val = Op->getOperand(3);
13277 return DAG.getAtomic(ISD::ATOMIC_STORE, DL, MII->getMemoryVT(), Chain, Val,
13278 Ptr, MII->getMemOperand());
13279 }
13280 case Intrinsic::amdgcn_av_store_b8:
13281 case Intrinsic::amdgcn_av_store_b16:
13282 case Intrinsic::amdgcn_av_store_b32:
13283 case Intrinsic::amdgcn_av_store_b64:
13284 case Intrinsic::amdgcn_av_store_b128: {
13285 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
13286 SDValue Chain = Op->getOperand(0);
13287 SDValue Ptr = Op->getOperand(2);
13288 SDValue Val = Op->getOperand(3);
13289 return DAG.getStore(Chain, DL, Val, Ptr, MII->getMemOperand());
13290 }
13291 default: {
13292 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
13294 return lowerImage(Op, ImageDimIntr, DAG, true);
13295
13296 return Op;
13297 }
13298 }
13299}
13300
13301// Return whether the operation has NoUnsignedWrap property.
13302static bool isNoUnsignedWrap(SDValue Addr) {
13303 return (Addr.getOpcode() == ISD::ADD &&
13304 Addr->getFlags().hasNoUnsignedWrap()) ||
13305 Addr->getOpcode() == ISD::OR;
13306}
13307
13309 EVT PtrVT) const {
13310 return PtrVT == MVT::i64;
13311}
13312
13314 EVT PtrVT) const {
13315 return true;
13316}
13317
13318// The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
13319// offset (the offset that is included in bounds checking and swizzling, to be
13320// split between the instruction's voffset and immoffset fields) and soffset
13321// (the offset that is excluded from bounds checking and swizzling, to go in
13322// the instruction's soffset field). This function takes the first kind of
13323// offset and figures out how to split it between voffset and immoffset.
13324std::pair<SDValue, SDValue>
13325SITargetLowering::splitBufferOffsets(SDValue Offset, SelectionDAG &DAG) const {
13326 SDLoc DL(Offset);
13327 const unsigned MaxImm = SIInstrInfo::getMaxMUBUFImmOffset(*Subtarget);
13328 SDValue N0 = Offset;
13329 ConstantSDNode *C1 = nullptr;
13330
13331 if ((C1 = dyn_cast<ConstantSDNode>(N0)))
13332 N0 = SDValue();
13333 else if (DAG.isBaseWithConstantOffset(N0)) {
13334 // On GFX1250+, voffset and immoffset are zero-extended from 32 bits before
13335 // being added, so we can only safely match a 32-bit addition with no
13336 // unsigned overflow.
13337 bool CheckNUW = Subtarget->hasGFX1250Insts();
13338 if (!CheckNUW || isNoUnsignedWrap(N0)) {
13340 N0 = N0.getOperand(0);
13341 }
13342 }
13343
13344 if (C1) {
13345 unsigned ImmOffset = C1->getZExtValue();
13346 // If the immediate value is too big for the immoffset field, put only bits
13347 // that would normally fit in the immoffset field. The remaining value that
13348 // is copied/added for the voffset field is a large power of 2, and it
13349 // stands more chance of being CSEd with the copy/add for another similar
13350 // load/store.
13351 // However, do not do that rounding down if that is a negative
13352 // number, as it appears to be illegal to have a negative offset in the
13353 // vgpr, even if adding the immediate offset makes it positive.
13354 unsigned Overflow = ImmOffset & ~MaxImm;
13355 ImmOffset -= Overflow;
13356 if ((int32_t)Overflow < 0) {
13357 Overflow += ImmOffset;
13358 ImmOffset = 0;
13359 }
13360 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
13361 if (Overflow) {
13362 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
13363 if (!N0)
13364 N0 = OverflowVal;
13365 else {
13366 SDValue Ops[] = {N0, OverflowVal};
13367 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
13368 }
13369 }
13370 }
13371 if (!N0)
13372 N0 = DAG.getConstant(0, DL, MVT::i32);
13373 if (!C1)
13374 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
13375 return {N0, SDValue(C1, 0)};
13376}
13377
13378// Analyze a combined offset from an amdgcn_s_buffer_load intrinsic and store
13379// the three offsets (voffset, soffset and instoffset) into the SDValue[3] array
13380// pointed to by Offsets.
13381void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
13382 SelectionDAG &DAG, SDValue *Offsets,
13383 Align Alignment) const {
13384 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
13385 SDLoc DL(CombinedOffset);
13386 if (auto *C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
13387 uint32_t Imm = C->getZExtValue();
13388 uint32_t SOffset, ImmOffset;
13389 if (TII->splitMUBUFOffset(Imm, SOffset, ImmOffset, Alignment)) {
13390 Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
13391 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
13392 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
13393 return;
13394 }
13395 }
13396 if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
13397 // On GFX1250+, voffset and immoffset are zero-extended from 32 bits before
13398 // being added, so we can only safely match a 32-bit addition with no
13399 // unsigned overflow.
13400 bool CheckNUW = Subtarget->hasGFX1250Insts();
13401 SDValue N0 = CombinedOffset.getOperand(0);
13402 SDValue N1 = CombinedOffset.getOperand(1);
13403 uint32_t SOffset, ImmOffset;
13404 int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
13405 if (Offset >= 0 && (!CheckNUW || isNoUnsignedWrap(CombinedOffset)) &&
13406 TII->splitMUBUFOffset(Offset, SOffset, ImmOffset, Alignment)) {
13407 Offsets[0] = N0;
13408 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
13409 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
13410 return;
13411 }
13412 }
13413
13414 SDValue SOffsetZero = Subtarget->hasRestrictedSOffset()
13415 ? DAG.getRegister(AMDGPU::SGPR_NULL, MVT::i32)
13416 : DAG.getConstant(0, DL, MVT::i32);
13417
13418 Offsets[0] = CombinedOffset;
13419 Offsets[1] = SOffsetZero;
13420 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
13421}
13422
13423SDValue SITargetLowering::bufferRsrcPtrToVector(SDValue MaybePointer,
13424 SelectionDAG &DAG) const {
13425 if (!MaybePointer.getValueType().isScalarInteger())
13426 return MaybePointer;
13427
13428 SDValue Rsrc = DAG.getBitcast(MVT::v4i32, MaybePointer);
13429 return Rsrc;
13430}
13431
13432// Wrap a global or flat pointer into a buffer intrinsic using the flags
13433// specified in the intrinsic.
13434SDValue SITargetLowering::lowerPointerAsRsrcIntrin(SDNode *Op,
13435 SelectionDAG &DAG) const {
13436 SDLoc Loc(Op);
13437
13438 SDValue Pointer = Op->getOperand(1);
13439 SDValue Stride = Op->getOperand(2);
13440 SDValue NumRecords = Op->getOperand(3);
13441 SDValue Flags = Op->getOperand(4);
13442
13443 SDValue ExtStride = DAG.getAnyExtOrTrunc(Stride, Loc, MVT::i32);
13444 SDValue Rsrc;
13445
13446 if (Subtarget->getBufferResourceNumRecordsWidth() == 45) {
13447 NumRecords = DAG.getZExtOrTrunc(NumRecords, Loc, MVT::i64);
13448 NumRecords = DAG.getNode(ISD::AND, Loc, MVT::i64, NumRecords,
13449 DAG.getConstant((1ULL << 45) - 1, Loc, MVT::i64));
13450 SDValue Zero = DAG.getConstant(0, Loc, MVT::i32);
13451 // Build the lower 64-bit value, which has a 57-bit base and the lower 7-bit
13452 // num_records.
13453 SDValue ExtPointer = DAG.getAnyExtOrTrunc(Pointer, Loc, MVT::i64);
13454 SDValue NumRecordsLHS =
13455 DAG.getNode(ISD::SHL, Loc, MVT::i64, NumRecords,
13456 DAG.getShiftAmountConstant(57, MVT::i32, Loc));
13457 SDValue LowHalf =
13458 DAG.getNode(ISD::OR, Loc, MVT::i64, ExtPointer, NumRecordsLHS);
13459
13460 // Build the higher 64-bit value, which has the higher 38-bit num_records,
13461 // 6-bit zero (omit), 16-bit stride and scale and 4-bit flag.
13462 SDValue NumRecordsRHS =
13463 DAG.getNode(ISD::SRL, Loc, MVT::i64, NumRecords,
13464 DAG.getShiftAmountConstant(7, MVT::i32, Loc));
13465 SDValue ShiftedStride =
13466 DAG.getNode(ISD::SHL, Loc, MVT::i32, ExtStride,
13467 DAG.getShiftAmountConstant(12, MVT::i32, Loc));
13468 SDValue ExtShiftedStrideVec =
13469 DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v2i32, Zero, ShiftedStride);
13470 SDValue ExtShiftedStride =
13471 DAG.getNode(ISD::BITCAST, Loc, MVT::i64, ExtShiftedStrideVec);
13472 SDValue ShiftedFlags =
13473 DAG.getNode(ISD::SHL, Loc, MVT::i32, Flags,
13474 DAG.getShiftAmountConstant(28, MVT::i32, Loc));
13475 SDValue ExtShiftedFlagsVec =
13476 DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v2i32, Zero, ShiftedFlags);
13477 SDValue ExtShiftedFlags =
13478 DAG.getNode(ISD::BITCAST, Loc, MVT::i64, ExtShiftedFlagsVec);
13479 SDValue CombinedFields =
13480 DAG.getNode(ISD::OR, Loc, MVT::i64, NumRecordsRHS, ExtShiftedStride);
13481 SDValue HighHalf =
13482 DAG.getNode(ISD::OR, Loc, MVT::i64, CombinedFields, ExtShiftedFlags);
13483
13484 Rsrc = DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v2i64, LowHalf, HighHalf);
13485 } else {
13486 NumRecords = DAG.getZExtOrTrunc(NumRecords, Loc, MVT::i32);
13487 auto [LowHalf, HighHalf] =
13488 DAG.SplitScalar(Pointer, Loc, MVT::i32, MVT::i32);
13489 SDValue Mask = DAG.getConstant(0x0000ffff, Loc, MVT::i32);
13490 SDValue Masked = DAG.getNode(ISD::AND, Loc, MVT::i32, HighHalf, Mask);
13491 SDValue ShiftedStride =
13492 DAG.getNode(ISD::SHL, Loc, MVT::i32, ExtStride,
13493 DAG.getShiftAmountConstant(16, MVT::i32, Loc));
13494 SDValue NewHighHalf =
13495 DAG.getNode(ISD::OR, Loc, MVT::i32, Masked, ShiftedStride);
13496
13497 Rsrc = DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v4i32, LowHalf, NewHighHalf,
13498 NumRecords, Flags);
13499 }
13500
13501 SDValue RsrcPtr = DAG.getNode(ISD::BITCAST, Loc, MVT::i128, Rsrc);
13502 return RsrcPtr;
13503}
13504
13505// Handle 8 bit and 16 bit buffer loads
13506SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
13507 EVT LoadVT, SDLoc DL,
13509 MachineMemOperand *MMO,
13510 bool IsTFE) const {
13511 EVT IntVT = LoadVT.changeTypeToInteger();
13512
13513 if (IsTFE) {
13514 unsigned Opc = (LoadVT.getScalarType() == MVT::i8)
13515 ? AMDGPUISD::BUFFER_LOAD_UBYTE_TFE
13516 : AMDGPUISD::BUFFER_LOAD_USHORT_TFE;
13518 MachineMemOperand *OpMMO = MF.getMachineMemOperand(MMO, 0, 8);
13519 SDVTList VTs = DAG.getVTList(MVT::v2i32, MVT::Other);
13520 SDValue Op = getMemIntrinsicNode(Opc, DL, VTs, Ops, MVT::v2i32, OpMMO, DAG);
13521 SDValue Status = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op,
13522 DAG.getConstant(1, DL, MVT::i32));
13523 SDValue Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op,
13524 DAG.getConstant(0, DL, MVT::i32));
13525 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, IntVT, Data);
13526 SDValue Value = DAG.getNode(ISD::BITCAST, DL, LoadVT, Trunc);
13527 return DAG.getMergeValues({Value, Status, SDValue(Op.getNode(), 1)}, DL);
13528 }
13529
13530 unsigned Opc = LoadVT.getScalarType() == MVT::i8
13531 ? AMDGPUISD::BUFFER_LOAD_UBYTE
13532 : AMDGPUISD::BUFFER_LOAD_USHORT;
13533
13534 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
13535 SDValue BufferLoad =
13536 DAG.getMemIntrinsicNode(Opc, DL, ResList, Ops, IntVT, MMO);
13537 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
13538 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
13539
13540 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
13541}
13542
13543// Handle 8 bit and 16 bit buffer stores
13544SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
13545 EVT VDataType, SDLoc DL,
13546 SDValue Ops[],
13547 MemSDNode *M) const {
13548 if (VDataType == MVT::f16 || VDataType == MVT::bf16)
13549 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
13550
13551 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
13552 Ops[1] = BufferStoreExt;
13553 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE
13554 : AMDGPUISD::BUFFER_STORE_SHORT;
13555 ArrayRef<SDValue> OpsRef = ArrayRef(&Ops[0], 9);
13556 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
13557 M->getMemOperand());
13558}
13559
13561 SDValue Op, const SDLoc &SL, EVT VT) {
13562 if (VT.bitsLT(Op.getValueType()))
13563 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
13564
13565 switch (ExtType) {
13566 case ISD::SEXTLOAD:
13567 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
13568 case ISD::ZEXTLOAD:
13569 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
13570 case ISD::EXTLOAD:
13571 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
13572 case ISD::NON_EXTLOAD:
13573 return Op;
13574 }
13575
13576 llvm_unreachable("invalid ext type");
13577}
13578
13579// Try to turn 8 and 16-bit scalar loads into SMEM eligible 32-bit loads.
13580// TODO: Skip this on GFX12 which does have scalar sub-dword loads.
13581SDValue SITargetLowering::widenLoad(LoadSDNode *Ld,
13582 DAGCombinerInfo &DCI) const {
13583 SelectionDAG &DAG = DCI.DAG;
13584 if (Ld->getAlign() < Align(4) || Ld->isDivergent())
13585 return SDValue();
13586
13587 // FIXME: Constant loads should all be marked invariant.
13588 unsigned AS = Ld->getAddressSpace();
13589 if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
13591 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
13592 return SDValue();
13593
13594 // Don't do this early, since it may interfere with adjacent load merging for
13595 // illegal types. We can avoid losing alignment information for exotic types
13596 // pre-legalize.
13597 EVT MemVT = Ld->getMemoryVT();
13598 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
13599 MemVT.getSizeInBits() >= 32)
13600 return SDValue();
13601
13602 SDLoc SL(Ld);
13603
13604 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
13605 "unexpected vector extload");
13606
13607 // TODO: Drop only high part of range.
13608 SDValue Ptr = Ld->getBasePtr();
13609 SDValue NewLoad = DAG.getLoad(
13610 ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr,
13611 Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(),
13612 Ld->getMemOperand()->getFlags(), Ld->getAAInfo()); // Drop ranges
13613
13614 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
13615 if (MemVT.isFloatingPoint()) {
13616 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
13617 "unexpected fp extload");
13618 TruncVT = MemVT.changeTypeToInteger();
13619 }
13620
13621 SDValue Cvt = NewLoad;
13622 if (Ld->getExtensionType() == ISD::SEXTLOAD) {
13623 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
13624 DAG.getValueType(TruncVT));
13625 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
13626 Ld->getExtensionType() == ISD::NON_EXTLOAD) {
13627 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
13628 } else {
13629 assert(Ld->getExtensionType() == ISD::EXTLOAD);
13630 }
13631
13632 EVT VT = Ld->getValueType(0);
13633 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
13634
13635 DCI.AddToWorklist(Cvt.getNode());
13636
13637 // We may need to handle exotic cases, such as i16->i64 extloads, so insert
13638 // the appropriate extension from the 32-bit load.
13639 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
13640 DCI.AddToWorklist(Cvt.getNode());
13641
13642 // Handle conversion back to floating point if necessary.
13643 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
13644
13645 return DAG.getMergeValues({Cvt, NewLoad.getValue(1)}, SL);
13646}
13647
13649 const SIMachineFunctionInfo &Info) {
13650 // TODO: Should check if the address can definitely not access stack.
13651 if (Info.isEntryFunction())
13652 return Info.getUserSGPRInfo().hasFlatScratchInit();
13653 return true;
13654}
13655
13656SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
13657 SDLoc DL(Op);
13658 LoadSDNode *Load = cast<LoadSDNode>(Op);
13659 ISD::LoadExtType ExtType = Load->getExtensionType();
13660 EVT MemVT = Load->getMemoryVT();
13661 MachineMemOperand *MMO = Load->getMemOperand();
13662
13663 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
13664 // Legalize uniform 16-bit loads to i16 = trunc (zextload i16->i32)
13665 // to match subword load patterns.
13666 // Only do this for loads that can use scalar subword load instructions.
13667 if (!MemVT.isVector() && MemVT.getSizeInBits() == 16 &&
13668 isTypeLegal(MemVT) && Subtarget->hasScalarSubwordLoads() &&
13670 SDValue Chain = Load->getChain();
13671 SDValue BasePtr = Load->getBasePtr();
13672
13673 // Load as i16 and zero-extend to i32 (matches S_LOAD_U16 behavior)
13674 SDValue NewLD = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
13675 BasePtr, MVT::i16, MMO);
13676
13677 // Truncate back to i16
13678 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, NewLD);
13679
13680 // For f16/bf16, bitcast from i16 to the original fp type
13681 SDValue Result = (MemVT == MVT::i16)
13682 ? Trunc
13683 : DAG.getNode(ISD::BITCAST, DL, MemVT, Trunc);
13684
13685 SDValue Ops[] = {Result, NewLD.getValue(1)};
13686 return DAG.getMergeValues(Ops, DL);
13687 }
13688
13689 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
13690 return SDValue();
13691
13692 // FIXME: Copied from PPC
13693 // First, load into 32 bits, then truncate to 1 bit.
13694
13695 SDValue Chain = Load->getChain();
13696 SDValue BasePtr = Load->getBasePtr();
13697
13698 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
13699
13700 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, BasePtr,
13701 RealMemVT, MMO);
13702
13703 if (!MemVT.isVector()) {
13704 SDValue Ops[] = {DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
13705 NewLD.getValue(1)};
13706
13707 return DAG.getMergeValues(Ops, DL);
13708 }
13709
13711 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
13712 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
13713 DAG.getConstant(I, DL, MVT::i32));
13714
13715 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
13716 }
13717
13718 SDValue Ops[] = {DAG.getBuildVector(MemVT, DL, Elts), NewLD.getValue(1)};
13719
13720 return DAG.getMergeValues(Ops, DL);
13721 }
13722
13723 if (!MemVT.isVector())
13724 return SDValue();
13725
13726 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
13727 "Custom lowering for non-i32 vectors hasn't been implemented.");
13728
13729 Align Alignment = Load->getAlign();
13730 unsigned AS = Load->getAddressSpace();
13731 if (Subtarget->hasLDSMisalignedBugInWGPMode() &&
13732 AS == AMDGPUAS::FLAT_ADDRESS &&
13733 Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
13734 return SplitVectorLoad(Op, DAG);
13735 }
13736
13738 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
13739 // If there is a possibility that flat instruction access scratch memory
13740 // then we need to use the same legalization rules we use for private.
13741 if (AS == AMDGPUAS::FLAT_ADDRESS &&
13742 !Subtarget->hasMultiDwordFlatScratchAddressing())
13743 AS = addressMayBeAccessedAsPrivate(Load->getMemOperand(), *MFI)
13746
13747 unsigned NumElements = MemVT.getVectorNumElements();
13748
13749 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
13751 (AS == AMDGPUAS::GLOBAL_ADDRESS && Load->isSimple() &&
13752 (Load->isInvariant() || isMemOpHasNoClobberedMemOperand(Load)))) {
13753 if ((!Op->isDivergent() || AMDGPU::isUniformMMO(MMO)) &&
13754 Alignment >= Align(4) && NumElements < 32) {
13755 if (MemVT.isPow2VectorType() ||
13756 (Subtarget->hasScalarDwordx3Loads() && NumElements == 3))
13757 return SDValue();
13758 return WidenOrSplitVectorLoad(Op, DAG);
13759 }
13760 // Non-uniform loads will be selected to MUBUF instructions, so they
13761 // have the same legalization requirements as global and private
13762 // loads.
13763 //
13764 }
13765 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
13768 if (NumElements > 4)
13769 return SplitVectorLoad(Op, DAG);
13770 // v3 loads not supported on SI.
13771 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
13772 return WidenOrSplitVectorLoad(Op, DAG);
13773
13774 // v3 and v4 loads are supported for private and global memory.
13775 return SDValue();
13776 }
13777 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
13778 // Depending on the setting of the private_element_size field in the
13779 // resource descriptor, we can only make private accesses up to a certain
13780 // size.
13781 switch (Subtarget->getMaxPrivateElementSize()) {
13782 case 4: {
13783 auto [Op0, Op1] = scalarizeVectorLoad(Load, DAG);
13784 return DAG.getMergeValues({Op0, Op1}, DL);
13785 }
13786 case 8:
13787 if (NumElements > 2)
13788 return SplitVectorLoad(Op, DAG);
13789 return SDValue();
13790 case 16:
13791 // Same as global/flat
13792 if (NumElements > 4)
13793 return SplitVectorLoad(Op, DAG);
13794 // v3 loads not supported on SI.
13795 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
13796 return WidenOrSplitVectorLoad(Op, DAG);
13797
13798 return SDValue();
13799 default:
13800 llvm_unreachable("unsupported private_element_size");
13801 }
13802 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
13803 unsigned Fast = 0;
13804 auto Flags = Load->getMemOperand()->getFlags();
13806 Load->getAlign(), Flags, &Fast) &&
13807 Fast > 1)
13808 return SDValue();
13809
13810 if (MemVT.isVector())
13811 return SplitVectorLoad(Op, DAG);
13812 }
13813
13815 MemVT, *Load->getMemOperand())) {
13816 auto [Op0, Op1] = expandUnalignedLoad(Load, DAG);
13817 return DAG.getMergeValues({Op0, Op1}, DL);
13818 }
13819
13820 return SDValue();
13821}
13822
13823SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13824 EVT VT = Op.getValueType();
13825 if (VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256 ||
13826 VT.getSizeInBits() == 512)
13827 return splitTernaryVectorOp(Op, DAG);
13828
13829 assert(VT.getSizeInBits() == 64);
13830
13831 SDLoc DL(Op);
13832 SDValue Cond = DAG.getFreeze(Op.getOperand(0));
13833
13834 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
13835 SDValue One = DAG.getConstant(1, DL, MVT::i32);
13836
13837 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
13838 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
13839
13840 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
13841 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
13842
13843 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
13844
13845 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
13846 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
13847
13848 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
13849
13850 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
13851 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
13852}
13853
13854// Catch division cases where we can use shortcuts with rcp and rsq
13855// instructions.
13856SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
13857 SelectionDAG &DAG) const {
13858 SDLoc SL(Op);
13859 SDValue LHS = Op.getOperand(0);
13860 SDValue RHS = Op.getOperand(1);
13861 EVT VT = Op.getValueType();
13862 const SDNodeFlags Flags = Op->getFlags();
13863
13864 bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
13865
13866 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
13867 // Without !fpmath accuracy information, we can't do more because we don't
13868 // know exactly whether rcp is accurate enough to meet !fpmath requirement.
13869 // f16 is always accurate enough
13870 if (!AllowInaccurateRcp && VT != MVT::f16 && VT != MVT::bf16)
13871 return SDValue();
13872
13873 if (CLHS->isOne()) {
13874 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
13875 // the CI documentation has a worst case error of 1 ulp.
13876 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
13877 // use it as long as we aren't trying to use denormals.
13878 //
13879 // v_rcp_f16 and v_rsq_f16 DO support denormals and 0.51ulp.
13880
13881 // 1.0 / sqrt(x) -> rsq(x)
13882
13883 // XXX - Is afn sufficient to do this for f64? The maximum ULP
13884 // error seems really high at 2^29 ULP.
13885 // 1.0 / x -> rcp(x)
13886 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
13887 }
13888
13889 // Same as for 1.0, but expand the sign out of the constant.
13890 if (CLHS->isMinusOne()) {
13891 // -1.0 / x -> rcp (fneg x)
13892 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
13893 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
13894 }
13895 }
13896
13897 // For f16 and bf16 require afn or arcp.
13898 // For f32 require afn.
13899 if (!AllowInaccurateRcp &&
13900 ((VT != MVT::f16 && VT != MVT::bf16) || !Flags.hasAllowReciprocal()))
13901 return SDValue();
13902
13903 // Turn into multiply by the reciprocal.
13904 // x / y -> x * (1.0 / y)
13905 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
13906 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
13907}
13908
13909SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
13910 SelectionDAG &DAG) const {
13911 SDLoc SL(Op);
13912 SDValue X = Op.getOperand(0);
13913 SDValue Y = Op.getOperand(1);
13914 EVT VT = Op.getValueType();
13915 const SDNodeFlags Flags = Op->getFlags();
13916
13917 bool AllowInaccurateDiv = Flags.hasApproximateFuncs();
13918 if (!AllowInaccurateDiv)
13919 return SDValue();
13920
13921 const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(X);
13922 bool IsNegRcp = CLHS && CLHS->isMinusOne();
13923
13924 // Pull out the negation so it folds for free into the source modifiers.
13925 if (IsNegRcp)
13926 X = DAG.getConstantFP(1.0, SL, VT);
13927
13928 SDValue NegY = IsNegRcp ? Y : DAG.getNode(ISD::FNEG, SL, VT, Y);
13929 SDValue One = DAG.getConstantFP(1.0, SL, VT);
13930
13931 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
13932 if (IsNegRcp)
13933 R = DAG.getNode(ISD::FNEG, SL, VT, R);
13934
13935 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
13936
13937 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
13938 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
13939 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
13940
13941 // Skip the last 2 correction terms for reciprocal.
13942 if (IsNegRcp || (CLHS && CLHS->isOne()))
13943 return R;
13944
13945 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
13946 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
13947 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
13948}
13949
13950static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
13951 EVT VT, SDValue A, SDValue B, SDValue GlueChain,
13952 SDNodeFlags Flags) {
13953 if (GlueChain->getNumValues() <= 1) {
13954 return DAG.getNode(Opcode, SL, VT, A, B, Flags);
13955 }
13956
13957 assert(GlueChain->getNumValues() == 3);
13958
13959 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
13960 switch (Opcode) {
13961 default:
13962 llvm_unreachable("no chain equivalent for opcode");
13963 case ISD::FMUL:
13964 Opcode = AMDGPUISD::FMUL_W_CHAIN;
13965 break;
13966 }
13967
13968 return DAG.getNode(Opcode, SL, VTList,
13969 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
13970 Flags);
13971}
13972
13973static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
13974 EVT VT, SDValue A, SDValue B, SDValue C,
13975 SDValue GlueChain, SDNodeFlags Flags) {
13976 if (GlueChain->getNumValues() <= 1) {
13977 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
13978 }
13979
13980 assert(GlueChain->getNumValues() == 3);
13981
13982 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
13983 switch (Opcode) {
13984 default:
13985 llvm_unreachable("no chain equivalent for opcode");
13986 case ISD::FMA:
13987 Opcode = AMDGPUISD::FMA_W_CHAIN;
13988 break;
13989 }
13990
13991 return DAG.getNode(Opcode, SL, VTList,
13992 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
13993 Flags);
13994}
13995
13996SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
13997 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
13998 return FastLowered;
13999
14000 SDLoc SL(Op);
14001 EVT VT = Op.getValueType();
14002 SDValue LHS = Op.getOperand(0);
14003 SDValue RHS = Op.getOperand(1);
14004
14005 SDValue LHSExt = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, LHS);
14006 SDValue RHSExt = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, RHS);
14007
14008 if (VT == MVT::bf16) {
14009 SDValue ExtDiv =
14010 DAG.getNode(ISD::FDIV, SL, MVT::f32, LHSExt, RHSExt, Op->getFlags());
14011 return DAG.getNode(ISD::FP_ROUND, SL, MVT::bf16, ExtDiv,
14012 DAG.getTargetConstant(0, SL, MVT::i32));
14013 }
14014
14015 assert(VT == MVT::f16);
14016
14017 // a32.u = opx(V_CVT_F32_F16, a.u); // CVT to F32
14018 // b32.u = opx(V_CVT_F32_F16, b.u); // CVT to F32
14019 // r32.u = opx(V_RCP_F32, b32.u); // rcp = 1 / d
14020 // q32.u = opx(V_MUL_F32, a32.u, r32.u); // q = n * rcp
14021 // e32.u = opx(V_MAD_F32, (b32.u^_neg32), q32.u, a32.u); // err = -d * q + n
14022 // q32.u = opx(V_MAD_F32, e32.u, r32.u, q32.u); // q = n * rcp
14023 // e32.u = opx(V_MAD_F32, (b32.u^_neg32), q32.u, a32.u); // err = -d * q + n
14024 // tmp.u = opx(V_MUL_F32, e32.u, r32.u);
14025 // tmp.u = opx(V_AND_B32, tmp.u, 0xff800000)
14026 // q32.u = opx(V_ADD_F32, tmp.u, q32.u);
14027 // q16.u = opx(V_CVT_F16_F32, q32.u);
14028 // q16.u = opx(V_DIV_FIXUP_F16, q16.u, b.u, a.u); // q = touchup(q, d, n)
14029
14030 // We will use ISD::FMA on targets that don't support ISD::FMAD.
14031 unsigned FMADOpCode =
14033 SDValue NegRHSExt = DAG.getNode(ISD::FNEG, SL, MVT::f32, RHSExt);
14034 SDValue Rcp =
14035 DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, RHSExt, Op->getFlags());
14036 SDValue Quot =
14037 DAG.getNode(ISD::FMUL, SL, MVT::f32, LHSExt, Rcp, Op->getFlags());
14038 SDValue Err = DAG.getNode(FMADOpCode, SL, MVT::f32, NegRHSExt, Quot, LHSExt,
14039 Op->getFlags());
14040 Quot = DAG.getNode(FMADOpCode, SL, MVT::f32, Err, Rcp, Quot, Op->getFlags());
14041 Err = DAG.getNode(FMADOpCode, SL, MVT::f32, NegRHSExt, Quot, LHSExt,
14042 Op->getFlags());
14043 SDValue Tmp = DAG.getNode(ISD::FMUL, SL, MVT::f32, Err, Rcp, Op->getFlags());
14044 SDValue TmpCast = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Tmp);
14045 TmpCast = DAG.getNode(ISD::AND, SL, MVT::i32, TmpCast,
14046 DAG.getConstant(0xff800000, SL, MVT::i32));
14047 Tmp = DAG.getNode(ISD::BITCAST, SL, MVT::f32, TmpCast);
14048 Quot = DAG.getNode(ISD::FADD, SL, MVT::f32, Tmp, Quot, Op->getFlags());
14049 SDValue RDst = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot,
14050 DAG.getTargetConstant(0, SL, MVT::i32));
14051 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, RDst, RHS, LHS,
14052 Op->getFlags());
14053}
14054
14055// Faster 2.5 ULP division that does not support denormals.
14056SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
14057 SDNodeFlags Flags = Op->getFlags();
14058 SDLoc SL(Op);
14059 SDValue LHS = Op.getOperand(1);
14060 SDValue RHS = Op.getOperand(2);
14061
14062 // TODO: The combiner should probably handle elimination of redundant fabs.
14064 ? RHS
14065 : DAG.getNode(ISD::FABS, SL, MVT::f32, RHS, Flags);
14066
14067 const APFloat K0Val(0x1p+96f);
14068 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
14069
14070 const APFloat K1Val(0x1p-32f);
14071 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
14072
14073 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
14074
14075 EVT SetCCVT =
14076 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
14077
14078 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
14079
14080 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One, Flags);
14081
14082 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3, Flags);
14083
14084 // rcp does not support denormals.
14085 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1, Flags);
14086
14087 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0, Flags);
14088
14089 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul, Flags);
14090}
14091
14092// Returns immediate value for setting the F32 denorm mode when using the
14093// S_DENORM_MODE instruction.
14095 const SIMachineFunctionInfo *Info,
14096 const GCNSubtarget *ST) {
14097 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
14098 uint32_t DPDenormModeDefault = Info->getMode().fpDenormModeDPValue();
14099 uint32_t Mode = SPDenormMode | (DPDenormModeDefault << 2);
14100 return DAG.getTargetConstant(Mode, SDLoc(), MVT::i32);
14101}
14102
14103SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
14104 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
14105 return FastLowered;
14106
14107 // The selection matcher assumes anything with a chain selecting to a
14108 // mayRaiseFPException machine instruction. Since we're introducing a chain
14109 // here, we need to explicitly report nofpexcept for the regular fdiv
14110 // lowering.
14111 SDNodeFlags Flags = Op->getFlags();
14112 Flags.setNoFPExcept(true);
14113
14114 SDLoc SL(Op);
14115 SDValue LHS = Op.getOperand(0);
14116 SDValue RHS = Op.getOperand(1);
14117
14118 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
14119
14120 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
14121
14122 SDValue DenominatorScaled =
14123 DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, {RHS, RHS, LHS}, Flags);
14124 SDValue NumeratorScaled =
14125 DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, {LHS, RHS, LHS}, Flags);
14126
14127 // Denominator is scaled to not be denormal, so using rcp is ok.
14128 SDValue ApproxRcp =
14129 DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, DenominatorScaled, Flags);
14130 SDValue NegDivScale0 =
14131 DAG.getNode(ISD::FNEG, SL, MVT::f32, DenominatorScaled, Flags);
14132
14133 using namespace AMDGPU::Hwreg;
14134 const unsigned Denorm32Reg = HwregEncoding::encode(ID_MODE, 4, 2);
14135 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
14136
14137 const MachineFunction &MF = DAG.getMachineFunction();
14138 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
14139 const DenormalMode DenormMode = Info->getMode().FP32Denormals;
14140
14141 const bool PreservesDenormals = DenormMode == DenormalMode::getIEEE();
14142 const bool HasDynamicDenormals =
14143 (DenormMode.Input == DenormalMode::Dynamic) ||
14144 (DenormMode.Output == DenormalMode::Dynamic);
14145
14146 SDValue SavedDenormMode;
14147
14148 if (!PreservesDenormals) {
14149 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
14150 // lowering. The chain dependence is insufficient, and we need glue. We do
14151 // not need the glue variants in a strictfp function.
14152
14153 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
14154
14155 SDValue Glue = DAG.getEntryNode();
14156 if (HasDynamicDenormals) {
14157 SDNode *GetReg = DAG.getMachineNode(AMDGPU::S_GETREG_B32, SL,
14158 DAG.getVTList(MVT::i32, MVT::Glue),
14159 {BitField, Glue});
14160 SavedDenormMode = SDValue(GetReg, 0);
14161
14162 Glue = DAG.getMergeValues(
14163 {DAG.getEntryNode(), SDValue(GetReg, 0), SDValue(GetReg, 1)}, SL);
14164 }
14165
14166 SDNode *EnableDenorm;
14167 if (Subtarget->hasDenormModeInst()) {
14168 const SDValue EnableDenormValue =
14169 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, Info, Subtarget);
14170
14171 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, Glue,
14172 EnableDenormValue)
14173 .getNode();
14174 } else {
14175 const SDValue EnableDenormValue =
14176 DAG.getConstant(FP_DENORM_FLUSH_NONE, SL, MVT::i32);
14177 EnableDenorm = DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
14178 {EnableDenormValue, BitField, Glue});
14179 }
14180
14181 SDValue Ops[3] = {NegDivScale0, SDValue(EnableDenorm, 0),
14182 SDValue(EnableDenorm, 1)};
14183
14184 NegDivScale0 = DAG.getMergeValues(Ops, SL);
14185 }
14186
14187 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
14188 ApproxRcp, One, NegDivScale0, Flags);
14189
14190 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
14191 ApproxRcp, Fma0, Flags);
14192
14193 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, Fma1,
14194 Fma1, Flags);
14195
14196 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
14197 NumeratorScaled, Mul, Flags);
14198
14199 SDValue Fma3 =
14200 getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2, Flags);
14201
14202 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
14203 NumeratorScaled, Fma3, Flags);
14204
14205 if (!PreservesDenormals) {
14206 SDNode *DisableDenorm;
14207 if (!HasDynamicDenormals && Subtarget->hasDenormModeInst()) {
14208 const SDValue DisableDenormValue = getSPDenormModeValue(
14209 FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, Info, Subtarget);
14210
14211 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
14212 DisableDenorm =
14213 DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
14214 Fma4.getValue(1), DisableDenormValue, Fma4.getValue(2))
14215 .getNode();
14216 } else {
14217 assert(HasDynamicDenormals == (bool)SavedDenormMode);
14218 const SDValue DisableDenormValue =
14219 HasDynamicDenormals
14220 ? SavedDenormMode
14221 : DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
14222
14223 DisableDenorm = DAG.getMachineNode(
14224 AMDGPU::S_SETREG_B32, SL, MVT::Other,
14225 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
14226 }
14227
14228 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
14229 SDValue(DisableDenorm, 0), DAG.getRoot());
14230 DAG.setRoot(OutputChain);
14231 }
14232
14233 SDValue Scale = NumeratorScaled.getValue(1);
14234 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
14235 {Fma4, Fma1, Fma3, Scale}, Flags);
14236
14237 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
14238}
14239
14240SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
14241 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
14242 return FastLowered;
14243
14244 SDLoc SL(Op);
14245 SDValue X = Op.getOperand(0);
14246 SDValue Y = Op.getOperand(1);
14247
14248 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
14249
14250 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
14251
14252 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
14253
14254 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
14255
14256 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
14257
14258 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
14259
14260 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
14261
14262 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
14263
14264 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
14265
14266 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
14267 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
14268
14269 SDValue Fma4 =
14270 DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Mul, DivScale1);
14271
14272 SDValue Scale;
14273
14274 if (!Subtarget->hasUsableDivScaleConditionOutput()) {
14275 // Workaround a hardware bug on SI where the condition output from div_scale
14276 // is not usable.
14277
14278 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
14279
14280 // Figure out if the scale to use for div_fmas.
14281 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
14282 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
14283 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
14284 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
14285
14286 SDValue NumHi =
14287 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
14288 SDValue DenHi =
14289 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
14290
14291 SDValue Scale0Hi =
14292 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
14293 SDValue Scale1Hi =
14294 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
14295
14296 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
14297 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
14298 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
14299 } else {
14300 Scale = DivScale1.getValue(1);
14301 }
14302
14303 SDValue Fmas =
14304 DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, Fma4, Fma3, Mul, Scale);
14305
14306 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
14307}
14308
14309SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
14310 EVT VT = Op.getValueType();
14311
14312 if (VT == MVT::f32)
14313 return LowerFDIV32(Op, DAG);
14314
14315 if (VT == MVT::f64)
14316 return LowerFDIV64(Op, DAG);
14317
14318 if (VT == MVT::f16 || VT == MVT::bf16)
14319 return LowerFDIV16(Op, DAG);
14320
14321 llvm_unreachable("Unexpected type for fdiv");
14322}
14323
14324SDValue SITargetLowering::LowerFFREXP(SDValue Op, SelectionDAG &DAG) const {
14325 SDLoc dl(Op);
14326 SDValue Val = Op.getOperand(0);
14327 EVT VT = Val.getValueType();
14328 EVT ResultExpVT = Op->getValueType(1);
14329 EVT InstrExpVT = VT == MVT::f16 ? MVT::i16 : MVT::i32;
14330
14331 SDValue Mant = DAG.getNode(
14333 DAG.getTargetConstant(Intrinsic::amdgcn_frexp_mant, dl, MVT::i32), Val);
14334
14335 SDValue Exp = DAG.getNode(
14336 ISD::INTRINSIC_WO_CHAIN, dl, InstrExpVT,
14337 DAG.getTargetConstant(Intrinsic::amdgcn_frexp_exp, dl, MVT::i32), Val);
14338
14339 if (Subtarget->hasFractBug()) {
14340 SDValue Fabs = DAG.getNode(ISD::FABS, dl, VT, Val);
14341 SDValue Inf =
14343
14344 SDValue IsFinite = DAG.getSetCC(dl, MVT::i1, Fabs, Inf, ISD::SETOLT);
14345 SDValue Zero = DAG.getConstant(0, dl, InstrExpVT);
14346 Exp = DAG.getNode(ISD::SELECT, dl, InstrExpVT, IsFinite, Exp, Zero);
14347 Mant = DAG.getNode(ISD::SELECT, dl, VT, IsFinite, Mant, Val);
14348 }
14349
14350 SDValue CastExp = DAG.getSExtOrTrunc(Exp, dl, ResultExpVT);
14351 return DAG.getMergeValues({Mant, CastExp}, dl);
14352}
14353
14354SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
14355 SDLoc DL(Op);
14356 StoreSDNode *Store = cast<StoreSDNode>(Op);
14357 EVT VT = Store->getMemoryVT();
14358
14359 if (VT == MVT::i1) {
14360 return DAG.getTruncStore(
14361 Store->getChain(), DL,
14362 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
14363 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
14364 }
14365
14366 assert(VT.isVector() &&
14367 Store->getValue().getValueType().getScalarType() == MVT::i32);
14368
14369 unsigned AS = Store->getAddressSpace();
14370 if (Subtarget->hasLDSMisalignedBugInWGPMode() &&
14371 AS == AMDGPUAS::FLAT_ADDRESS &&
14372 Store->getAlign().value() < VT.getStoreSize() &&
14373 VT.getSizeInBits() > 32) {
14374 return SplitVectorStore(Op, DAG);
14375 }
14376
14378 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
14379 // If there is a possibility that flat instruction access scratch memory
14380 // then we need to use the same legalization rules we use for private.
14381 if (AS == AMDGPUAS::FLAT_ADDRESS &&
14382 !Subtarget->hasMultiDwordFlatScratchAddressing())
14383 AS = addressMayBeAccessedAsPrivate(Store->getMemOperand(), *MFI)
14386
14387 unsigned NumElements = VT.getVectorNumElements();
14389 if (NumElements > 4)
14390 return SplitVectorStore(Op, DAG);
14391 // v3 stores not supported on SI.
14392 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
14393 return SplitVectorStore(Op, DAG);
14394
14396 VT, *Store->getMemOperand()))
14397 return expandUnalignedStore(Store, DAG);
14398
14399 return SDValue();
14400 }
14401 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
14402 switch (Subtarget->getMaxPrivateElementSize()) {
14403 case 4:
14404 return scalarizeVectorStore(Store, DAG);
14405 case 8:
14406 if (NumElements > 2)
14407 return SplitVectorStore(Op, DAG);
14408 return SDValue();
14409 case 16:
14410 if (NumElements > 4 ||
14411 (NumElements == 3 && !Subtarget->hasFlatScratchEnabled()))
14412 return SplitVectorStore(Op, DAG);
14413 return SDValue();
14414 default:
14415 llvm_unreachable("unsupported private_element_size");
14416 }
14417 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
14418 unsigned Fast = 0;
14419 auto Flags = Store->getMemOperand()->getFlags();
14421 Store->getAlign(), Flags, &Fast) &&
14422 Fast > 1)
14423 return SDValue();
14424
14425 if (VT.isVector())
14426 return SplitVectorStore(Op, DAG);
14427
14428 return expandUnalignedStore(Store, DAG);
14429 }
14430
14431 // Probably an invalid store. If so we'll end up emitting a selection error.
14432 return SDValue();
14433}
14434
14435// Avoid the full correct expansion for f32 sqrt when promoting from f16.
14436SDValue SITargetLowering::lowerFSQRTF16(SDValue Op, SelectionDAG &DAG) const {
14437 SDLoc SL(Op);
14438 assert(!Subtarget->has16BitInsts());
14439 SDNodeFlags Flags = Op->getFlags();
14440 SDValue Ext =
14441 DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Op.getOperand(0), Flags);
14442
14443 SDValue SqrtID = DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, SL, MVT::i32);
14444 SDValue Sqrt =
14445 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::f32, SqrtID, Ext, Flags);
14446
14447 return DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Sqrt,
14448 DAG.getTargetConstant(0, SL, MVT::i32), Flags);
14449}
14450
14451SDValue SITargetLowering::lowerFSQRTF32(SDValue Op, SelectionDAG &DAG) const {
14452 SDLoc DL(Op);
14453 SDNodeFlags Flags = Op->getFlags();
14454 MVT VT = Op.getValueType().getSimpleVT();
14455 const SDValue X = Op.getOperand(0);
14456
14457 if (allowApproxFunc(DAG, Flags)) {
14458 // Instruction is 1ulp but ignores denormals.
14459 return DAG.getNode(
14461 DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, DL, MVT::i32), X, Flags);
14462 }
14463
14464 SDValue ScaleThreshold = DAG.getConstantFP(0x1.0p-96f, DL, VT);
14465 SDValue NeedScale = DAG.getSetCC(DL, MVT::i1, X, ScaleThreshold, ISD::SETOLT);
14466
14467 SDValue ScaleUpFactor = DAG.getConstantFP(0x1.0p+32f, DL, VT);
14468
14469 SDValue ScaledX = DAG.getNode(ISD::FMUL, DL, VT, X, ScaleUpFactor, Flags);
14470
14471 SDValue SqrtX =
14472 DAG.getNode(ISD::SELECT, DL, VT, NeedScale, ScaledX, X, Flags);
14473
14474 SDValue SqrtS;
14475 if (needsDenormHandlingF32(DAG, X, Flags)) {
14476 SDValue SqrtID =
14477 DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, DL, MVT::i32);
14478 SqrtS = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, SqrtID, SqrtX, Flags);
14479
14480 SDValue SqrtSAsInt = DAG.getNode(ISD::BITCAST, DL, MVT::i32, SqrtS);
14481 SDValue SqrtSNextDownInt =
14482 DAG.getNode(ISD::ADD, DL, MVT::i32, SqrtSAsInt,
14483 DAG.getAllOnesConstant(DL, MVT::i32));
14484 SDValue SqrtSNextDown = DAG.getNode(ISD::BITCAST, DL, VT, SqrtSNextDownInt);
14485
14486 SDValue NegSqrtSNextDown =
14487 DAG.getNode(ISD::FNEG, DL, VT, SqrtSNextDown, Flags);
14488
14489 SDValue SqrtVP =
14490 DAG.getNode(ISD::FMA, DL, VT, NegSqrtSNextDown, SqrtS, SqrtX, Flags);
14491
14492 SDValue SqrtSNextUpInt = DAG.getNode(ISD::ADD, DL, MVT::i32, SqrtSAsInt,
14493 DAG.getConstant(1, DL, MVT::i32));
14494 SDValue SqrtSNextUp = DAG.getNode(ISD::BITCAST, DL, VT, SqrtSNextUpInt);
14495
14496 SDValue NegSqrtSNextUp = DAG.getNode(ISD::FNEG, DL, VT, SqrtSNextUp, Flags);
14497 SDValue SqrtVS =
14498 DAG.getNode(ISD::FMA, DL, VT, NegSqrtSNextUp, SqrtS, SqrtX, Flags);
14499
14500 SDValue Zero = DAG.getConstantFP(0.0f, DL, VT);
14501 SDValue SqrtVPLE0 = DAG.getSetCC(DL, MVT::i1, SqrtVP, Zero, ISD::SETOLE);
14502
14503 SqrtS = DAG.getNode(ISD::SELECT, DL, VT, SqrtVPLE0, SqrtSNextDown, SqrtS,
14504 Flags);
14505
14506 SDValue SqrtVPVSGT0 = DAG.getSetCC(DL, MVT::i1, SqrtVS, Zero, ISD::SETOGT);
14507 SqrtS = DAG.getNode(ISD::SELECT, DL, VT, SqrtVPVSGT0, SqrtSNextUp, SqrtS,
14508 Flags);
14509 } else {
14510 SDValue SqrtR = DAG.getNode(AMDGPUISD::RSQ, DL, VT, SqrtX, Flags);
14511
14512 SqrtS = DAG.getNode(ISD::FMUL, DL, VT, SqrtX, SqrtR, Flags);
14513
14514 SDValue Half = DAG.getConstantFP(0.5f, DL, VT);
14515 SDValue SqrtH = DAG.getNode(ISD::FMUL, DL, VT, SqrtR, Half, Flags);
14516 SDValue NegSqrtH = DAG.getNode(ISD::FNEG, DL, VT, SqrtH, Flags);
14517
14518 SDValue SqrtE = DAG.getNode(ISD::FMA, DL, VT, NegSqrtH, SqrtS, Half, Flags);
14519 SqrtH = DAG.getNode(ISD::FMA, DL, VT, SqrtH, SqrtE, SqrtH, Flags);
14520 SqrtS = DAG.getNode(ISD::FMA, DL, VT, SqrtS, SqrtE, SqrtS, Flags);
14521
14522 SDValue NegSqrtS = DAG.getNode(ISD::FNEG, DL, VT, SqrtS, Flags);
14523 SDValue SqrtD =
14524 DAG.getNode(ISD::FMA, DL, VT, NegSqrtS, SqrtS, SqrtX, Flags);
14525 SqrtS = DAG.getNode(ISD::FMA, DL, VT, SqrtD, SqrtH, SqrtS, Flags);
14526 }
14527
14528 SDValue ScaleDownFactor = DAG.getConstantFP(0x1.0p-16f, DL, VT);
14529
14530 SDValue ScaledDown =
14531 DAG.getNode(ISD::FMUL, DL, VT, SqrtS, ScaleDownFactor, Flags);
14532
14533 SqrtS = DAG.getNode(ISD::SELECT, DL, VT, NeedScale, ScaledDown, SqrtS, Flags);
14534 SDValue IsZeroOrInf =
14535 DAG.getNode(ISD::IS_FPCLASS, DL, MVT::i1, SqrtX,
14536 DAG.getTargetConstant(fcZero | fcPosInf, DL, MVT::i32));
14537
14538 return DAG.getNode(ISD::SELECT, DL, VT, IsZeroOrInf, SqrtX, SqrtS, Flags);
14539}
14540
14541SDValue SITargetLowering::lowerFSQRTF64(SDValue Op, SelectionDAG &DAG) const {
14542 // For double type, the SQRT and RSQ instructions don't have required
14543 // precision, we apply Goldschmidt's algorithm to improve the result:
14544 //
14545 // y0 = rsq(x)
14546 // g0 = x * y0
14547 // h0 = 0.5 * y0
14548 //
14549 // r0 = 0.5 - h0 * g0
14550 // g1 = g0 * r0 + g0
14551 // h1 = h0 * r0 + h0
14552 //
14553 // r1 = 0.5 - h1 * g1 => d0 = x - g1 * g1
14554 // g2 = g1 * r1 + g1 g2 = d0 * h1 + g1
14555 // h2 = h1 * r1 + h1
14556 //
14557 // r2 = 0.5 - h2 * g2 => d1 = x - g2 * g2
14558 // g3 = g2 * r2 + g2 g3 = d1 * h1 + g2
14559 //
14560 // sqrt(x) = g3
14561
14562 SDNodeFlags Flags = Op->getFlags();
14563
14564 SDLoc DL(Op);
14565
14566 SDValue X = Op.getOperand(0);
14567 SDValue ZeroInt = DAG.getConstant(0, DL, MVT::i32);
14568
14569 SDValue SqrtX = X;
14570 SDValue Scaling;
14571 if (!Flags.hasApproximateFuncs()) {
14572 SDValue ScaleConstant = DAG.getConstantFP(0x1.0p-767, DL, MVT::f64);
14573 Scaling = DAG.getSetCC(DL, MVT::i1, X, ScaleConstant, ISD::SETOLT);
14574
14575 // Scale up input if it is too small.
14576 SDValue ScaleUpFactor = DAG.getConstant(256, DL, MVT::i32);
14577 SDValue ScaleUp =
14578 DAG.getNode(ISD::SELECT, DL, MVT::i32, Scaling, ScaleUpFactor, ZeroInt);
14579 SqrtX = DAG.getNode(ISD::FLDEXP, DL, MVT::f64, X, ScaleUp, Flags);
14580 }
14581
14582 SDValue SqrtY = DAG.getNode(AMDGPUISD::RSQ, DL, MVT::f64, SqrtX);
14583
14584 SDValue SqrtS0 = DAG.getNode(ISD::FMUL, DL, MVT::f64, SqrtX, SqrtY);
14585
14586 SDValue Half = DAG.getConstantFP(0.5, DL, MVT::f64);
14587 SDValue SqrtH0 = DAG.getNode(ISD::FMUL, DL, MVT::f64, SqrtY, Half);
14588
14589 SDValue NegSqrtH0 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtH0);
14590 SDValue SqrtR0 = DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtH0, SqrtS0, Half);
14591
14592 SDValue SqrtH1 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtH0, SqrtR0, SqrtH0);
14593
14594 SDValue SqrtS1 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtS0, SqrtR0, SqrtS0);
14595
14596 SDValue NegSqrtS1 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtS1);
14597 SDValue SqrtD0 =
14598 DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtS1, SqrtS1, SqrtX);
14599
14600 SDValue SqrtS2 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtD0, SqrtH1, SqrtS1);
14601
14602 SDValue SqrtRet = SqrtS2;
14603 if (!Flags.hasApproximateFuncs()) {
14604 SDValue NegSqrtS2 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtS2);
14605 SDValue SqrtD1 =
14606 DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtS2, SqrtS2, SqrtX);
14607
14608 SqrtRet = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtD1, SqrtH1, SqrtS2);
14609
14610 SDValue ScaleDownFactor = DAG.getSignedConstant(-128, DL, MVT::i32);
14611 SDValue ScaleDown = DAG.getNode(ISD::SELECT, DL, MVT::i32, Scaling,
14612 ScaleDownFactor, ZeroInt);
14613 SqrtRet = DAG.getNode(ISD::FLDEXP, DL, MVT::f64, SqrtRet, ScaleDown, Flags);
14614 }
14615
14616 // TODO: Check for DAZ and expand to subnormals
14617
14618 SDValue IsZeroOrInf;
14619 if (Flags.hasNoInfs()) {
14620 SDValue Zero = DAG.getConstantFP(0.0, DL, MVT::f64);
14621 IsZeroOrInf = DAG.getSetCC(DL, MVT::i1, SqrtX, Zero, ISD::SETOEQ);
14622 } else {
14623 IsZeroOrInf =
14624 DAG.getNode(ISD::IS_FPCLASS, DL, MVT::i1, SqrtX,
14625 DAG.getTargetConstant(fcZero | fcPosInf, DL, MVT::i32));
14626 }
14627
14628 // If x is +INF, +0, or -0, use its original value
14629 return DAG.getNode(ISD::SELECT, DL, MVT::f64, IsZeroOrInf, SqrtX, SqrtRet,
14630 Flags);
14631}
14632
14633SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
14634 SDLoc DL(Op);
14635 EVT VT = Op.getValueType();
14636 SDValue Arg = Op.getOperand(0);
14637 SDValue TrigVal;
14638
14639 // Propagate fast-math flags so that the multiply we introduce can be folded
14640 // if Arg is already the result of a multiply by constant.
14641 auto Flags = Op->getFlags();
14642
14643 // AMDGPUISD nodes of vector type must be unrolled here since
14644 // they will not be expanded elsewhere.
14645 auto UnrollIfVec = [&DAG](SDValue V) -> SDValue {
14646 if (!V.getValueType().isVector())
14647 return V;
14648
14649 return DAG.UnrollVectorOp(cast<SDNode>(V));
14650 };
14651
14652 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
14653
14654 if (Subtarget->hasTrigReducedRange()) {
14655 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
14656 TrigVal = UnrollIfVec(DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags));
14657 } else {
14658 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
14659 }
14660
14661 switch (Op.getOpcode()) {
14662 case ISD::FCOS:
14663 TrigVal = DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
14664 break;
14665 case ISD::FSIN:
14666 TrigVal = DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
14667 break;
14668 default:
14669 llvm_unreachable("Wrong trig opcode");
14670 }
14671
14672 return UnrollIfVec(TrigVal);
14673}
14674
14675SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
14676 SelectionDAG &DAG) const {
14677 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
14678 assert(AtomicNode->isCompareAndSwap());
14679 unsigned AS = AtomicNode->getAddressSpace();
14680
14681 // No custom lowering required for local address space
14683 return Op;
14684
14685 // Non-local address space requires custom lowering for atomic compare
14686 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
14687 SDLoc DL(Op);
14688 SDValue ChainIn = Op.getOperand(0);
14689 SDValue Addr = Op.getOperand(1);
14690 SDValue Old = Op.getOperand(2);
14691 SDValue New = Op.getOperand(3);
14692 EVT VT = Op.getValueType();
14693 MVT SimpleVT = VT.getSimpleVT();
14694 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
14695
14696 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
14697 SDValue Ops[] = {ChainIn, Addr, NewOld};
14698
14699 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL,
14700 Op->getVTList(), Ops, VT,
14701 AtomicNode->getMemOperand());
14702}
14703
14704//===----------------------------------------------------------------------===//
14705// Custom DAG optimizations
14706//===----------------------------------------------------------------------===//
14707
14708SDValue
14709SITargetLowering::performUCharToFloatCombine(SDNode *N,
14710 DAGCombinerInfo &DCI) const {
14711 EVT VT = N->getValueType(0);
14712 EVT ScalarVT = VT.getScalarType();
14713 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
14714 return SDValue();
14715
14716 SelectionDAG &DAG = DCI.DAG;
14717 SDLoc DL(N);
14718
14719 SDValue Src = N->getOperand(0);
14720 EVT SrcVT = Src.getValueType();
14721
14722 // TODO: We could try to match extracting the higher bytes, which would be
14723 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
14724 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
14725 // about in practice.
14726 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
14727 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
14728 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
14729 DCI.AddToWorklist(Cvt.getNode());
14730
14731 // For the f16 case, fold to a cast to f32 and then cast back to f16.
14732 if (ScalarVT != MVT::f32) {
14733 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
14734 DAG.getTargetConstant(0, DL, MVT::i32));
14735 }
14736 return Cvt;
14737 }
14738 }
14739
14740 return SDValue();
14741}
14742
14743SDValue SITargetLowering::performFCopySignCombine(SDNode *N,
14744 DAGCombinerInfo &DCI) const {
14745 SDValue MagnitudeOp = N->getOperand(0);
14746 SDValue SignOp = N->getOperand(1);
14747
14748 // The generic combine for fcopysign + fp cast is too conservative with
14749 // vectors, and also gets confused by the splitting we will perform here, so
14750 // peek through FP casts.
14751 if (SignOp.getOpcode() == ISD::FP_EXTEND ||
14752 SignOp.getOpcode() == ISD::FP_ROUND)
14753 SignOp = SignOp.getOperand(0);
14754
14755 SelectionDAG &DAG = DCI.DAG;
14756 SDLoc DL(N);
14757 EVT SignVT = SignOp.getValueType();
14758
14759 // f64 fcopysign is really an f32 copysign on the high bits, so replace the
14760 // lower half with a copy.
14761 // fcopysign f64:x, _:y -> x.lo32, (fcopysign (f32 x.hi32), _:y)
14762 EVT MagVT = MagnitudeOp.getValueType();
14763
14764 unsigned NumElts = MagVT.isVector() ? MagVT.getVectorNumElements() : 1;
14765
14766 if (MagVT.getScalarType() == MVT::f64) {
14767 EVT F32VT = MagVT.isVector()
14768 ? EVT::getVectorVT(*DAG.getContext(), MVT::f32, 2 * NumElts)
14769 : MVT::v2f32;
14770
14771 SDValue MagAsVector = DAG.getNode(ISD::BITCAST, DL, F32VT, MagnitudeOp);
14772
14774 for (unsigned I = 0; I != NumElts; ++I) {
14775 SDValue MagLo =
14776 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, MagAsVector,
14777 DAG.getConstant(2 * I, DL, MVT::i32));
14778 SDValue MagHi =
14779 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, MagAsVector,
14780 DAG.getConstant(2 * I + 1, DL, MVT::i32));
14781
14782 SDValue SignOpElt =
14783 MagVT.isVector()
14785 SignOp, DAG.getConstant(I, DL, MVT::i32))
14786 : SignOp;
14787
14788 SDValue HiOp =
14789 DAG.getNode(ISD::FCOPYSIGN, DL, MVT::f32, MagHi, SignOpElt);
14790
14791 SDValue Vector =
14792 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2f32, MagLo, HiOp);
14793
14794 SDValue NewElt = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Vector);
14795 NewElts.push_back(NewElt);
14796 }
14797
14798 if (NewElts.size() == 1)
14799 return NewElts[0];
14800
14801 return DAG.getNode(ISD::BUILD_VECTOR, DL, MagVT, NewElts);
14802 }
14803
14804 if (SignVT.getScalarType() != MVT::f64)
14805 return SDValue();
14806
14807 // Reduce width of sign operand, we only need the highest bit.
14808 //
14809 // fcopysign f64:x, f64:y ->
14810 // fcopysign f64:x, (extract_vector_elt (bitcast f64:y to v2f32), 1)
14811 // TODO: In some cases it might make sense to go all the way to f16.
14812
14813 EVT F32VT = MagVT.isVector()
14814 ? EVT::getVectorVT(*DAG.getContext(), MVT::f32, 2 * NumElts)
14815 : MVT::v2f32;
14816
14817 SDValue SignAsVector = DAG.getNode(ISD::BITCAST, DL, F32VT, SignOp);
14818
14819 SmallVector<SDValue, 8> F32Signs;
14820 for (unsigned I = 0; I != NumElts; ++I) {
14821 // Take sign from odd elements of cast vector
14822 SDValue SignAsF32 =
14823 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, SignAsVector,
14824 DAG.getConstant(2 * I + 1, DL, MVT::i32));
14825 F32Signs.push_back(SignAsF32);
14826 }
14827
14828 SDValue NewSign =
14829 NumElts == 1
14830 ? F32Signs.back()
14832 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumElts),
14833 F32Signs);
14834
14835 return DAG.getNode(ISD::FCOPYSIGN, DL, N->getValueType(0), N->getOperand(0),
14836 NewSign);
14837}
14838
14839// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
14840// (shl (or x, c1), c2) -> add (shl x, c2), (shl c1, c2) iff x and c1 share no
14841// bits
14842
14843// This is a variant of
14844// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
14845//
14846// The normal DAG combiner will do this, but only if the add has one use since
14847// that would increase the number of instructions.
14848//
14849// This prevents us from seeing a constant offset that can be folded into a
14850// memory instruction's addressing mode. If we know the resulting add offset of
14851// a pointer can be folded into an addressing offset, we can replace the pointer
14852// operand with the add of new constant offset. This eliminates one of the uses,
14853// and may allow the remaining use to also be simplified.
14854//
14855SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, unsigned AddrSpace,
14856 EVT MemVT,
14857 DAGCombinerInfo &DCI) const {
14858 SDValue N0 = N->getOperand(0);
14859 SDValue N1 = N->getOperand(1);
14860
14861 // We only do this to handle cases where it's profitable when there are
14862 // multiple uses of the add, so defer to the standard combine.
14863 if ((!N0->isAnyAdd() && N0.getOpcode() != ISD::OR) || N0->hasOneUse())
14864 return SDValue();
14865
14866 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
14867 if (!CN1)
14868 return SDValue();
14869
14870 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14871 if (!CAdd)
14872 return SDValue();
14873
14874 SelectionDAG &DAG = DCI.DAG;
14875
14876 if (N0->getOpcode() == ISD::OR &&
14877 !DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1)))
14878 return SDValue();
14879
14880 // If the resulting offset is too large, we can't fold it into the
14881 // addressing mode offset.
14882 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
14883 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
14884
14885 AddrMode AM;
14886 AM.HasBaseReg = true;
14887 AM.BaseOffs = Offset.getSExtValue();
14888 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
14889 return SDValue();
14890
14891 SDLoc SL(N);
14892 EVT VT = N->getValueType(0);
14893
14894 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
14895 SDValue COffset = DAG.getConstant(Offset, SL, VT);
14896
14897 SDNodeFlags Flags;
14898 Flags.setNoUnsignedWrap(
14899 N->getFlags().hasNoUnsignedWrap() &&
14900 (N0.getOpcode() == ISD::OR || N0->getFlags().hasNoUnsignedWrap()));
14901
14902 // Use ISD::ADD even if the original operation was ISD::PTRADD, since we can't
14903 // be sure that the new left operand is a proper base pointer.
14904 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
14905}
14906
14907/// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
14908/// by the chain and intrinsic ID. Theoretically we would also need to check the
14909/// specific intrinsic, but they all place the pointer operand first.
14910static unsigned getBasePtrIndex(const MemSDNode *N) {
14911 switch (N->getOpcode()) {
14912 case ISD::STORE:
14915 return 2;
14916 default:
14917 return 1;
14918 }
14919}
14920
14921SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
14922 DAGCombinerInfo &DCI) const {
14923 SelectionDAG &DAG = DCI.DAG;
14924
14925 unsigned PtrIdx = getBasePtrIndex(N);
14926 SDValue Ptr = N->getOperand(PtrIdx);
14927
14928 // TODO: We could also do this for multiplies.
14929 if (Ptr.getOpcode() == ISD::SHL) {
14930 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
14931 N->getMemoryVT(), DCI);
14932 if (NewPtr) {
14933 SmallVector<SDValue, 8> NewOps(N->ops());
14934
14935 NewOps[PtrIdx] = NewPtr;
14936 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
14937 }
14938 }
14939
14940 return SDValue();
14941}
14942
14943static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
14944 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
14945 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
14946 (Opc == ISD::XOR && Val == 0);
14947}
14948
14949// Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
14950// will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
14951// integer combine opportunities since most 64-bit operations are decomposed
14952// this way. TODO: We won't want this for SALU especially if it is an inline
14953// immediate.
14954SDValue SITargetLowering::splitBinaryBitConstantOp(
14955 DAGCombinerInfo &DCI, const SDLoc &SL, unsigned Opc, SDValue LHS,
14956 const ConstantSDNode *CRHS) const {
14957 uint64_t Val = CRHS->getZExtValue();
14958 uint32_t ValLo = Lo_32(Val);
14959 uint32_t ValHi = Hi_32(Val);
14960 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
14961
14962 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
14964 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
14965 // We have 64-bit scalar and/or/xor, but do not have vector forms.
14966 if (Subtarget->has64BitLiterals() && CRHS->hasOneUse() &&
14967 !CRHS->user_begin()->isDivergent())
14968 return SDValue();
14969
14970 // If we need to materialize a 64-bit immediate, it will be split up later
14971 // anyway. Avoid creating the harder to understand 64-bit immediate
14972 // materialization.
14973 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
14974 }
14975
14976 return SDValue();
14977}
14978
14980 if (V.getValueType() != MVT::i1)
14981 return false;
14982 switch (V.getOpcode()) {
14983 default:
14984 break;
14985 case ISD::SETCC:
14986 case ISD::IS_FPCLASS:
14987 case AMDGPUISD::FP_CLASS:
14988 return true;
14989 case ISD::AND:
14990 case ISD::OR:
14991 case ISD::XOR:
14992 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
14993 case ISD::SADDO:
14994 case ISD::UADDO:
14995 case ISD::SSUBO:
14996 case ISD::USUBO:
14997 case ISD::SMULO:
14998 case ISD::UMULO:
14999 return V.getResNo() == 1;
15001 unsigned IntrinsicID = V.getConstantOperandVal(0);
15002 switch (IntrinsicID) {
15003 case Intrinsic::amdgcn_is_shared:
15004 case Intrinsic::amdgcn_is_private:
15005 return true;
15006 default:
15007 return false;
15008 }
15009
15010 return false;
15011 }
15012 }
15013 return false;
15014}
15015
15016// If a constant has all zeroes or all ones within each byte return it.
15017// Otherwise return 0.
15019 // 0xff for any zero byte in the mask
15020 uint32_t ZeroByteMask = 0;
15021 if (!(C & 0x000000ff))
15022 ZeroByteMask |= 0x000000ff;
15023 if (!(C & 0x0000ff00))
15024 ZeroByteMask |= 0x0000ff00;
15025 if (!(C & 0x00ff0000))
15026 ZeroByteMask |= 0x00ff0000;
15027 if (!(C & 0xff000000))
15028 ZeroByteMask |= 0xff000000;
15029 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
15030 if ((NonZeroByteMask & C) != NonZeroByteMask)
15031 return 0; // Partial bytes selected.
15032 return C;
15033}
15034
15035// Check if a node selects whole bytes from its operand 0 starting at a byte
15036// boundary while masking the rest. Returns select mask as in the v_perm_b32
15037// or -1 if not succeeded.
15038// Note byte select encoding:
15039// value 0-3 selects corresponding source byte;
15040// value 0xc selects zero;
15041// value 0xff selects 0xff.
15043 assert(V.getValueSizeInBits() == 32);
15044
15045 if (V.getNumOperands() != 2)
15046 return ~0;
15047
15048 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
15049 if (!N1)
15050 return ~0;
15051
15052 uint32_t C = N1->getZExtValue();
15053
15054 switch (V.getOpcode()) {
15055 default:
15056 break;
15057 case ISD::AND:
15058 if (uint32_t ConstMask = getConstantPermuteMask(C))
15059 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
15060 break;
15061
15062 case ISD::OR:
15063 if (uint32_t ConstMask = getConstantPermuteMask(C))
15064 return (0x03020100 & ~ConstMask) | ConstMask;
15065 break;
15066
15067 case ISD::SHL:
15068 if (C % 8)
15069 return ~0;
15070
15071 return uint32_t((0x030201000c0c0c0cull << C) >> 32);
15072
15073 case ISD::SRL:
15074 if (C % 8)
15075 return ~0;
15076
15077 return uint32_t(0x0c0c0c0c03020100ull >> C);
15078 }
15079
15080 return ~0;
15081}
15082
15083SDValue SITargetLowering::performAndCombine(SDNode *N,
15084 DAGCombinerInfo &DCI) const {
15085 if (DCI.isBeforeLegalize())
15086 return SDValue();
15087
15088 SelectionDAG &DAG = DCI.DAG;
15089 EVT VT = N->getValueType(0);
15090 SDValue LHS = N->getOperand(0);
15091 SDValue RHS = N->getOperand(1);
15092
15093 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
15094 if (VT == MVT::i64 && CRHS) {
15095 if (SDValue Split =
15096 splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
15097 return Split;
15098 }
15099
15100 if (CRHS && VT == MVT::i32) {
15101 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
15102 // nb = number of trailing zeroes in mask
15103 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
15104 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
15105 uint64_t Mask = CRHS->getZExtValue();
15106 unsigned Bits = llvm::popcount(Mask);
15107 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
15108 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
15109 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
15110 unsigned Shift = CShift->getZExtValue();
15111 unsigned NB = CRHS->getAPIntValue().countr_zero();
15112 unsigned Offset = NB + Shift;
15113 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
15114 SDLoc SL(N);
15115 SDValue BFE =
15116 DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, LHS->getOperand(0),
15117 DAG.getConstant(Offset, SL, MVT::i32),
15118 DAG.getConstant(Bits, SL, MVT::i32));
15119 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
15120 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
15121 DAG.getValueType(NarrowVT));
15122 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
15123 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
15124 return Shl;
15125 }
15126 }
15127 }
15128
15129 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
15130 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
15131 isa<ConstantSDNode>(LHS.getOperand(2))) {
15132 uint32_t Sel = getConstantPermuteMask(Mask);
15133 if (!Sel)
15134 return SDValue();
15135
15136 // Select 0xc for all zero bytes
15137 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
15138 SDLoc DL(N);
15139 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15140 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
15141 }
15142 }
15143
15144 // and (trunc (srl x, c)), mask => srl (trunc x), c
15145 // if mask keeps exactly the bits that srl leaves in the low half
15146 if (CRHS && VT == MVT::i16 && LHS.getOpcode() == ISD::TRUNCATE &&
15147 LHS.hasOneUse() && LHS.getOperand(0).getOpcode() == ISD::SRL) {
15148 auto *Shift = dyn_cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1));
15149 if (Shift && Shift->getZExtValue() < 16 &&
15150 CRHS->getAPIntValue().isMask(16 - Shift->getZExtValue())) {
15151 SDLoc SL(N);
15152 SDValue Trunc =
15153 DAG.getNode(ISD::TRUNCATE, SL, VT, LHS.getOperand(0).getOperand(0));
15154 return DAG.getNode(
15155 ISD::SRL, SL, VT, Trunc,
15156 DAG.getShiftAmountConstant(Shift->getZExtValue(), VT, SL));
15157 }
15158 }
15159
15160 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
15161 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
15162 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
15163 ISD::CondCode LCC = LHS.getOperandCondCode(2);
15164 ISD::CondCode RCC = RHS.getOperandCondCode(2);
15165
15166 SDValue X = LHS.getOperand(0);
15167 SDValue Y = RHS.getOperand(0);
15168 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X ||
15169 !isTypeLegal(X.getValueType()))
15170 return SDValue();
15171
15172 if (LCC == ISD::SETO) {
15173 if (X != LHS.getOperand(1))
15174 return SDValue();
15175
15176 if (RCC == ISD::SETUNE) {
15177 const ConstantFPSDNode *C1 =
15178 dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
15179 if (!C1 || !C1->isInfinity() || C1->isNegative())
15180 return SDValue();
15181
15182 const uint32_t Mask = SIInstrFlags::N_NORMAL |
15186
15187 static_assert(
15190 0x3ff) == Mask,
15191 "mask not equal");
15192
15193 SDLoc DL(N);
15194 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, X,
15195 DAG.getConstant(Mask, DL, MVT::i32));
15196 }
15197 }
15198 }
15199
15200 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
15201 std::swap(LHS, RHS);
15202
15203 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
15204 RHS.hasOneUse()) {
15205 ISD::CondCode LCC = LHS.getOperandCondCode(2);
15206 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan |
15207 // n_nan) and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan
15208 // | n_nan)
15209 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
15210 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
15211 (RHS.getOperand(0) == LHS.getOperand(0) &&
15212 LHS.getOperand(0) == LHS.getOperand(1))) {
15213 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
15214 unsigned NewMask = LCC == ISD::SETO ? Mask->getZExtValue() & ~OrdMask
15215 : Mask->getZExtValue() & OrdMask;
15216
15217 SDLoc DL(N);
15218 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
15219 DAG.getConstant(NewMask, DL, MVT::i32));
15220 }
15221 }
15222
15223 if (VT == MVT::i32 && (RHS.getOpcode() == ISD::SIGN_EXTEND ||
15224 LHS.getOpcode() == ISD::SIGN_EXTEND)) {
15225 // and x, (sext cc from i1) => select cc, x, 0
15226 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
15227 std::swap(LHS, RHS);
15228 if (isBoolSGPR(RHS.getOperand(0)))
15229 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), LHS,
15230 DAG.getConstant(0, SDLoc(N), MVT::i32));
15231 }
15232
15233 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
15234 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
15235 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
15236 TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
15237 uint32_t LHSMask = getPermuteMask(LHS);
15238 uint32_t RHSMask = getPermuteMask(RHS);
15239 if (LHSMask != ~0u && RHSMask != ~0u) {
15240 // Canonicalize the expression in an attempt to have fewer unique masks
15241 // and therefore fewer registers used to hold the masks.
15242 if (LHSMask > RHSMask) {
15243 std::swap(LHSMask, RHSMask);
15244 std::swap(LHS, RHS);
15245 }
15246
15247 // Select 0xc for each lane used from source operand. Zero has 0xc mask
15248 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
15249 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15250 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15251
15252 // Check of we need to combine values from two sources within a byte.
15253 if (!(LHSUsedLanes & RHSUsedLanes) &&
15254 // If we select high and lower word keep it for SDWA.
15255 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
15256 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
15257 // Each byte in each mask is either selector mask 0-3, or has higher
15258 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
15259 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
15260 // mask which is not 0xff wins. By anding both masks we have a correct
15261 // result except that 0x0c shall be corrected to give 0x0c only.
15262 uint32_t Mask = LHSMask & RHSMask;
15263 for (unsigned I = 0; I < 32; I += 8) {
15264 uint32_t ByteSel = 0xff << I;
15265 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
15266 Mask &= (0x0c << I) & 0xffffffff;
15267 }
15268
15269 // Add 4 to each active LHS lane. It will not affect any existing 0xff
15270 // or 0x0c.
15271 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
15272 SDLoc DL(N);
15273
15274 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15275 RHS.getOperand(0),
15276 DAG.getConstant(Sel, DL, MVT::i32));
15277 }
15278 }
15279 }
15280
15281 return SDValue();
15282}
15283
15284// A key component of v_perm is a mapping between byte position of the src
15285// operands, and the byte position of the dest. To provide such, we need: 1. the
15286// node that provides x byte of the dest of the OR, and 2. the byte of the node
15287// used to provide that x byte. calculateByteProvider finds which node provides
15288// a certain byte of the dest of the OR, and calculateSrcByte takes that node,
15289// and finds an ultimate src and byte position For example: The supported
15290// LoadCombine pattern for vector loads is as follows
15291// t1
15292// or
15293// / \
15294// t2 t3
15295// zext shl
15296// | | \
15297// t4 t5 16
15298// or anyext
15299// / \ |
15300// t6 t7 t8
15301// srl shl or
15302// / | / \ / \
15303// t9 t10 t11 t12 t13 t14
15304// trunc* 8 trunc* 8 and and
15305// | | / | | \
15306// t15 t16 t17 t18 t19 t20
15307// trunc* 255 srl -256
15308// | / \
15309// t15 t15 16
15310//
15311// *In this example, the truncs are from i32->i16
15312//
15313// calculateByteProvider would find t6, t7, t13, and t14 for bytes 0-3
15314// respectively. calculateSrcByte would find (given node) -> ultimate src &
15315// byteposition: t6 -> t15 & 1, t7 -> t16 & 0, t13 -> t15 & 0, t14 -> t15 & 3.
15316// After finding the mapping, we can combine the tree into vperm t15, t16,
15317// 0x05000407
15318
15319// Find the source and byte position from a node.
15320// \p DestByte is the byte position of the dest of the or that the src
15321// ultimately provides. \p SrcIndex is the byte of the src that maps to this
15322// dest of the or byte. \p Depth tracks how many recursive iterations we have
15323// performed.
15324static const std::optional<ByteProvider<SDValue>>
15325calculateSrcByte(const SDValue Op, uint64_t DestByte, uint64_t SrcIndex = 0,
15326 unsigned Depth = 0) {
15327 // We may need to recursively traverse a series of SRLs
15328 if (Depth >= 6)
15329 return std::nullopt;
15330
15331 if (Op.getValueSizeInBits() < 8)
15332 return std::nullopt;
15333
15334 if (Op.getValueType().isVector())
15335 return ByteProvider<SDValue>::getSrc(Op, DestByte, SrcIndex);
15336
15337 switch (Op->getOpcode()) {
15338 case ISD::TRUNCATE: {
15339 return calculateSrcByte(Op->getOperand(0), DestByte, SrcIndex, Depth + 1);
15340 }
15341
15342 case ISD::ANY_EXTEND:
15343 case ISD::SIGN_EXTEND:
15344 case ISD::ZERO_EXTEND:
15346 SDValue NarrowOp = Op->getOperand(0);
15347 auto NarrowVT = NarrowOp.getValueType();
15348 if (Op->getOpcode() == ISD::SIGN_EXTEND_INREG) {
15349 auto *VTSign = cast<VTSDNode>(Op->getOperand(1));
15350 NarrowVT = VTSign->getVT();
15351 }
15352 if (!NarrowVT.isByteSized())
15353 return std::nullopt;
15354 uint64_t NarrowByteWidth = NarrowVT.getStoreSize();
15355
15356 if (SrcIndex >= NarrowByteWidth)
15357 return std::nullopt;
15358 return calculateSrcByte(Op->getOperand(0), DestByte, SrcIndex, Depth + 1);
15359 }
15360
15361 case ISD::SRA:
15362 case ISD::SRL: {
15363 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15364 if (!ShiftOp)
15365 return std::nullopt;
15366
15367 uint64_t BitShift = ShiftOp->getZExtValue();
15368
15369 if (BitShift % 8 != 0)
15370 return std::nullopt;
15371
15372 uint64_t NewSrcIndex = SrcIndex + BitShift / 8;
15373 if (NewSrcIndex >= Op.getScalarValueSizeInBits() / 8)
15374 return std::nullopt;
15375
15376 return calculateSrcByte(Op->getOperand(0), DestByte, NewSrcIndex,
15377 Depth + 1);
15378 }
15379
15380 default: {
15381 return ByteProvider<SDValue>::getSrc(Op, DestByte, SrcIndex);
15382 }
15383 }
15384 llvm_unreachable("fully handled switch");
15385}
15386
15387// For a byte position in the result of an Or, traverse the tree and find the
15388// node (and the byte of the node) which ultimately provides this {Or,
15389// BytePosition}. \p Op is the operand we are currently examining. \p Index is
15390// the byte position of the Op that corresponds with the originally requested
15391// byte of the Or \p Depth tracks how many recursive iterations we have
15392// performed. \p StartingIndex is the originally requested byte of the Or
15393static const std::optional<ByteProvider<SDValue>>
15394calculateByteProvider(const SDValue &Op, unsigned Index, unsigned Depth,
15395 unsigned StartingIndex = 0) {
15396 // Finding Src tree of RHS of or typically requires at least 1 additional
15397 // depth
15398 if (Depth > 6)
15399 return std::nullopt;
15400
15401 unsigned BitWidth = Op.getScalarValueSizeInBits();
15402 if (BitWidth % 8 != 0)
15403 return std::nullopt;
15404 if (Index > BitWidth / 8 - 1)
15405 return std::nullopt;
15406
15407 bool IsVec = Op.getValueType().isVector();
15408 switch (Op.getOpcode()) {
15409 case ISD::OR: {
15410 if (IsVec)
15411 return std::nullopt;
15412
15413 auto RHS = calculateByteProvider(Op.getOperand(1), Index, Depth + 1,
15414 StartingIndex);
15415 if (!RHS)
15416 return std::nullopt;
15417 auto LHS = calculateByteProvider(Op.getOperand(0), Index, Depth + 1,
15418 StartingIndex);
15419 if (!LHS)
15420 return std::nullopt;
15421 // A well formed Or will have two ByteProviders for each byte, one of which
15422 // is constant zero
15423 if (!LHS->isConstantZero() && !RHS->isConstantZero())
15424 return std::nullopt;
15425 if (!LHS || LHS->isConstantZero())
15426 return RHS;
15427 if (!RHS || RHS->isConstantZero())
15428 return LHS;
15429 return std::nullopt;
15430 }
15431
15432 case ISD::AND: {
15433 if (IsVec)
15434 return std::nullopt;
15435
15436 auto *BitMaskOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15437 if (!BitMaskOp)
15438 return std::nullopt;
15439
15440 uint32_t BitMask = BitMaskOp->getZExtValue();
15441 // Bits we expect for our StartingIndex
15442 uint32_t IndexMask = 0xFF << (Index * 8);
15443
15444 if ((IndexMask & BitMask) != IndexMask) {
15445 // If the result of the and partially provides the byte, then it
15446 // is not well formatted
15447 if (IndexMask & BitMask)
15448 return std::nullopt;
15450 }
15451
15452 return calculateSrcByte(Op->getOperand(0), StartingIndex, Index);
15453 }
15454
15455 case ISD::FSHR: {
15456 if (IsVec)
15457 return std::nullopt;
15458
15459 // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
15460 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(2));
15461 if (!ShiftOp || Op.getValueType().isVector())
15462 return std::nullopt;
15463
15464 uint64_t BitsProvided = Op.getValueSizeInBits();
15465 if (BitsProvided % 8 != 0)
15466 return std::nullopt;
15467
15468 uint64_t BitShift = ShiftOp->getAPIntValue().urem(BitsProvided);
15469 if (BitShift % 8)
15470 return std::nullopt;
15471
15472 uint64_t ConcatSizeInBytes = BitsProvided / 4;
15473 uint64_t ByteShift = BitShift / 8;
15474
15475 uint64_t NewIndex = (Index + ByteShift) % ConcatSizeInBytes;
15476 uint64_t BytesProvided = BitsProvided / 8;
15477 SDValue NextOp = Op.getOperand(NewIndex >= BytesProvided ? 0 : 1);
15478 NewIndex %= BytesProvided;
15479 return calculateByteProvider(NextOp, NewIndex, Depth + 1, StartingIndex);
15480 }
15481
15482 case ISD::SRA:
15483 case ISD::SRL: {
15484 if (IsVec)
15485 return std::nullopt;
15486
15487 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15488 if (!ShiftOp)
15489 return std::nullopt;
15490
15491 uint64_t BitShift = ShiftOp->getZExtValue();
15492 if (BitShift % 8)
15493 return std::nullopt;
15494
15495 auto BitsProvided = Op.getScalarValueSizeInBits();
15496 if (BitsProvided % 8 != 0)
15497 return std::nullopt;
15498
15499 uint64_t BytesProvided = BitsProvided / 8;
15500 uint64_t ByteShift = BitShift / 8;
15501 if (Index + ByteShift < BytesProvided)
15502 return calculateSrcByte(Op->getOperand(0), StartingIndex,
15503 Index + ByteShift);
15504 // SRA's out-of-range bytes are sign bits, not constant zero.
15505 if (Op.getOpcode() == ISD::SRA)
15506 return std::nullopt;
15508 }
15509
15510 case ISD::SHL: {
15511 if (IsVec)
15512 return std::nullopt;
15513
15514 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15515 if (!ShiftOp)
15516 return std::nullopt;
15517
15518 uint64_t BitShift = ShiftOp->getZExtValue();
15519 if (BitShift % 8 != 0)
15520 return std::nullopt;
15521 uint64_t ByteShift = BitShift / 8;
15522
15523 // If we are shifting by an amount greater than (or equal to)
15524 // the index we are trying to provide, then it provides 0s. If not,
15525 // then this bytes are not definitively 0s, and the corresponding byte
15526 // of interest is Index - ByteShift of the src
15527 return Index < ByteShift
15529 : calculateByteProvider(Op.getOperand(0), Index - ByteShift,
15530 Depth + 1, StartingIndex);
15531 }
15532 case ISD::ANY_EXTEND:
15533 case ISD::SIGN_EXTEND:
15534 case ISD::ZERO_EXTEND:
15536 case ISD::AssertZext:
15537 case ISD::AssertSext: {
15538 if (IsVec)
15539 return std::nullopt;
15540
15541 SDValue NarrowOp = Op->getOperand(0);
15542 unsigned NarrowBitWidth = NarrowOp.getValueSizeInBits();
15543 if (Op->getOpcode() == ISD::SIGN_EXTEND_INREG ||
15544 Op->getOpcode() == ISD::AssertZext ||
15545 Op->getOpcode() == ISD::AssertSext) {
15546 auto *VTSign = cast<VTSDNode>(Op->getOperand(1));
15547 NarrowBitWidth = VTSign->getVT().getSizeInBits();
15548 }
15549 if (NarrowBitWidth % 8 != 0)
15550 return std::nullopt;
15551 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
15552
15553 if (Index >= NarrowByteWidth)
15554 return Op.getOpcode() == ISD::ZERO_EXTEND
15555 ? std::optional<ByteProvider<SDValue>>(
15557 : std::nullopt;
15558 return calculateByteProvider(NarrowOp, Index, Depth + 1, StartingIndex);
15559 }
15560
15561 case ISD::TRUNCATE: {
15562 if (IsVec)
15563 return std::nullopt;
15564
15565 uint64_t NarrowByteWidth = BitWidth / 8;
15566
15567 if (NarrowByteWidth >= Index) {
15568 return calculateByteProvider(Op.getOperand(0), Index, Depth + 1,
15569 StartingIndex);
15570 }
15571
15572 return std::nullopt;
15573 }
15574
15575 case ISD::CopyFromReg: {
15576 if (BitWidth / 8 > Index)
15577 return calculateSrcByte(Op, StartingIndex, Index);
15578
15579 return std::nullopt;
15580 }
15581
15582 case ISD::LOAD: {
15583 auto *L = cast<LoadSDNode>(Op.getNode());
15584
15585 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
15586 if (NarrowBitWidth % 8 != 0)
15587 return std::nullopt;
15588 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
15589
15590 // If the width of the load does not reach byte we are trying to provide for
15591 // and it is not a ZEXTLOAD, then the load does not provide for the byte in
15592 // question
15593 if (Index >= NarrowByteWidth) {
15594 return L->getExtensionType() == ISD::ZEXTLOAD
15595 ? std::optional<ByteProvider<SDValue>>(
15597 : std::nullopt;
15598 }
15599
15600 if (NarrowByteWidth > Index) {
15601 return calculateSrcByte(Op, StartingIndex, Index);
15602 }
15603
15604 return std::nullopt;
15605 }
15606
15607 case ISD::BSWAP: {
15608 if (IsVec)
15609 return std::nullopt;
15610
15611 return calculateByteProvider(Op->getOperand(0), BitWidth / 8 - Index - 1,
15612 Depth + 1, StartingIndex);
15613 }
15614
15616 auto *IdxOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15617 if (!IdxOp)
15618 return std::nullopt;
15619 auto VecIdx = IdxOp->getZExtValue();
15620 auto ScalarSize = Op.getScalarValueSizeInBits();
15621 if (ScalarSize < 32)
15622 Index = ScalarSize == 8 ? VecIdx : VecIdx * 2 + Index;
15623 return calculateSrcByte(ScalarSize >= 32 ? Op : Op.getOperand(0),
15624 StartingIndex, Index);
15625 }
15626
15627 case AMDGPUISD::PERM: {
15628 if (IsVec)
15629 return std::nullopt;
15630
15631 auto *PermMask = dyn_cast<ConstantSDNode>(Op->getOperand(2));
15632 if (!PermMask)
15633 return std::nullopt;
15634
15635 auto IdxMask =
15636 (PermMask->getZExtValue() & (0xFF << (Index * 8))) >> (Index * 8);
15637 if (IdxMask > 0x07 && IdxMask != 0x0c)
15638 return std::nullopt;
15639
15640 auto NextOp = Op.getOperand(IdxMask > 0x03 ? 0 : 1);
15641 auto NextIndex = IdxMask > 0x03 ? IdxMask % 4 : IdxMask;
15642
15643 return IdxMask != 0x0c ? calculateSrcByte(NextOp, StartingIndex, NextIndex)
15646 }
15647
15648 default: {
15649 return std::nullopt;
15650 }
15651 }
15652
15653 llvm_unreachable("fully handled switch");
15654}
15655
15656// Returns true if the Operand is a scalar and is 16 bits
15657static bool isExtendedFrom16Bits(SDValue &Operand) {
15658
15659 switch (Operand.getOpcode()) {
15660 case ISD::ANY_EXTEND:
15661 case ISD::SIGN_EXTEND:
15662 case ISD::ZERO_EXTEND: {
15663 auto OpVT = Operand.getOperand(0).getValueType();
15664 return !OpVT.isVector() && OpVT.getSizeInBits() == 16;
15665 }
15666 case ISD::LOAD: {
15667 LoadSDNode *L = cast<LoadSDNode>(Operand.getNode());
15668 auto ExtType = cast<LoadSDNode>(L)->getExtensionType();
15669 if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::SEXTLOAD ||
15670 ExtType == ISD::EXTLOAD) {
15671 auto MemVT = L->getMemoryVT();
15672 return !MemVT.isVector() && MemVT.getSizeInBits() == 16;
15673 }
15674 return L->getMemoryVT().getSizeInBits() == 16;
15675 }
15676 default:
15677 return false;
15678 }
15679}
15680
15681// Returns true if the mask matches consecutive bytes, and the first byte
15682// begins at a power of 2 byte offset from 0th byte
15683static bool addresses16Bits(int Mask) {
15684 int Low8 = Mask & 0xff;
15685 int Hi8 = (Mask & 0xff00) >> 8;
15686
15687 assert(Low8 < 8 && Hi8 < 8);
15688 // Are the bytes contiguous in the order of increasing addresses.
15689 bool IsConsecutive = (Hi8 - Low8 == 1);
15690 // Is the first byte at location that is aligned for 16 bit instructions.
15691 // A counter example is taking 2 consecutive bytes starting at the 8th bit.
15692 // In this case, we still need code to extract the 16 bit operand, so it
15693 // is better to use i8 v_perm
15694 bool Is16Aligned = !(Low8 % 2);
15695
15696 return IsConsecutive && Is16Aligned;
15697}
15698
15699// Do not lower into v_perm if the operands are actually 16 bit
15700// and the selected bits (based on PermMask) correspond with two
15701// easily addressable 16 bit operands.
15703 SDValue &OtherOp) {
15704 int Low16 = PermMask & 0xffff;
15705 int Hi16 = (PermMask & 0xffff0000) >> 16;
15706
15707 auto TempOp = peekThroughBitcasts(Op);
15708 auto TempOtherOp = peekThroughBitcasts(OtherOp);
15709
15710 auto OpIs16Bit =
15711 TempOp.getValueSizeInBits() == 16 || isExtendedFrom16Bits(TempOp);
15712 if (!OpIs16Bit)
15713 return true;
15714
15715 auto OtherOpIs16Bit = TempOtherOp.getValueSizeInBits() == 16 ||
15716 isExtendedFrom16Bits(TempOtherOp);
15717 if (!OtherOpIs16Bit)
15718 return true;
15719
15720 // Do we cleanly address both
15721 return !addresses16Bits(Low16) || !addresses16Bits(Hi16);
15722}
15723
15725 unsigned DWordOffset) {
15726 SDValue Ret;
15727
15728 auto TypeSize = Src.getValueSizeInBits().getFixedValue();
15729 // ByteProvider must be at least 8 bits
15730 assert(Src.getValueSizeInBits().isKnownMultipleOf(8));
15731
15732 if (TypeSize <= 32)
15733 return DAG.getBitcastedAnyExtOrTrunc(Src, SL, MVT::i32);
15734
15735 if (Src.getValueType().isVector()) {
15736 auto ScalarTySize = Src.getScalarValueSizeInBits();
15737 auto ScalarTy = Src.getValueType().getScalarType();
15738 if (ScalarTySize == 32) {
15739 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Src,
15740 DAG.getConstant(DWordOffset, SL, MVT::i32));
15741 }
15742 if (ScalarTySize > 32) {
15743 Ret = DAG.getNode(
15744 ISD::EXTRACT_VECTOR_ELT, SL, ScalarTy, Src,
15745 DAG.getConstant(DWordOffset / (ScalarTySize / 32), SL, MVT::i32));
15746 auto ShiftVal = 32 * (DWordOffset % (ScalarTySize / 32));
15747 if (ShiftVal)
15748 Ret = DAG.getNode(ISD::SRL, SL, Ret.getValueType(), Ret,
15749 DAG.getConstant(ShiftVal, SL, MVT::i32));
15750 return DAG.getBitcastedAnyExtOrTrunc(Ret, SL, MVT::i32);
15751 }
15752
15753 assert(ScalarTySize < 32);
15754 if (TypeSize % 32 == 0) {
15755 assert(DWordOffset < TypeSize / 32);
15756 SDValue Cast = DAG.getBitcast(
15757 EVT::getVectorVT(*DAG.getContext(), MVT::i32, TypeSize / 32), Src);
15758 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
15759 DAG.getConstant(DWordOffset, SL, MVT::i32));
15760 }
15761
15762 auto NumElements = TypeSize / ScalarTySize;
15763 auto Trunc32Elements = (ScalarTySize * NumElements) / 32;
15764 auto NormalizedTrunc = Trunc32Elements * 32 / ScalarTySize;
15765 auto NumElementsIn32 = 32 / ScalarTySize;
15766 auto NumAvailElements = DWordOffset < Trunc32Elements
15767 ? NumElementsIn32
15768 : NumElements - NormalizedTrunc;
15769
15771 DAG.ExtractVectorElements(Src, VecSrcs, DWordOffset * NumElementsIn32,
15772 NumAvailElements);
15773
15774 Ret = DAG.getBuildVector(
15775 MVT::getVectorVT(MVT::getIntegerVT(ScalarTySize), NumAvailElements), SL,
15776 VecSrcs);
15777 return Ret = DAG.getBitcastedAnyExtOrTrunc(Ret, SL, MVT::i32);
15778 }
15779
15780 /// Scalar Type
15781 auto ShiftVal = 32 * DWordOffset;
15782 Ret = DAG.getNode(ISD::SRL, SL, Src.getValueType(), Src,
15783 DAG.getConstant(ShiftVal, SL, MVT::i32));
15784 return DAG.getBitcastedAnyExtOrTrunc(Ret, SL, MVT::i32);
15785}
15786
15788 SelectionDAG &DAG = DCI.DAG;
15789 [[maybe_unused]] EVT VT = N->getValueType(0);
15791
15792 // VT is known to be MVT::i32, so we need to provide 4 bytes.
15793 assert(VT == MVT::i32);
15794 for (int i = 0; i < 4; i++) {
15795 // Find the ByteProvider that provides the ith byte of the result of OR
15796 std::optional<ByteProvider<SDValue>> P =
15797 calculateByteProvider(SDValue(N, 0), i, 0, /*StartingIndex = */ i);
15798 // TODO support constantZero
15799 if (!P || P->isConstantZero())
15800 return SDValue();
15801
15802 PermNodes.push_back(*P);
15803 }
15804 if (PermNodes.size() != 4)
15805 return SDValue();
15806
15807 std::pair<unsigned, unsigned> FirstSrc(0, PermNodes[0].SrcOffset / 4);
15808 std::optional<std::pair<unsigned, unsigned>> SecondSrc;
15809 uint64_t PermMask = 0x00000000;
15810 for (size_t i = 0; i < PermNodes.size(); i++) {
15811 auto PermOp = PermNodes[i];
15812 // Since the mask is applied to Src1:Src2, Src1 bytes must be offset
15813 // by sizeof(Src2) = 4
15814 int SrcByteAdjust = 4;
15815
15816 // If the Src uses a byte from a different DWORD, then it corresponds
15817 // with a difference source
15818 if (!PermOp.hasSameSrc(PermNodes[FirstSrc.first]) ||
15819 ((PermOp.SrcOffset / 4) != FirstSrc.second)) {
15820 if (SecondSrc)
15821 if (!PermOp.hasSameSrc(PermNodes[SecondSrc->first]) ||
15822 ((PermOp.SrcOffset / 4) != SecondSrc->second))
15823 return SDValue();
15824
15825 // Set the index of the second distinct Src node
15826 SecondSrc = {i, PermNodes[i].SrcOffset / 4};
15827 assert(!(PermNodes[SecondSrc->first].Src->getValueSizeInBits() % 8));
15828 SrcByteAdjust = 0;
15829 }
15830 assert((PermOp.SrcOffset % 4) + SrcByteAdjust < 8);
15832 PermMask |= ((PermOp.SrcOffset % 4) + SrcByteAdjust) << (i * 8);
15833 }
15834 SDLoc DL(N);
15835 SDValue Op = *PermNodes[FirstSrc.first].Src;
15836 Op = getDWordFromOffset(DAG, DL, Op, FirstSrc.second);
15837 assert(Op.getValueSizeInBits() == 32);
15838
15839 // Check that we are not just extracting the bytes in order from an op
15840 if (!SecondSrc) {
15841 int Low16 = PermMask & 0xffff;
15842 int Hi16 = (PermMask & 0xffff0000) >> 16;
15843
15844 bool WellFormedLow = (Low16 == 0x0504) || (Low16 == 0x0100);
15845 bool WellFormedHi = (Hi16 == 0x0706) || (Hi16 == 0x0302);
15846
15847 // The perm op would really just produce Op. So combine into Op
15848 if (WellFormedLow && WellFormedHi)
15849 return DAG.getBitcast(MVT::getIntegerVT(32), Op);
15850 }
15851
15852 SDValue OtherOp = SecondSrc ? *PermNodes[SecondSrc->first].Src : Op;
15853
15854 if (SecondSrc) {
15855 OtherOp = getDWordFromOffset(DAG, DL, OtherOp, SecondSrc->second);
15856 assert(OtherOp.getValueSizeInBits() == 32);
15857 }
15858
15859 // Check that we haven't just recreated the same FSHR node.
15860 if (N->getOpcode() == ISD::FSHR &&
15861 (N->getOperand(0) == Op || N->getOperand(0) == OtherOp) &&
15862 (N->getOperand(1) == Op || N->getOperand(1) == OtherOp))
15863 return SDValue();
15864
15865 if (hasNon16BitAccesses(PermMask, Op, OtherOp)) {
15866
15867 assert(Op.getValueType().isByteSized() &&
15868 OtherOp.getValueType().isByteSized());
15869
15870 // If the ultimate src is less than 32 bits, then we will only be
15871 // using bytes 0: Op.getValueSizeInBytes() - 1 in the or.
15872 // CalculateByteProvider would not have returned Op as source if we
15873 // used a byte that is outside its ValueType. Thus, we are free to
15874 // ANY_EXTEND as the extended bits are dont-cares.
15875 Op = DAG.getBitcastedAnyExtOrTrunc(Op, DL, MVT::i32);
15876 OtherOp = DAG.getBitcastedAnyExtOrTrunc(OtherOp, DL, MVT::i32);
15877
15878 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op, OtherOp,
15879 DAG.getConstant(PermMask, DL, MVT::i32));
15880 }
15881 return SDValue();
15882}
15883
15884SDValue SITargetLowering::performOrCombine(SDNode *N,
15885 DAGCombinerInfo &DCI) const {
15886 SelectionDAG &DAG = DCI.DAG;
15887 SDValue LHS = N->getOperand(0);
15888 SDValue RHS = N->getOperand(1);
15889
15890 EVT VT = N->getValueType(0);
15891 if (VT == MVT::i1) {
15892 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
15893 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
15894 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
15895 SDValue Src = LHS.getOperand(0);
15896 if (Src != RHS.getOperand(0))
15897 return SDValue();
15898
15899 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
15900 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
15901 if (!CLHS || !CRHS)
15902 return SDValue();
15903
15904 // Only 10 bits are used.
15905 static const uint32_t MaxMask = 0x3ff;
15906
15907 uint32_t NewMask =
15908 (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
15909 SDLoc DL(N);
15910 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, Src,
15911 DAG.getConstant(NewMask, DL, MVT::i32));
15912 }
15913
15914 return SDValue();
15915 }
15916
15917 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
15919 LHS.getOpcode() == AMDGPUISD::PERM &&
15920 isa<ConstantSDNode>(LHS.getOperand(2))) {
15921 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
15922 if (!Sel)
15923 return SDValue();
15924
15925 Sel |= LHS.getConstantOperandVal(2);
15926 SDLoc DL(N);
15927 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15928 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
15929 }
15930
15931 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
15932 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
15933 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
15934 TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
15935
15936 // If all the uses of an or need to extract the individual elements, do not
15937 // attempt to lower into v_perm
15938 auto usesCombinedOperand = [](SDNode *OrUse) {
15939 // If we have any non-vectorized use, then it is a candidate for v_perm
15940 if (OrUse->getOpcode() != ISD::BITCAST ||
15941 !OrUse->getValueType(0).isVector())
15942 return true;
15943
15944 // If we have any non-vectorized use, then it is a candidate for v_perm
15945 for (auto *VUser : OrUse->users()) {
15946 if (!VUser->getValueType(0).isVector())
15947 return true;
15948
15949 // If the use of a vector is a store, then combining via a v_perm
15950 // is beneficial.
15951 // TODO -- whitelist more uses
15952 for (auto VectorwiseOp : {ISD::STORE, ISD::CopyToReg, ISD::CopyFromReg})
15953 if (VUser->getOpcode() == VectorwiseOp)
15954 return true;
15955 }
15956 return false;
15957 };
15958
15959 if (!any_of(N->users(), usesCombinedOperand))
15960 return SDValue();
15961
15962 uint32_t LHSMask = getPermuteMask(LHS);
15963 uint32_t RHSMask = getPermuteMask(RHS);
15964
15965 if (LHSMask != ~0u && RHSMask != ~0u) {
15966 // Canonicalize the expression in an attempt to have fewer unique masks
15967 // and therefore fewer registers used to hold the masks.
15968 if (LHSMask > RHSMask) {
15969 std::swap(LHSMask, RHSMask);
15970 std::swap(LHS, RHS);
15971 }
15972
15973 // Select 0xc for each lane used from source operand. Zero has 0xc mask
15974 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
15975 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15976 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15977
15978 // Check of we need to combine values from two sources within a byte.
15979 if (!(LHSUsedLanes & RHSUsedLanes) &&
15980 // If we select high and lower word keep it for SDWA.
15981 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
15982 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
15983 // Kill zero bytes selected by other mask. Zero value is 0xc.
15984 LHSMask &= ~RHSUsedLanes;
15985 RHSMask &= ~LHSUsedLanes;
15986 // Add 4 to each active LHS lane
15987 LHSMask |= LHSUsedLanes & 0x04040404;
15988 // Combine masks
15989 uint32_t Sel = LHSMask | RHSMask;
15990 SDLoc DL(N);
15991
15992 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15993 RHS.getOperand(0),
15994 DAG.getConstant(Sel, DL, MVT::i32));
15995 }
15996 }
15997 if (LHSMask == ~0u || RHSMask == ~0u) {
15998 if (SDValue Perm = matchPERM(N, DCI))
15999 return Perm;
16000 }
16001 }
16002
16003 // Detect identity v2i32 OR and replace with identity source node.
16004 // Specifically an Or that has operands constructed from the same source node
16005 // via extract_vector_elt and build_vector. I.E.
16006 // v2i32 or(
16007 // v2i32 build_vector(
16008 // i32 extract_elt(%IdentitySrc, 0),
16009 // i32 0
16010 // ),
16011 // v2i32 build_vector(
16012 // i32 0,
16013 // i32 extract_elt(%IdentitySrc, 1)
16014 // ) )
16015 // =>
16016 // v2i32 %IdentitySrc
16017
16018 if (VT == MVT::v2i32 && LHS->getOpcode() == ISD::BUILD_VECTOR &&
16019 RHS->getOpcode() == ISD::BUILD_VECTOR) {
16020
16021 ConstantSDNode *LC = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
16022 ConstantSDNode *RC = dyn_cast<ConstantSDNode>(RHS->getOperand(0));
16023
16024 // Test for and normalise build vectors.
16025 if (LC && RC && LC->getZExtValue() == 0 && RC->getZExtValue() == 0) {
16026
16027 // Get the extract_vector_element operands.
16028 SDValue LEVE = LHS->getOperand(0);
16029 SDValue REVE = RHS->getOperand(1);
16030
16031 if (LEVE->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
16033 // Check that different elements from the same vector are
16034 // extracted.
16035 if (LEVE->getOperand(0) == REVE->getOperand(0) &&
16036 LEVE->getOperand(1) != REVE->getOperand(1)) {
16037 SDValue IdentitySrc = LEVE.getOperand(0);
16038 return IdentitySrc;
16039 }
16040 }
16041 }
16042 }
16043
16044 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
16045 return SDValue();
16046
16047 // TODO: This could be a generic combine with a predicate for extracting the
16048 // high half of an integer being free.
16049
16050 // (or i64:x, (zero_extend i32:y)) ->
16051 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
16052 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
16053 RHS.getOpcode() != ISD::ZERO_EXTEND)
16054 std::swap(LHS, RHS);
16055
16056 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
16057 SDValue ExtSrc = RHS.getOperand(0);
16058 EVT SrcVT = ExtSrc.getValueType();
16059 if (SrcVT == MVT::i32) {
16060 SDLoc SL(N);
16061 auto [LowLHS, HiBits] = split64BitValue(LHS, DAG);
16062 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
16063
16064 DCI.AddToWorklist(LowOr.getNode());
16065 DCI.AddToWorklist(HiBits.getNode());
16066
16067 SDValue Vec =
16068 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, LowOr, HiBits);
16069 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
16070 }
16071 }
16072
16073 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
16074 if (CRHS) {
16075 if (SDValue Split = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
16076 N->getOperand(0), CRHS))
16077 return Split;
16078 }
16079
16080 return SDValue();
16081}
16082
16083SDValue SITargetLowering::performXorCombine(SDNode *N,
16084 DAGCombinerInfo &DCI) const {
16085 if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
16086 return RV;
16087
16088 SDValue LHS = N->getOperand(0);
16089 SDValue RHS = N->getOperand(1);
16090
16091 const ConstantSDNode *CRHS = isConstOrConstSplat(RHS);
16092 SelectionDAG &DAG = DCI.DAG;
16093
16094 EVT VT = N->getValueType(0);
16095 if (CRHS && VT == MVT::i64) {
16096 if (SDValue Split =
16097 splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
16098 return Split;
16099 }
16100
16101 // v2i32 (xor (vselect cc, x, y), K) ->
16102 // (v2i32 svelect cc, (xor x, K), (xor y, K)) This enables the xor to be
16103 // replaced with source modifiers when the select is lowered to CNDMASK.
16104 unsigned Opc = LHS.getOpcode();
16105 if (((Opc == ISD::VSELECT && VT == MVT::v2i32) ||
16106 (Opc == ISD::SELECT && VT == MVT::i64)) &&
16107 CRHS && CRHS->getAPIntValue().isSignMask()) {
16108 SDValue CC = LHS->getOperand(0);
16109 SDValue TRUE = LHS->getOperand(1);
16110 SDValue FALSE = LHS->getOperand(2);
16111 SDValue XTrue = DAG.getNode(ISD::XOR, SDLoc(N), VT, TRUE, RHS);
16112 SDValue XFalse = DAG.getNode(ISD::XOR, SDLoc(N), VT, FALSE, RHS);
16113 SDValue XSelect =
16114 DAG.getNode(ISD::VSELECT, SDLoc(N), VT, CC, XTrue, XFalse);
16115 return XSelect;
16116 }
16117
16118 // Make sure to apply the 64-bit constant splitting fold before trying to fold
16119 // fneg-like xors into 64-bit select.
16120 if (LHS.getOpcode() == ISD::SELECT && VT == MVT::i32) {
16121 // This looks like an fneg, try to fold as a source modifier.
16122 if (CRHS && CRHS->getAPIntValue().isSignMask() &&
16124 // xor (select c, a, b), 0x80000000 ->
16125 // bitcast (select c, (fneg (bitcast a)), (fneg (bitcast b)))
16126 SDLoc DL(N);
16127 SDValue CastLHS =
16128 DAG.getNode(ISD::BITCAST, DL, MVT::f32, LHS->getOperand(1));
16129 SDValue CastRHS =
16130 DAG.getNode(ISD::BITCAST, DL, MVT::f32, LHS->getOperand(2));
16131 SDValue FNegLHS = DAG.getNode(ISD::FNEG, DL, MVT::f32, CastLHS);
16132 SDValue FNegRHS = DAG.getNode(ISD::FNEG, DL, MVT::f32, CastRHS);
16133 SDValue NewSelect = DAG.getNode(ISD::SELECT, DL, MVT::f32,
16134 LHS->getOperand(0), FNegLHS, FNegRHS);
16135 return DAG.getNode(ISD::BITCAST, DL, VT, NewSelect);
16136 }
16137 }
16138
16139 return SDValue();
16140}
16141
16142SDValue
16143SITargetLowering::performZeroOrAnyExtendCombine(SDNode *N,
16144 DAGCombinerInfo &DCI) const {
16145 if (!Subtarget->has16BitInsts() ||
16146 DCI.getDAGCombineLevel() < AfterLegalizeTypes)
16147 return SDValue();
16148
16149 EVT VT = N->getValueType(0);
16150 if (VT != MVT::i32)
16151 return SDValue();
16152
16153 SDValue Src = N->getOperand(0);
16154 if (Src.getValueType() != MVT::i16)
16155 return SDValue();
16156
16157 if (!Src->hasOneUse())
16158 return SDValue();
16159
16160 if (SDValue Ext = performExtendTruncShiftCombine(N, DCI))
16161 return Ext;
16162
16163 // TODO: We bail out below if SrcOffset is not in the first dword (>= 4). It's
16164 // possible we're missing out on some combine opportunities, but we'd need to
16165 // weigh the cost of extracting the byte from the upper dwords.
16166
16167 std::optional<ByteProvider<SDValue>> BP0 =
16168 calculateByteProvider(SDValue(N, 0), 0, 0, 0);
16169 if (!BP0 || BP0->SrcOffset >= 4 || !BP0->Src)
16170 return SDValue();
16171 SDValue V0 = *BP0->Src;
16172
16173 std::optional<ByteProvider<SDValue>> BP1 =
16174 calculateByteProvider(SDValue(N, 0), 1, 0, 1);
16175 if (!BP1 || BP1->SrcOffset >= 4 || !BP1->Src)
16176 return SDValue();
16177
16178 SDValue V1 = *BP1->Src;
16179
16180 if (V0 == V1)
16181 return SDValue();
16182
16183 SelectionDAG &DAG = DCI.DAG;
16184 SDLoc DL(N);
16185 uint32_t PermMask = 0x0c0c0c0c;
16186 if (V0) {
16187 V0 = getDWordFromOffset(DAG, DL, V0, /*DWordOffset=*/0);
16188 PermMask = (PermMask & ~0xFF) | (BP0->SrcOffset + 4);
16189 }
16190
16191 if (V1) {
16192 V1 = getDWordFromOffset(DAG, DL, V1, /*DWordOffset=*/0);
16193 PermMask = (PermMask & ~(0xFF << 8)) | (BP1->SrcOffset << 8);
16194 }
16195
16196 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, V0, V1,
16197 DAG.getConstant(PermMask, DL, MVT::i32));
16198}
16199
16200// zext (srl (trunc x), c) => and (srl x, c), lowbits
16201// aext (srl (trunc x), c) => and (srl x, c), lowbits
16202// sext (sra (trunc x), 8) => sext_inreg (srl x, 8), i8
16203SDValue
16204SITargetLowering::performExtendTruncShiftCombine(SDNode *N,
16205 DAGCombinerInfo &DCI) const {
16206 if (DCI.getDAGCombineLevel() < AfterLegalizeTypes)
16207 return SDValue();
16208
16209 const unsigned Opc = N->getOpcode();
16210 const bool IsSigned = Opc == ISD::SIGN_EXTEND;
16211 SDValue Src = N->getOperand(0);
16212 if (N->getValueType(0) != MVT::i32 || Src.getValueType() != MVT::i16 ||
16213 Src.getOpcode() != (IsSigned ? ISD::SRA : ISD::SRL) || !Src.hasOneUse() ||
16214 Src.getOperand(0).getOpcode() != ISD::TRUNCATE)
16215 return SDValue();
16216
16217 // A uniform i16 srl is promoted to i32 later and yields the same nodes.
16218 // Skip it so that the node order, and with it the schedule, stays the same.
16219 if (!IsSigned && !Src->isDivergent())
16220 return SDValue();
16221
16222 SDValue X = Src.getOperand(0).getOperand(0);
16223 auto *Shift = dyn_cast<ConstantSDNode>(Src.getOperand(1));
16224 if (X.getValueType() != MVT::i32 || !Shift || Shift->getZExtValue() == 0 ||
16225 Shift->getZExtValue() >= 16 || (IsSigned && Shift->getZExtValue() != 8))
16226 return SDValue();
16227
16228 SelectionDAG &DAG = DCI.DAG;
16229 SDLoc SL(N);
16230 const unsigned Width = 16 - Shift->getZExtValue();
16231 SDValue Srl = DAG.getNode(
16232 ISD::SRL, SL, MVT::i32, X,
16233 DAG.getShiftAmountConstant(Shift->getZExtValue(), MVT::i32, SL));
16234 if (IsSigned)
16235 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, Srl,
16236 DAG.getValueType(MVT::i8));
16237 return DAG.getNode(
16238 ISD::AND, SL, MVT::i32, Srl,
16239 DAG.getConstant(maskTrailingOnes<uint32_t>(Width), SL, MVT::i32));
16240}
16241
16242SDValue
16243SITargetLowering::performSignExtendInRegCombine(SDNode *N,
16244 DAGCombinerInfo &DCI) const {
16245 SDValue Src = N->getOperand(0);
16246 auto *VTSign = cast<VTSDNode>(N->getOperand(1));
16247
16248 // Combine s_buffer_load_u8 or s_buffer_load_u16 with sext and replace them
16249 // with s_buffer_load_i8 and s_buffer_load_i16 respectively.
16250 if (((Src.getOpcode() == AMDGPUISD::SBUFFER_LOAD_UBYTE &&
16251 VTSign->getVT() == MVT::i8) ||
16252 (Src.getOpcode() == AMDGPUISD::SBUFFER_LOAD_USHORT &&
16253 VTSign->getVT() == MVT::i16))) {
16254 assert(Subtarget->hasScalarSubwordLoads() &&
16255 "s_buffer_load_{u8, i8} are supported "
16256 "in GFX12 (or newer) architectures.");
16257 unsigned Opc = (Src.getOpcode() == AMDGPUISD::SBUFFER_LOAD_UBYTE)
16258 ? AMDGPUISD::SBUFFER_LOAD_BYTE
16259 : AMDGPUISD::SBUFFER_LOAD_SHORT;
16260 SDLoc DL(N);
16261 SDVTList ResList =
16262 DCI.DAG.getVTList(MVT::i32, Src.getOperand(0).getValueType());
16263 SDValue Ops[] = {
16264 Src.getOperand(0), // Chain
16265 Src.getOperand(1), // source register
16266 Src.getOperand(2), // offset
16267 Src.getOperand(3) // cachePolicy
16268 };
16269 auto *M = cast<MemSDNode>(Src);
16270 SDValue BufferLoad = DCI.DAG.getMemIntrinsicNode(
16271 Opc, DL, ResList, Ops, M->getMemoryVT(), M->getMemOperand());
16272 return DCI.DAG.getMergeValues({BufferLoad, BufferLoad.getValue(1)}, DL);
16273 }
16274 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
16275 VTSign->getVT() == MVT::i8) ||
16276 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
16277 VTSign->getVT() == MVT::i16)) &&
16278 Src.hasOneUse()) {
16279 auto *M = cast<MemSDNode>(Src);
16280 SDValue Ops[] = {Src.getOperand(0), // Chain
16281 Src.getOperand(1), // rsrc
16282 Src.getOperand(2), // vindex
16283 Src.getOperand(3), // voffset
16284 Src.getOperand(4), // soffset
16285 Src.getOperand(5), // offset
16286 Src.getOperand(6), Src.getOperand(7)};
16287 // replace with BUFFER_LOAD_BYTE/SHORT
16288 SDVTList ResList =
16289 DCI.DAG.getVTList(MVT::i32, Src.getOperand(0).getValueType());
16290 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE)
16291 ? AMDGPUISD::BUFFER_LOAD_BYTE
16292 : AMDGPUISD::BUFFER_LOAD_SHORT;
16293 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(
16294 Opc, SDLoc(N), ResList, Ops, M->getMemoryVT(), M->getMemOperand());
16295 return DCI.DAG.getMergeValues(
16296 {BufferLoadSignExt, BufferLoadSignExt.getValue(1)}, SDLoc(N));
16297 }
16298 return SDValue();
16299}
16300
16301SDValue SITargetLowering::performClassCombine(SDNode *N,
16302 DAGCombinerInfo &DCI) const {
16303 SelectionDAG &DAG = DCI.DAG;
16304 SDValue Mask = N->getOperand(1);
16305
16306 // fp_class x, 0 -> false
16307 if (isNullConstant(Mask))
16308 return DAG.getConstant(0, SDLoc(N), MVT::i1);
16309
16310 if (N->getOperand(0).isUndef())
16311 return DAG.getUNDEF(MVT::i1);
16312
16313 return SDValue();
16314}
16315
16316SDValue SITargetLowering::performRcpCombine(SDNode *N,
16317 DAGCombinerInfo &DCI) const {
16318 EVT VT = N->getValueType(0);
16319 SDValue N0 = N->getOperand(0);
16320
16321 if (N0.isUndef()) {
16322 return DCI.DAG.getConstantFP(APFloat::getQNaN(VT.getFltSemantics()),
16323 SDLoc(N), VT);
16324 }
16325
16326 // TODO: Could handle f32 + amdgcn.sqrt but probably never reaches here.
16327 if ((VT == MVT::f16 && N0.getOpcode() == ISD::FSQRT) &&
16328 N->getFlags().hasAllowContract() && N0->getFlags().hasAllowContract()) {
16329 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, N0.getOperand(0),
16330 N->getFlags());
16331 }
16332
16334}
16335
16337 SDNodeFlags UserFlags,
16338 unsigned MaxDepth) const {
16339 EVT VT = Op.getValueType();
16340 assert(VT.isFloatingPoint() &&
16341 "expected a floating-point value to query canonicality of");
16342 return isCanonicalized(DAG, Op, VT.getScalarType(), UserFlags, MaxDepth);
16343}
16344
16346 EVT QueryVT, SDNodeFlags UserFlags,
16347 unsigned MaxDepth) const {
16348 assert(QueryVT.isFloatingPoint() && !QueryVT.isVector() &&
16349 "QueryVT must be a floating-point scalar type");
16350 EVT VT = Op.getValueType();
16351 if (VT.isFloatingPoint() && VT.getScalarType() != QueryVT)
16352 return false;
16353
16354 unsigned Opcode = Op.getOpcode();
16355 if (Opcode == ISD::FCANONICALIZE)
16356 return true;
16357
16358 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
16359 const auto &F = CFP->getValueAPF();
16360 if (F.isNaN() && F.isSignaling())
16361 return false;
16362 if (!F.isDenormal())
16363 return true;
16364
16365 DenormalMode Mode =
16366 DAG.getMachineFunction().getDenormalMode(F.getSemantics());
16367 return Mode == DenormalMode::getIEEE();
16368 }
16369
16370 // If source is a result of another standard FP operation it is already in
16371 // canonical form.
16372 if (MaxDepth == 0)
16373 return false;
16374
16375 switch (Opcode) {
16376 // These will flush denorms if required.
16377 case ISD::FADD:
16378 case ISD::FSUB:
16379 case ISD::FMUL:
16380 case ISD::FCEIL:
16381 case ISD::FFLOOR:
16382 case ISD::FMA:
16383 case ISD::FMAD:
16384 case ISD::FSQRT:
16385 case ISD::FDIV:
16386 case ISD::FREM:
16387 case ISD::FP_ROUND:
16388 case ISD::FP_EXTEND:
16389 case ISD::FP16_TO_FP:
16390 case ISD::FP_TO_FP16:
16391 case ISD::BF16_TO_FP:
16392 case ISD::FP_TO_BF16:
16393 case ISD::FLDEXP:
16394 case AMDGPUISD::FMUL_LEGACY:
16395 case AMDGPUISD::FMAD_FTZ:
16396 case AMDGPUISD::RCP:
16397 case AMDGPUISD::RSQ:
16398 case AMDGPUISD::RSQ_CLAMP:
16399 case AMDGPUISD::RCP_LEGACY:
16400 case AMDGPUISD::RCP_IFLAG:
16401 case AMDGPUISD::LOG:
16402 case AMDGPUISD::EXP:
16403 case AMDGPUISD::DIV_SCALE:
16404 case AMDGPUISD::DIV_FMAS:
16405 case AMDGPUISD::DIV_FIXUP:
16406 case AMDGPUISD::FRACT:
16407 case AMDGPUISD::CVT_PKRTZ_F16_F32:
16408 case AMDGPUISD::CVT_F32_UBYTE0:
16409 case AMDGPUISD::CVT_F32_UBYTE1:
16410 case AMDGPUISD::CVT_F32_UBYTE2:
16411 case AMDGPUISD::CVT_F32_UBYTE3:
16412 case AMDGPUISD::FP_TO_FP16:
16413 case AMDGPUISD::SIN_HW:
16414 case AMDGPUISD::COS_HW:
16415 return true;
16416
16417 // It can/will be lowered or combined as a bit operation.
16418 // Need to check their input recursively to handle.
16419 case ISD::FNEG:
16420 case ISD::FABS:
16421 case ISD::FCOPYSIGN:
16422 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16423 MaxDepth - 1);
16424
16425 case ISD::AND:
16426 if (Op.getValueType() == MVT::i32) {
16427 // Be careful as we only know it is a bitcast floating point type. It
16428 // could be f32, v2f16, we have no way of knowing. Luckily the constant
16429 // value that we optimize for, which comes up in fp32 to bf16 conversions,
16430 // is valid to optimize for all types.
16431 if (auto *RHS = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16432 if (RHS->getZExtValue() == 0xffff0000) {
16433 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16434 MaxDepth - 1);
16435 }
16436 }
16437 }
16438 break;
16439
16440 case ISD::FSIN:
16441 case ISD::FCOS:
16442 case ISD::FSINCOS:
16443 return Op.getValueType().getScalarType() != MVT::f16;
16444
16445 case ISD::FMINNUM:
16446 case ISD::FMAXNUM:
16447 case ISD::FMINNUM_IEEE:
16448 case ISD::FMAXNUM_IEEE:
16449 case ISD::FMINIMUM:
16450 case ISD::FMAXIMUM:
16451 case ISD::FMINIMUMNUM:
16452 case ISD::FMAXIMUMNUM:
16453 case AMDGPUISD::CLAMP:
16454 case AMDGPUISD::FMED3:
16455 case AMDGPUISD::FMAX3:
16456 case AMDGPUISD::FMIN3:
16457 case AMDGPUISD::FMAXIMUM3:
16458 case AMDGPUISD::FMINIMUM3: {
16459 // FIXME: Shouldn't treat the generic operations different based these.
16460 // However, we aren't really required to flush the result from
16461 // minnum/maxnum..
16462
16463 // snans will be quieted, so we only need to worry about denormals.
16464 if (Subtarget->supportsMinMaxDenormModes() ||
16465 // FIXME: denormalsEnabledForType is broken for dynamic
16466 denormalsEnabledForType(DAG, Op.getValueType()))
16467 return true;
16468
16469 // Flushing may be required.
16470 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
16471 // targets need to check their input recursively.
16472
16473 // FIXME: Does this apply with clamp? It's implemented with max.
16474 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
16475 if (!isCanonicalized(DAG, Op.getOperand(I), QueryVT, UserFlags,
16476 MaxDepth - 1))
16477 return false;
16478 }
16479
16480 return true;
16481 }
16482 case ISD::SELECT: {
16483 return isCanonicalized(DAG, Op.getOperand(1), QueryVT, UserFlags,
16484 MaxDepth - 1) &&
16485 isCanonicalized(DAG, Op.getOperand(2), QueryVT, UserFlags,
16486 MaxDepth - 1);
16487 }
16488 case ISD::BUILD_VECTOR: {
16489 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
16490 SDValue SrcOp = Op.getOperand(i);
16491 if (!isCanonicalized(DAG, SrcOp, QueryVT, UserFlags, MaxDepth - 1))
16492 return false;
16493 }
16494
16495 return true;
16496 }
16499 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16500 MaxDepth - 1);
16501 }
16503 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16504 MaxDepth - 1) &&
16505 isCanonicalized(DAG, Op.getOperand(1), QueryVT, UserFlags,
16506 MaxDepth - 1);
16507 }
16508 case ISD::POISON:
16509 return true;
16510 case ISD::UNDEF:
16511 // Could be anything.
16512 return false;
16513
16514 case ISD::BITCAST: {
16515 // Carry QueryVT through the bitcast unchanged. The top-of-function guard
16516 // rejects a source whose FP format differs from the consumed type, so a
16517 // value canonical in one FP format is not assumed canonical in another.
16518 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
16519 return isCanonicalized(DAG, Src, QueryVT, UserFlags, MaxDepth - 1);
16520 }
16521 case ISD::TRUNCATE: {
16522 // Hack round the mess we make when legalizing extract_vector_elt
16523 if (Op.getValueType() == MVT::i16) {
16524 SDValue TruncSrc = Op.getOperand(0);
16525 if (TruncSrc.getValueType() == MVT::i32 &&
16526 TruncSrc.getOpcode() == ISD::BITCAST &&
16527 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
16528 return isCanonicalized(DAG, TruncSrc.getOperand(0), QueryVT, UserFlags,
16529 MaxDepth - 1);
16530 }
16531 }
16532 return false;
16533 }
16535 unsigned IntrinsicID = Op.getConstantOperandVal(0);
16536 // TODO: Handle more intrinsics
16537 switch (IntrinsicID) {
16538 case Intrinsic::amdgcn_update_dpp: {
16539 enum UpdateDPPOperand {
16540 Src = 2,
16541 RowMask = 4,
16542 BankMask = 5,
16543 BoundCtrl = 6,
16544 };
16545
16546 if (QueryVT == MVT::f32 && (VT == MVT::i32 || VT == MVT::f32) &&
16547 Op.getConstantOperandVal(RowMask) == 0xf && // Enable all rows.
16548 Op.getConstantOperandVal(BankMask) == 0xf && // Enable all banks.
16549 Op.getConstantOperandVal(BoundCtrl) != 0) // Zero-fill OOB lanes.
16550 return isCanonicalized(DAG, Op.getOperand(2), QueryVT, UserFlags,
16551 MaxDepth - 1);
16552 return false;
16553 }
16554 case Intrinsic::amdgcn_cvt_pkrtz:
16555 case Intrinsic::amdgcn_cubeid:
16556 case Intrinsic::amdgcn_frexp_mant:
16557 case Intrinsic::amdgcn_fdot2:
16558 case Intrinsic::amdgcn_rcp:
16559 case Intrinsic::amdgcn_rsq:
16560 case Intrinsic::amdgcn_rsq_clamp:
16561 case Intrinsic::amdgcn_rcp_legacy:
16562 case Intrinsic::amdgcn_rsq_legacy:
16563 case Intrinsic::amdgcn_trig_preop:
16564 case Intrinsic::amdgcn_tanh:
16565 case Intrinsic::amdgcn_log:
16566 case Intrinsic::amdgcn_exp2:
16567 case Intrinsic::amdgcn_sqrt:
16568 return true;
16569 default:
16570 break;
16571 }
16572
16573 break;
16574 }
16575 default:
16576 break;
16577 }
16578
16579 // FIXME: denormalsEnabledForType is broken for dynamic
16580 return denormalsEnabledForType(DAG, Op.getValueType()) &&
16581 (UserFlags.hasNoNaNs() || DAG.isKnownNeverSNaN(Op));
16582}
16583
16585 unsigned MaxDepth) const {
16586 const MachineRegisterInfo &MRI = MF.getRegInfo();
16587 MachineInstr *MI = MRI.getVRegDef(Reg);
16588 unsigned Opcode = MI->getOpcode();
16589
16590 if (Opcode == AMDGPU::G_FCANONICALIZE)
16591 return true;
16592
16593 std::optional<FPValueAndVReg> FCR;
16594 // Constant splat (can be padded with undef) or scalar constant.
16596 if (FCR->Value.isSignaling())
16597 return false;
16598 if (!FCR->Value.isDenormal())
16599 return true;
16600
16601 DenormalMode Mode = MF.getDenormalMode(FCR->Value.getSemantics());
16602 return Mode == DenormalMode::getIEEE();
16603 }
16604
16605 if (MaxDepth == 0)
16606 return false;
16607
16608 switch (Opcode) {
16609 case AMDGPU::G_FADD:
16610 case AMDGPU::G_FSUB:
16611 case AMDGPU::G_FMUL:
16612 case AMDGPU::G_FCEIL:
16613 case AMDGPU::G_FFLOOR:
16614 case AMDGPU::G_FRINT:
16615 case AMDGPU::G_FNEARBYINT:
16616 case AMDGPU::G_INTRINSIC_FPTRUNC_ROUND:
16617 case AMDGPU::G_INTRINSIC_TRUNC:
16618 case AMDGPU::G_INTRINSIC_ROUNDEVEN:
16619 case AMDGPU::G_FMA:
16620 case AMDGPU::G_FMAD:
16621 case AMDGPU::G_FSQRT:
16622 case AMDGPU::G_FDIV:
16623 case AMDGPU::G_FREM:
16624 case AMDGPU::G_FPOW:
16625 case AMDGPU::G_FPEXT:
16626 case AMDGPU::G_FLOG:
16627 case AMDGPU::G_FLOG2:
16628 case AMDGPU::G_FLOG10:
16629 case AMDGPU::G_FPTRUNC:
16630 case AMDGPU::G_AMDGPU_RCP_IFLAG:
16631 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE0:
16632 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE1:
16633 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE2:
16634 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE3:
16635 return true;
16636 case AMDGPU::G_FNEG:
16637 case AMDGPU::G_FABS:
16638 case AMDGPU::G_FCOPYSIGN:
16639 return isCanonicalized(MI->getOperand(1).getReg(), MF, MaxDepth - 1);
16640 case AMDGPU::G_FMINNUM:
16641 case AMDGPU::G_FMAXNUM:
16642 case AMDGPU::G_FMINNUM_IEEE:
16643 case AMDGPU::G_FMAXNUM_IEEE:
16644 case AMDGPU::G_FMINIMUM:
16645 case AMDGPU::G_FMAXIMUM:
16646 case AMDGPU::G_FMINIMUMNUM:
16647 case AMDGPU::G_FMAXIMUMNUM: {
16648 if (Subtarget->supportsMinMaxDenormModes() ||
16649 // FIXME: denormalsEnabledForType is broken for dynamic
16650 denormalsEnabledForType(MRI.getType(Reg), MF))
16651 return true;
16652
16653 [[fallthrough]];
16654 }
16655 case AMDGPU::G_BUILD_VECTOR:
16656 for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
16657 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
16658 return false;
16659 return true;
16660 case AMDGPU::G_INTRINSIC:
16661 case AMDGPU::G_INTRINSIC_CONVERGENT:
16662 switch (cast<GIntrinsic>(MI)->getIntrinsicID()) {
16663 case Intrinsic::amdgcn_fmul_legacy:
16664 case Intrinsic::amdgcn_fmad_ftz:
16665 case Intrinsic::amdgcn_sqrt:
16666 case Intrinsic::amdgcn_fmed3:
16667 case Intrinsic::amdgcn_sin:
16668 case Intrinsic::amdgcn_cos:
16669 case Intrinsic::amdgcn_log:
16670 case Intrinsic::amdgcn_exp2:
16671 case Intrinsic::amdgcn_log_clamp:
16672 case Intrinsic::amdgcn_rcp:
16673 case Intrinsic::amdgcn_rcp_legacy:
16674 case Intrinsic::amdgcn_rsq:
16675 case Intrinsic::amdgcn_rsq_clamp:
16676 case Intrinsic::amdgcn_rsq_legacy:
16677 case Intrinsic::amdgcn_div_scale:
16678 case Intrinsic::amdgcn_div_fmas:
16679 case Intrinsic::amdgcn_div_fixup:
16680 case Intrinsic::amdgcn_fract:
16681 case Intrinsic::amdgcn_cvt_pkrtz:
16682 case Intrinsic::amdgcn_cubeid:
16683 case Intrinsic::amdgcn_cubema:
16684 case Intrinsic::amdgcn_cubesc:
16685 case Intrinsic::amdgcn_cubetc:
16686 case Intrinsic::amdgcn_frexp_mant:
16687 case Intrinsic::amdgcn_fdot2:
16688 case Intrinsic::amdgcn_trig_preop:
16689 case Intrinsic::amdgcn_tanh:
16690 return true;
16691 default:
16692 break;
16693 }
16694
16695 [[fallthrough]];
16696 default:
16697 return false;
16698 }
16699
16700 llvm_unreachable("invalid operation");
16701}
16702
16703// Constant fold canonicalize.
16704SDValue SITargetLowering::getCanonicalConstantFP(SelectionDAG &DAG,
16705 const SDLoc &SL, EVT VT,
16706 const APFloat &C) const {
16707 // Flush denormals to 0 if not enabled.
16708 if (C.isDenormal()) {
16709 DenormalMode Mode =
16710 DAG.getMachineFunction().getDenormalMode(C.getSemantics());
16711 if (Mode == DenormalMode::getPreserveSign()) {
16712 return DAG.getConstantFP(
16713 APFloat::getZero(C.getSemantics(), C.isNegative()), SL, VT);
16714 }
16715
16716 if (Mode != DenormalMode::getIEEE())
16717 return SDValue();
16718 }
16719
16720 if (C.isNaN()) {
16721 if (C.isSignaling()) {
16722 // Quiet a signaling NaN.
16723 return DAG.getConstantFP(C.makeQuiet(), SL, VT);
16724 }
16725 }
16726
16727 // Already canonical.
16728 return DAG.getConstantFP(C, SL, VT);
16729}
16730
16732 return Op.isUndef() || isa<ConstantFPSDNode>(Op);
16733}
16734
16735SDValue
16736SITargetLowering::performFCanonicalizeCombine(SDNode *N,
16737 DAGCombinerInfo &DCI) const {
16738 SelectionDAG &DAG = DCI.DAG;
16739 SDValue N0 = N->getOperand(0);
16740 EVT VT = N->getValueType(0);
16741
16742 // fcanonicalize undef -> qnan
16743 if (N0.isUndef()) {
16745 return DAG.getConstantFP(QNaN, SDLoc(N), VT);
16746 }
16747
16748 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0))
16749 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
16750
16751 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
16752 // (fcanonicalize k)
16753 //
16754 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
16755
16756 // TODO: This could be better with wider vectors that will be split to v2f16,
16757 // and to consider uses since there aren't that many packed operations.
16758 if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNumOperands() == 2 &&
16759 isTypeLegal(VT)) {
16760 SDLoc SL(N);
16761 SDValue NewElts[2];
16762 SDValue Lo = N0.getOperand(0);
16763 SDValue Hi = N0.getOperand(1);
16764 EVT EltVT = Lo.getValueType();
16765
16766 // Only apply this optimization if scalar canonicalize is legal for the
16767 // element type. Otherwise, scalarizing may require widening the scalar back
16768 // to a vector, adding overhead (e.g., bf16 has no scalar instructions).
16770 return SDValue();
16771
16773 for (unsigned I = 0; I != 2; ++I) {
16774 SDValue Op = N0.getOperand(I);
16775 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
16776 NewElts[I] =
16777 getCanonicalConstantFP(DAG, SL, EltVT, CFP->getValueAPF());
16778 } else if (Op.isUndef()) {
16779 // Handled below based on what the other operand is.
16780 NewElts[I] = Op;
16781 } else {
16782 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
16783 }
16784 }
16785
16786 // If one half is undef, and one is constant, prefer a splat vector.
16787 // Otherwise, convert the undef to 0.0 since that's cheaper to use and may
16788 // be free with a packed operation.
16789 if (NewElts[0].isUndef()) {
16790 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1])
16791 ? NewElts[1]
16792 : DAG.getConstantFP(0.0f, SL, EltVT);
16793 }
16794
16795 if (NewElts[1].isUndef()) {
16796 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0])
16797 ? NewElts[0]
16798 : DAG.getConstantFP(0.0f, SL, EltVT);
16799 }
16800
16801 return DAG.getBuildVector(VT, SL, NewElts);
16802 }
16803 }
16804
16805 return SDValue();
16806}
16807
16808static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
16809 switch (Opc) {
16810 case ISD::FMAXNUM:
16811 case ISD::FMAXNUM_IEEE:
16812 case ISD::FMAXIMUMNUM:
16813 return AMDGPUISD::FMAX3;
16814 case ISD::FMAXIMUM:
16815 return AMDGPUISD::FMAXIMUM3;
16816 case ISD::SMAX:
16817 return AMDGPUISD::SMAX3;
16818 case ISD::UMAX:
16819 return AMDGPUISD::UMAX3;
16820 case ISD::FMINNUM:
16821 case ISD::FMINNUM_IEEE:
16822 case ISD::FMINIMUMNUM:
16823 return AMDGPUISD::FMIN3;
16824 case ISD::FMINIMUM:
16825 return AMDGPUISD::FMINIMUM3;
16826 case ISD::SMIN:
16827 return AMDGPUISD::SMIN3;
16828 case ISD::UMIN:
16829 return AMDGPUISD::UMIN3;
16830 default:
16831 llvm_unreachable("Not a min/max opcode");
16832 }
16833}
16834
16835SDValue SITargetLowering::performIntMed3ImmCombine(SelectionDAG &DAG,
16836 const SDLoc &SL, SDValue Src,
16837 SDValue MinVal,
16838 SDValue MaxVal,
16839 bool Signed) const {
16840
16841 // med3 comes from
16842 // min(max(x, K0), K1), K0 < K1
16843 // max(min(x, K0), K1), K1 < K0
16844 //
16845 // "MinVal" and "MaxVal" respectively refer to the rhs of the
16846 // min/max op.
16847 ConstantSDNode *MinK = dyn_cast<ConstantSDNode>(MinVal);
16848 ConstantSDNode *MaxK = dyn_cast<ConstantSDNode>(MaxVal);
16849
16850 if (!MinK || !MaxK)
16851 return SDValue();
16852
16853 if (Signed) {
16854 if (MaxK->getAPIntValue().sge(MinK->getAPIntValue()))
16855 return SDValue();
16856 } else {
16857 if (MaxK->getAPIntValue().uge(MinK->getAPIntValue()))
16858 return SDValue();
16859 }
16860
16861 EVT VT = MinK->getValueType(0);
16862 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
16863 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16()))
16864 return DAG.getNode(Med3Opc, SL, VT, Src, MaxVal, MinVal);
16865
16866 // Note: we could also extend to i32 and use i32 med3 if i16 med3 is
16867 // not available, but this is unlikely to be profitable as constants
16868 // will often need to be materialized & extended, especially on
16869 // pre-GFX10 where VOP3 instructions couldn't take literal operands.
16870 return SDValue();
16871}
16872
16875 return C;
16876
16878 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
16879 return C;
16880 }
16881
16882 return nullptr;
16883}
16884
16885SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
16886 const SDLoc &SL, SDValue Op0,
16887 SDValue Op1,
16888 bool IsKnownNoNaNs) const {
16889 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
16890 if (!K1)
16891 return SDValue();
16892
16893 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
16894 if (!K0)
16895 return SDValue();
16896
16897 // Ordered >= (although NaN inputs should have folded away by now).
16898 if (K0->getValueAPF() > K1->getValueAPF())
16899 return SDValue();
16900
16901 // med3 with a nan input acts like
16902 // v_min_f32(v_min_f32(S0.f32, S1.f32), S2.f32)
16903 //
16904 // So the result depends on whether the IEEE mode bit is enabled or not with a
16905 // signaling nan input.
16906 // ieee=1
16907 // s0 snan: yields s2
16908 // s1 snan: yields s2
16909 // s2 snan: qnan
16910
16911 // s0 qnan: min(s1, s2)
16912 // s1 qnan: min(s0, s2)
16913 // s2 qnan: min(s0, s1)
16914
16915 // ieee=0
16916 // s0 snan: min(s1, s2)
16917 // s1 snan: min(s0, s2)
16918 // s2 snan: qnan
16919
16920 // s0 qnan: min(s1, s2)
16921 // s1 qnan: min(s0, s2)
16922 // s2 qnan: min(s0, s1)
16923 const MachineFunction &MF = DAG.getMachineFunction();
16924 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
16925
16926 // TODO: Check IEEE bit enabled. We can form fmed3 with IEEE=0 regardless of
16927 // whether the input is a signaling nan if op0 is fmaximum or fmaximumnum. We
16928 // can only form if op0 is fmaxnum_ieee if IEEE=1.
16929 EVT VT = Op0.getValueType();
16930 if (Info->getMode().DX10Clamp) {
16931 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
16932 // hardware fmed3 behavior converting to a min.
16933 // FIXME: Should this be allowing -0.0?
16934 if (K1->isOne() && K0->isPosZero())
16935 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
16936 }
16937
16938 // med3 for f16 is only available on gfx9+, and not available for v2f16.
16939 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
16940 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
16941 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
16942 // then give the other result, which is different from med3 with a NaN
16943 // input.
16944 SDValue Var = Op0.getOperand(0);
16945 if (!IsKnownNoNaNs && !DAG.isKnownNeverSNaN(Var))
16946 return SDValue();
16947
16948 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
16949
16950 if ((!K0->hasOneUse() || TII->isInlineConstant(K0->getValueAPF())) &&
16951 (!K1->hasOneUse() || TII->isInlineConstant(K1->getValueAPF()))) {
16952 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), Var,
16953 SDValue(K0, 0), SDValue(K1, 0));
16954 }
16955 }
16956
16957 return SDValue();
16958}
16959
16960/// \return true if the subtarget supports minimum3 and maximum3 with the given
16961/// base min/max opcode \p Opc for type \p VT.
16962static bool supportsMin3Max3(const GCNSubtarget &Subtarget, unsigned Opc,
16963 EVT VT) {
16964 switch (Opc) {
16965 case ISD::FMINNUM:
16966 case ISD::FMAXNUM:
16967 case ISD::FMINNUM_IEEE:
16968 case ISD::FMAXNUM_IEEE:
16969 case ISD::FMINIMUMNUM:
16970 case ISD::FMAXIMUMNUM:
16971 case AMDGPUISD::FMIN_LEGACY:
16972 case AMDGPUISD::FMAX_LEGACY:
16973 return (VT == MVT::f32) || (VT == MVT::f16 && Subtarget.hasMin3Max3_16()) ||
16974 (VT == MVT::v2f16 && Subtarget.hasMin3Max3PKF16());
16975 case ISD::FMINIMUM:
16976 case ISD::FMAXIMUM:
16977 return (VT == MVT::f32 && Subtarget.hasMinimum3Maximum3F32()) ||
16978 (VT == MVT::f16 && Subtarget.hasMinimum3Maximum3F16()) ||
16979 (VT == MVT::v2f16 && Subtarget.hasMinimum3Maximum3PKF16());
16980 case ISD::SMAX:
16981 case ISD::SMIN:
16982 case ISD::UMAX:
16983 case ISD::UMIN:
16984 return (VT == MVT::i32) || (VT == MVT::i16 && Subtarget.hasMin3Max3_16());
16985 default:
16986 return false;
16987 }
16988
16989 llvm_unreachable("not a min/max opcode");
16990}
16991
16992SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
16993 DAGCombinerInfo &DCI) const {
16994 SelectionDAG &DAG = DCI.DAG;
16995
16996 EVT VT = N->getValueType(0);
16997 unsigned Opc = N->getOpcode();
16998 SDValue Op0 = N->getOperand(0);
16999 SDValue Op1 = N->getOperand(1);
17000
17001 // Only do this if the inner op has one use since this will just increases
17002 // register pressure for no benefit.
17003
17004 if (supportsMin3Max3(*Subtarget, Opc, VT)) {
17005 auto IsTreeWithCombinableChildren = [Opc](SDValue Op) {
17006 return (Op.getOperand(0).getOpcode() == Opc &&
17007 Op.getOperand(0).hasOneUse()) ||
17008 (Op.getOperand(1).getOpcode() == Opc &&
17009 Op.getOperand(1).hasOneUse());
17010 };
17011
17012 bool CanTreeCombineApply = Op0.getOpcode() == Opc && Op0.hasOneUse() &&
17013 Op1.getOpcode() == Opc && Op1.hasOneUse();
17014 bool HasCombinableTreeChild =
17015 CanTreeCombineApply && (IsTreeWithCombinableChildren(Op0) ||
17016 IsTreeWithCombinableChildren(Op1));
17017
17018 // Tree reduction: when both operands are the same min/max op, restructure
17019 // to keep a 2-op node on top so higher tree levels can still combine.
17020 //
17021 // max(max(a, b), max(c, d)) -> max(max3(a, b, c), d)
17022 // min(min(a, b), min(c, d)) -> min(min3(a, b, c), d)
17023 //
17024 // Defer when either inner op is a tree node with combinable children.
17025 if (CanTreeCombineApply && !HasCombinableTreeChild) {
17026 SDLoc DL(N);
17027 SDValue Inner =
17029 Op0.getOperand(1), Op1.getOperand(0));
17030 return DAG.getNode(Opc, DL, VT, Inner, Op1.getOperand(1));
17031 }
17032
17033 // max(max(a, b), c) -> max3(a, b, c)
17034 // min(min(a, b), c) -> min3(a, b, c)
17035 // Deferred when Op0 is a tree node with combinable children.
17036 if (Op0.getOpcode() == Opc && Op0.hasOneUse() && !HasCombinableTreeChild) {
17037 SDLoc DL(N);
17038 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), DL, N->getValueType(0),
17039 Op0.getOperand(0), Op0.getOperand(1), Op1);
17040 }
17041
17042 // Try commuted.
17043 // max(a, max(b, c)) -> max3(a, b, c)
17044 // min(a, min(b, c)) -> min3(a, b, c)
17045 // Deferred when Op1 is a tree node with combinable children.
17046 if (Op1.getOpcode() == Opc && Op1.hasOneUse() && !HasCombinableTreeChild) {
17047 SDLoc DL(N);
17048 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), DL, N->getValueType(0),
17049 Op0, Op1.getOperand(0), Op1.getOperand(1));
17050 }
17051 }
17052
17053 // umin(sffbh(x), bitwidth) -> sffbh(x) if x is known to be not 0 or -1.
17054 SDValue FfbhSrc;
17055 uint64_t Clamp = 0;
17056 if (Opc == ISD::UMIN &&
17057 sd_match(Op0,
17059 sd_match(Op1, m_ConstInt(Clamp))) {
17060 unsigned BitWidth = FfbhSrc.getValueType().getScalarSizeInBits();
17061 if (Clamp >= BitWidth) {
17062 KnownBits Known = DAG.computeKnownBits(FfbhSrc);
17063 if (Known.isNonZero() && Known.Zero.getBoolValue())
17064 return Op0;
17065 }
17066 }
17067
17068 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
17069 // max(min(x, K0), K1), K1 < K0 -> med3(x, K1, K0)
17070 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
17071 if (SDValue Med3 = performIntMed3ImmCombine(
17072 DAG, SDLoc(N), Op0->getOperand(0), Op1, Op0->getOperand(1), true))
17073 return Med3;
17074 }
17075 if (Opc == ISD::SMAX && Op0.getOpcode() == ISD::SMIN && Op0.hasOneUse()) {
17076 if (SDValue Med3 = performIntMed3ImmCombine(
17077 DAG, SDLoc(N), Op0->getOperand(0), Op0->getOperand(1), Op1, true))
17078 return Med3;
17079 }
17080
17081 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
17082 if (SDValue Med3 = performIntMed3ImmCombine(
17083 DAG, SDLoc(N), Op0->getOperand(0), Op1, Op0->getOperand(1), false))
17084 return Med3;
17085 }
17086 if (Opc == ISD::UMAX && Op0.getOpcode() == ISD::UMIN && Op0.hasOneUse()) {
17087 if (SDValue Med3 = performIntMed3ImmCombine(
17088 DAG, SDLoc(N), Op0->getOperand(0), Op0->getOperand(1), Op1, false))
17089 return Med3;
17090 }
17091
17092 // if !is_snan(x):
17093 // fminnum(fmaxnum(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
17094 // fminnum_ieee(fmaxnum_ieee(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
17095 // fminnumnum(fmaxnumnum(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
17096 // fmin_legacy(fmax_legacy(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
17097 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
17100 (Opc == AMDGPUISD::FMIN_LEGACY &&
17101 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
17102 (VT == MVT::f32 || VT == MVT::f64 ||
17103 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
17104 (VT == MVT::bf16 && Subtarget->hasBF16PackedInsts()) ||
17105 (VT == MVT::v2bf16 && Subtarget->hasBF16PackedInsts()) ||
17106 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
17107 Op0.hasOneUse()) {
17108 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1,
17109 N->getFlags().hasNoNaNs()))
17110 return Res;
17111 }
17112
17113 // Prefer fminnum_ieee over fminimum. For gfx950, minimum/maximum are legal
17114 // for some types, but at a higher cost since it's implemented with a 3
17115 // operand form.
17116 const SDNodeFlags Flags = N->getFlags();
17117 if ((Opc == ISD::FMINIMUM || Opc == ISD::FMAXIMUM) && Flags.hasNoNaNs() &&
17118 !Subtarget->hasIEEEMinimumMaximumInsts() &&
17120 unsigned NewOpc =
17122 return DAG.getNode(NewOpc, SDLoc(N), VT, Op0, Op1, Flags);
17123 }
17124
17125 return SDValue();
17126}
17127
17131 // FIXME: Should this be allowing -0.0?
17132 return (CA->isPosZero() && CB->isOne()) ||
17133 (CA->isOne() && CB->isPosZero());
17134 }
17135 }
17136
17137 return false;
17138}
17139
17140// FIXME: Should only worry about snans for version with chain.
17141SDValue SITargetLowering::performFMed3Combine(SDNode *N,
17142 DAGCombinerInfo &DCI) const {
17143 EVT VT = N->getValueType(0);
17144 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
17145 // NaNs. With a NaN input, the order of the operands may change the result.
17146
17147 SelectionDAG &DAG = DCI.DAG;
17148 SDLoc SL(N);
17149
17150 SDValue Src0 = N->getOperand(0);
17151 SDValue Src1 = N->getOperand(1);
17152 SDValue Src2 = N->getOperand(2);
17153
17154 if (isClampZeroToOne(Src0, Src1)) {
17155 // const_a, const_b, x -> clamp is safe in all cases including signaling
17156 // nans.
17157 // FIXME: Should this be allowing -0.0?
17158 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
17159 }
17160
17161 const MachineFunction &MF = DAG.getMachineFunction();
17162 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
17163
17164 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
17165 // handling no dx10-clamp?
17166 if (Info->getMode().DX10Clamp) {
17167 // If NaNs is clamped to 0, we are free to reorder the inputs.
17168
17169 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
17170 std::swap(Src0, Src1);
17171
17172 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
17173 std::swap(Src1, Src2);
17174
17175 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
17176 std::swap(Src0, Src1);
17177
17178 if (isClampZeroToOne(Src1, Src2))
17179 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
17180 }
17181
17182 return SDValue();
17183}
17184
17185SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
17186 DAGCombinerInfo &DCI) const {
17187 SDValue Src0 = N->getOperand(0);
17188 SDValue Src1 = N->getOperand(1);
17189 if (Src0.isUndef() && Src1.isUndef())
17190 return DCI.DAG.getUNDEF(N->getValueType(0));
17191 return SDValue();
17192}
17193
17194/// V_CVT_SCALEF32_* conversions to a narrow format only read the exponent
17195/// field of their f32 scale operand.
17196SDValue
17197SITargetLowering::performExponentOnlyScaleCombine(SDNode *N,
17198 DAGCombinerInfo &DCI) const {
17199 std::optional<unsigned> ScaleArgIdx =
17200 AMDGPU::getExponentOnlyScaleArgIdx(N->getConstantOperandVal(0));
17201 if (!ScaleArgIdx)
17202 return SDValue();
17203
17204 // Operand 0 is the intrinsic ID.
17205 unsigned OpIdx = *ScaleArgIdx + 1;
17206 SelectionDAG &DAG = DCI.DAG;
17207 SDValue Scale = N->getOperand(OpIdx);
17209
17210 if (SDValue DemandedScale =
17211 SimplifyMultipleUseDemandedBits(Scale, Demanded, DAG)) {
17212 SmallVector<SDValue> Ops(N->ops());
17213 Ops[OpIdx] = DemandedScale;
17214 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getVTList(), Ops);
17215 }
17216
17217 if (SimplifyDemandedBits(Scale, Demanded, DCI))
17218 return SDValue(N, 0);
17219
17220 return SDValue();
17221}
17222
17223// Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
17224// expanded into a set of cmp/select instructions.
17226 unsigned NumElem,
17227 bool IsDivergentIdx,
17228 const GCNSubtarget *Subtarget) {
17229 if (Subtarget->getCLOpts().use_divergent_register_indexing)
17230 return false;
17231
17232 unsigned VecSize = EltSize * NumElem;
17233
17234 // Sub-dword vectors of size 2 dword or less have better implementation.
17235 if (VecSize <= 64 && EltSize < 32)
17236 return false;
17237
17238 // Always expand the rest of sub-dword instructions, otherwise it will be
17239 // lowered via memory.
17240 if (EltSize < 32)
17241 return true;
17242
17243 // Always do this if var-idx is divergent, otherwise it will become a loop.
17244 if (IsDivergentIdx)
17245 return true;
17246
17247 // Large vectors would yield too many compares and v_cndmask_b32 instructions.
17248 unsigned NumInsts = NumElem /* Number of compares */ +
17249 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
17250
17251 // On some architectures (GFX9) movrel is not available and it's better
17252 // to expand.
17253 if (Subtarget->useVGPRIndexMode())
17254 return NumInsts <= 16;
17255
17256 // If movrel is available, use it instead of expanding for vector of 8
17257 // elements.
17258 if (Subtarget->hasMovrel())
17259 return NumInsts <= 15;
17260
17261 return true;
17262}
17263
17265 SDValue Idx = N->getOperand(N->getNumOperands() - 1);
17266 if (isa<ConstantSDNode>(Idx))
17267 return false;
17268
17269 SDValue Vec = N->getOperand(0);
17270 EVT VecVT = Vec.getValueType();
17271 EVT EltVT = VecVT.getVectorElementType();
17272 unsigned EltSize = EltVT.getSizeInBits();
17273 unsigned NumElem = VecVT.getVectorNumElements();
17274
17276 EltSize, NumElem, Idx->isDivergent(), getSubtarget());
17277}
17278
17279SDValue
17280SITargetLowering::performExtractVectorEltCombine(SDNode *N,
17281 DAGCombinerInfo &DCI) const {
17282 SDValue Vec = N->getOperand(0);
17283 SelectionDAG &DAG = DCI.DAG;
17284
17285 EVT VecVT = Vec.getValueType();
17286 EVT VecEltVT = VecVT.getVectorElementType();
17287 EVT ResVT = N->getValueType(0);
17288
17289 unsigned VecSize = VecVT.getSizeInBits();
17290 unsigned VecEltSize = VecEltVT.getSizeInBits();
17291
17292 if ((Vec.getOpcode() == ISD::FNEG || Vec.getOpcode() == ISD::FABS) &&
17294 SDLoc SL(N);
17295 SDValue Idx = N->getOperand(1);
17296 SDValue Elt =
17297 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT, Vec.getOperand(0), Idx);
17298 return DAG.getNode(Vec.getOpcode(), SL, ResVT, Elt);
17299 }
17300
17301 // (extract_vector_element (and {y0, y1}, (build_vector 0x1f, 0x1f)), index)
17302 // -> (and (extract_vector_element {y0, y1}, index), 0x1f)
17303 // There are optimisations to transform 64-bit shifts into 32-bit shifts
17304 // depending on the shift operand. See e.g. performSraCombine().
17305 // This combine ensures that the optimisation is compatible with v2i32
17306 // legalised AND.
17307 if (VecVT == MVT::v2i32 && Vec->getOpcode() == ISD::AND &&
17308 Vec->getOperand(1)->getOpcode() == ISD::BUILD_VECTOR) {
17309
17311 if (!C || C->getZExtValue() != 0x1f)
17312 return SDValue();
17313
17314 SDLoc SL(N);
17315 SDValue AndMask = DAG.getConstant(0x1f, SL, MVT::i32);
17316 SDValue EVE = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32,
17317 Vec->getOperand(0), N->getOperand(1));
17318 SDValue A = DAG.getNode(ISD::AND, SL, MVT::i32, EVE, AndMask);
17319 DAG.ReplaceAllUsesWith(N, A.getNode());
17320 }
17321
17322 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
17323 // =>
17324 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
17325 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
17326 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
17327 if (Vec.hasOneUse() && DCI.isBeforeLegalize() && VecEltVT == ResVT) {
17328 SDLoc SL(N);
17329 SDValue Idx = N->getOperand(1);
17330 unsigned Opc = Vec.getOpcode();
17331
17332 switch (Opc) {
17333 default:
17334 break;
17335 // TODO: Support other binary operations.
17336 case ISD::FADD:
17337 case ISD::FSUB:
17338 case ISD::FMUL:
17339 case ISD::ADD:
17340 case ISD::UMIN:
17341 case ISD::UMAX:
17342 case ISD::SMIN:
17343 case ISD::SMAX:
17344 case ISD::FMAXNUM:
17345 case ISD::FMINNUM:
17346 case ISD::FMAXNUM_IEEE:
17347 case ISD::FMINNUM_IEEE:
17348 case ISD::FMAXIMUM:
17349 case ISD::FMINIMUM: {
17350 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT,
17351 Vec.getOperand(0), Idx);
17352 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT,
17353 Vec.getOperand(1), Idx);
17354
17355 DCI.AddToWorklist(Elt0.getNode());
17356 DCI.AddToWorklist(Elt1.getNode());
17357 return DAG.getNode(Opc, SL, ResVT, Elt0, Elt1, Vec->getFlags());
17358 }
17359 }
17360 }
17361
17362 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
17364 SDLoc SL(N);
17365 SDValue Idx = N->getOperand(1);
17366 SDValue V;
17367 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
17368 SDValue IC = DAG.getVectorIdxConstant(I, SL);
17369 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT, Vec, IC);
17370 if (I == 0)
17371 V = Elt;
17372 else
17373 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
17374 }
17375 return V;
17376 }
17377
17378 // EXTRACT_VECTOR_ELT (v2i32 bitcast (i64/f64:k), Idx)
17379 // =>
17380 // i32:Lo(k) if Idx == 0, or
17381 // i32:Hi(k) if Idx == 1
17382 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
17383 if (Vec.getOpcode() == ISD::BITCAST && VecVT == MVT::v2i32 && Idx) {
17384 SDLoc SL(N);
17385 SDValue PeekThrough = Vec.getOperand(0);
17386 auto *KImm = dyn_cast<ConstantSDNode>(PeekThrough);
17387 if (KImm && KImm->getValueType(0).getSizeInBits() == 64) {
17388 uint64_t KImmValue = KImm->getZExtValue();
17389 return DAG.getConstant(
17390 (KImmValue >> (32 * Idx->getZExtValue())) & 0xffffffff, SL, MVT::i32);
17391 }
17392 auto *KFPImm = dyn_cast<ConstantFPSDNode>(PeekThrough);
17393 if (KFPImm && KFPImm->getValueType(0).getSizeInBits() == 64) {
17394 uint64_t KFPImmValue =
17395 KFPImm->getValueAPF().bitcastToAPInt().getZExtValue();
17396 return DAG.getConstant((KFPImmValue >> (32 * Idx->getZExtValue())) &
17397 0xffffffff,
17398 SL, MVT::i32);
17399 }
17400 }
17401
17402 if (!DCI.isBeforeLegalize())
17403 return SDValue();
17404
17405 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
17406 // elements. This exposes more load reduction opportunities by replacing
17407 // multiple small extract_vector_elements with a single 32-bit extract.
17408 if (isa<MemSDNode>(Vec) && VecEltSize <= 16 && VecEltVT.isByteSized() &&
17409 VecSize > 32 && VecSize % 32 == 0 && Idx) {
17410 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
17411
17412 unsigned BitIndex = Idx->getZExtValue() * VecEltSize;
17413 unsigned EltIdx = BitIndex / 32;
17414 unsigned LeftoverBitIdx = BitIndex % 32;
17415 SDLoc SL(N);
17416
17417 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
17418 DCI.AddToWorklist(Cast.getNode());
17419
17420 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
17421 DAG.getConstant(EltIdx, SL, MVT::i32));
17422 DCI.AddToWorklist(Elt.getNode());
17423 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
17424 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
17425 DCI.AddToWorklist(Srl.getNode());
17426
17427 EVT VecEltAsIntVT = VecEltVT.changeTypeToInteger();
17428 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VecEltAsIntVT, Srl);
17429 DCI.AddToWorklist(Trunc.getNode());
17430
17431 if (VecEltVT == ResVT) {
17432 return DAG.getNode(ISD::BITCAST, SL, VecEltVT, Trunc);
17433 }
17434
17435 assert(ResVT.isScalarInteger());
17436 return DAG.getAnyExtOrTrunc(Trunc, SL, ResVT);
17437 }
17438
17439 return SDValue();
17440}
17441
17442SDValue
17443SITargetLowering::performInsertVectorEltCombine(SDNode *N,
17444 DAGCombinerInfo &DCI) const {
17445 SDValue Vec = N->getOperand(0);
17446 SDValue Idx = N->getOperand(2);
17447 EVT VecVT = Vec.getValueType();
17448 EVT EltVT = VecVT.getVectorElementType();
17449
17450 // INSERT_VECTOR_ELT (<n x e>, var-idx)
17451 // => BUILD_VECTOR n x select (e, const-idx)
17452 // 16-bit elements are left to lowerINSERT_VECTOR_ELT, which is cheaper.
17454 (EltVT.getSizeInBits() == 16 &&
17456 return SDValue();
17457
17458 SelectionDAG &DAG = DCI.DAG;
17459 SDLoc SL(N);
17460 SDValue Ins = N->getOperand(1);
17461 EVT IdxVT = Idx.getValueType();
17462
17464 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
17465 SDValue IC = DAG.getConstant(I, SL, IdxVT);
17466 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
17467 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
17468 Ops.push_back(V);
17469 }
17470
17471 return DAG.getBuildVector(VecVT, SL, Ops);
17472}
17473
17474/// Return the source of an fp_extend from f16 to f32, or a converted FP
17475/// constant.
17477 if (Src.getOpcode() == ISD::FP_EXTEND &&
17478 Src.getOperand(0).getValueType() == MVT::f16) {
17479 return Src.getOperand(0);
17480 }
17481
17482 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Src)) {
17483 APFloat Val = CFP->getValueAPF();
17484 bool LosesInfo = true;
17486 if (!LosesInfo)
17487 return DAG.getConstantFP(Val, SDLoc(Src), MVT::f16);
17488 }
17489
17490 return SDValue();
17491}
17492
17493SDValue SITargetLowering::performFPRoundCombine(SDNode *N,
17494 DAGCombinerInfo &DCI) const {
17495 assert(Subtarget->has16BitInsts() && !Subtarget->hasMed3_16() &&
17496 "combine only useful on gfx8");
17497
17498 SDValue TruncSrc = N->getOperand(0);
17499 EVT VT = N->getValueType(0);
17500 if (VT != MVT::f16)
17501 return SDValue();
17502
17503 if (TruncSrc.getOpcode() != AMDGPUISD::FMED3 ||
17504 TruncSrc.getValueType() != MVT::f32 || !TruncSrc.hasOneUse())
17505 return SDValue();
17506
17507 SelectionDAG &DAG = DCI.DAG;
17508 SDLoc SL(N);
17509
17510 // Optimize f16 fmed3 pattern performed on f32. On gfx8 there is no f16 fmed3,
17511 // and expanding it with min/max saves 1 instruction vs. casting to f32 and
17512 // casting back.
17513
17514 // fptrunc (f32 (fmed3 (fpext f16:a, fpext f16:b, fpext f16:c))) =>
17515 // fmin(fmax(a, b), fmax(fmin(a, b), c))
17516 SDValue A = strictFPExtFromF16(DAG, TruncSrc.getOperand(0));
17517 if (!A)
17518 return SDValue();
17519
17520 SDValue B = strictFPExtFromF16(DAG, TruncSrc.getOperand(1));
17521 if (!B)
17522 return SDValue();
17523
17524 SDValue C = strictFPExtFromF16(DAG, TruncSrc.getOperand(2));
17525 if (!C)
17526 return SDValue();
17527
17528 // This changes signaling nan behavior. If an input is a signaling nan, it
17529 // would have been quieted by the fpext originally. We don't care because
17530 // these are unconstrained ops. If we needed to insert quieting canonicalizes
17531 // we would be worse off than just doing the promotion.
17532 SDValue A1 = DAG.getNode(ISD::FMINNUM_IEEE, SL, VT, A, B);
17533 SDValue B1 = DAG.getNode(ISD::FMAXNUM_IEEE, SL, VT, A, B);
17534 SDValue C1 = DAG.getNode(ISD::FMAXNUM_IEEE, SL, VT, A1, C);
17535 return DAG.getNode(ISD::FMINNUM_IEEE, SL, VT, B1, C1);
17536}
17537
17538unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
17539 const SDNode *N0,
17540 const SDNode *N1) const {
17541 EVT VT = N0->getValueType(0);
17542
17543 // Only do this if we are not trying to support denormals. v_mad_f32 does not
17544 // support denormals ever.
17545 if (((VT == MVT::f32 &&
17547 (VT == MVT::f16 && Subtarget->hasMadF16() &&
17550 return ISD::FMAD;
17551
17552 if (N0->getFlags().hasAllowContract() && N1->getFlags().hasAllowContract() &&
17554 return ISD::FMA;
17555 }
17556
17557 return 0;
17558}
17559
17560// For a reassociatable opcode perform:
17561// op x, (op y, z) -> op (op x, z), y, if x and z are uniform
17562SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
17563 SelectionDAG &DAG) const {
17564 EVT VT = N->getValueType(0);
17565 if (VT != MVT::i32 && VT != MVT::i64)
17566 return SDValue();
17567
17568 if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
17569 return SDValue();
17570
17571 unsigned Opc = N->getOpcode();
17572 SDValue Op0 = N->getOperand(0);
17573 SDValue Op1 = N->getOperand(1);
17574
17575 if (!(Op0->isDivergent() ^ Op1->isDivergent()))
17576 return SDValue();
17577
17578 if (Op0->isDivergent())
17579 std::swap(Op0, Op1);
17580
17581 if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
17582 return SDValue();
17583
17584 SDValue Op2 = Op1.getOperand(1);
17585 Op1 = Op1.getOperand(0);
17586 if (!(Op1->isDivergent() ^ Op2->isDivergent()))
17587 return SDValue();
17588
17589 if (Op1->isDivergent())
17590 std::swap(Op1, Op2);
17591
17592 SDLoc SL(N);
17593 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
17594 return DAG.getNode(Opc, SL, VT, Add1, Op2);
17595}
17596
17597static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, EVT VT,
17598 SDValue N0, SDValue N1, SDValue N2, bool Signed) {
17600 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
17601 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
17602 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
17603}
17604
17605// Fold
17606// y = lshr i64 x, 32
17607// res = add (mul i64 y, Const), x where "Const" is a 64-bit constant
17608// with Const.hi == -1
17609// To
17610// res = mad_u64_u32 y.lo ,Const.lo, x.lo
17612 SDValue MulLHS, SDValue MulRHS,
17613 SDValue AddRHS) {
17614 if (MulRHS.getOpcode() == ISD::SRL)
17615 std::swap(MulLHS, MulRHS);
17616
17617 if (MulLHS.getValueType() != MVT::i64 || MulLHS.getOpcode() != ISD::SRL)
17618 return SDValue();
17619
17620 ConstantSDNode *ShiftVal = dyn_cast<ConstantSDNode>(MulLHS.getOperand(1));
17621 if (!ShiftVal || ShiftVal->getAsZExtVal() != 32 ||
17622 MulLHS.getOperand(0) != AddRHS)
17623 return SDValue();
17624
17626 if (!Const || Hi_32(Const->getZExtValue()) != uint32_t(-1))
17627 return SDValue();
17628
17629 SDValue ConstMul =
17630 DAG.getConstant(Lo_32(Const->getZExtValue()), SL, MVT::i32);
17631 return getMad64_32(DAG, SL, MVT::i64,
17632 DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS), ConstMul,
17633 DAG.getZeroExtendInReg(AddRHS, SL, MVT::i32), false);
17634}
17635
17636// Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high
17637// multiplies, if any.
17638//
17639// Full 64-bit multiplies that feed into an addition are lowered here instead
17640// of using the generic expansion. The generic expansion ends up with
17641// a tree of ADD nodes that prevents us from using the "add" part of the
17642// MAD instruction. The expansion produced here results in a chain of ADDs
17643// instead of a tree.
17644SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
17645 DAGCombinerInfo &DCI) const {
17646 assert(N->isAnyAdd());
17647
17648 SelectionDAG &DAG = DCI.DAG;
17649 EVT VT = N->getValueType(0);
17650 SDLoc SL(N);
17651 SDValue LHS = N->getOperand(0);
17652 SDValue RHS = N->getOperand(1);
17653
17654 if (VT.isVector())
17655 return SDValue();
17656
17657 // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall
17658 // result in scalar registers for uniform values.
17659 if (!N->isDivergent() && Subtarget->hasSMulHi())
17660 return SDValue();
17661
17662 unsigned NumBits = VT.getScalarSizeInBits();
17663 if (NumBits <= 32 || NumBits > 64)
17664 return SDValue();
17665
17666 if (LHS.getOpcode() != ISD::MUL) {
17667 assert(RHS.getOpcode() == ISD::MUL);
17668 std::swap(LHS, RHS);
17669 }
17670
17671 // Avoid the fold if it would unduly increase the number of multiplies due to
17672 // multiple uses, except on hardware with full-rate multiply-add (which is
17673 // part of full-rate 64-bit ops).
17674 if (!Subtarget->hasFullRate64Ops()) {
17675 unsigned NumUsers = 0;
17676 for (SDNode *User : LHS->users()) {
17677 // There is a use that does not feed into addition, so the multiply can't
17678 // be removed. We prefer MUL + ADD + ADDC over MAD + MUL.
17679 if (!User->isAnyAdd())
17680 return SDValue();
17681
17682 // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer
17683 // MUL + 3xADD + 3xADDC over 3xMAD.
17684 ++NumUsers;
17685 if (NumUsers >= 3)
17686 return SDValue();
17687 }
17688 }
17689
17690 SDValue MulLHS = LHS.getOperand(0);
17691 SDValue MulRHS = LHS.getOperand(1);
17692 SDValue AddRHS = RHS;
17693
17694 if (SDValue FoldedMAD = tryFoldMADwithSRL(DAG, SL, MulLHS, MulRHS, AddRHS))
17695 return FoldedMAD;
17696
17697 // Always check whether operands are small unsigned values, since that
17698 // knowledge is useful in more cases. Check for small signed values only if
17699 // doing so can unlock a shorter code sequence.
17700 bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32;
17701 bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32;
17702
17703 bool MulSignedLo = false;
17704 if (!MulLHSUnsigned32 || !MulRHSUnsigned32) {
17705 MulSignedLo =
17706 numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32;
17707 }
17708
17709 // The operands and final result all have the same number of bits. If
17710 // operands need to be extended, they can be extended with garbage. The
17711 // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is
17712 // truncated away in the end.
17713 if (VT != MVT::i64) {
17714 MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS);
17715 MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS);
17716 AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS);
17717 }
17718
17719 // The basic code generated is conceptually straightforward. Pseudo code:
17720 //
17721 // accum = mad_64_32 lhs.lo, rhs.lo, accum
17722 // accum.hi = add (mul lhs.hi, rhs.lo), accum.hi
17723 // accum.hi = add (mul lhs.lo, rhs.hi), accum.hi
17724 //
17725 // The second and third lines are optional, depending on whether the factors
17726 // are {sign,zero}-extended or not.
17727 //
17728 // The actual DAG is noisier than the pseudo code, but only due to
17729 // instructions that disassemble values into low and high parts, and
17730 // assemble the final result.
17731 SDValue One = DAG.getConstant(1, SL, MVT::i32);
17732
17733 auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS);
17734 auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS);
17735 SDValue Accum =
17736 getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo);
17737
17738 if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) {
17739 auto [AccumLo, AccumHi] = DAG.SplitScalar(Accum, SL, MVT::i32, MVT::i32);
17740
17741 if (!MulLHSUnsigned32) {
17742 auto MulLHSHi =
17743 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One);
17744 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo);
17745 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
17746 }
17747
17748 if (!MulRHSUnsigned32) {
17749 auto MulRHSHi =
17750 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One);
17751 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi);
17752 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
17753 }
17754
17755 Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi});
17756 Accum = DAG.getBitcast(MVT::i64, Accum);
17757 }
17758
17759 if (VT != MVT::i64)
17760 Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum);
17761 return Accum;
17762}
17763
17764SDValue
17765SITargetLowering::foldAddSub64WithZeroLowBitsTo32(SDNode *N,
17766 DAGCombinerInfo &DCI) const {
17767 SDValue RHS = N->getOperand(1);
17768 auto *CRHS = dyn_cast<ConstantSDNode>(RHS);
17769 if (!CRHS)
17770 return SDValue();
17771
17772 // TODO: Worth using computeKnownBits? Maybe expensive since it's so
17773 // common.
17774 uint64_t Val = CRHS->getZExtValue();
17775 if (countr_zero(Val) >= 32) {
17776 SelectionDAG &DAG = DCI.DAG;
17777 SDLoc SL(N);
17778 SDValue LHS = N->getOperand(0);
17779
17780 // Avoid carry machinery if we know the low half of the add does not
17781 // contribute to the final result.
17782 //
17783 // add i64:x, K if computeTrailingZeros(K) >= 32
17784 // => build_pair (add x.hi, K.hi), x.lo
17785
17786 // Breaking the 64-bit add here with this strange constant is unlikely
17787 // to interfere with addressing mode patterns.
17788
17789 SDValue Hi = getHiHalf64(LHS, DAG);
17790 SDValue ConstHi32 = DAG.getConstant(Hi_32(Val), SL, MVT::i32);
17791 unsigned Opcode = N->getOpcode();
17792 if (Opcode == ISD::PTRADD)
17793 Opcode = ISD::ADD;
17794 SDValue AddHi =
17795 DAG.getNode(Opcode, SL, MVT::i32, Hi, ConstHi32, N->getFlags());
17796
17797 SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
17798 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i64, Lo, AddHi);
17799 }
17800
17801 return SDValue();
17802}
17803
17804// Collect the ultimate src of each of the mul node's operands, and confirm
17805// each operand is 8 bytes.
17806static std::optional<ByteProvider<SDValue>>
17807handleMulOperand(const SDValue &MulOperand) {
17808 auto Byte0 = calculateByteProvider(MulOperand, 0, 0);
17809 if (!Byte0 || Byte0->isConstantZero()) {
17810 return std::nullopt;
17811 }
17812 auto Byte1 = calculateByteProvider(MulOperand, 1, 0);
17813 if (Byte1 && !Byte1->isConstantZero()) {
17814 return std::nullopt;
17815 }
17816 return Byte0;
17817}
17818
17819static unsigned addPermMasks(unsigned First, unsigned Second) {
17820 unsigned FirstCs = First & 0x0c0c0c0c;
17821 unsigned SecondCs = Second & 0x0c0c0c0c;
17822 unsigned FirstNoCs = First & ~0x0c0c0c0c;
17823 unsigned SecondNoCs = Second & ~0x0c0c0c0c;
17824
17825 assert((FirstCs & 0xFF) | (SecondCs & 0xFF));
17826 assert((FirstCs & 0xFF00) | (SecondCs & 0xFF00));
17827 assert((FirstCs & 0xFF0000) | (SecondCs & 0xFF0000));
17828 assert((FirstCs & 0xFF000000) | (SecondCs & 0xFF000000));
17829
17830 return (FirstNoCs | SecondNoCs) | (FirstCs & SecondCs);
17831}
17832
17833struct DotSrc {
17835 int64_t PermMask;
17837};
17838
17842 SmallVectorImpl<DotSrc> &Src1s, int Step) {
17843
17844 assert(Src0.Src.has_value() && Src1.Src.has_value());
17845 // Src0s and Src1s are empty, just place arbitrarily.
17846 if (Step == 0) {
17847 Src0s.push_back({*Src0.Src, ((Src0.SrcOffset % 4) << 24) + 0x0c0c0c,
17848 Src0.SrcOffset / 4});
17849 Src1s.push_back({*Src1.Src, ((Src1.SrcOffset % 4) << 24) + 0x0c0c0c,
17850 Src1.SrcOffset / 4});
17851 return;
17852 }
17853
17854 for (int BPI = 0; BPI < 2; BPI++) {
17855 std::pair<ByteProvider<SDValue>, ByteProvider<SDValue>> BPP = {Src0, Src1};
17856 if (BPI == 1) {
17857 BPP = {Src1, Src0};
17858 }
17859 unsigned ZeroMask = 0x0c0c0c0c;
17860 unsigned FMask = 0xFF << (8 * (3 - Step));
17861
17862 unsigned FirstMask =
17863 (BPP.first.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask);
17864 unsigned SecondMask =
17865 (BPP.second.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask);
17866 // Attempt to find Src vector which contains our SDValue, if so, add our
17867 // perm mask to the existing one. If we are unable to find a match for the
17868 // first SDValue, attempt to find match for the second.
17869 int FirstGroup = -1;
17870 for (int I = 0; I < 2; I++) {
17871 SmallVectorImpl<DotSrc> &Srcs = I == 0 ? Src0s : Src1s;
17872 auto MatchesFirst = [&BPP](DotSrc &IterElt) {
17873 return IterElt.SrcOp == *BPP.first.Src &&
17874 (IterElt.DWordOffset == (BPP.first.SrcOffset / 4));
17875 };
17876
17877 auto *Match = llvm::find_if(Srcs, MatchesFirst);
17878 if (Match != Srcs.end()) {
17879 Match->PermMask = addPermMasks(FirstMask, Match->PermMask);
17880 FirstGroup = I;
17881 break;
17882 }
17883 }
17884 if (FirstGroup != -1) {
17885 SmallVectorImpl<DotSrc> &Srcs = FirstGroup == 1 ? Src0s : Src1s;
17886 auto MatchesSecond = [&BPP](DotSrc &IterElt) {
17887 return IterElt.SrcOp == *BPP.second.Src &&
17888 (IterElt.DWordOffset == (BPP.second.SrcOffset / 4));
17889 };
17890 auto *Match = llvm::find_if(Srcs, MatchesSecond);
17891 if (Match != Srcs.end()) {
17892 Match->PermMask = addPermMasks(SecondMask, Match->PermMask);
17893 } else
17894 Srcs.push_back({*BPP.second.Src, SecondMask, BPP.second.SrcOffset / 4});
17895 return;
17896 }
17897 }
17898
17899 // If we have made it here, then we could not find a match in Src0s or Src1s
17900 // for either Src0 or Src1, so just place them arbitrarily.
17901
17902 unsigned ZeroMask = 0x0c0c0c0c;
17903 unsigned FMask = 0xFF << (8 * (3 - Step));
17904
17905 Src0s.push_back(
17906 {*Src0.Src,
17907 ((Src0.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask)),
17908 Src0.SrcOffset / 4});
17909 Src1s.push_back(
17910 {*Src1.Src,
17911 ((Src1.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask)),
17912 Src1.SrcOffset / 4});
17913}
17914
17916 SmallVectorImpl<DotSrc> &Srcs, bool IsSigned,
17917 bool IsAny) {
17918
17919 // If we just have one source, just permute it accordingly.
17920 if (Srcs.size() == 1) {
17921 auto *Elt = Srcs.begin();
17922 auto EltOp = getDWordFromOffset(DAG, SL, Elt->SrcOp, Elt->DWordOffset);
17923
17924 // v_perm will produce the original value
17925 if (Elt->PermMask == 0x3020100)
17926 return EltOp;
17927
17928 return DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, EltOp, EltOp,
17929 DAG.getConstant(Elt->PermMask, SL, MVT::i32));
17930 }
17931
17932 auto *FirstElt = Srcs.begin();
17933 auto *SecondElt = std::next(FirstElt);
17934
17936
17937 // If we have multiple sources in the chain, combine them via perms (using
17938 // calculated perm mask) and Ors.
17939 while (true) {
17940 auto FirstMask = FirstElt->PermMask;
17941 auto SecondMask = SecondElt->PermMask;
17942
17943 unsigned FirstCs = FirstMask & 0x0c0c0c0c;
17944 unsigned FirstPlusFour = FirstMask | 0x04040404;
17945 // 0x0c + 0x04 = 0x10, so anding with 0x0F will produced 0x00 for any
17946 // original 0x0C.
17947 FirstMask = (FirstPlusFour & 0x0F0F0F0F) | FirstCs;
17948
17949 auto PermMask = addPermMasks(FirstMask, SecondMask);
17950 auto FirstVal =
17951 getDWordFromOffset(DAG, SL, FirstElt->SrcOp, FirstElt->DWordOffset);
17952 auto SecondVal =
17953 getDWordFromOffset(DAG, SL, SecondElt->SrcOp, SecondElt->DWordOffset);
17954
17955 Perms.push_back(DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, FirstVal,
17956 SecondVal,
17957 DAG.getConstant(PermMask, SL, MVT::i32)));
17958
17959 FirstElt = std::next(SecondElt);
17960 if (FirstElt == Srcs.end())
17961 break;
17962
17963 SecondElt = std::next(FirstElt);
17964 // If we only have a FirstElt, then just combine that into the cumulative
17965 // source node.
17966 if (SecondElt == Srcs.end()) {
17967 auto EltOp =
17968 getDWordFromOffset(DAG, SL, FirstElt->SrcOp, FirstElt->DWordOffset);
17969
17970 Perms.push_back(
17971 DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, EltOp, EltOp,
17972 DAG.getConstant(FirstElt->PermMask, SL, MVT::i32)));
17973 break;
17974 }
17975 }
17976
17977 assert(Perms.size() == 1 || Perms.size() == 2);
17978 return Perms.size() == 2
17979 ? DAG.getNode(ISD::OR, SL, MVT::i32, Perms[0], Perms[1])
17980 : Perms[0];
17981}
17982
17983static void fixMasks(SmallVectorImpl<DotSrc> &Srcs, unsigned ChainLength) {
17984 for (auto &[EntryVal, EntryMask, EntryOffset] : Srcs) {
17985 EntryMask = EntryMask >> ((4 - ChainLength) * 8);
17986 auto ZeroMask = ChainLength == 2 ? 0x0c0c0000 : 0x0c000000;
17987 EntryMask += ZeroMask;
17988 }
17989}
17990
17991static bool isMul(const SDValue Op) {
17992 auto Opcode = Op.getOpcode();
17993
17994 return (Opcode == ISD::MUL || Opcode == AMDGPUISD::MUL_U24 ||
17995 Opcode == AMDGPUISD::MUL_I24);
17996}
17997
17998static std::optional<bool>
18000 ByteProvider<SDValue> &Src1, const SDValue &S0Op,
18001 const SDValue &S1Op, const SelectionDAG &DAG) {
18002 // If we both ops are i8s (pre legalize-dag), then the signedness semantics
18003 // of the dot4 is irrelevant.
18004 if (S0Op.getValueSizeInBits() == 8 && S1Op.getValueSizeInBits() == 8)
18005 return false;
18006
18007 auto Known0 = DAG.computeKnownBits(S0Op, 0);
18008 bool S0IsUnsigned = Known0.countMinLeadingZeros() > 0;
18009 bool S0IsSigned = Known0.countMinLeadingOnes() > 0;
18010 auto Known1 = DAG.computeKnownBits(S1Op, 0);
18011 bool S1IsUnsigned = Known1.countMinLeadingZeros() > 0;
18012 bool S1IsSigned = Known1.countMinLeadingOnes() > 0;
18013
18014 assert(!(S0IsUnsigned && S0IsSigned));
18015 assert(!(S1IsUnsigned && S1IsSigned));
18016
18017 // There are 9 possible permutations of
18018 // {S0IsUnsigned, S0IsSigned, S1IsUnsigned, S1IsSigned}
18019
18020 // In two permutations, the sign bits are known to be the same for both Ops,
18021 // so simply return Signed / Unsigned corresponding to the MSB
18022
18023 if ((S0IsUnsigned && S1IsUnsigned) || (S0IsSigned && S1IsSigned))
18024 return S0IsSigned;
18025
18026 // In another two permutations, the sign bits are known to be opposite. In
18027 // this case return std::nullopt to indicate a bad match.
18028
18029 if ((S0IsUnsigned && S1IsSigned) || (S0IsSigned && S1IsUnsigned))
18030 return std::nullopt;
18031
18032 // In the remaining five permutations, we don't know the value of the sign
18033 // bit for at least one Op. Since we have a valid ByteProvider, we know that
18034 // the upper bits must be extension bits. Thus, the only ways for the sign
18035 // bit to be unknown is if it was sign extended from unknown value, or if it
18036 // was any extended. In either case, it is correct to use the signed
18037 // version of the signedness semantics of dot4
18038
18039 // In two of such permutations, we known the sign bit is set for
18040 // one op, and the other is unknown. It is okay to used signed version of
18041 // dot4.
18042 if ((S0IsSigned && !(S1IsSigned || S1IsUnsigned)) ||
18043 ((S1IsSigned && !(S0IsSigned || S0IsUnsigned))))
18044 return true;
18045
18046 // In one such permutation, we don't know either of the sign bits. It is okay
18047 // to used the signed version of dot4.
18048 if ((!(S1IsSigned || S1IsUnsigned) && !(S0IsSigned || S0IsUnsigned)))
18049 return true;
18050
18051 // In two of such permutations, we known the sign bit is unset for
18052 // one op, and the other is unknown. Return std::nullopt to indicate a
18053 // bad match.
18054 if ((S0IsUnsigned && !(S1IsSigned || S1IsUnsigned)) ||
18055 ((S1IsUnsigned && !(S0IsSigned || S0IsUnsigned))))
18056 return std::nullopt;
18057
18058 llvm_unreachable("Fully covered condition");
18059}
18060
18061SDValue SITargetLowering::performAddCombine(SDNode *N,
18062 DAGCombinerInfo &DCI) const {
18063 SelectionDAG &DAG = DCI.DAG;
18064 EVT VT = N->getValueType(0);
18065 SDLoc SL(N);
18066 SDValue LHS = N->getOperand(0);
18067 SDValue RHS = N->getOperand(1);
18068
18069 if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
18070 if (Subtarget->hasMad64_32()) {
18071 if (SDValue Folded = tryFoldToMad64_32(N, DCI))
18072 return Folded;
18073 }
18074 }
18075
18076 if (SDValue V = reassociateScalarOps(N, DAG)) {
18077 return V;
18078 }
18079
18080 if (VT == MVT::i64) {
18081 if (SDValue Folded = foldAddSub64WithZeroLowBitsTo32(N, DCI))
18082 return Folded;
18083 }
18084
18085 // dot4 produces a 32-bit result, so a wider VT can't be folded.
18086 if (!VT.isVector() && VT.getSizeInBits() <= 32 &&
18087 (isMul(LHS) || isMul(RHS)) && Subtarget->hasDot7Insts() &&
18088 (Subtarget->hasDot1Insts() || Subtarget->hasDot8Insts())) {
18089 SDValue TempNode(N, 0);
18090 std::optional<bool> IsSigned;
18094
18095 // Match the v_dot4 tree, while collecting src nodes.
18096 int ChainLength = 0;
18097 for (int I = 0; I < 4; I++) {
18098 auto MulIdx = isMul(LHS) ? 0 : isMul(RHS) ? 1 : -1;
18099 if (MulIdx == -1)
18100 break;
18101 auto Src0 = handleMulOperand(TempNode->getOperand(MulIdx)->getOperand(0));
18102 if (!Src0)
18103 break;
18104 auto Src1 = handleMulOperand(TempNode->getOperand(MulIdx)->getOperand(1));
18105 if (!Src1)
18106 break;
18107
18108 auto IterIsSigned = checkDot4MulSignedness(
18109 TempNode->getOperand(MulIdx), *Src0, *Src1,
18110 TempNode->getOperand(MulIdx)->getOperand(0),
18111 TempNode->getOperand(MulIdx)->getOperand(1), DAG);
18112 if (!IterIsSigned)
18113 break;
18114 if (!IsSigned)
18115 IsSigned = *IterIsSigned;
18116 if (*IterIsSigned != *IsSigned)
18117 break;
18118 placeSources(*Src0, *Src1, Src0s, Src1s, I);
18119 auto AddIdx = 1 - MulIdx;
18120 // Allow the special case where add (add (mul24, 0), mul24) became ->
18121 // add (mul24, mul24).
18122 if (I == 2 && isMul(TempNode->getOperand(AddIdx))) {
18123 Src2s.push_back(TempNode->getOperand(AddIdx));
18124 auto Src0 =
18125 handleMulOperand(TempNode->getOperand(AddIdx)->getOperand(0));
18126 if (!Src0)
18127 break;
18128 auto Src1 =
18129 handleMulOperand(TempNode->getOperand(AddIdx)->getOperand(1));
18130 if (!Src1)
18131 break;
18132 auto IterIsSigned = checkDot4MulSignedness(
18133 TempNode->getOperand(AddIdx), *Src0, *Src1,
18134 TempNode->getOperand(AddIdx)->getOperand(0),
18135 TempNode->getOperand(AddIdx)->getOperand(1), DAG);
18136 if (!IterIsSigned)
18137 break;
18138 assert(IsSigned);
18139 if (*IterIsSigned != *IsSigned)
18140 break;
18141 placeSources(*Src0, *Src1, Src0s, Src1s, I + 1);
18142 Src2s.push_back(DAG.getConstant(0, SL, MVT::i32));
18143 ChainLength = I + 2;
18144 break;
18145 }
18146
18147 TempNode = TempNode->getOperand(AddIdx);
18148 Src2s.push_back(TempNode);
18149 ChainLength = I + 1;
18150 // The loop body treats TempNode's operands as addends.
18151 if (TempNode.getOpcode() != ISD::ADD)
18152 break;
18153 LHS = TempNode->getOperand(0);
18154 RHS = TempNode->getOperand(1);
18155 }
18156
18157 if (ChainLength < 2)
18158 return SDValue();
18159
18160 // Masks were constructed with assumption that we would find a chain of
18161 // length 4. If not, then we need to 0 out the MSB bits (via perm mask of
18162 // 0x0c) so they do not affect dot calculation.
18163 if (ChainLength < 4) {
18164 fixMasks(Src0s, ChainLength);
18165 fixMasks(Src1s, ChainLength);
18166 }
18167
18168 SDValue Src0, Src1;
18169
18170 // If we are just using a single source for both, and have permuted the
18171 // bytes consistently, we can just use the sources without permuting
18172 // (commutation).
18173 bool UseOriginalSrc = false;
18174 if (ChainLength == 4 && Src0s.size() == 1 && Src1s.size() == 1 &&
18175 Src0s.begin()->PermMask == Src1s.begin()->PermMask &&
18176 Src0s.begin()->SrcOp.getValueSizeInBits() >= 32 &&
18177 Src1s.begin()->SrcOp.getValueSizeInBits() >= 32) {
18178 SmallVector<unsigned, 4> SrcBytes;
18179 auto Src0Mask = Src0s.begin()->PermMask;
18180 SrcBytes.push_back((Src0Mask >> 24) & 0xFF);
18181 bool UniqueEntries = true;
18182 for (auto I = 1; I < 4; I++) {
18183 auto NextByte = (Src0Mask >> ((3 - I) * 8)) & 0xFF;
18184
18185 if (is_contained(SrcBytes, NextByte)) {
18186 UniqueEntries = false;
18187 break;
18188 }
18189 SrcBytes.push_back(NextByte);
18190 }
18191
18192 if (UniqueEntries) {
18193 UseOriginalSrc = true;
18194
18195 auto *FirstElt = Src0s.begin();
18196 auto FirstEltOp =
18197 getDWordFromOffset(DAG, SL, FirstElt->SrcOp, FirstElt->DWordOffset);
18198
18199 auto *SecondElt = Src1s.begin();
18200 auto SecondEltOp = getDWordFromOffset(DAG, SL, SecondElt->SrcOp,
18201 SecondElt->DWordOffset);
18202
18203 Src0 = DAG.getBitcastedAnyExtOrTrunc(FirstEltOp, SL,
18204 MVT::getIntegerVT(32));
18205 Src1 = DAG.getBitcastedAnyExtOrTrunc(SecondEltOp, SL,
18206 MVT::getIntegerVT(32));
18207 }
18208 }
18209
18210 if (!UseOriginalSrc) {
18211 Src0 = resolveSources(DAG, SL, Src0s, false, true);
18212 Src1 = resolveSources(DAG, SL, Src1s, false, true);
18213 }
18214
18215 assert(IsSigned);
18216 SDValue Src2 =
18217 DAG.getExtOrTrunc(*IsSigned, Src2s[ChainLength - 1], SL, MVT::i32);
18218
18219 SDValue IID = DAG.getTargetConstant(*IsSigned ? Intrinsic::amdgcn_sdot4
18220 : Intrinsic::amdgcn_udot4,
18221 SL, MVT::i64);
18222
18223 assert(!VT.isVector());
18224 auto Dot = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32, IID, Src0,
18225 Src1, Src2, DAG.getTargetConstant(0, SL, MVT::i1));
18226
18227 return DAG.getExtOrTrunc(*IsSigned, Dot, SL, VT);
18228 }
18229
18230 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
18231 return SDValue();
18232
18233 // add x, zext (setcc) => uaddo_carry x, 0, setcc
18234 // add x, sext (setcc) => usubo_carry x, 0, setcc
18235 unsigned Opc = LHS.getOpcode();
18238 std::swap(RHS, LHS);
18239
18240 Opc = RHS.getOpcode();
18241 switch (Opc) {
18242 default:
18243 break;
18244 case ISD::ZERO_EXTEND:
18245 case ISD::SIGN_EXTEND:
18246 case ISD::ANY_EXTEND: {
18247 auto Cond = RHS.getOperand(0);
18248 // If this won't be a real VOPC output, we would still need to insert an
18249 // extra instruction anyway.
18250 if (!isBoolSGPR(Cond))
18251 break;
18252 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
18253 SDValue Args[] = {LHS, DAG.getConstant(0, SL, MVT::i32), Cond};
18255 return DAG.getNode(Opc, SL, VTList, Args);
18256 }
18257 case ISD::UADDO_CARRY: {
18258 // add x, (uaddo_carry y, 0, cc) => uaddo_carry x, y, cc
18259 if (!isNullConstant(RHS.getOperand(1)))
18260 break;
18261 SDValue Args[] = {LHS, RHS.getOperand(0), RHS.getOperand(2)};
18262 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), RHS->getVTList(), Args);
18263 }
18264 }
18265 return SDValue();
18266}
18267
18268SDValue SITargetLowering::performPtrAddCombine(SDNode *N,
18269 DAGCombinerInfo &DCI) const {
18270 SelectionDAG &DAG = DCI.DAG;
18271 SDLoc DL(N);
18272 EVT VT = N->getValueType(0);
18273 SDValue N0 = N->getOperand(0);
18274 SDValue N1 = N->getOperand(1);
18275
18276 // The following folds transform PTRADDs into regular arithmetic in cases
18277 // where the PTRADD wouldn't be folded as an immediate offset into memory
18278 // instructions anyway. They are target-specific in that other targets might
18279 // prefer to not lose information about the pointer arithmetic.
18280
18281 // Fold (ptradd x, shl(0 - v, k)) -> sub(x, shl(v, k)).
18282 // Adapted from DAGCombiner::visitADDLikeCommutative.
18283 SDValue V, K;
18284 if (sd_match(N1, m_Shl(m_Neg(m_Value(V)), m_Value(K)))) {
18285 SDNodeFlags ShlFlags = N1->getFlags();
18286 // If the original shl is NUW and NSW, the first k+1 bits of 0-v are all 0,
18287 // so v is either 0 or the first k+1 bits of v are all 1 -> NSW can be
18288 // preserved.
18289 SDNodeFlags NewShlFlags =
18290 ShlFlags.hasNoUnsignedWrap() && ShlFlags.hasNoSignedWrap()
18292 : SDNodeFlags();
18293 SDValue Inner = DAG.getNode(ISD::SHL, DL, VT, V, K, NewShlFlags);
18294 DCI.AddToWorklist(Inner.getNode());
18295 return DAG.getNode(ISD::SUB, DL, VT, N0, Inner);
18296 }
18297
18298 // Fold into Mad64 if the right-hand side is a MUL. Analogous to a fold in
18299 // performAddCombine.
18300 if (N1.getOpcode() == ISD::MUL) {
18301 if (Subtarget->hasMad64_32()) {
18302 if (SDValue Folded = tryFoldToMad64_32(N, DCI))
18303 return Folded;
18304 }
18305 }
18306
18307 // If the 32 low bits of the constant are all zero, there is nothing to fold
18308 // into an immediate offset, so it's better to eliminate the unnecessary
18309 // addition for the lower 32 bits than to preserve the PTRADD.
18310 // Analogous to a fold in performAddCombine.
18311 if (VT == MVT::i64) {
18312 if (SDValue Folded = foldAddSub64WithZeroLowBitsTo32(N, DCI))
18313 return Folded;
18314 }
18315
18316 if (N1.getOpcode() != ISD::ADD || !N1.hasOneUse())
18317 return SDValue();
18318
18319 SDValue X = N0;
18320 SDValue Y = N1.getOperand(0);
18321 SDValue Z = N1.getOperand(1);
18322 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
18323 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
18324
18325 if (!YIsConstant && !ZIsConstant && !X->isDivergent() &&
18326 Y->isDivergent() != Z->isDivergent()) {
18327 // Reassociate (ptradd x, (add y, z)) -> (ptradd (ptradd x, y), z) if x and
18328 // y are uniform and z isn't.
18329 // Reassociate (ptradd x, (add y, z)) -> (ptradd (ptradd x, z), y) if x and
18330 // z are uniform and y isn't.
18331 // The goal is to push uniform operands up in the computation, so that they
18332 // can be handled with scalar operations. We can't use reassociateScalarOps
18333 // for this since it requires two identical commutative operations to
18334 // reassociate.
18335 if (Y->isDivergent())
18336 std::swap(Y, Z);
18337 // If both additions in the original were NUW, reassociation preserves that.
18338 SDNodeFlags ReassocFlags =
18339 (N->getFlags() & N1->getFlags()) & SDNodeFlags::NoUnsignedWrap;
18340 SDValue UniformInner = DAG.getMemBasePlusOffset(X, Y, DL, ReassocFlags);
18341 DCI.AddToWorklist(UniformInner.getNode());
18342 return DAG.getMemBasePlusOffset(UniformInner, Z, DL, ReassocFlags);
18343 }
18344
18345 return SDValue();
18346}
18347
18348static bool isCtlzOpc(unsigned Opc) {
18349 return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_POISON;
18350}
18351
18352SDValue SITargetLowering::performSubCombine(SDNode *N,
18353 DAGCombinerInfo &DCI) const {
18354 SelectionDAG &DAG = DCI.DAG;
18355 EVT VT = N->getValueType(0);
18356
18357 if (VT == MVT::i64) {
18358 if (SDValue Folded = foldAddSub64WithZeroLowBitsTo32(N, DCI))
18359 return Folded;
18360 }
18361
18362 if (VT != MVT::i32)
18363 return SDValue();
18364
18365 SDLoc SL(N);
18366 SDValue LHS = N->getOperand(0);
18367 SDValue RHS = N->getOperand(1);
18368
18369 // sub x, zext (setcc) => usubo_carry x, 0, setcc
18370 // sub x, sext (setcc) => uaddo_carry x, 0, setcc
18371 unsigned Opc = RHS.getOpcode();
18372 switch (Opc) {
18373 default:
18374 break;
18375 case ISD::ZERO_EXTEND:
18376 case ISD::SIGN_EXTEND:
18377 case ISD::ANY_EXTEND: {
18378 auto Cond = RHS.getOperand(0);
18379 // If this won't be a real VOPC output, we would still need to insert an
18380 // extra instruction anyway.
18381 if (!isBoolSGPR(Cond))
18382 break;
18383 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
18384 SDValue Args[] = {LHS, DAG.getConstant(0, SL, MVT::i32), Cond};
18386 return DAG.getNode(Opc, SL, VTList, Args);
18387 }
18388 }
18389
18390 if (LHS.getOpcode() == ISD::USUBO_CARRY) {
18391 // sub (usubo_carry x, 0, cc), y => usubo_carry x, y, cc
18392 if (!isNullConstant(LHS.getOperand(1)))
18393 return SDValue();
18394 SDValue Args[] = {LHS.getOperand(0), RHS, LHS.getOperand(2)};
18395 return DAG.getNode(ISD::USUBO_CARRY, SDLoc(N), LHS->getVTList(), Args);
18396 }
18397
18398 // sub (ctlz (xor x, (sra x, 31))), 1 -> ctls x.
18399 if (isOneConstant(RHS) && isCtlzOpc(LHS.getOpcode())) {
18400 SDValue CtlzSrc = LHS.getOperand(0);
18401 // Check for xor x, (sra x, 31) pattern.
18402 if (CtlzSrc.getOpcode() == ISD::XOR) {
18403 SDValue X = CtlzSrc.getOperand(0);
18404 SDValue SignExt = CtlzSrc.getOperand(1);
18405 // Try both ordering of XOR operands.
18406 if (SignExt.getOpcode() != ISD::SRA)
18407 std::swap(X, SignExt);
18408 if (SignExt.getOpcode() == ISD::SRA && SignExt.getOperand(0) == X) {
18409 ConstantSDNode *ShiftAmt =
18411 unsigned BitWidth = X.getValueType().getScalarSizeInBits();
18412 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1)
18413 return DAG.getNode(ISD::CTLS, SL, VT, X);
18414 }
18415 }
18416 }
18417
18418 return SDValue();
18419}
18420
18421SDValue SITargetLowering::performFAddCombine(SDNode *N,
18422 DAGCombinerInfo &DCI) const {
18423 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
18424 return SDValue();
18425
18426 SelectionDAG &DAG = DCI.DAG;
18427 EVT VT = N->getValueType(0);
18428
18429 SDLoc SL(N);
18430 SDValue LHS = N->getOperand(0);
18431 SDValue RHS = N->getOperand(1);
18432
18433 // These should really be instruction patterns, but writing patterns with
18434 // source modifiers is a pain.
18435
18436 // fadd (fadd (a, a), b) -> mad 2.0, a, b
18437 if (LHS.getOpcode() == ISD::FADD) {
18438 SDValue A = LHS.getOperand(0);
18439 if (A == LHS.getOperand(1)) {
18440 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
18441 if (FusedOp != 0) {
18442 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
18443 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
18444 }
18445 }
18446 }
18447
18448 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
18449 if (RHS.getOpcode() == ISD::FADD) {
18450 SDValue A = RHS.getOperand(0);
18451 if (A == RHS.getOperand(1)) {
18452 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
18453 if (FusedOp != 0) {
18454 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
18455 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
18456 }
18457 }
18458 }
18459
18460 return SDValue();
18461}
18462
18463SDValue SITargetLowering::performFSubCombine(SDNode *N,
18464 DAGCombinerInfo &DCI) const {
18465 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
18466 return SDValue();
18467
18468 SelectionDAG &DAG = DCI.DAG;
18469 SDLoc SL(N);
18470 EVT VT = N->getValueType(0);
18471 assert(!VT.isVector());
18472
18473 // Try to get the fneg to fold into the source modifier. This undoes generic
18474 // DAG combines and folds them into the mad.
18475 //
18476 // Only do this if we are not trying to support denormals. v_mad_f32 does
18477 // not support denormals ever.
18478 SDValue LHS = N->getOperand(0);
18479 SDValue RHS = N->getOperand(1);
18480 if (LHS.getOpcode() == ISD::FADD) {
18481 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
18482 SDValue A = LHS.getOperand(0);
18483 if (A == LHS.getOperand(1)) {
18484 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
18485 if (FusedOp != 0) {
18486 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
18487 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
18488
18489 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
18490 }
18491 }
18492 }
18493
18494 if (RHS.getOpcode() == ISD::FADD) {
18495 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
18496
18497 SDValue A = RHS.getOperand(0);
18498 if (A == RHS.getOperand(1)) {
18499 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
18500 if (FusedOp != 0) {
18501 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
18502 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
18503 }
18504 }
18505 }
18506
18507 return SDValue();
18508}
18509
18510SDValue SITargetLowering::performFDivCombine(SDNode *N,
18511 DAGCombinerInfo &DCI) const {
18512 SelectionDAG &DAG = DCI.DAG;
18513 SDLoc SL(N);
18514 EVT VT = N->getValueType(0);
18515
18516 if (VT != MVT::f16 && VT != MVT::bf16)
18517 return SDValue();
18518
18519 SDValue LHS = N->getOperand(0);
18520 SDValue RHS = N->getOperand(1);
18521
18522 SDNodeFlags Flags = N->getFlags();
18523 SDNodeFlags RHSFlags = RHS->getFlags();
18524 if (!Flags.hasAllowContract() || !RHSFlags.hasAllowContract() ||
18525 !RHS->hasOneUse())
18526 return SDValue();
18527
18528 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
18529 bool IsNegative = false;
18530 if (CLHS->isOne() || (IsNegative = CLHS->isMinusOne())) {
18531 // fdiv contract 1.0, (sqrt contract x) -> rsq
18532 // fdiv contract -1.0, (sqrt contract x) -> fneg(rsq)
18533 if (RHS.getOpcode() == ISD::FSQRT) {
18534 // TODO: Or in RHS flags, somehow missing from SDNodeFlags
18535 SDValue SqrtOp = RHS.getOperand(0);
18536 SDValue Rsq;
18537 if (isOperationLegal(ISD::FSQRT, VT)) {
18538 // fsqrt legality correlates to rsq availability of the same type.
18539 Rsq = DAG.getNode(AMDGPUISD::RSQ, SL, VT, SqrtOp, Flags);
18540 } else if (VT == MVT::f16) {
18541 // Targets without 16-bit instructions (gfx6/gfx7) have no f16 rsq,
18542 // but v_rsq_f32 is more than accurate enough for f16. Unlike bf16,
18543 // every f16 value (including denormals) extends to a normal f32, and
18544 // an f16 rsq result is never denormal, so the f32 reciprocal square
18545 // root needs no denormal handling. Compute it in f32 and round back.
18546 SDValue Ext =
18547 DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, SqrtOp, Flags);
18548 SDValue F32Rsq =
18549 DAG.getNode(AMDGPUISD::RSQ, SL, MVT::f32, Ext, Flags);
18550 Rsq = DAG.getNode(ISD::FP_ROUND, SL, VT, F32Rsq,
18551 DAG.getTargetConstant(0, SL, MVT::i32), Flags);
18552 } else {
18553 // bf16 shares f32's exponent range, so bf16 denormals would extend to
18554 // f32 denormals that v_rsq_f32 does not handle. Leave it expanded.
18555 return SDValue();
18556 }
18557 return IsNegative ? DAG.getNode(ISD::FNEG, SL, VT, Rsq, Flags) : Rsq;
18558 }
18559 }
18560 }
18561
18562 return SDValue();
18563}
18564
18565SDValue SITargetLowering::performFMulCombine(SDNode *N,
18566 DAGCombinerInfo &DCI) const {
18567 SelectionDAG &DAG = DCI.DAG;
18568 EVT VT = N->getValueType(0);
18569 EVT ScalarVT = VT.getScalarType();
18570 EVT IntVT = VT.changeElementType(*DAG.getContext(), MVT::i32);
18571
18572 if (!N->isDivergent() && getSubtarget()->hasSALUFloatInsts() &&
18573 (ScalarVT == MVT::f32 || ScalarVT == MVT::f16)) {
18574 // Prefer to use s_mul_f16/f32 instead of v_ldexp_f16/f32.
18575 return SDValue();
18576 }
18577
18578 SDValue LHS = N->getOperand(0);
18579 SDValue RHS = N->getOperand(1);
18580
18581 // It is cheaper to realize i32 inline constants as compared against
18582 // materializing f16 or f64 (or even non-inline f32) values,
18583 // possible via ldexp usage, as shown below :
18584 //
18585 // Given : A = 2^a & B = 2^b ; where a and b are integers.
18586 // fmul x, (select y, A, B) -> ldexp( x, (select i32 y, a, b) )
18587 // fmul x, (select y, -A, -B) -> ldexp( (fneg x), (select i32 y, a, b) )
18588 if ((ScalarVT == MVT::f64 || ScalarVT == MVT::f32 || ScalarVT == MVT::f16) &&
18589 (RHS.hasOneUse() && RHS.getOpcode() == ISD::SELECT)) {
18590 const ConstantFPSDNode *TrueNode = isConstOrConstSplatFP(RHS.getOperand(1));
18591 if (!TrueNode)
18592 return SDValue();
18593 const ConstantFPSDNode *FalseNode =
18594 isConstOrConstSplatFP(RHS.getOperand(2));
18595 if (!FalseNode)
18596 return SDValue();
18597
18598 if (TrueNode->isNegative() != FalseNode->isNegative())
18599 return SDValue();
18600
18601 // For f32, only non-inline constants should be transformed.
18602 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
18603 if (ScalarVT == MVT::f32 &&
18604 TII->isInlineConstant(TrueNode->getValueAPF()) &&
18605 TII->isInlineConstant(FalseNode->getValueAPF()))
18606 return SDValue();
18607
18608 int TrueNodeExpVal = TrueNode->getValueAPF().getExactLog2Abs();
18609 if (TrueNodeExpVal == INT_MIN)
18610 return SDValue();
18611 int FalseNodeExpVal = FalseNode->getValueAPF().getExactLog2Abs();
18612 if (FalseNodeExpVal == INT_MIN)
18613 return SDValue();
18614
18615 SDLoc SL(N);
18616 SDValue SelectNode =
18617 DAG.getNode(ISD::SELECT, SL, IntVT, RHS.getOperand(0),
18618 DAG.getSignedConstant(TrueNodeExpVal, SL, IntVT),
18619 DAG.getSignedConstant(FalseNodeExpVal, SL, IntVT));
18620
18621 LHS = TrueNode->isNegative()
18622 ? DAG.getNode(ISD::FNEG, SL, VT, LHS, LHS->getFlags())
18623 : LHS;
18624
18625 return DAG.getNode(ISD::FLDEXP, SL, VT, LHS, SelectNode, N->getFlags());
18626 }
18627
18628 return SDValue();
18629}
18630
18631SDValue SITargetLowering::performFMACombine(SDNode *N,
18632 DAGCombinerInfo &DCI) const {
18633 SelectionDAG &DAG = DCI.DAG;
18634 EVT VT = N->getValueType(0);
18635 SDLoc SL(N);
18636
18637 if (!Subtarget->hasDot10Insts() || VT != MVT::f32)
18638 return SDValue();
18639
18640 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
18641 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
18642 SDValue Op1 = N->getOperand(0);
18643 SDValue Op2 = N->getOperand(1);
18644 SDValue FMA = N->getOperand(2);
18645
18646 if (FMA.getOpcode() != ISD::FMA || Op1.getOpcode() != ISD::FP_EXTEND ||
18647 Op2.getOpcode() != ISD::FP_EXTEND)
18648 return SDValue();
18649
18650 // The fdot2 fold (fma_mix -> dot2) is only safe when both instructions agree
18651 // on how f16 subnormal inputs are handled. However, if both FMAs carry afn
18652 // the caller accepts approximate results, so any subnormal flushing
18653 // introduced by dot2 is acceptable regardless of mode.
18654 //
18655 // gfx90a (CDNA2) is the sole exception (dot2UnconditionalFlush): v_dot2c
18656 // unconditionally flushes f16 subnormal inputs to zero regardless of MODE,
18657 // while v_fma_mix_f32 preserves them when ieee=1 (the default compute kernel
18658 // mode). The fold is safe only when f32 denorm = PreserveSign, which implies
18659 // ieee=0 so both flush.
18660 //
18661 // All other GPUs: v_dot2 does NOT flush f16 subnormal inputs. v_fma_mix_f32
18662 // flushes them only when f32 denorm = PreserveSign. The fold is safe only
18663 // when f32 denorm is IEEE (both preserve the subnormal). Dynamic mode is
18664 // also rejected since the runtime value is unknown.
18665 bool AllowInaccuracy = N->getFlags().hasApproximateFuncs() &&
18666 FMA->getFlags().hasApproximateFuncs();
18667 if (!AllowInaccuracy) {
18668 const MachineFunction &MF = DAG.getMachineFunction();
18669 DenormalMode Mode = MF.getDenormalMode(APFloat::IEEEsingle());
18670 if (Subtarget->dot2UnconditionalFlush()) {
18671 // gfx90a: fold safe only when f32 denorm flushes.
18673 return SDValue();
18674 } else {
18675 // All other GPUs: fold safe only when f32 denorm is IEEE.
18676 if (Mode != DenormalMode::getIEEE())
18677 return SDValue();
18678 }
18679 }
18680
18681 // fp-contract allows reassociating the fma tree into a dot product.
18682 if (N->getFlags().hasAllowContract() && FMA->getFlags().hasAllowContract()) {
18683 Op1 = Op1.getOperand(0);
18684 Op2 = Op2.getOperand(0);
18685 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18687 return SDValue();
18688
18689 SDValue Vec1 = Op1.getOperand(0);
18690 SDValue Idx1 = Op1.getOperand(1);
18691 SDValue Vec2 = Op2.getOperand(0);
18692
18693 SDValue FMAOp1 = FMA.getOperand(0);
18694 SDValue FMAOp2 = FMA.getOperand(1);
18695 SDValue FMAAcc = FMA.getOperand(2);
18696
18697 if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
18698 FMAOp2.getOpcode() != ISD::FP_EXTEND)
18699 return SDValue();
18700
18701 FMAOp1 = FMAOp1.getOperand(0);
18702 FMAOp2 = FMAOp2.getOperand(0);
18703 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18705 return SDValue();
18706
18707 SDValue Vec3 = FMAOp1.getOperand(0);
18708 SDValue Vec4 = FMAOp2.getOperand(0);
18709 SDValue Idx2 = FMAOp1.getOperand(1);
18710
18711 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1))
18712 return SDValue();
18713
18714 if (!isa<ConstantSDNode>(Idx1) || !isa<ConstantSDNode>(Idx2) ||
18715 Idx1 == Idx2)
18716 return SDValue();
18717
18718 if (Vec1 == Vec2 || Vec3 == Vec4)
18719 return SDValue();
18720
18721 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
18722 return SDValue();
18723
18724 if ((Vec1 == Vec3 && Vec2 == Vec4) || (Vec1 == Vec4 && Vec2 == Vec3)) {
18725 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
18726 DAG.getTargetConstant(0, SL, MVT::i1));
18727 }
18728 }
18729 return SDValue();
18730}
18731
18732// Given a double-precision ordered or unordered comparison, return the
18733// condition code for an equivalent integral comparison of the operands' upper
18734// 32 bits, or `SETCC_INVALID` if not possible.
18735// For simplicity, no simplification occurs if the operands are not both known
18736// to have sign bit zero.
18737//
18738// EQ/NE:
18739// If LHS.lo32 == RHS.lo32:
18740// setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, eq/ne
18741// If LHS.lo32 != RHS.lo32:
18742// setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, false/true
18743// The reduction is not possible if operands may be +0 and -0.
18744// For ordered eq / unordered ne, at most one operand may be NaN.
18745// For unordered eq / ordered ne, neither operand can be NaN.
18746//
18747// LT/GE:
18748// If LHS.lo32 >= RHS.lo32 (unsigned):
18749// setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]lt/ge
18750// If LHS.lo32 < RHS.lo32 (unsigned):
18751// setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]le/gt
18752// The reduction is only supported if both operands are nonnegative.
18753// For ordered lt / unordered ge, the RHS cannot be NaN.
18754// For unordered lt / ordered ge, neither operand can be NaN.
18755//
18756// LE/GT:
18757// If LHS.lo32 > RHS.lo32 (unsigned):
18758// setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]lt/ge
18759// If LHS.lo32 <= RHS.lo32 (unsigned):
18760// setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]le/gt
18761// The reduction is only supported if both operands are nonnegative.
18762// For unordered le / ordered gt, the LHS cannot be NaN.
18763// For ordered le / unordered gt, neither operand can be NaN.
18765 const SDValue LHS,
18766 const SDValue RHS,
18767 const SelectionDAG &DAG) {
18768 EVT VT = LHS.getValueType();
18769 assert(VT == MVT::f64 && "Incorrect operand type!");
18770
18771 const KnownBits RHSBits = DAG.computeKnownBits(RHS);
18772 // Bail if RHS sign bit is not known to be zero.
18773 if (!RHSBits.Zero.isSignBitSet())
18774 return ISD::SETCC_INVALID;
18775
18776 const KnownBits RHSKnownLo32 = RHSBits.trunc(32);
18777 const KnownFPClass RHSFPClass =
18779 const bool RHSMaybeNaN = !RHSFPClass.isKnownNeverNaN();
18780
18781 const KnownBits LHSBits = DAG.computeKnownBits(LHS);
18782 const KnownBits LHSKnownLo32 = LHSBits.trunc(32);
18783 const KnownFPClass LHSFPClass =
18785 const bool LHSMaybeNaN = !LHSFPClass.isKnownNeverNaN();
18786
18787 // Bail if LHS sign bit is not known to be zero.
18788 if (!LHSBits.Zero.isSignBitSet())
18789 return ISD::SETCC_INVALID;
18790
18791 switch (CC) {
18792 default:
18793 break;
18794 case ISD::SETEQ:
18795 case ISD::SETOEQ:
18796 case ISD::SETUEQ:
18797 case ISD::SETONE:
18798 case ISD::SETUNE: {
18799 // OEQ should be false if either operand is NaN, so it suffices that at
18800 // least one operand is not NaN.
18801 if (CC == ISD::SETOEQ && LHSMaybeNaN && RHSMaybeNaN)
18802 break;
18803 // UEQ should be true if either operand is NaN, but this cannot be checked
18804 // on underlying bits.
18805 if (CC == ISD::SETUEQ && (LHSMaybeNaN || RHSMaybeNaN))
18806 break;
18807 // ONE should be false if either operand is NaN, but this cannot be
18808 // checked on underlying bits.
18809 if (CC == ISD::SETONE && (LHSMaybeNaN || RHSMaybeNaN))
18810 break;
18811 // UNE should be true if either operand is NaN, so it suffices that they
18812 // are not both NaN.
18813 if (CC == ISD::SETUNE && LHSMaybeNaN && RHSMaybeNaN)
18814 break;
18815
18816 const std::optional<bool> KnownEq =
18817 KnownBits::eq(LHSKnownLo32, RHSKnownLo32);
18818
18819 if (!KnownEq)
18820 break;
18821
18822 if (*KnownEq)
18823 return (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ)
18824 ? ISD::SETEQ
18825 : ISD::SETNE;
18826
18827 return (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ)
18829 : ISD::SETTRUE;
18830 }
18831 case ISD::SETLT:
18832 case ISD::SETOLT:
18833 case ISD::SETULT:
18834 case ISD::SETGE:
18835 case ISD::SETOGE:
18836 case ISD::SETUGE: {
18837 // OLT should be false if either operand is NaN.
18838 // Since NaNs have maximum exponent and nonzero mantissa, false positives
18839 // are only possible if the RHS is NaN. (No issue with RHS == +inf since
18840 // the inequality is strict)
18841 if (CC == ISD::SETOLT && RHSMaybeNaN)
18842 break;
18843 // ULT should be true if either operand is NaN, but this cannot be ensured
18844 // with a truncated comparison.
18845 if (CC == ISD::SETULT && (LHSMaybeNaN || RHSMaybeNaN))
18846 break;
18847 // OGE should be false if either operand is NaN, but this cannot be
18848 // ensured with a truncated comparison.
18849 if (CC == ISD::SETOGE && (LHSMaybeNaN || RHSMaybeNaN))
18850 break;
18851 // UGE should be true if either operand is NaN.
18852 // False negatives are only possible if the RHS is NaN.
18853 // (No issue with RHS == +inf since the inequality is inclusive)
18854 if (CC == ISD::SETUGE && RHSMaybeNaN)
18855 break;
18856
18857 const std::optional<bool> KnownUge =
18858 KnownBits::uge(LHSKnownLo32, RHSKnownLo32);
18859
18860 if (!KnownUge)
18861 break;
18862
18863 if (*KnownUge) {
18864 // LHS.lo32 uge RHS.lo32, so LHS >= RHS iff LHS.hi32 >= RHS.hi32
18865 return (CC == ISD::SETLT || CC == ISD::SETOLT || CC == ISD::SETULT)
18866 ? ISD::SETLT
18867 : ISD::SETGE;
18868 }
18869 // LHS.lo32 ult RHS.lo32, so LHS >= RHS iff LHS.hi32 > RHS.hi32
18870 return (CC == ISD::SETLT || CC == ISD::SETOLT || CC == ISD::SETULT)
18871 ? ISD::SETLE
18872 : ISD::SETGT;
18873 }
18874 case ISD::SETLE:
18875 case ISD::SETOLE:
18876 case ISD::SETULE:
18877 case ISD::SETGT:
18878 case ISD::SETOGT:
18879 case ISD::SETUGT: {
18880 // OLE should be false if either operand is NaN, but this cannot be
18881 // ensured with a truncated comparison.
18882 if (CC == ISD::SETOLE && (LHSMaybeNaN || RHSMaybeNaN))
18883 break;
18884 // ULE should be true if either operand is NaN.
18885 // False negatives are only possible if the LHS is NaN.
18886 // (No issue with LHS == +inf since the inequality is inclusive)
18887 if (CC == ISD::SETULE && LHSMaybeNaN)
18888 break;
18889 // OGT should be false if either operand is NaN.
18890 // False positives are only possible if the LHS is NaN.
18891 // (No issue with LHS == +inf since the inequality is strict)
18892 if (CC == ISD::SETOGT && LHSMaybeNaN)
18893 break;
18894 // UGT should be true if either operand is NaN, but this cannot be ensured
18895 // with a truncated comparison.
18896 if (CC == ISD::SETUGT && (LHSMaybeNaN || RHSMaybeNaN))
18897 break;
18898
18899 const std::optional<bool> KnownUle =
18900 KnownBits::ule(LHSKnownLo32, RHSKnownLo32);
18901
18902 if (!KnownUle)
18903 break;
18904
18905 if (*KnownUle) {
18906 // LHS.lo32 ule RHS.lo32, so LHS <= RHS iff LHS.hi32 <= RHS.hi32
18907 return (CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE)
18908 ? ISD::SETLE
18909 : ISD::SETGT;
18910 }
18911 // LHS.lo32 ugt RHS.lo32, so LHS <= RHS iff LHS.hi32 < RHS.hi32
18912 return (CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE)
18913 ? ISD::SETLT
18914 : ISD::SETGE;
18915 }
18916 }
18917
18918 return ISD::SETCC_INVALID;
18919}
18920
18921SDValue SITargetLowering::performSetCCCombine(SDNode *N,
18922 DAGCombinerInfo &DCI) const {
18923 SelectionDAG &DAG = DCI.DAG;
18924 SDLoc SL(N);
18925
18926 SDValue LHS = N->getOperand(0);
18927 SDValue RHS = N->getOperand(1);
18928 EVT VT = LHS.getValueType();
18929 ISD::CondCode CC = N->getOperandCondCode(2);
18930
18931 auto *CRHS = dyn_cast<ConstantSDNode>(RHS);
18932 if (!CRHS) {
18934 if (CRHS) {
18935 std::swap(LHS, RHS);
18937 }
18938 }
18939
18940 if (CRHS) {
18941 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
18942 isBoolSGPR(LHS.getOperand(0))) {
18943 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
18944 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
18945 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
18946 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
18947 if ((CRHS->isAllOnes() &&
18948 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
18949 (CRHS->isZero() &&
18950 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
18951 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
18952 DAG.getAllOnesConstant(SL, MVT::i1));
18953 if ((CRHS->isAllOnes() &&
18954 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
18955 (CRHS->isZero() &&
18956 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
18957 return LHS.getOperand(0);
18958 }
18959
18960 const APInt &CRHSVal = CRHS->getAPIntValue();
18961 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
18962 LHS.getOpcode() == ISD::SELECT &&
18963 isa<ConstantSDNode>(LHS.getOperand(1)) &&
18964 isa<ConstantSDNode>(LHS.getOperand(2)) &&
18965 isBoolSGPR(LHS.getOperand(0))) {
18966 // Given CT != FT:
18967 // setcc (select cc, CT, CF), CF, eq => xor cc, -1
18968 // setcc (select cc, CT, CF), CF, ne => cc
18969 // setcc (select cc, CT, CF), CT, ne => xor cc, -1
18970 // setcc (select cc, CT, CF), CT, eq => cc
18971 const APInt &CT = LHS.getConstantOperandAPInt(1);
18972 const APInt &CF = LHS.getConstantOperandAPInt(2);
18973
18974 if (CT != CF) {
18975 if ((CF == CRHSVal && CC == ISD::SETEQ) ||
18976 (CT == CRHSVal && CC == ISD::SETNE))
18977 return DAG.getNOT(SL, LHS.getOperand(0), MVT::i1);
18978 if ((CF == CRHSVal && CC == ISD::SETNE) ||
18979 (CT == CRHSVal && CC == ISD::SETEQ))
18980 return LHS.getOperand(0);
18981 }
18982 }
18983 }
18984
18985 // Truncate 64-bit setcc to only test upper or lower 32-bits.
18986 if (VT == MVT::i64) {
18987 const KnownBits LHSKnown = DAG.computeKnownBits(LHS);
18988 const KnownBits RHSKnown = DAG.computeKnownBits(RHS);
18989 const KnownBits LHSKnownLo32 = LHSKnown.trunc(32);
18990 const KnownBits RHSKnownLo32 = RHSKnown.trunc(32);
18991 // Truncate 64-bit setcc to test only upper 32-bits of its operands in the
18992 // following cases where information about the lower 32-bits of its operands
18993 // is known:
18994 //
18995 // If LHS.lo32 == RHS.lo32:
18996 // setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, eq/ne
18997 // If LHS.lo32 != RHS.lo32:
18998 // setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, false/true
18999 // If LHS.lo32 >= RHS.lo32 (unsigned):
19000 // setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]lt/ge
19001 // If LHS.lo32 > RHS.lo32 (unsigned):
19002 // setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]lt/ge
19003 // If LHS.lo32 <= RHS.lo32 (unsigned):
19004 // setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]le/gt
19005 // If LHS.lo32 < RHS.lo32 (unsigned):
19006 // setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]le/gt
19007
19008 // NewCC is valid iff we can truncate the setcc to only test the upper 32
19009 // bits
19011
19012 switch (CC) {
19013 default:
19014 llvm_unreachable("Unexpected condition code for integer setcc");
19015 break;
19016 case ISD::SETEQ: {
19017 const std::optional<bool> KnownEq =
19018 KnownBits::eq(LHSKnownLo32, RHSKnownLo32);
19019 if (KnownEq)
19020 NewCC = *KnownEq ? ISD::SETEQ : ISD::SETFALSE;
19021
19022 break;
19023 }
19024 case ISD::SETNE: {
19025 const std::optional<bool> KnownEq =
19026 KnownBits::eq(LHSKnownLo32, RHSKnownLo32);
19027 if (KnownEq)
19028 NewCC = *KnownEq ? ISD::SETNE : ISD::SETTRUE;
19029
19030 break;
19031 }
19032 case ISD::SETULT:
19033 case ISD::SETUGE:
19034 case ISD::SETLT:
19035 case ISD::SETGE: {
19036 const std::optional<bool> KnownUge =
19037 KnownBits::uge(LHSKnownLo32, RHSKnownLo32);
19038 if (KnownUge) {
19039 if (*KnownUge) {
19040 // LHS.lo32 uge RHS.lo32, so LHS >= RHS iff LHS.hi32 >= RHS.hi32
19041 NewCC = CC;
19042 } else {
19043 // LHS.lo32 ult RHS.lo32, so LHS >= RHS iff LHS.hi32 > RHS.hi32
19044 NewCC = CC == ISD::SETULT ? ISD::SETULE
19046 : CC == ISD::SETLT ? ISD::SETLE
19047 : ISD::SETGT;
19048 }
19049 }
19050 break;
19051 }
19052 case ISD::SETULE:
19053 case ISD::SETUGT:
19054 case ISD::SETLE:
19055 case ISD::SETGT: {
19056 const std::optional<bool> KnownUle =
19057 KnownBits::ule(LHSKnownLo32, RHSKnownLo32);
19058 if (KnownUle) {
19059 if (*KnownUle) {
19060 // LHS.lo32 ule RHS.lo32, so LHS <= RHS iff LHS.hi32 <= RHS.hi32
19061 NewCC = CC;
19062 } else {
19063 // LHS.lo32 ugt RHS.lo32, so LHS <= RHS iff LHS.hi32 < RHS.hi32
19064 NewCC = CC == ISD::SETULE ? ISD::SETULT
19066 : CC == ISD::SETLE ? ISD::SETLT
19067 : ISD::SETGE;
19068 }
19069 }
19070 break;
19071 }
19072 }
19073
19074 if (NewCC != ISD::SETCC_INVALID)
19075 return DAG.getSetCC(SL, N->getValueType(0), getHiHalf64(LHS, DAG),
19076 getHiHalf64(RHS, DAG), NewCC);
19077
19078 // Truncate 64-bit setcc to test only lower 32-bits when upper 32-bits are
19079 // known equal.
19080 const KnownBits LHSKnownHi32 = LHSKnown.extractBits(32, 32);
19081 const KnownBits RHSKnownHi32 = RHSKnown.extractBits(32, 32);
19082 const std::optional<bool> KnownEq =
19083 KnownBits::eq(LHSKnownHi32, RHSKnownHi32);
19084
19085 if (KnownEq == true) {
19086 // For signed comparisons, convert to unsigned since upper halves match
19088
19089 SDValue LHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
19090 SDValue RHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, RHS);
19091 return DAG.getSetCC(SL, N->getValueType(0), LHSLo, RHSLo, NewCC);
19092 }
19093 }
19094
19095 // Eliminate setcc by using carryout from add/sub instruction
19096
19097 // LHS = ADD i64 RHS, Z LHSlo = UADDO i32 RHSlo, Zlo
19098 // setcc LHS ult RHS -> LHSHi = UADDO_CARRY i32 RHShi, Zhi
19099 // similarly for subtraction
19100
19101 // LHS = ADD i64 Y, 1 LHSlo = UADDO i32 Ylo, 1
19102 // setcc LHS eq 0 -> LHSHi = UADDO_CARRY i32 Yhi, 0
19103
19104 if (VT == MVT::i64 && ((CC == ISD::SETULT &&
19106 (CC == ISD::SETUGT &&
19108 (CC == ISD::SETEQ && CRHS && CRHS->isZero() &&
19109 sd_match(LHS, m_Add(m_Value(), m_One()))))) {
19110 bool IsAdd = LHS.getOpcode() == ISD::ADD;
19111
19112 SDValue Op0 = LHS.getOperand(0);
19113 SDValue Op1 = LHS.getOperand(1);
19114
19115 SDValue Op0Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Op0);
19116 SDValue Op1Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Op1);
19117
19118 SDValue Op0Hi = getHiHalf64(Op0, DAG);
19119 SDValue Op1Hi = getHiHalf64(Op1, DAG);
19120
19121 SDValue NodeLo =
19122 DAG.getNode(IsAdd ? ISD::UADDO : ISD::USUBO, SL,
19123 DAG.getVTList(MVT::i32, MVT::i1), {Op0Lo, Op1Lo});
19124
19125 SDValue CarryInHi = NodeLo.getValue(1);
19126 SDValue NodeHi = DAG.getNode(IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY,
19127 SL, DAG.getVTList(MVT::i32, MVT::i1),
19128 {Op0Hi, Op1Hi, CarryInHi});
19129
19130 SDValue ResultLo = NodeLo.getValue(0);
19131 SDValue ResultHi = NodeHi.getValue(0);
19132
19133 SDValue JoinedResult =
19134 DAG.getBuildVector(MVT::v2i32, SL, {ResultLo, ResultHi});
19135
19136 SDValue Result = DAG.getNode(ISD::BITCAST, SL, VT, JoinedResult);
19137 SDValue Overflow = NodeHi.getValue(1);
19138 DCI.CombineTo(LHS.getNode(), Result);
19139 return Overflow;
19140 }
19141
19142 if (VT != MVT::f32 && VT != MVT::f64 &&
19143 (!Subtarget->has16BitInsts() || VT != MVT::f16))
19144 return SDValue();
19145
19146 // Match isinf/isfinite pattern
19147 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
19148 // (fcmp one (fabs x), inf) -> (fp_class x,
19149 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
19150 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) &&
19151 LHS.getOpcode() == ISD::FABS) {
19152 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
19153 if (!CRHS)
19154 return SDValue();
19155
19156 const APFloat &APF = CRHS->getValueAPF();
19157 if (APF.isInfinity() && !APF.isNegative()) {
19158 const unsigned IsInfMask =
19160 const unsigned IsFiniteMask =
19164 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
19165 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
19166 DAG.getConstant(Mask, SL, MVT::i32));
19167 }
19168 }
19169
19170 if (VT == MVT::f64) {
19172 if (HiHalfCC != ISD::SETCC_INVALID)
19173 return DAG.getSetCC(SL, N->getValueType(0), getHiHalf64(LHS, DAG),
19174 getHiHalf64(RHS, DAG), HiHalfCC);
19175 }
19176
19177 return SDValue();
19178}
19179
19180SDValue
19181SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
19182 DAGCombinerInfo &DCI) const {
19183 SelectionDAG &DAG = DCI.DAG;
19184 SDLoc SL(N);
19185 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
19186
19187 SDValue Src = N->getOperand(0);
19188 SDValue Shift = N->getOperand(0);
19189
19190 // TODO: Extend type shouldn't matter (assuming legal types).
19191 if (Shift.getOpcode() == ISD::ZERO_EXTEND)
19192 Shift = Shift.getOperand(0);
19193
19194 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
19195 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x
19196 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
19197 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
19198 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
19199 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
19200 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
19201 SDValue Shifted = DAG.getZExtOrTrunc(
19202 Shift.getOperand(0), SDLoc(Shift.getOperand(0)), MVT::i32);
19203
19204 unsigned ShiftOffset = 8 * Offset;
19205 if (Shift.getOpcode() == ISD::SHL)
19206 ShiftOffset -= C->getZExtValue();
19207 else
19208 ShiftOffset += C->getZExtValue();
19209
19210 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
19211 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
19212 MVT::f32, Shifted);
19213 }
19214 }
19215 }
19216
19218 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
19219 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
19220 // We simplified Src. If this node is not dead, visit it again so it is
19221 // folded properly.
19222 if (N->getOpcode() != ISD::DELETED_NODE)
19223 DCI.AddToWorklist(N);
19224 return SDValue(N, 0);
19225 }
19226
19227 // Handle (or x, (srl y, 8)) pattern when known bits are zero.
19228 if (SDValue DemandedSrc =
19229 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
19230 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
19231
19232 return SDValue();
19233}
19234
19235SDValue SITargetLowering::performClampCombine(SDNode *N,
19236 DAGCombinerInfo &DCI) const {
19237 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
19238 if (!CSrc)
19239 return SDValue();
19240
19241 const MachineFunction &MF = DCI.DAG.getMachineFunction();
19242 const APFloat &F = CSrc->getValueAPF();
19243 APFloat Zero = APFloat::getZero(F.getSemantics());
19244 if (F < Zero ||
19245 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
19246 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
19247 }
19248
19249 APFloat One = APFloat::getOne(F.getSemantics());
19250 if (F > One)
19251 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
19252
19253 return getCanonicalConstantFP(DCI.DAG, SDLoc(N), N->getValueType(0), F);
19254}
19255
19256// Check if V is the exponent result of a frexp operation. Returns the frexp
19257// input via FrexpInput if matched. We only match the exponent (not mantissa)
19258// because V_FREXP_MANT returns its input for Inf/NaN, not zero.
19259static bool isFrexpExp(SDValue V, SDValue &FrexpInput) {
19260 // ISD::FFREXP returns {mant, exp} - only match if using the exp result
19261 // (result number 1).
19262 if (V.getOpcode() == ISD::FFREXP && V.getResNo() == 1) {
19263 FrexpInput = V.getOperand(0);
19264 return true;
19265 }
19267 m_Value(FrexpInput))))
19268 return true;
19269 return false;
19270}
19271
19272SDValue
19273SITargetLowering::performFrexpSelectCombine(SDNode *N,
19274 DAGCombinerInfo &DCI) const {
19275 // This optimization only applies when the hardware handles inf/nan correctly.
19276 if (Subtarget->hasFractBug())
19277 return SDValue();
19278
19279 SDValue Cond = N->getOperand(0);
19280 SDValue TrueVal = N->getOperand(1);
19281 SDValue FalseVal = N->getOperand(2);
19282
19283 // Identify which operand is the frexp result and which is the zero constant.
19284 // Pattern 1: select cond, 0, frexp_result (cond true -> return 0)
19285 // Pattern 2: select cond, frexp_result, 0 (cond false -> return 0)
19286 SDValue FrexpVal;
19287 SDValue ZeroVal;
19288 bool CondSelectsZero; // If true, condition=true selects zero
19289
19290 // Check if FrexpVal comes from ISD::FFREXP (exponent result only) or
19291 // amdgcn_frexp_exp intrinsic.
19292 SDValue FrexpInput;
19293 if (isFrexpExp(FalseVal, FrexpInput)) {
19294 FrexpVal = FalseVal;
19295 ZeroVal = TrueVal;
19296 CondSelectsZero = true;
19297 } else if (isFrexpExp(TrueVal, FrexpInput)) {
19298 FrexpVal = TrueVal;
19299 ZeroVal = FalseVal;
19300 CondSelectsZero = false;
19301 } else {
19302 return SDValue();
19303 }
19304
19305 // frexp_exp returns integer, so check for integer zero.
19306 if (!isNullConstant(ZeroVal))
19307 return SDValue();
19308
19309 // The frexp intrinsics ignore sign, so we can strip sign ops when comparing.
19310 SDValue FrexpInputStripped = peekFPSignOps(FrexpInput);
19311
19312 bool IsNonFiniteTest = false;
19313
19314 // Handle SETCC conditions for inf/nan tests.
19315 // The canonical form of these checks is fcmp + fabs.
19316 if (Cond.getOpcode() == ISD::SETCC) {
19317 ISD::CondCode CC = Cond.getOperandCondCode(2);
19318 SDValue CondLHS = Cond.getOperand(0);
19319 SDValue CondRHS = Cond.getOperand(1);
19320
19321 // Check if LHS is fabs(FrexpInput) - required for infinity comparisons.
19322 SDValue FAbsInput;
19323 bool LHSIsFabs = sd_match(CondLHS, m_FAbs(m_Value(FAbsInput)));
19324 bool LHSMatchesFrexp =
19325 (CondLHS == FrexpInput) ||
19326 (LHSIsFabs && peekFPSignOps(FAbsInput) == FrexpInputStripped) ||
19327 (peekFPSignOps(CondLHS) == FrexpInputStripped);
19328 bool RHSMatchesFrexp = (CondRHS == FrexpInput) ||
19329 (peekFPSignOps(CondRHS) == FrexpInputStripped);
19330
19331 if (CC == ISD::SETUO) {
19332 // fcmp uno x, y - true if either x or y is NaN
19333 // We can only fold if the non-frexp operand is known to never be NaN,
19334 // otherwise the comparison could be true due to the other operand.
19335 // Special case: fcmp uno x, x (same operand) is a valid NaN test.
19336 SelectionDAG &DAG = DCI.DAG;
19337 if (LHSMatchesFrexp &&
19338 (CondLHS == CondRHS || DAG.isKnownNeverNaN(CondRHS)))
19339 IsNonFiniteTest = CondSelectsZero;
19340 else if (RHSMatchesFrexp && DAG.isKnownNeverNaN(CondLHS))
19341 IsNonFiniteTest = CondSelectsZero;
19342 } else if ((CC == ISD::SETOEQ || CC == ISD::SETUEQ) && LHSMatchesFrexp &&
19343 LHSIsFabs &&
19344 sd_match(CondRHS,
19346 CondRHS.getValueType().getFltSemantics())))) {
19347 // fcmp oeq/ueq fabs(x), +inf - true if x is inf (or inf/nan for ueq)
19348 IsNonFiniteTest = CondSelectsZero;
19349 } else if ((CC == ISD::SETONE || CC == ISD::SETUNE) && LHSMatchesFrexp &&
19350 LHSIsFabs &&
19351 sd_match(CondRHS,
19353 CondRHS.getValueType().getFltSemantics())))) {
19354 // fcmp one/une fabs(x), +inf - true if x is NOT inf
19355 IsNonFiniteTest = !CondSelectsZero;
19356 } else if (CC == ISD::SETO) {
19357 // fcmp ord x, y - true if both are NOT NaN
19358 // We can only fold if the non-frexp operand is known to never be NaN,
19359 // otherwise the comparison could be false due to the other operand.
19360 // Special case: fcmp ord x, x (same operand) is a valid not-NaN test.
19361 SelectionDAG &DAG = DCI.DAG;
19362 if (LHSMatchesFrexp &&
19363 (CondLHS == CondRHS || DAG.isKnownNeverNaN(CondRHS)))
19364 IsNonFiniteTest = !CondSelectsZero;
19365 else if (RHSMatchesFrexp && DAG.isKnownNeverNaN(CondLHS))
19366 IsNonFiniteTest = !CondSelectsZero;
19367 }
19368 }
19369
19370 if (!IsNonFiniteTest)
19371 return SDValue();
19372
19373 // The select can be eliminated - just return the frexp result directly.
19374 return FrexpVal;
19375}
19376
19377SDValue SITargetLowering::performSelectCombine(SDNode *N,
19378 DAGCombinerInfo &DCI) const {
19379
19380 // Try to fold CMP + SELECT patterns with shared constants (both FP and
19381 // integer).
19382 // Detect when CMP and SELECT use the same constant and fold them to avoid
19383 // loading the constant twice. Specifically handles patterns like:
19384 // %cmp = icmp eq i32 %val, 4242
19385 // %sel = select i1 %cmp, i32 4242, i32 %other
19386 // It can be optimized to reuse %val instead of 4242 in select.
19387 SDValue Cond = N->getOperand(0);
19388 SDValue TrueVal = N->getOperand(1);
19389 SDValue FalseVal = N->getOperand(2);
19390
19391 // Check if condition is a comparison.
19392 if (Cond.getOpcode() != ISD::SETCC)
19393 return SDValue();
19394
19395 SDValue LHS = Cond.getOperand(0);
19396 SDValue RHS = Cond.getOperand(1);
19397 ISD::CondCode CC = Cond.getOperandCondCode(2);
19398
19399 bool isFloatingPoint = LHS.getValueType().isFloatingPoint();
19400 bool isInteger = LHS.getValueType().isInteger();
19401
19402 // Handle simple floating-point and integer types only.
19403 if (!isFloatingPoint && !isInteger)
19404 return SDValue();
19405
19406 // Bare SETEQ/SETNE is the builder's NaN-impossible downgrade.
19407 bool isEquality = CC == ISD::SETEQ || (isFloatingPoint && CC == ISD::SETOEQ);
19408 bool isNonEquality =
19409 CC == ISD::SETNE || (isFloatingPoint && CC == ISD::SETONE);
19410 if (!isEquality && !isNonEquality)
19411 return SDValue();
19412
19413 SDValue ArgVal, ConstVal;
19414 if ((isFloatingPoint && isa<ConstantFPSDNode>(RHS)) ||
19415 (isInteger && isa<ConstantSDNode>(RHS))) {
19416 ConstVal = RHS;
19417 ArgVal = LHS;
19418 } else if ((isFloatingPoint && isa<ConstantFPSDNode>(LHS)) ||
19419 (isInteger && isa<ConstantSDNode>(LHS))) {
19420 ConstVal = LHS;
19421 ArgVal = RHS;
19422 } else {
19423 return SDValue();
19424 }
19425
19426 // Skip optimization for inlinable immediates.
19427 if (isFloatingPoint) {
19428 const APFloat &Val = cast<ConstantFPSDNode>(ConstVal)->getValueAPF();
19429 if (!Val.isNormal() || Subtarget->getInstrInfo()->isInlineConstant(Val))
19430 return SDValue();
19431 } else {
19432 const std::optional<int64_t> Val =
19433 cast<ConstantSDNode>(ConstVal)->getAPIntValue().trySExtValue();
19434 if (Val && AMDGPU::isInlinableIntLiteral(*Val))
19435 return SDValue();
19436 }
19437
19438 // For equality and non-equality comparisons, patterns:
19439 // select (setcc x, const), const, y -> select (setcc x, const), x, y
19440 // select (setccinv x, const), y, const -> select (setccinv x, const), y, x
19441 if (!(isEquality && TrueVal == ConstVal) &&
19442 !(isNonEquality && FalseVal == ConstVal))
19443 return SDValue();
19444
19445 // SETONE's false arm is also taken for NaN ArgVal, so require NaN excluded.
19446 if (isFloatingPoint && isNonEquality && FalseVal == ConstVal &&
19447 !Cond->getFlags().hasNoNaNs() && !DCI.DAG.isKnownNeverNaN(ArgVal))
19448 return SDValue();
19449
19450 SDValue SelectLHS = (isEquality && TrueVal == ConstVal) ? ArgVal : TrueVal;
19451 SDValue SelectRHS =
19452 (isNonEquality && FalseVal == ConstVal) ? ArgVal : FalseVal;
19453 return DCI.DAG.getNode(ISD::SELECT, SDLoc(N), N->getValueType(0), Cond,
19454 SelectLHS, SelectRHS);
19455}
19456
19458 DAGCombinerInfo &DCI) const {
19459 switch (N->getOpcode()) {
19460 case ISD::ABS:
19461 if (SDValue Res = promoteUniformUnaryOpToI32(SDValue(N, 0), DCI))
19462 return Res;
19463 break;
19464 case ISD::ADD:
19465 case ISD::SUB:
19466 case ISD::SHL:
19467 case ISD::SRL:
19468 case ISD::SRA:
19469 case ISD::AND:
19470 case ISD::OR:
19471 case ISD::XOR:
19472 case ISD::MUL:
19473 case ISD::SETCC:
19474 case ISD::SELECT:
19475 case ISD::SMIN:
19476 case ISD::SMAX:
19477 case ISD::UMIN:
19478 case ISD::UMAX:
19479 case ISD::USUBSAT:
19480 case ISD::UADDSAT:
19481 if (auto Res = promoteUniformOpToI32(SDValue(N, 0), DCI))
19482 return Res;
19483 break;
19484 default:
19485 break;
19486 }
19487
19488 if (getTargetMachine().getOptLevel() == CodeGenOptLevel::None)
19489 return SDValue();
19490
19491 switch (N->getOpcode()) {
19492 case ISD::ADD:
19493 return performAddCombine(N, DCI);
19494 case ISD::PTRADD:
19495 return performPtrAddCombine(N, DCI);
19496 case ISD::SUB:
19497 return performSubCombine(N, DCI);
19498 case ISD::FADD:
19499 return performFAddCombine(N, DCI);
19500 case ISD::FSUB:
19501 return performFSubCombine(N, DCI);
19502 case ISD::FDIV:
19503 return performFDivCombine(N, DCI);
19504 case ISD::FMUL:
19505 return performFMulCombine(N, DCI);
19506 case ISD::SETCC:
19507 return performSetCCCombine(N, DCI);
19508 case ISD::SELECT:
19509 if (auto Res = performFrexpSelectCombine(N, DCI))
19510 return Res;
19511 if (auto Res = performSelectCombine(N, DCI))
19512 return Res;
19513 break;
19514 case ISD::FMAXNUM:
19515 case ISD::FMINNUM:
19516 case ISD::FMAXNUM_IEEE:
19517 case ISD::FMINNUM_IEEE:
19518 case ISD::FMAXIMUM:
19519 case ISD::FMINIMUM:
19520 case ISD::FMAXIMUMNUM:
19521 case ISD::FMINIMUMNUM:
19522 case ISD::SMAX:
19523 case ISD::SMIN:
19524 case ISD::UMAX:
19525 case ISD::UMIN:
19526 case AMDGPUISD::FMIN_LEGACY:
19527 case AMDGPUISD::FMAX_LEGACY:
19528 return performMinMaxCombine(N, DCI);
19529 case ISD::FMA:
19530 return performFMACombine(N, DCI);
19531 case ISD::AND:
19532 return performAndCombine(N, DCI);
19533 case ISD::OR:
19534 return performOrCombine(N, DCI);
19535 case ISD::FSHR: {
19537 if (N->getValueType(0) == MVT::i32 && N->isDivergent() &&
19538 TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
19539 return matchPERM(N, DCI);
19540 }
19541 break;
19542 }
19543 case ISD::XOR:
19544 return performXorCombine(N, DCI);
19545 case ISD::ANY_EXTEND:
19546 case ISD::ZERO_EXTEND:
19547 return performZeroOrAnyExtendCombine(N, DCI);
19548 case ISD::SIGN_EXTEND:
19549 return performExtendTruncShiftCombine(N, DCI);
19551 return performSignExtendInRegCombine(N, DCI);
19552 case AMDGPUISD::FP_CLASS:
19553 return performClassCombine(N, DCI);
19554 case ISD::FCANONICALIZE:
19555 return performFCanonicalizeCombine(N, DCI);
19556 case AMDGPUISD::RCP:
19557 return performRcpCombine(N, DCI);
19558 case ISD::FLDEXP:
19559 case AMDGPUISD::FRACT:
19560 case AMDGPUISD::RSQ:
19561 case AMDGPUISD::RCP_LEGACY:
19562 case AMDGPUISD::RCP_IFLAG:
19563 case AMDGPUISD::RSQ_CLAMP: {
19564 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
19565 SDValue Src = N->getOperand(0);
19566 if (Src.isUndef())
19567 return Src;
19568 break;
19569 }
19570 case ISD::SINT_TO_FP:
19571 case ISD::UINT_TO_FP:
19572 return performUCharToFloatCombine(N, DCI);
19573 case ISD::FCOPYSIGN:
19574 return performFCopySignCombine(N, DCI);
19575 case AMDGPUISD::CVT_F32_UBYTE0:
19576 case AMDGPUISD::CVT_F32_UBYTE1:
19577 case AMDGPUISD::CVT_F32_UBYTE2:
19578 case AMDGPUISD::CVT_F32_UBYTE3:
19579 return performCvtF32UByteNCombine(N, DCI);
19580 case AMDGPUISD::FMED3:
19581 return performFMed3Combine(N, DCI);
19582 case AMDGPUISD::CVT_PKRTZ_F16_F32:
19583 return performCvtPkRTZCombine(N, DCI);
19585 if (SDValue Res = performExponentOnlyScaleCombine(N, DCI))
19586 return Res;
19587 break;
19588 case AMDGPUISD::CLAMP:
19589 return performClampCombine(N, DCI);
19590 case ISD::SCALAR_TO_VECTOR: {
19591 SelectionDAG &DAG = DCI.DAG;
19592 EVT VT = N->getValueType(0);
19593
19594 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
19595 if (VT == MVT::v2i16 || VT == MVT::v2f16 || VT == MVT::v2bf16) {
19596 SDLoc SL(N);
19597 SDValue Src = N->getOperand(0);
19598 EVT EltVT = Src.getValueType();
19599 if (EltVT != MVT::i16)
19600 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
19601
19602 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
19603 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
19604 }
19605
19606 break;
19607 }
19609 return performExtractVectorEltCombine(N, DCI);
19611 return performInsertVectorEltCombine(N, DCI);
19612 case ISD::FP_ROUND:
19613 return performFPRoundCombine(N, DCI);
19614 case ISD::LOAD: {
19615 if (SDValue Widened = widenLoad(cast<LoadSDNode>(N), DCI))
19616 return Widened;
19617 [[fallthrough]];
19618 }
19619 default: {
19620 if (!DCI.isBeforeLegalize()) {
19621 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
19622 return performMemSDNodeCombine(MemNode, DCI);
19623 }
19624
19625 break;
19626 }
19627 }
19628
19630}
19631
19632/// Helper function for adjustWritemask
19633static unsigned SubIdx2Lane(unsigned Idx) {
19634 switch (Idx) {
19635 default:
19636 return ~0u;
19637 case AMDGPU::sub0:
19638 return 0;
19639 case AMDGPU::sub1:
19640 return 1;
19641 case AMDGPU::sub2:
19642 return 2;
19643 case AMDGPU::sub3:
19644 return 3;
19645 case AMDGPU::sub4:
19646 return 4; // Possible with TFE/LWE
19647 }
19648}
19649
19650/// Adjust the writemask of MIMG, VIMAGE or VSAMPLE instructions
19651SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
19652 SelectionDAG &DAG) const {
19653 unsigned Opcode = Node->getMachineOpcode();
19654
19655 // Subtract 1 because the vdata output is not a MachineSDNode operand.
19656 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
19657 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
19658 return Node; // not implemented for D16
19659
19660 SDNode *Users[5] = {nullptr};
19661 unsigned Lane = 0;
19662 unsigned DmaskIdx =
19663 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
19664 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
19665 unsigned NewDmask = 0;
19666 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
19667 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
19668 bool UsesTFC = (int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
19669 (int(LWEIdx) >= 0 && Node->getConstantOperandVal(LWEIdx));
19670 unsigned TFCLane = 0;
19671 bool HasChain = Node->getNumValues() > 1;
19672
19673 if (OldDmask == 0) {
19674 // These are folded out, but on the chance it happens don't assert.
19675 return Node;
19676 }
19677
19678 unsigned OldBitsSet = llvm::popcount(OldDmask);
19679 // Work out which is the TFE/LWE lane if that is enabled.
19680 if (UsesTFC) {
19681 TFCLane = OldBitsSet;
19682 }
19683
19684 // Try to figure out the used register components
19685 for (SDUse &Use : Node->uses()) {
19686
19687 // Don't look at users of the chain.
19688 if (Use.getResNo() != 0)
19689 continue;
19690
19691 SDNode *User = Use.getUser();
19692
19693 // Abort if we can't understand the usage
19694 if (!User->isMachineOpcode() ||
19695 User->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
19696 return Node;
19697
19698 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
19699 // Note that subregs are packed, i.e. Lane==0 is the first bit set
19700 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
19701 // set, etc.
19702 Lane = SubIdx2Lane(User->getConstantOperandVal(1));
19703 if (Lane == ~0u)
19704 return Node;
19705
19706 // Check if the use is for the TFE/LWE generated result at VGPRn+1.
19707 if (UsesTFC && Lane == TFCLane) {
19708 Users[Lane] = User;
19709 } else {
19710 // Set which texture component corresponds to the lane.
19711 unsigned Comp;
19712 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
19713 Comp = llvm::countr_zero(Dmask);
19714 Dmask &= ~(1 << Comp);
19715 }
19716
19717 // Abort if we have more than one user per component.
19718 if (Users[Lane])
19719 return Node;
19720
19721 Users[Lane] = User;
19722 NewDmask |= 1 << Comp;
19723 }
19724 }
19725
19726 // Don't allow 0 dmask, as hardware assumes one channel enabled.
19727 bool NoChannels = !NewDmask;
19728 if (NoChannels) {
19729 if (!UsesTFC) {
19730 // No uses of the result and not using TFC. Then do nothing.
19731 return Node;
19732 }
19733 // If the original dmask has one channel - then nothing to do
19734 if (OldBitsSet == 1)
19735 return Node;
19736 // Use an arbitrary dmask - required for the instruction to work
19737 NewDmask = 1;
19738 }
19739 // Abort if there's no change
19740 if (NewDmask == OldDmask)
19741 return Node;
19742
19743 unsigned BitsSet = llvm::popcount(NewDmask);
19744
19745 // Check for TFE or LWE - increase the number of channels by one to account
19746 // for the extra return value
19747 // This will need adjustment for D16 if this is also included in
19748 // adjustWriteMask (this function) but at present D16 are excluded.
19749 unsigned NewChannels = BitsSet + UsesTFC;
19750
19751 int NewOpcode =
19752 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
19753 assert(NewOpcode != -1 &&
19754 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
19755 "failed to find equivalent MIMG op");
19756
19757 // Adjust the writemask in the node
19759 llvm::append_range(Ops, Node->ops().take_front(DmaskIdx));
19760 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
19761 llvm::append_range(Ops, Node->ops().drop_front(DmaskIdx + 1));
19762
19763 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
19764
19765 MVT ResultVT = NewChannels == 1
19766 ? SVT
19767 : MVT::getVectorVT(SVT, NewChannels == 3 ? 4
19768 : NewChannels == 5 ? 8
19769 : NewChannels);
19770 SDVTList NewVTList =
19771 HasChain ? DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
19772
19773 MachineSDNode *NewNode =
19774 DAG.getMachineNode(NewOpcode, SDLoc(Node), NewVTList, Ops);
19775
19776 if (HasChain) {
19777 // Update chain.
19778 DAG.setNodeMemRefs(NewNode, Node->memoperands());
19779 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
19780 }
19781
19782 if (NewChannels == 1) {
19783 assert(Node->hasNUsesOfValue(1, 0));
19784 SDNode *Copy =
19785 DAG.getMachineNode(TargetOpcode::COPY, SDLoc(Node),
19786 Users[Lane]->getValueType(0), SDValue(NewNode, 0));
19787 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
19788 return nullptr;
19789 }
19790
19791 // Update the users of the node with the new indices
19792 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
19793 SDNode *User = Users[i];
19794 if (!User) {
19795 // Handle the special case of NoChannels. We set NewDmask to 1 above, but
19796 // Users[0] is still nullptr because channel 0 doesn't really have a use.
19797 if (i || !NoChannels)
19798 continue;
19799 } else {
19800 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
19801 SDNode *NewUser = DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
19802 if (NewUser != User) {
19803 DAG.ReplaceAllUsesWith(SDValue(User, 0), SDValue(NewUser, 0));
19804 DAG.RemoveDeadNode(User);
19805 }
19806 }
19807
19808 switch (Idx) {
19809 default:
19810 break;
19811 case AMDGPU::sub0:
19812 Idx = AMDGPU::sub1;
19813 break;
19814 case AMDGPU::sub1:
19815 Idx = AMDGPU::sub2;
19816 break;
19817 case AMDGPU::sub2:
19818 Idx = AMDGPU::sub3;
19819 break;
19820 case AMDGPU::sub3:
19821 Idx = AMDGPU::sub4;
19822 break;
19823 }
19824 }
19825
19826 DAG.RemoveDeadNode(Node);
19827 return nullptr;
19828}
19829
19831 if (Op.getOpcode() == ISD::AssertZext)
19832 Op = Op.getOperand(0);
19833
19834 return isa<FrameIndexSDNode>(Op);
19835}
19836
19837/// Legalize target independent instructions (e.g. INSERT_SUBREG)
19838/// with frame index operands.
19839/// LLVM assumes that inputs are to these instructions are registers.
19840SDNode *
19842 SelectionDAG &DAG) const {
19843 if (Node->getOpcode() == ISD::CopyToReg) {
19844 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
19845 SDValue SrcVal = Node->getOperand(2);
19846
19847 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
19848 // to try understanding copies to physical registers.
19849 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
19850 SDLoc SL(Node);
19852 SDValue VReg = DAG.getRegister(
19853 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
19854
19855 SDNode *Glued = Node->getGluedNode();
19856 SDValue ToVReg = DAG.getCopyToReg(
19857 Node->getOperand(0), SL, VReg, SrcVal,
19858 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
19859 SDValue ToResultReg = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
19860 VReg, ToVReg.getValue(1));
19861 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
19862 DAG.RemoveDeadNode(Node);
19863 return ToResultReg.getNode();
19864 }
19865 }
19866
19868 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
19869 if (!isFrameIndexOp(Node->getOperand(i))) {
19870 Ops.push_back(Node->getOperand(i));
19871 continue;
19872 }
19873
19874 SDLoc DL(Node);
19875 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
19876 Node->getOperand(i).getValueType(),
19877 Node->getOperand(i)),
19878 0));
19879 }
19880
19881 return DAG.UpdateNodeOperands(Node, Ops);
19882}
19883
19884/// Fold the instructions after selecting them.
19885/// Returns null if users were already updated.
19887 SelectionDAG &DAG) const {
19889 unsigned Opcode = Node->getMachineOpcode();
19890
19891 if (TII->isImage(Opcode) && !TII->get(Opcode).mayStore() &&
19892 !TII->isGather4(Opcode) &&
19893 AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::dmask)) {
19894 return adjustWritemask(Node, DAG);
19895 }
19896
19897 if (Opcode == AMDGPU::INSERT_SUBREG || Opcode == AMDGPU::REG_SEQUENCE) {
19899 return Node;
19900 }
19901
19902 switch (Opcode) {
19903 case AMDGPU::V_DIV_SCALE_F32_e64:
19904 case AMDGPU::V_DIV_SCALE_F64_e64: {
19905 // Satisfy the operand register constraint when one of the inputs is
19906 // undefined. Ordinarily each undef value will have its own implicit_def of
19907 // a vreg, so force these to use a single register.
19908 SDValue Src0 = Node->getOperand(1);
19909 SDValue Src1 = Node->getOperand(3);
19910 SDValue Src2 = Node->getOperand(5);
19911
19912 if ((Src0.isMachineOpcode() &&
19913 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
19914 (Src0 == Src1 || Src0 == Src2))
19915 break;
19916
19917 MVT VT = Src0.getValueType().getSimpleVT();
19918 const TargetRegisterClass *RC =
19919 getRegClassFor(VT, Src0.getNode()->isDivergent());
19920
19922 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
19923
19924 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), UndefReg,
19925 Src0, SDValue());
19926
19927 // src0 must be the same register as src1 or src2, even if the value is
19928 // undefined, so make sure we don't violate this constraint.
19929 if (Src0.isMachineOpcode() &&
19930 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
19931 if (Src1.isMachineOpcode() &&
19932 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
19933 Src0 = Src1;
19934 else if (Src2.isMachineOpcode() &&
19935 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
19936 Src0 = Src2;
19937 else {
19938 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
19939 Src0 = UndefReg;
19940 Src1 = UndefReg;
19941 }
19942 } else
19943 break;
19944
19946 Ops[1] = Src0;
19947 Ops[3] = Src1;
19948 Ops[5] = Src2;
19949 Ops.push_back(ImpDef.getValue(1));
19950 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
19951 }
19952 default:
19953 break;
19954 }
19955
19956 return Node;
19957}
19958
19959// Any MIMG instructions that use tfe or lwe require an initialization of the
19960// result register that will be written in the case of a memory access failure.
19961// The required code is also added to tie this init code to the result of the
19962// img instruction.
19965 const SIRegisterInfo &TRI = TII->getRegisterInfo();
19966 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
19967 MachineBasicBlock &MBB = *MI.getParent();
19968
19969 int DstIdx =
19970 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
19971 unsigned InitIdx = 0;
19972
19973 if (TII->isImage(MI)) {
19974 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
19975 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
19976 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
19977
19978 if (!TFE && !LWE) // intersect_ray
19979 return;
19980
19981 unsigned TFEVal = TFE ? TFE->getImm() : 0;
19982 unsigned LWEVal = LWE ? LWE->getImm() : 0;
19983 unsigned D16Val = D16 ? D16->getImm() : 0;
19984
19985 if (!TFEVal && !LWEVal)
19986 return;
19987
19988 // At least one of TFE or LWE are non-zero
19989 // We have to insert a suitable initialization of the result value and
19990 // tie this to the dest of the image instruction.
19991
19992 // Calculate which dword we have to initialize to 0.
19993 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
19994
19995 // check that dmask operand is found.
19996 assert(MO_Dmask && "Expected dmask operand in instruction");
19997
19998 unsigned dmask = MO_Dmask->getImm();
19999 // Determine the number of active lanes taking into account the
20000 // Gather4 special case
20001 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : llvm::popcount(dmask);
20002
20003 bool Packed = !Subtarget->hasUnpackedD16VMem();
20004
20005 InitIdx = D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
20006
20007 // Abandon attempt if the dst size isn't large enough
20008 // - this is in fact an error but this is picked up elsewhere and
20009 // reported correctly.
20010 const TargetRegisterClass *DstRC = TII->getRegClass(MI.getDesc(), DstIdx);
20011
20012 uint32_t DstSize = TRI.getRegSizeInBits(*DstRC) / 32;
20013 if (DstSize < InitIdx)
20014 return;
20015 } else if (TII->isMUBUF(MI) && AMDGPU::getMUBUFTfe(MI.getOpcode())) {
20016 const TargetRegisterClass *DstRC = TII->getRegClass(MI.getDesc(), DstIdx);
20017 InitIdx = TRI.getRegSizeInBits(*DstRC) / 32;
20018 } else {
20019 return;
20020 }
20021
20022 const DebugLoc &DL = MI.getDebugLoc();
20023
20024 // Create a register for the initialization value.
20025 Register PrevDst = MRI.cloneVirtualRegister(MI.getOperand(DstIdx).getReg());
20026 unsigned NewDst = 0; // Final initialized value will be in here
20027
20028 // If PRTStrictNull feature is enabled (the default) then initialize
20029 // all the result registers to 0, otherwise just the error indication
20030 // register (VGPRn+1)
20031 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
20032 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
20033
20034 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
20035 for (; SizeLeft; SizeLeft--, CurrIdx++) {
20036 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
20037 // Initialize dword
20038 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
20039 // clang-format off
20040 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
20041 .addImm(0);
20042 // clang-format on
20043 // Insert into the super-reg
20044 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
20045 .addReg(PrevDst)
20046 .addReg(SubReg)
20048
20049 PrevDst = NewDst;
20050 }
20051
20052 // Add as an implicit operand
20053 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
20054
20055 // Tie the just added implicit operand to the dst
20056 MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
20057}
20058
20059/// Assign the register class depending on the number of
20060/// bits set in the writemask
20062 SDNode *Node) const {
20064
20065 MachineFunction *MF = MI.getMF();
20067
20068 if (TII->isVOP3(MI.getOpcode())) {
20069 // Make sure constant bus requirements are respected.
20070 TII->legalizeOperandsVOP3(MRI, MI);
20071
20072 if (TII->isMAI(MI)) {
20073 // The ordinary src0, src1, src2 were legalized above.
20074 //
20075 // We have to also legalize the appended v_mfma_ld_scale_b32 operands,
20076 // as a separate instruction.
20077 int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
20078 AMDGPU::OpName::scale_src0);
20079 if (Src0Idx != -1) {
20080 int Src1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
20081 AMDGPU::OpName::scale_src1);
20082 if (TII->usesConstantBus(MRI, MI, Src0Idx) &&
20083 TII->usesConstantBus(MRI, MI, Src1Idx))
20084 TII->legalizeOpWithMove(MI, Src1Idx);
20085 }
20086 }
20087
20088 return;
20089 }
20090
20091 if (TII->isImage(MI))
20092 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr);
20093}
20094
20096 uint64_t Val) {
20097 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
20098 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
20099}
20100
20102 const SDLoc &DL,
20103 SDValue Ptr) const {
20105
20106 // Build the half of the subregister with the constants before building the
20107 // full 128-bit register. If we are building multiple resource descriptors,
20108 // this will allow CSEing of the 2-component register.
20109 const SDValue Ops0[] = {
20110 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
20111 buildSMovImm32(DAG, DL, 0),
20112 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
20113 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
20114 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)};
20115
20116 SDValue SubRegHi = SDValue(
20117 DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v2i32, Ops0), 0);
20118
20119 // Combine the constants and the pointer.
20120 const SDValue Ops1[] = {
20121 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), Ptr,
20122 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), SubRegHi,
20123 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)};
20124
20125 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
20126}
20127
20128/// Return a resource descriptor with the 'Add TID' bit enabled
20129/// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
20130/// of the resource descriptor) to create an offset, which is added to
20131/// the resource pointer.
20133 SDValue Ptr, uint32_t RsrcDword1,
20134 uint64_t RsrcDword2And3) const {
20135 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
20136 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
20137 if (RsrcDword1) {
20138 PtrHi = DAG.getNode(ISD::OR, DL, MVT::i32, PtrHi,
20139 DAG.getConstant(RsrcDword1, DL, MVT::i32));
20140 }
20141
20142 SDValue DataLo =
20143 buildSMovImm32(DAG, DL, RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
20144 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
20145
20146 const SDValue Ops[] = {
20147 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
20148 PtrLo,
20149 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
20150 PtrHi,
20151 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
20152 DataLo,
20153 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
20154 DataHi,
20155 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)};
20156
20157 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
20158}
20159
20160//===----------------------------------------------------------------------===//
20161// SI Inline Assembly Support
20162//===----------------------------------------------------------------------===//
20163
20164std::pair<unsigned, const TargetRegisterClass *>
20166 StringRef Constraint,
20167 MVT VT) const {
20168 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
20169
20170 const TargetRegisterClass *RC = nullptr;
20171 if (Constraint.size() == 1) {
20172 // Check if we cannot determine the bit size of the given value type. This
20173 // can happen, for example, in this situation where we have an empty struct
20174 // (size 0): `call void asm "", "v"({} poison)`-
20175 if (VT == MVT::Other)
20176 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20177 const unsigned BitWidth = VT.getSizeInBits();
20178 switch (Constraint[0]) {
20179 default:
20180 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20181 case 's':
20182 case 'r':
20183 switch (BitWidth) {
20184 case 16:
20185 RC = &AMDGPU::SReg_32RegClass;
20186 break;
20187 case 64:
20188 RC = &AMDGPU::SGPR_64RegClass;
20189 break;
20190 default:
20192 if (!RC)
20193 return std::pair(0U, nullptr);
20194 break;
20195 }
20196 break;
20197 case 'v':
20198 switch (BitWidth) {
20199 case 1:
20200 return std::pair(0U, nullptr);
20201 case 16:
20202 RC = Subtarget->useRealTrue16Insts() ? &AMDGPU::VGPR_16RegClass
20203 : &AMDGPU::VGPR_32_Lo256RegClass;
20204 break;
20205 default:
20206 RC = Subtarget->hasVGPRMSBs()
20207 ? TRI->getAlignedLo256VGPRClassForBitWidth(BitWidth)
20208 : TRI->getVGPRClassForBitWidth(BitWidth);
20209 if (!RC)
20210 return std::pair(0U, nullptr);
20211 break;
20212 }
20213 break;
20214 case 'a':
20215 if (!Subtarget->hasMAIInsts())
20216 break;
20217 switch (BitWidth) {
20218 case 1:
20219 return std::pair(0U, nullptr);
20220 case 16:
20221 RC = &AMDGPU::AGPR_32RegClass;
20222 break;
20223 default:
20224 RC = TRI->getAGPRClassForBitWidth(BitWidth);
20225 if (!RC)
20226 return std::pair(0U, nullptr);
20227 break;
20228 }
20229 break;
20230 }
20231 } else if (Constraint == "VA" && Subtarget->hasGFX90AInsts()) {
20232 const unsigned BitWidth = VT.getSizeInBits();
20233 switch (BitWidth) {
20234 case 16:
20235 RC = &AMDGPU::AV_32RegClass;
20236 break;
20237 default:
20238 RC = TRI->getVectorSuperClassForBitWidth(BitWidth);
20239 if (!RC)
20240 return std::pair(0U, nullptr);
20241 break;
20242 }
20243 }
20244
20245 // We actually support i128, i16 and f16 as inline parameters
20246 // even if they are not reported as legal
20247 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
20248 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
20249 return std::pair(0U, RC);
20250
20251 auto [Kind, Idx, NumRegs] = AMDGPU::parseAsmConstraintPhysReg(Constraint);
20252 if (Kind != '\0') {
20253 if (Kind == 'v') {
20254 RC = &AMDGPU::VGPR_32_Lo256RegClass;
20255 } else if (Kind == 's') {
20256 RC = &AMDGPU::SGPR_32RegClass;
20257 } else if (Kind == 'a') {
20258 RC = &AMDGPU::AGPR_32RegClass;
20259 }
20260
20261 if (RC) {
20262 if (NumRegs > 1) {
20263 if (Idx >= RC->getNumRegs() || Idx + NumRegs - 1 >= RC->getNumRegs())
20264 return std::pair(0U, nullptr);
20265
20266 uint32_t Width = NumRegs * 32;
20267 // Prohibit constraints for register ranges with a width that does not
20268 // match the required type.
20269 if (VT.SimpleTy != MVT::Other && Width != VT.getSizeInBits())
20270 return std::pair(0U, nullptr);
20271
20272 MCRegister Reg = RC->getRegister(Idx);
20274 RC = TRI->getVGPRClassForBitWidth(Width);
20275 else if (SIRegisterInfo::isSGPRClass(RC))
20276 RC = TRI->getSGPRClassForBitWidth(Width);
20277 else if (SIRegisterInfo::isAGPRClass(RC))
20278 RC = TRI->getAGPRClassForBitWidth(Width);
20279 if (RC) {
20280 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
20281 if (!Reg) {
20282 // The register class does not contain the requested register,
20283 // e.g., because it is an SGPR pair that would violate alignment
20284 // requirements.
20285 return std::pair(0U, nullptr);
20286 }
20287 return std::pair(Reg, RC);
20288 }
20289 }
20290
20291 // Reject types that do not fit a single 32-bit register: any scalar wider
20292 // than 32 bits, or a vector that is not exactly 32 bits.
20293 if (VT.SimpleTy != MVT::Other &&
20294 (VT.getSizeInBits() > 32 ||
20295 (VT.isVector() && VT.getSizeInBits() != 32)))
20296 return std::pair(0U, nullptr);
20297 if (RC && Idx < RC->getNumRegs())
20298 return std::pair(RC->getRegister(Idx), RC);
20299 return std::pair(0U, nullptr);
20300 }
20301 }
20302
20303 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20304 if (Ret.first) {
20305 Ret.second = TRI->getPhysRegBaseClass(Ret.first);
20306 if (!Subtarget->useRealTrue16Insts() &&
20307 TRI->getRegSizeInBits(*Ret.second) == 16)
20308 return std::pair(0U, nullptr);
20309 }
20310
20311 return Ret;
20312}
20313
20314static bool isImmConstraint(StringRef Constraint) {
20315 if (Constraint.size() == 1) {
20316 switch (Constraint[0]) {
20317 default:
20318 break;
20319 case 'I':
20320 case 'J':
20321 case 'A':
20322 case 'B':
20323 case 'C':
20324 return true;
20325 }
20326 } else if (Constraint == "DA" || Constraint == "DB") {
20327 return true;
20328 }
20329 return false;
20330}
20331
20334 if (Constraint.size() == 1) {
20335 switch (Constraint[0]) {
20336 default:
20337 break;
20338 case 's':
20339 case 'v':
20340 case 'a':
20341 return C_RegisterClass;
20342 case 'm':
20343 return C_Memory;
20344 }
20345 } else if (Constraint.size() == 2) {
20346 if (Constraint == "VA")
20347 return C_RegisterClass;
20348 if (Constraint == "RF")
20349 return C_Memory;
20350 }
20351 if (isImmConstraint(Constraint)) {
20352 return C_Other;
20353 }
20354 return TargetLowering::getConstraintType(Constraint);
20355}
20356
20359 if (ConstraintCode == "RF")
20361
20362 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
20363}
20364
20365static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
20367 Val = Val & maskTrailingOnes<uint64_t>(Size);
20368 }
20369 return Val;
20370}
20371
20373 StringRef Constraint,
20374 std::vector<SDValue> &Ops,
20375 SelectionDAG &DAG) const {
20376 if (isImmConstraint(Constraint)) {
20377 uint64_t Val;
20378 if (getAsmOperandConstVal(Op, Val) &&
20379 checkAsmConstraintVal(Op, Constraint, Val)) {
20380 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
20381 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
20382 }
20383 } else {
20385 }
20386}
20387
20389 unsigned Size = Op.getScalarValueSizeInBits();
20390 if (Size > 64)
20391 return false;
20392
20393 if (Size == 16 && !Subtarget->has16BitInsts())
20394 return false;
20395
20397 Val = C->getSExtValue();
20398 return true;
20399 }
20401 Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
20402 return true;
20403 }
20405 if (Size != 16 || Op.getNumOperands() != 2)
20406 return false;
20407 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
20408 return false;
20409 if (ConstantSDNode *C = V->getConstantSplatNode()) {
20410 Val = C->getSExtValue();
20411 return true;
20412 }
20413 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
20414 Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
20415 return true;
20416 }
20417 }
20418
20419 return false;
20420}
20421
20423 uint64_t Val) const {
20424 if (Constraint.size() == 1) {
20425 switch (Constraint[0]) {
20426 case 'I':
20428 case 'J':
20429 return isInt<16>(Val);
20430 case 'A':
20431 return checkAsmConstraintValA(Op, Val);
20432 case 'B':
20433 return isInt<32>(Val);
20434 case 'C':
20435 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
20437 default:
20438 break;
20439 }
20440 } else if (Constraint.size() == 2) {
20441 if (Constraint == "DA") {
20442 int64_t HiBits = static_cast<int32_t>(Val >> 32);
20443 int64_t LoBits = static_cast<int32_t>(Val);
20444 return checkAsmConstraintValA(Op, HiBits, 32) &&
20445 checkAsmConstraintValA(Op, LoBits, 32);
20446 }
20447 if (Constraint == "DB") {
20448 return true;
20449 }
20450 }
20451 llvm_unreachable("Invalid asm constraint");
20452}
20453
20455 unsigned MaxSize) const {
20456 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
20457 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
20458 if (Size == 16) {
20459 MVT VT = Op.getSimpleValueType();
20460 switch (VT.SimpleTy) {
20461 default:
20462 return false;
20463 case MVT::i16:
20464 return AMDGPU::isInlinableLiteralI16(Val, HasInv2Pi);
20465 case MVT::f16:
20466 return AMDGPU::isInlinableLiteralFP16(Val, HasInv2Pi);
20467 case MVT::bf16:
20468 return AMDGPU::isInlinableLiteralBF16(Val, HasInv2Pi);
20469 case MVT::v2i16:
20470 return AMDGPU::getInlineEncodingV2I16(Val).has_value();
20471 case MVT::v2f16:
20472 return AMDGPU::getInlineEncodingV2F16(Val).has_value();
20473 case MVT::v2bf16:
20474 return AMDGPU::getInlineEncodingV2BF16(Val).has_value();
20475 }
20476 }
20477 if ((Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
20478 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi)))
20479 return true;
20480 return false;
20481}
20482
20483static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
20484 switch (UnalignedClassID) {
20485 case AMDGPU::VReg_64RegClassID:
20486 return AMDGPU::VReg_64_Align2RegClassID;
20487 case AMDGPU::VReg_96RegClassID:
20488 return AMDGPU::VReg_96_Align2RegClassID;
20489 case AMDGPU::VReg_128RegClassID:
20490 return AMDGPU::VReg_128_Align2RegClassID;
20491 case AMDGPU::VReg_160RegClassID:
20492 return AMDGPU::VReg_160_Align2RegClassID;
20493 case AMDGPU::VReg_192RegClassID:
20494 return AMDGPU::VReg_192_Align2RegClassID;
20495 case AMDGPU::VReg_224RegClassID:
20496 return AMDGPU::VReg_224_Align2RegClassID;
20497 case AMDGPU::VReg_256RegClassID:
20498 return AMDGPU::VReg_256_Align2RegClassID;
20499 case AMDGPU::VReg_288RegClassID:
20500 return AMDGPU::VReg_288_Align2RegClassID;
20501 case AMDGPU::VReg_320RegClassID:
20502 return AMDGPU::VReg_320_Align2RegClassID;
20503 case AMDGPU::VReg_352RegClassID:
20504 return AMDGPU::VReg_352_Align2RegClassID;
20505 case AMDGPU::VReg_384RegClassID:
20506 return AMDGPU::VReg_384_Align2RegClassID;
20507 case AMDGPU::VReg_512RegClassID:
20508 return AMDGPU::VReg_512_Align2RegClassID;
20509 case AMDGPU::VReg_1024RegClassID:
20510 return AMDGPU::VReg_1024_Align2RegClassID;
20511 case AMDGPU::AReg_64RegClassID:
20512 return AMDGPU::AReg_64_Align2RegClassID;
20513 case AMDGPU::AReg_96RegClassID:
20514 return AMDGPU::AReg_96_Align2RegClassID;
20515 case AMDGPU::AReg_128RegClassID:
20516 return AMDGPU::AReg_128_Align2RegClassID;
20517 case AMDGPU::AReg_160RegClassID:
20518 return AMDGPU::AReg_160_Align2RegClassID;
20519 case AMDGPU::AReg_192RegClassID:
20520 return AMDGPU::AReg_192_Align2RegClassID;
20521 case AMDGPU::AReg_256RegClassID:
20522 return AMDGPU::AReg_256_Align2RegClassID;
20523 case AMDGPU::AReg_512RegClassID:
20524 return AMDGPU::AReg_512_Align2RegClassID;
20525 case AMDGPU::AReg_1024RegClassID:
20526 return AMDGPU::AReg_1024_Align2RegClassID;
20527 default:
20528 return -1;
20529 }
20530}
20531
20532// Figure out which registers should be reserved for stack access. Only after
20533// the function is legalized do we know all of the non-spill stack objects or if
20534// calls are present.
20538 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
20539 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
20540 const SIInstrInfo *TII = ST.getInstrInfo();
20541
20542 if (Info->isEntryFunction()) {
20543 // Callable functions have fixed registers used for stack access.
20545 }
20546
20547 // TODO: Move this logic to getReservedRegs()
20548 // Reserve the SGPR(s) to save/restore EXEC for WWM spill/copy handling.
20549 unsigned MaxNumSGPRs = ST.getMaxNumSGPRs(MF);
20550 Register SReg = ST.isWave32()
20551 ? AMDGPU::SGPR_32RegClass.getRegister(MaxNumSGPRs - 1)
20552 : TRI->getAlignedHighSGPRForRC(MF, /*Align=*/2,
20553 &AMDGPU::SGPR_64RegClass);
20554 Info->setSGPRForEXECCopy(SReg);
20555
20556 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
20557 Info->getStackPtrOffsetReg()));
20558 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
20559 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
20560
20561 // We need to worry about replacing the default register with itself in case
20562 // of MIR testcases missing the MFI.
20563 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
20564 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
20565
20566 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
20567 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
20568
20569 Info->limitOccupancy(MF);
20570
20571 if (ST.isWave32() && !MF.empty()) {
20572 for (auto &MBB : MF) {
20573 for (auto &MI : MBB) {
20574 TII->fixImplicitOperands(MI);
20575 }
20576 }
20577 }
20578
20579 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
20580 // classes if required. Ideally the register class constraints would differ
20581 // per-subtarget, but there's no easy way to achieve that right now. This is
20582 // not a problem for VGPRs because the correctly aligned VGPR class is implied
20583 // from using them as the register class for legal types.
20584 if (ST.needsAlignedVGPRs()) {
20585 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
20586 const Register Reg = Register::index2VirtReg(I);
20587 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
20588 if (!RC)
20589 continue;
20590 int NewClassID = getAlignedAGPRClassID(RC->getID());
20591 if (NewClassID != -1)
20592 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
20593 }
20594 }
20595
20597}
20598
20601 const APInt &DemandedElts,
20602 const SelectionDAG &DAG,
20603 unsigned Depth) const {
20604 Known.resetAll();
20605 unsigned Opc = Op.getOpcode();
20606 switch (Opc) {
20608 unsigned IID = Op.getConstantOperandVal(0);
20609 switch (IID) {
20610 case Intrinsic::amdgcn_mbcnt_lo:
20611 case Intrinsic::amdgcn_mbcnt_hi: {
20612 const GCNSubtarget &ST =
20614 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
20615 // most 31 + src1.
20616 Known.Zero.setBitsFrom(
20617 IID == Intrinsic::amdgcn_mbcnt_lo ? ST.getWavefrontSizeLog2() : 5);
20618 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(2), Depth + 1);
20619 Known = KnownBits::add(Known, Known2);
20620 return;
20621 }
20622 }
20623 break;
20624 }
20625 }
20627 Op, Known, DemandedElts, DAG, Depth);
20628}
20629
20631 KnownBits &Known, const MachineFunction &MF, Align Alignment) const {
20633
20634 // Set the high bits to zero based on the maximum allowed scratch size per
20635 // wave. We can't use vaddr in MUBUF instructions if we don't know the address
20636 // calculation won't overflow, so assume the sign bit is never set.
20637 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
20638}
20639
20642 unsigned Dim) {
20643 unsigned MaxValue =
20644 ST.getMaxWorkitemID(VT.getMachineFunction().getFunction(), Dim);
20645 Known.Zero.setHighBits(llvm::countl_zero(MaxValue));
20646}
20647
20649 KnownBits &Known, const APInt &DemandedElts,
20650 unsigned BFEWidth, bool SExt, unsigned Depth) {
20652 const MachineOperand &Src1 = MI.getOperand(2);
20653
20654 unsigned Src1Cst = 0;
20655 if (Src1.isImm()) {
20656 Src1Cst = Src1.getImm();
20657 } else if (Src1.isReg()) {
20658 auto Cst = getIConstantVRegValWithLookThrough(Src1.getReg(), MRI);
20659 if (!Cst)
20660 return;
20661 Src1Cst = Cst->Value.getZExtValue();
20662 } else {
20663 return;
20664 }
20665
20666 // Offset is at bits [4:0] for 32 bit, [5:0] for 64 bit.
20667 // Width is always [22:16].
20668 const unsigned Offset =
20669 Src1Cst & maskTrailingOnes<unsigned>((BFEWidth == 32) ? 5 : 6);
20670 const unsigned Width = (Src1Cst >> 16) & maskTrailingOnes<unsigned>(6);
20671
20672 if (Width >= BFEWidth) // Ill-formed.
20673 return;
20674
20675 VT.computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
20676 Depth + 1);
20677
20678 Known = Known.extractBits(Width, Offset);
20679
20680 if (SExt)
20681 Known = Known.sext(BFEWidth);
20682 else
20683 Known = Known.zext(BFEWidth);
20684}
20685
20688 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
20689 unsigned Depth) const {
20690 Known.resetAll();
20691 const MachineInstr *MI = MRI.getVRegDef(R);
20692 switch (MI->getOpcode()) {
20693 case AMDGPU::S_BFE_I32:
20694 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/32,
20695 /*SExt=*/true, Depth);
20696 case AMDGPU::S_BFE_U32:
20697 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/32,
20698 /*SExt=*/false, Depth);
20699 case AMDGPU::S_BFE_I64:
20700 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/64,
20701 /*SExt=*/true, Depth);
20702 case AMDGPU::S_BFE_U64:
20703 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/64,
20704 /*SExt=*/false, Depth);
20705 case AMDGPU::G_INTRINSIC:
20706 case AMDGPU::G_INTRINSIC_CONVERGENT: {
20707 Intrinsic::ID IID = cast<GIntrinsic>(MI)->getIntrinsicID();
20708 switch (IID) {
20709 case Intrinsic::amdgcn_workitem_id_x:
20711 break;
20712 case Intrinsic::amdgcn_workitem_id_y:
20714 break;
20715 case Intrinsic::amdgcn_workitem_id_z:
20717 break;
20718 case Intrinsic::amdgcn_mbcnt_lo:
20719 case Intrinsic::amdgcn_mbcnt_hi: {
20720 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
20721 // most 31 + src1.
20722 Known.Zero.setBitsFrom(IID == Intrinsic::amdgcn_mbcnt_lo
20723 ? getSubtarget()->getWavefrontSizeLog2()
20724 : 5);
20725 KnownBits Known2;
20726 VT.computeKnownBitsImpl(MI->getOperand(3).getReg(), Known2, DemandedElts,
20727 Depth + 1);
20728 Known = KnownBits::add(Known, Known2);
20729 break;
20730 }
20731 case Intrinsic::amdgcn_groupstaticsize: {
20732 // We can report everything over the maximum size as 0. We can't report
20733 // based on the actual size because we don't know if it's accurate or not
20734 // at any given point.
20735 Known.Zero.setHighBits(
20736 llvm::countl_zero(getSubtarget()->getAddressableLocalMemorySize()));
20737 break;
20738 }
20739 case Intrinsic::amdgcn_readfirstlane:
20740 case Intrinsic::amdgcn_readlane: {
20741 // Result is the data operand's value from some lane.
20742 VT.computeKnownBitsImpl(MI->getOperand(2).getReg(), Known, DemandedElts,
20743 Depth + 1);
20744 break;
20745 }
20746 case Intrinsic::amdgcn_mul_u24:
20747 case Intrinsic::amdgcn_mul_i24: {
20748 Register LHS = MI->getOperand(2).getReg();
20749 Register RHS = MI->getOperand(3).getReg();
20750
20751 KnownBits RHSKnown;
20752 VT.computeKnownBitsImpl(RHS, RHSKnown, DemandedElts, Depth + 1);
20753
20754 bool SelfMultiply = LHS == RHS;
20755
20756 // For a self-multiply both operands are the same value, so RHSKnown also
20757 // describes the LHS; avoid the duplicated query.
20758 KnownBits LHSKnown;
20759 if (SelfMultiply)
20760 LHSKnown = RHSKnown;
20761 else
20762 VT.computeKnownBitsImpl(LHS, LHSKnown, DemandedElts, Depth + 1);
20763
20764 if (SelfMultiply)
20765 SelfMultiply &= isGuaranteedNotToBeUndef(LHS, MRI, Depth + 1);
20766
20767 Known = computeKnownBitsForMul24(LHSKnown, RHSKnown, Known.getBitWidth(),
20768 IID == Intrinsic::amdgcn_mul_i24,
20769 SelfMultiply);
20770 break;
20771 }
20772 }
20773 break;
20774 }
20775 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
20776 Known.Zero.setHighBits(24);
20777 break;
20778 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
20779 Known.Zero.setHighBits(16);
20780 break;
20781 case AMDGPU::G_AMDGPU_COPY_SCC_VCC:
20782 // G_AMDGPU_COPY_SCC_VCC converts a uniform boolean in VCC to SGPR s32,
20783 // producing exactly 0 or 1.
20784 Known.Zero.setHighBits(Known.getBitWidth() - 1);
20785 break;
20786 case AMDGPU::G_AMDGPU_SMED3:
20787 case AMDGPU::G_AMDGPU_UMED3: {
20788 auto [Dst, Src0, Src1, Src2] = MI->getFirst4Regs();
20789
20790 KnownBits Known2;
20791 VT.computeKnownBitsImpl(Src2, Known2, DemandedElts, Depth + 1);
20792 if (Known2.isUnknown())
20793 break;
20794
20795 KnownBits Known1;
20796 VT.computeKnownBitsImpl(Src1, Known1, DemandedElts, Depth + 1);
20797 if (Known1.isUnknown())
20798 break;
20799
20800 KnownBits Known0;
20801 VT.computeKnownBitsImpl(Src0, Known0, DemandedElts, Depth + 1);
20802 if (Known0.isUnknown())
20803 break;
20804
20805 // TODO: Handle LeadZero/LeadOne from UMIN/UMAX handling.
20806 Known.Zero = Known0.Zero & Known1.Zero & Known2.Zero;
20807 Known.One = Known0.One & Known1.One & Known2.One;
20808 break;
20809 }
20810 }
20811}
20812
20815 unsigned Depth) const {
20816 const MachineInstr *MI = MRI.getVRegDef(R);
20817 if (auto *GI = dyn_cast<GIntrinsic>(MI)) {
20818 // FIXME: Can this move to generic code? What about the case where the call
20819 // site specifies a lower alignment?
20820 Intrinsic::ID IID = GI->getIntrinsicID();
20822 AttributeList Attrs =
20823 Intrinsic::getAttributes(Ctx, IID, Intrinsic::getType(Ctx, IID));
20824 if (MaybeAlign RetAlign = Attrs.getRetAlignment())
20825 return *RetAlign;
20826 }
20827 return Align(1);
20828}
20829
20831 MachineLoop *ML, const MachineBasicBlock *BlockToAlign) const {
20833 const Align CacheLineAlign = Align(64);
20834
20835 // GFX950: Prevent an 8-byte instruction at the block being aligned from being
20836 // split by the 32-byte instruction fetch window boundary. This avoids a
20837 // significant fetch delay after a backward branch. We use 32-byte alignment
20838 // with max padding of 4 bytes (one s_nop), see
20839 // getMaxPermittedBytesForAlignment().
20840 if (ML && getSubtarget()->getCLOpts().loop_alignment &&
20841 getSubtarget()->hasLoopHeadInstSplitSensitivity()) {
20842 // Loop rotation can make the backedge destination a block other than the
20843 // LoopInfo header, so prefer the block the caller is actually aligning.
20844 if (!BlockToAlign)
20845 BlockToAlign = ML->getHeader();
20846 // Respect user-specified or previously set alignment.
20847 if (BlockToAlign->getAlignment() != PrefAlign)
20848 return BlockToAlign->getAlignment();
20849 if (needsFetchWindowAlignment(*BlockToAlign))
20850 return Align(32);
20851 }
20852
20853 // Pre-GFX10 target did not benefit from loop alignment
20854 if (!ML || !getSubtarget()->getCLOpts().loop_alignment ||
20855 !getSubtarget()->hasInstPrefetch() ||
20856 getSubtarget()->hasInstFwdPrefetchBug())
20857 return PrefAlign;
20858
20859 // On GFX10 I$ is 4 x 64 bytes cache lines.
20860 // By default prefetcher keeps one cache line behind and reads two ahead.
20861 // We can modify it with S_INST_PREFETCH for larger loops to have two lines
20862 // behind and one ahead.
20863 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
20864 // If loop fits 64 bytes it always spans no more than two cache lines and
20865 // does not need an alignment.
20866 // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
20867 // Else if loop is less or equal 192 bytes we need two lines behind.
20868
20870 const MachineBasicBlock *Header = ML->getHeader();
20871 if (Header->getAlignment() != PrefAlign)
20872 return Header->getAlignment(); // Already processed.
20873
20874 unsigned LoopSize = 0;
20875 for (const MachineBasicBlock *MBB : ML->blocks()) {
20876 // If inner loop block is aligned assume in average half of the alignment
20877 // size to be added as nops.
20878 if (MBB != Header)
20879 LoopSize += MBB->getAlignment().value() / 2;
20880
20881 for (const MachineInstr &MI : *MBB) {
20882 LoopSize += TII->getInstSizeInBytes(MI);
20883 if (LoopSize > 192)
20884 return PrefAlign;
20885 }
20886 }
20887
20888 if (LoopSize <= 64)
20889 return PrefAlign;
20890
20891 if (LoopSize <= 128)
20892 return CacheLineAlign;
20893
20894 // If any of parent loops is surrounded by prefetch instructions do not
20895 // insert new for inner loop, which would reset parent's settings.
20896 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
20897 if (MachineBasicBlock *Exit = P->getExitBlock()) {
20898 auto I = Exit->getFirstNonDebugInstr();
20899 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
20900 return CacheLineAlign;
20901 }
20902 }
20903
20904 MachineBasicBlock *Pre = ML->getLoopPreheader();
20905 MachineBasicBlock *Exit = ML->getExitBlock();
20906
20907 if (Pre && Exit) {
20908 auto PreTerm = Pre->getFirstTerminator();
20909 if (PreTerm == Pre->begin() ||
20910 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
20911 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
20912 .addImm(1); // prefetch 2 lines behind PC
20913
20914 auto ExitHead = Exit->getFirstNonDebugInstr();
20915 if (ExitHead == Exit->end() ||
20916 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
20917 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
20918 .addImm(2); // prefetch 1 line behind PC
20919 }
20920
20921 return CacheLineAlign;
20922}
20923
20925 MachineBasicBlock *MBB) const {
20926 // GFX950: Limit padding to 4 bytes (one s_nop) for blocks where an 8-byte
20927 // instruction could be split by the 32-byte fetch window boundary.
20928 // See getPrefLoopAlignment() for context.
20929 if (needsFetchWindowAlignment(*MBB))
20930 return 4;
20932}
20933
20934bool SITargetLowering::needsFetchWindowAlignment(
20935 const MachineBasicBlock &MBB) const {
20936 if (!getSubtarget()->hasLoopHeadInstSplitSensitivity())
20937 return false;
20939 for (const MachineInstr &MI : MBB) {
20940 if (MI.isMetaInstruction())
20941 continue;
20942 // Instructions larger than 4 bytes can be split by a 32-byte boundary.
20943 return TII->getInstSizeInBytes(MI) > 4;
20944 }
20945 return false;
20946}
20947
20948[[maybe_unused]]
20949static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
20950 assert(N->getOpcode() == ISD::CopyFromReg);
20951 do {
20952 // Follow the chain until we find an INLINEASM node.
20953 N = N->getOperand(0).getNode();
20954 if (N->getOpcode() == ISD::INLINEASM || N->getOpcode() == ISD::INLINEASM_BR)
20955 return true;
20956 } while (N->getOpcode() == ISD::CopyFromReg);
20957 return false;
20958}
20959
20962 UniformityInfo *UA) const {
20963 switch (N->getOpcode()) {
20964 case ISD::CopyFromReg: {
20965 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
20966 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
20967 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
20968 Register Reg = R->getReg();
20969
20970 // FIXME: Why does this need to consider isLiveIn?
20971 if (Reg.isPhysical() || MRI.isLiveIn(Reg))
20972 return !TRI->isSGPRReg(MRI, Reg);
20973
20974 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
20975 return UA->isDivergentAtDef(V);
20976
20978 return !TRI->isSGPRReg(MRI, Reg);
20979 }
20980 case ISD::LOAD: {
20981 const LoadSDNode *L = cast<LoadSDNode>(N);
20982 unsigned AS = L->getAddressSpace();
20983 // A flat load may access private memory.
20985 }
20986 case ISD::CALLSEQ_END:
20987 return true;
20989 return AMDGPU::isIntrinsicSourceOfDivergence(N->getConstantOperandVal(0));
20991 return AMDGPU::isIntrinsicSourceOfDivergence(N->getConstantOperandVal(1));
20992 case AMDGPUISD::ATOMIC_CMP_SWAP:
20993 case AMDGPUISD::BUFFER_ATOMIC_SWAP:
20994 case AMDGPUISD::BUFFER_ATOMIC_ADD:
20995 case AMDGPUISD::BUFFER_ATOMIC_SUB:
20996 case AMDGPUISD::BUFFER_ATOMIC_SMIN:
20997 case AMDGPUISD::BUFFER_ATOMIC_UMIN:
20998 case AMDGPUISD::BUFFER_ATOMIC_SMAX:
20999 case AMDGPUISD::BUFFER_ATOMIC_UMAX:
21000 case AMDGPUISD::BUFFER_ATOMIC_AND:
21001 case AMDGPUISD::BUFFER_ATOMIC_OR:
21002 case AMDGPUISD::BUFFER_ATOMIC_XOR:
21003 case AMDGPUISD::BUFFER_ATOMIC_INC:
21004 case AMDGPUISD::BUFFER_ATOMIC_DEC:
21005 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
21006 case AMDGPUISD::BUFFER_ATOMIC_FADD:
21007 case AMDGPUISD::BUFFER_ATOMIC_FMIN:
21008 case AMDGPUISD::BUFFER_ATOMIC_FMAX:
21009 // Target-specific read-modify-write atomics are sources of divergence.
21010 return true;
21011 default:
21012 if (auto *A = dyn_cast<AtomicSDNode>(N)) {
21013 // Generic read-modify-write atomics are sources of divergence.
21014 return A->readMem() && A->writeMem();
21015 }
21016 return false;
21017 }
21018}
21019
21021 EVT VT) const {
21022 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
21023 case MVT::f32:
21025 case MVT::f64:
21026 case MVT::f16:
21028 default:
21029 return false;
21030 }
21031}
21032
21034 LLT Ty, const MachineFunction &MF) const {
21035 switch (Ty.getScalarSizeInBits()) {
21036 case 32:
21037 return !denormalModeIsFlushAllF32(MF);
21038 case 64:
21039 case 16:
21040 return !denormalModeIsFlushAllF64F16(MF);
21041 default:
21042 return false;
21043 }
21044}
21045
21047 const APInt &DemandedElts,
21048 const SelectionDAG &DAG,
21049 bool SNaN,
21050 unsigned Depth) const {
21051 if (Op.getOpcode() == AMDGPUISD::CLAMP) {
21052 const MachineFunction &MF = DAG.getMachineFunction();
21054
21055 if (Info->getMode().DX10Clamp)
21056 return true; // Clamped to 0.
21057 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
21058 }
21059
21061 DAG, SNaN, Depth);
21062}
21063
21064namespace {
21065
21066/// Why a floating-point atomic instruction which may flush denormals is
21067/// acceptable.
21068enum class AtomicFlushDenormalReason {
21069 Native,
21070 IEEE,
21071 IgnoreDenormalMode,
21072 FunctionFlushesDenormals
21073};
21074
21075/// Why a native floating-point atomic instruction is acceptable for a global
21076/// memory address.
21077enum class GlobalFPAtomicLegality {
21078 Illegal,
21079 AgentScopeFineGrainedRemoteMemory,
21080 EmulatedSystemScope,
21081 NoRemoteMemory,
21082 NoFineGrainedMemory
21083};
21084
21085} // end anonymous namespace
21086
21087// On older subtargets, global FP atomic instructions have a hardcoded FP mode
21088// and do not support FP32 denormals, and only support v2f16/f64 denormals.
21089static AtomicFlushDenormalReason
21091 if (RMW->hasMetadata(LLVMContext::MD_atomic_ignore_denormal_mode))
21092 return AtomicFlushDenormalReason::IgnoreDenormalMode;
21093
21094 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
21095 auto DenormMode = RMW->getFunction()->getDenormalMode(Flt);
21096 return DenormMode == DenormalMode::getPreserveSign()
21097 ? AtomicFlushDenormalReason::FunctionFlushesDenormals
21098 : AtomicFlushDenormalReason::IEEE;
21099}
21100
21101static OptimizationRemark
21103 GlobalFPAtomicLegality MemLegality,
21104 AtomicFlushDenormalReason DenormReason) {
21105 LLVMContext &Ctx = RMW->getContext();
21106 StringRef MemScope = Ctx.getSyncScopeName(RMW->getSyncScopeID()).value_or("");
21107 if (MemScope.empty())
21108 MemScope = "system";
21109
21110 OptimizationRemark R(DEBUG_TYPE, "Passed", RMW);
21111 R << "hardware instruction generated for atomic "
21112 << ore::NV("Operation", RMW->getOperationName(RMW->getOperation()))
21113 << " at " << ore::NV("SyncScope", MemScope) << " scope since ";
21114
21115 switch (MemLegality) {
21116 case GlobalFPAtomicLegality::AgentScopeFineGrainedRemoteMemory:
21117 R << "fine-grained remote memory atomics work below system scope";
21118 break;
21119 case GlobalFPAtomicLegality::EmulatedSystemScope:
21120 R << "system scope atomics are emulated in hardware";
21121 break;
21122 case GlobalFPAtomicLegality::NoRemoteMemory:
21123 R << "memory is not remote (!amdgpu.no.remote.memory)";
21124 break;
21125 case GlobalFPAtomicLegality::NoFineGrainedMemory:
21126 R << "memory is not fine-grained (!amdgpu.no.fine.grained.memory)";
21127 break;
21128 case GlobalFPAtomicLegality::Illegal:
21129 llvm_unreachable("remark for illegal atomic");
21130 }
21131
21132 switch (DenormReason) {
21133 case AtomicFlushDenormalReason::Native:
21134 break;
21135 case AtomicFlushDenormalReason::IgnoreDenormalMode:
21136 R << ", and denormals may be flushed (!atomic.ignore.denormal.mode)";
21137 break;
21138 case AtomicFlushDenormalReason::FunctionFlushesDenormals:
21139 R << ", and the floating-point environment flushes denormals";
21140 break;
21141 case AtomicFlushDenormalReason::IEEE:
21142 llvm_unreachable("remark for illegal atomic");
21143 }
21144
21145 return R;
21146}
21147
21148static bool isV2F16OrV2BF16(Type *Ty) {
21149 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
21150 Type *EltTy = VT->getElementType();
21151 return VT->getNumElements() == 2 &&
21152 (EltTy->isHalfTy() || EltTy->isBFloatTy());
21153 }
21154
21155 return false;
21156}
21157
21158static bool isV2F16(Type *Ty) {
21160 return VT && VT->getNumElements() == 2 && VT->getElementType()->isHalfTy();
21161}
21162
21163static bool isV2BF16(Type *Ty) {
21165 return VT && VT->getNumElements() == 2 && VT->getElementType()->isBFloatTy();
21166}
21167
21168/// \return true if atomicrmw integer ops work for the type.
21169static bool isAtomicRMWLegalIntTy(Type *Ty) {
21170 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
21171 unsigned BW = IT->getBitWidth();
21172 return BW == 32 || BW == 64;
21173 }
21174
21175 return false;
21176}
21177
21178/// \return true if this atomicrmw xchg type can be selected.
21179static bool isAtomicRMWLegalXChgTy(const AtomicRMWInst *RMW) {
21180 Type *Ty = RMW->getType();
21181 if (isAtomicRMWLegalIntTy(Ty))
21182 return true;
21183
21184 if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
21185 const DataLayout &DL = RMW->getFunction()->getDataLayout();
21186 unsigned BW = DL.getPointerSizeInBits(PT->getAddressSpace());
21187 return BW == 32 || BW == 64;
21188 }
21189
21190 if (Ty->isFloatTy() || Ty->isDoubleTy())
21191 return true;
21192
21194 return VT->getNumElements() == 2 &&
21195 VT->getElementType()->getPrimitiveSizeInBits() == 16;
21196 }
21197
21198 return false;
21199}
21200
21201/// \returns whether it's valid to emit a native instruction for \p RMW, and
21202/// why, based on the properties of the target memory.
21203static GlobalFPAtomicLegality
21205 const AtomicRMWInst *RMW, bool HasSystemScope) {
21206 // The remote/fine-grained access logic is different from the integer
21207 // atomics. Without AgentScopeFineGrainedRemoteMemoryAtomics support,
21208 // fine-grained access does not work, even for a device local allocation.
21209 //
21210 // With AgentScopeFineGrainedRemoteMemoryAtomics, system scoped device local
21211 // allocations work.
21212 if (HasSystemScope) {
21213 if (Subtarget.hasAgentScopeFineGrainedRemoteMemoryAtomics() &&
21214 RMW->hasMetadata("amdgpu.no.remote.memory"))
21215 return GlobalFPAtomicLegality::NoRemoteMemory;
21216 if (Subtarget.hasEmulatedSystemScopeAtomics())
21217 return GlobalFPAtomicLegality::EmulatedSystemScope;
21218 } else if (Subtarget.hasAgentScopeFineGrainedRemoteMemoryAtomics())
21219 return GlobalFPAtomicLegality::AgentScopeFineGrainedRemoteMemory;
21220
21221 return RMW->hasMetadata("amdgpu.no.fine.grained.memory")
21222 ? GlobalFPAtomicLegality::NoFineGrainedMemory
21223 : GlobalFPAtomicLegality::Illegal;
21224}
21225
21226/// \return Action to perform on AtomicRMWInsts for integer operations.
21233
21234/// Return if a flat address space atomicrmw can access private memory.
21236 const MDNode *MD = I->getMetadata(LLVMContext::MD_noalias_addrspace);
21237 return !MD ||
21239}
21240
21243 // For GAS, lower to flat atomic.
21244 return STI.hasGloballyAddressableScratch()
21247}
21248
21251 unsigned AS = RMW->getPointerAddressSpace();
21252 if (AS == AMDGPUAS::PRIVATE_ADDRESS)
21254
21255 // 64-bit flat atomics that dynamically reside in private memory will silently
21256 // be dropped.
21257 //
21258 // Note that we will emit a new copy of the original atomic in the expansion,
21259 // which will be incrementally relegalized.
21260 const DataLayout &DL = RMW->getFunction()->getDataLayout();
21261 if (AS == AMDGPUAS::FLAT_ADDRESS &&
21262 DL.getTypeSizeInBits(RMW->getType()) == 64 &&
21265
21266 GlobalFPAtomicLegality MemLegality = GlobalFPAtomicLegality::Illegal;
21267 AtomicFlushDenormalReason DenormReason = AtomicFlushDenormalReason::Native;
21268 auto ReportHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
21270 ORE.emit([&]() {
21271 return emitAtomicRMWLegalRemark(RMW, MemLegality, DenormReason);
21272 });
21273 return Kind;
21274 };
21275
21276 auto SSID = RMW->getSyncScopeID();
21277 bool HasSystemScope =
21278 SSID == SyncScope::System ||
21280 getTargetMachine().getTargetTriple(), AtomicScope::System,
21281 /*OneAddressSpace=*/true));
21282
21283 auto Op = RMW->getOperation();
21284 switch (Op) {
21286 // PCIe supports add and xchg for system atomics.
21287 return isAtomicRMWLegalXChgTy(RMW)
21290 case AtomicRMWInst::Add:
21291 // PCIe supports add and xchg for system atomics.
21293 case AtomicRMWInst::Sub:
21294 case AtomicRMWInst::And:
21295 case AtomicRMWInst::Or:
21296 case AtomicRMWInst::Xor:
21297 case AtomicRMWInst::Max:
21298 case AtomicRMWInst::Min:
21305 if (Op == AtomicRMWInst::USubCond && !Subtarget->hasCondSubInsts())
21307 if (Op == AtomicRMWInst::USubSat) {
21308 // The global and buffer forms predate the LDS and flat ones.
21309 if (!Subtarget->hasSubClampInsts() ||
21310 (AS == AMDGPUAS::LOCAL_ADDRESS &&
21311 !Subtarget->hasAtomicDsCondSubClampInsts()) ||
21312 (AS == AMDGPUAS::FLAT_ADDRESS &&
21313 !Subtarget->hasAtomicCondSubClampFlatInsts()))
21315 }
21317 auto *IT = dyn_cast<IntegerType>(RMW->getType());
21318 if (!IT || IT->getBitWidth() != 32)
21320 }
21321
21324 if (Subtarget->hasEmulatedSystemScopeAtomics())
21326
21327 // On most subtargets, for atomicrmw operations other than add/xchg,
21328 // whether or not the instructions will behave correctly depends on where
21329 // the address physically resides and what interconnect is used in the
21330 // system configuration. On some some targets the instruction will nop,
21331 // and in others synchronization will only occur at degraded device scope.
21332 //
21333 // If the allocation is known local to the device, the instructions should
21334 // work correctly.
21335 if (RMW->hasMetadata("amdgpu.no.remote.memory"))
21337
21338 // If fine-grained remote memory works at device scope, we don't need to
21339 // do anything.
21340 if (!HasSystemScope &&
21341 Subtarget->hasAgentScopeFineGrainedRemoteMemoryAtomics())
21343
21344 // If we are targeting a remote allocated address, it depends what kind of
21345 // allocation the address belongs to.
21346 //
21347 // If the allocation is fine-grained (in host memory, or in PCIe peer
21348 // device memory), the operation will fail depending on the target.
21349 //
21350 // Note fine-grained host memory access does work on APUs or if XGMI is
21351 // used, but we do not know if we are targeting an APU or the system
21352 // configuration from the ISA version/target-cpu.
21353 if (RMW->hasMetadata("amdgpu.no.fine.grained.memory"))
21355
21358 // Atomic sub/or/xor do not work over PCI express, but atomic add
21359 // does. InstCombine transforms these with 0 to or, so undo that.
21360 // Sub-word types are not selectable and take the cmpxchg expansion.
21361 if (const Constant *ConstVal = dyn_cast<Constant>(RMW->getValOperand());
21362 ConstVal && ConstVal->isNullValue() &&
21365 }
21366
21367 // If the allocation could be in remote, fine-grained memory, the rmw
21368 // instructions may fail. cmpxchg should work, so emit that. On some
21369 // system configurations, PCIe atomics aren't supported so cmpxchg won't
21370 // even work, so you're out of luck anyway.
21371
21372 // In summary:
21373 //
21374 // Cases that may fail:
21375 // - fine-grained pinned host memory
21376 // - fine-grained migratable host memory
21377 // - fine-grained PCIe peer device
21378 //
21379 // Cases that should work, but may be treated overly conservatively.
21380 // - fine-grained host memory on an APU
21381 // - fine-grained XGMI peer device
21383 }
21384
21386 }
21387 case AtomicRMWInst::FAdd: {
21388 Type *Ty = RMW->getType();
21389
21390 // TODO: Handle REGION_ADDRESS
21391 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
21392 // DS F32 FP atomics do respect the denormal mode, but the rounding mode
21393 // is fixed to round-to-nearest-even.
21394 //
21395 // F64 / PK_F16 / PK_BF16 never flush and are also fixed to
21396 // round-to-nearest-even.
21397 //
21398 // We ignore the rounding mode problem, even in strictfp. The C++ standard
21399 // suggests it is OK if the floating-point mode may not match the calling
21400 // thread.
21401 if (Ty->isFloatTy()) {
21402 return Subtarget->hasLDSFPAtomicAddF32() ? AtomicExpansionKind::None
21404 }
21405
21406 if (Ty->isDoubleTy()) {
21407 // Ignores denormal mode, but we don't consider flushing mandatory.
21408 return Subtarget->hasLdsAtomicAddF64() ? AtomicExpansionKind::None
21410 }
21411
21412 if (Subtarget->hasAtomicDsPkAdd16Insts() && isV2F16OrV2BF16(Ty))
21414
21416 }
21417
21418 // LDS atomics respect the denormal mode from the mode register.
21419 //
21420 // Traditionally f32 global/buffer memory atomics would unconditionally
21421 // flush denormals, but newer targets do not flush. f64/f16/bf16 cases never
21422 // flush.
21423 //
21424 // On targets with flat atomic fadd, denormals would flush depending on
21425 // whether the target address resides in LDS or global memory. We consider
21426 // this flat-maybe-flush as will-flush.
21427 if (Ty->isFloatTy() &&
21428 !Subtarget->hasMemoryAtomicFaddF32DenormalSupport()) {
21429 DenormReason = getAtomicFlushDenormalReason(RMW);
21430 if (DenormReason == AtomicFlushDenormalReason::IEEE)
21432 }
21433
21434 MemLegality =
21435 getGlobalMemoryFPAtomicLegality(*Subtarget, RMW, HasSystemScope);
21436 if (MemLegality != GlobalFPAtomicLegality::Illegal) {
21437 if (AS == AMDGPUAS::FLAT_ADDRESS) {
21438 // gfx942, gfx12
21439 if (Subtarget->hasAtomicFlatPkAdd16Insts() && isV2F16OrV2BF16(Ty))
21440 return ReportHWInst(AtomicExpansionKind::None);
21441 } else if (AMDGPU::isExtendedGlobalAddrSpace(AS)) {
21442 // gfx90a, gfx942, gfx12
21443 if (Subtarget->hasAtomicBufferGlobalPkAddF16Insts() && isV2F16(Ty))
21444 return ReportHWInst(AtomicExpansionKind::None);
21445
21446 // gfx942, gfx12
21447 if (Subtarget->hasAtomicGlobalPkAddBF16Inst() && isV2BF16(Ty))
21448 return ReportHWInst(AtomicExpansionKind::None);
21449 } else if (AS == AMDGPUAS::BUFFER_FAT_POINTER) {
21450 // gfx90a, gfx942, gfx12
21451 if (Subtarget->hasAtomicBufferGlobalPkAddF16Insts() && isV2F16(Ty))
21452 return ReportHWInst(AtomicExpansionKind::None);
21453
21454 // While gfx90a/gfx942 supports v2bf16 for global/flat, it does not for
21455 // buffer. gfx12 does have the buffer version.
21456 if (Subtarget->hasAtomicBufferPkAddBF16Inst() && isV2BF16(Ty))
21457 return ReportHWInst(AtomicExpansionKind::None);
21458 }
21459
21460 // global and flat atomic fadd f64: gfx90a, gfx942.
21461 if (Subtarget->hasFlatBufferGlobalAtomicFaddF64Inst() && Ty->isDoubleTy())
21462 return ReportHWInst(AtomicExpansionKind::None);
21463
21464 if (AS != AMDGPUAS::FLAT_ADDRESS) {
21465 if (Ty->isFloatTy()) {
21466 // global/buffer atomic fadd f32 no-rtn: gfx908, gfx90a, gfx942,
21467 // gfx11+.
21468 if (RMW->use_empty() && Subtarget->hasAtomicFaddNoRtnInsts())
21469 return ReportHWInst(AtomicExpansionKind::None);
21470 // global/buffer atomic fadd f32 rtn: gfx90a, gfx942, gfx11+.
21471 if (!RMW->use_empty() && Subtarget->hasAtomicFaddRtnInsts())
21472 return ReportHWInst(AtomicExpansionKind::None);
21473 } else {
21474 // gfx908
21475 if (RMW->use_empty() &&
21476 Subtarget->hasAtomicBufferGlobalPkAddF16NoRtnInsts() &&
21477 isV2F16(Ty))
21478 return ReportHWInst(AtomicExpansionKind::None);
21479 }
21480 }
21481
21482 // flat atomic fadd f32: gfx942, gfx11+.
21483 if (AS == AMDGPUAS::FLAT_ADDRESS && Ty->isFloatTy()) {
21484 if (Subtarget->hasFlatAtomicFaddF32Inst())
21485 return ReportHWInst(AtomicExpansionKind::None);
21486
21487 // If it is in flat address space, and the type is float, we will try to
21488 // expand it, if the target supports global and lds atomic fadd. The
21489 // reason we need that is, in the expansion, we emit the check of
21490 // address space. If it is in global address space, we emit the global
21491 // atomic fadd; if it is in shared address space, we emit the LDS atomic
21492 // fadd.
21493 if (Subtarget->hasLDSFPAtomicAddF32()) {
21494 if (RMW->use_empty() && Subtarget->hasAtomicFaddNoRtnInsts())
21496 if (!RMW->use_empty() && Subtarget->hasAtomicFaddRtnInsts())
21498 }
21499 }
21500 }
21501
21503 }
21505 case AtomicRMWInst::FMax: {
21506 Type *Ty = RMW->getType();
21507
21508 // LDS float and double fmin/fmax were always supported.
21509 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
21510 return Ty->isFloatTy() || Ty->isDoubleTy() ? AtomicExpansionKind::None
21512 }
21513
21514 MemLegality =
21515 getGlobalMemoryFPAtomicLegality(*Subtarget, RMW, HasSystemScope);
21516 if (MemLegality != GlobalFPAtomicLegality::Illegal) {
21517 // For flat and global cases:
21518 // float, double in gfx7. Manual claims denormal support.
21519 // Removed in gfx8.
21520 // float, double restored in gfx10.
21521 // double removed again in gfx11, so only f32 for gfx11/gfx12.
21522 //
21523 // For gfx9, gfx90a and gfx942 support f64 for global (same as fadd), but
21524 // no f32.
21525 if (AS == AMDGPUAS::FLAT_ADDRESS) {
21526 if (Subtarget->hasAtomicFMinFMaxF32FlatInsts() && Ty->isFloatTy())
21527 return ReportHWInst(AtomicExpansionKind::None);
21528 if (Subtarget->hasAtomicFMinFMaxF64FlatInsts() && Ty->isDoubleTy())
21529 return ReportHWInst(AtomicExpansionKind::None);
21530 } else if (AMDGPU::isExtendedGlobalAddrSpace(AS) ||
21532 if (Subtarget->hasAtomicFMinFMaxF32GlobalInsts() && Ty->isFloatTy())
21533 return ReportHWInst(AtomicExpansionKind::None);
21534 if (Subtarget->hasAtomicFMinFMaxF64GlobalInsts() && Ty->isDoubleTy())
21535 return ReportHWInst(AtomicExpansionKind::None);
21536 }
21537 }
21538
21540 }
21543 default:
21545 }
21546
21547 llvm_unreachable("covered atomicrmw op switch");
21548}
21549
21556
21563
21566 const AtomicCmpXchgInst *CmpX) const {
21567 unsigned AddrSpace = CmpX->getPointerAddressSpace();
21568 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
21570
21571 if (AddrSpace != AMDGPUAS::FLAT_ADDRESS || !flatInstrMayAccessPrivate(CmpX))
21573
21574 const DataLayout &DL = CmpX->getDataLayout();
21575
21576 Type *ValTy = CmpX->getNewValOperand()->getType();
21577
21578 // If a 64-bit flat atomic may alias private, we need to avoid using the
21579 // atomic in the private case.
21580 return DL.getTypeSizeInBits(ValTy) == 64 ? AtomicExpansionKind::CustomExpand
21582}
21583
21584const TargetRegisterClass *
21585SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
21587 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
21588 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
21589 return Subtarget->isWave64() ? &AMDGPU::SReg_64RegClass
21590 : &AMDGPU::SReg_32RegClass;
21591 if (!TRI->isSGPRClass(RC) && !isDivergent)
21592 return TRI->getEquivalentSGPRClass(RC);
21593 if (TRI->isSGPRClass(RC) && isDivergent) {
21594 if (Subtarget->hasGFX90AInsts())
21595 return TRI->getEquivalentAVClass(RC);
21596 return TRI->getEquivalentVGPRClass(RC);
21597 }
21598
21599 return RC;
21600}
21601
21602// FIXME: This is a workaround for DivergenceAnalysis not understanding always
21603// uniform values (as produced by the mask results of control flow intrinsics)
21604// used outside of divergent blocks. The phi users need to also be treated as
21605// always uniform.
21606//
21607// FIXME: DA is no longer in-use. Does this still apply to UniformityAnalysis?
21609 unsigned WaveSize) {
21610 // FIXME: We assume we never cast the mask results of a control flow
21611 // intrinsic.
21612 // Early exit if the type won't be consistent as a compile time hack.
21613 IntegerType *IT = dyn_cast<IntegerType>(V->getType());
21614 if (!IT || IT->getBitWidth() != WaveSize)
21615 return false;
21616
21617 if (!isa<Instruction>(V))
21618 return false;
21619 if (!Visited.insert(V).second)
21620 return false;
21621 bool Result = false;
21622 for (const auto *U : V->users()) {
21624 if (V == U->getOperand(1)) {
21625 switch (Intrinsic->getIntrinsicID()) {
21626 default:
21627 Result = false;
21628 break;
21629 case Intrinsic::amdgcn_if_break:
21630 case Intrinsic::amdgcn_if:
21631 case Intrinsic::amdgcn_else:
21632 Result = true;
21633 break;
21634 }
21635 }
21636 if (V == U->getOperand(0)) {
21637 switch (Intrinsic->getIntrinsicID()) {
21638 default:
21639 Result = false;
21640 break;
21641 case Intrinsic::amdgcn_end_cf:
21642 case Intrinsic::amdgcn_loop:
21643 Result = true;
21644 break;
21645 }
21646 }
21647 } else {
21648 Result = hasCFUser(U, Visited, WaveSize);
21649 }
21650 if (Result)
21651 break;
21652 }
21653 return Result;
21654}
21655
21657 const Value *V) const {
21658 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
21659 if (CI->isInlineAsm()) {
21660 // FIXME: This cannot give a correct answer. This should only trigger in
21661 // the case where inline asm returns mixed SGPR and VGPR results, used
21662 // outside the defining block. We don't have a specific result to
21663 // consider, so this assumes if any value is SGPR, the overall register
21664 // also needs to be SGPR.
21665 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
21667 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
21668 for (auto &TC : TargetConstraints) {
21669 if (TC.Type == InlineAsm::isOutput) {
21671 const TargetRegisterClass *RC =
21672 getRegForInlineAsmConstraint(SIRI, TC.ConstraintCode,
21673 TC.ConstraintVT)
21674 .second;
21675 if (RC && SIRI->isSGPRClass(RC))
21676 return true;
21677 }
21678 }
21679 }
21680 }
21682 return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
21683}
21684
21686 for (SDUse &Use : N->uses()) {
21688 if (getBasePtrIndex(M) == Use.getOperandNo())
21689 return true;
21690 }
21691 }
21692 return false;
21693}
21694
21696 SDValue N1) const {
21697 if (!N0.hasOneUse())
21698 return false;
21699 // Take care of the opportunity to keep N0 uniform
21700 if (N0->isDivergent() || !N1->isDivergent())
21701 return true;
21702 // Check if we have a good chance to form the memory access pattern with the
21703 // base and offset
21704 return (DAG.isBaseWithConstantOffset(N0) &&
21706}
21707
21709 Register N0, Register N1) const {
21710 return MRI.hasOneNonDBGUse(N0); // FIXME: handle regbanks
21711}
21712
21715 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
21717 if (I.getMetadata("amdgpu.noclobber"))
21718 Flags |= MONoClobber;
21719 if (I.getMetadata("amdgpu.last.use"))
21720 Flags |= MOLastUse;
21721 if (MDNode *N = I.getMetadata("amdgpu.cfs")) {
21722 const ConstantAsMetadata *CAM = cast<ConstantAsMetadata>(N->getOperand(0));
21724 unsigned CFS = CI->getZExtValue() & AMDGPU::CPol::CFS_MASK;
21725 static_assert((MOCFSB0 << 1) == MOCFSB1,
21726 "MOCFSB0 and MOCFSB1 are not adjacent bits");
21727 Flags |= static_cast<MachineMemOperand::Flags>(CFS * MOCFSB0);
21728 }
21729 return Flags;
21730}
21731
21733 Instruction *AI) const {
21734 // Given: atomicrmw fadd ptr %addr, float %val ordering
21735 //
21736 // With this expansion we produce the following code:
21737 // [...]
21738 // %is.shared = call i1 @llvm.amdgcn.is.shared(ptr %addr)
21739 // br i1 %is.shared, label %atomicrmw.shared, label %atomicrmw.check.private
21740 //
21741 // atomicrmw.shared:
21742 // %cast.shared = addrspacecast ptr %addr to ptr addrspace(3)
21743 // %loaded.shared = atomicrmw fadd ptr addrspace(3) %cast.shared,
21744 // float %val ordering
21745 // br label %atomicrmw.phi
21746 //
21747 // atomicrmw.check.private:
21748 // %is.private = call i1 @llvm.amdgcn.is.private(ptr %int8ptr)
21749 // br i1 %is.private, label %atomicrmw.private, label %atomicrmw.global
21750 //
21751 // atomicrmw.private:
21752 // %cast.private = addrspacecast ptr %addr to ptr addrspace(5)
21753 // %loaded.private = load float, ptr addrspace(5) %cast.private
21754 // %val.new = fadd float %loaded.private, %val
21755 // store float %val.new, ptr addrspace(5) %cast.private
21756 // br label %atomicrmw.phi
21757 //
21758 // atomicrmw.global:
21759 // %cast.global = addrspacecast ptr %addr to ptr addrspace(1)
21760 // %loaded.global = atomicrmw fadd ptr addrspace(1) %cast.global,
21761 // float %val ordering
21762 // br label %atomicrmw.phi
21763 //
21764 // atomicrmw.phi:
21765 // %loaded.phi = phi float [ %loaded.shared, %atomicrmw.shared ],
21766 // [ %loaded.private, %atomicrmw.private ],
21767 // [ %loaded.global, %atomicrmw.global ]
21768 // br label %atomicrmw.end
21769 //
21770 // atomicrmw.end:
21771 // [...]
21772 //
21773 //
21774 // For 64-bit atomics which may reside in private memory, we perform a simpler
21775 // version that only inserts the private check, and uses the flat operation.
21776
21777 IRBuilder<> Builder(AI);
21778 LLVMContext &Ctx = Builder.getContext();
21779
21780 auto *RMW = dyn_cast<AtomicRMWInst>(AI);
21781 const unsigned PtrOpIdx = RMW ? AtomicRMWInst::getPointerOperandIndex()
21783 Value *Addr = AI->getOperand(PtrOpIdx);
21784
21785 /// TODO: Only need to check private, then emit flat-known-not private (no
21786 /// need for shared block, or cast to global).
21788
21789 Align Alignment;
21790 if (RMW)
21791 Alignment = RMW->getAlign();
21792 else if (CX)
21793 Alignment = CX->getAlign();
21794 else
21795 llvm_unreachable("unhandled atomic operation");
21796
21797 // FullFlatEmulation is true if we need to issue the private, shared, and
21798 // global cases.
21799 //
21800 // If this is false, we are only dealing with the flat-targeting-private case,
21801 // where we only insert a check for private and still use the flat instruction
21802 // for global and shared.
21803
21804 bool FullFlatEmulation =
21805 RMW && RMW->getOperation() == AtomicRMWInst::FAdd &&
21806 ((Subtarget->hasAtomicFaddInsts() && RMW->getType()->isFloatTy()) ||
21807 (Subtarget->hasFlatBufferGlobalAtomicFaddF64Inst() &&
21808 RMW->getType()->isDoubleTy()));
21809
21810 // If the return value isn't used, do not introduce a false use in the phi.
21811 bool ReturnValueIsUsed = !AI->use_empty();
21812
21813 BasicBlock *BB = Builder.GetInsertBlock();
21814 Function *F = BB->getParent();
21815 BasicBlock *ExitBB =
21816 BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
21817 BasicBlock *SharedBB = nullptr;
21818
21819 BasicBlock *CheckPrivateBB = BB;
21820 if (FullFlatEmulation) {
21821 SharedBB = BasicBlock::Create(Ctx, "atomicrmw.shared", F, ExitBB);
21822 CheckPrivateBB =
21823 BasicBlock::Create(Ctx, "atomicrmw.check.private", F, ExitBB);
21824 }
21825
21826 BasicBlock *PrivateBB =
21827 BasicBlock::Create(Ctx, "atomicrmw.private", F, ExitBB);
21828 BasicBlock *GlobalBB = BasicBlock::Create(Ctx, "atomicrmw.global", F, ExitBB);
21829 BasicBlock *PhiBB = BasicBlock::Create(Ctx, "atomicrmw.phi", F, ExitBB);
21830
21831 std::prev(BB->end())->eraseFromParent();
21832 Builder.SetInsertPoint(BB);
21833
21834 Value *LoadedShared = nullptr;
21835 if (FullFlatEmulation) {
21836 Value *IsShared = Builder.CreateIntrinsic(Intrinsic::amdgcn_is_shared,
21837 {Addr}, nullptr, "is.shared");
21838 Builder.CreateCondBr(IsShared, SharedBB, CheckPrivateBB);
21839 Builder.SetInsertPoint(SharedBB);
21840 Value *CastToLocal = Builder.CreateAddrSpaceCast(
21842
21843 Instruction *Clone = AI->clone();
21844 Clone->insertInto(SharedBB, SharedBB->end());
21845 Clone->getOperandUse(PtrOpIdx).set(CastToLocal);
21846 LoadedShared = Clone;
21847
21848 Builder.CreateBr(PhiBB);
21849 Builder.SetInsertPoint(CheckPrivateBB);
21850 }
21851
21852 Value *IsPrivate = Builder.CreateIntrinsic(Intrinsic::amdgcn_is_private,
21853 {Addr}, nullptr, "is.private");
21854 Builder.CreateCondBr(IsPrivate, PrivateBB, GlobalBB);
21855
21856 Builder.SetInsertPoint(PrivateBB);
21857
21858 Value *CastToPrivate = Builder.CreateAddrSpaceCast(
21860
21861 Value *LoadedPrivate;
21862 if (RMW) {
21863 LoadedPrivate = Builder.CreateAlignedLoad(
21864 RMW->getType(), CastToPrivate, RMW->getAlign(), RMW->isVolatile(),
21865 "loaded.private");
21866
21867 Value *NewVal = buildAtomicRMWValue(RMW->getOperation(), Builder,
21868 LoadedPrivate, RMW->getValOperand());
21869
21870 Builder.CreateAlignedStore(NewVal, CastToPrivate, RMW->getAlign(),
21871 RMW->isVolatile());
21872 } else {
21873 auto [ResultLoad, Equal] = buildCmpXchgValue(
21874 Builder, CastToPrivate, CX->getCompareOperand(), CX->getNewValOperand(),
21875 CX->getAlign(), CX->isVolatile());
21876
21877 Value *Insert = Builder.CreateInsertValue(PoisonValue::get(CX->getType()),
21878 ResultLoad, 0);
21879 LoadedPrivate = Builder.CreateInsertValue(Insert, Equal, 1);
21880 }
21881
21882 Builder.CreateBr(PhiBB);
21883
21884 Builder.SetInsertPoint(GlobalBB);
21885
21886 // Continue using a flat instruction if we only emitted the check for private.
21887 Instruction *LoadedGlobal = AI;
21888 if (FullFlatEmulation) {
21889 Value *CastToGlobal = Builder.CreateAddrSpaceCast(
21891 AI->getOperandUse(PtrOpIdx).set(CastToGlobal);
21892 }
21893
21894 AI->removeFromParent();
21895 AI->insertInto(GlobalBB, GlobalBB->end());
21896
21897 // The new atomicrmw may go through another round of legalization later.
21898 if (!FullFlatEmulation) {
21899 // We inserted the runtime check already, make sure we do not try to
21900 // re-expand this.
21901 // TODO: Should union with any existing metadata.
21902 MDBuilder MDB(F->getContext());
21903 MDNode *RangeNotPrivate =
21906 LoadedGlobal->setMetadata(LLVMContext::MD_noalias_addrspace,
21907 RangeNotPrivate);
21908 }
21909
21910 Builder.CreateBr(PhiBB);
21911
21912 Builder.SetInsertPoint(PhiBB);
21913
21914 if (ReturnValueIsUsed) {
21915 PHINode *Loaded = Builder.CreatePHI(AI->getType(), 3);
21916 AI->replaceAllUsesWith(Loaded);
21917 if (FullFlatEmulation)
21918 Loaded->addIncoming(LoadedShared, SharedBB);
21919 Loaded->addIncoming(LoadedPrivate, PrivateBB);
21920 Loaded->addIncoming(LoadedGlobal, GlobalBB);
21921 Loaded->takeName(AI);
21922 }
21923
21924 Builder.CreateBr(ExitBB);
21925}
21926
21928 unsigned PtrOpIdx) {
21929 Value *PtrOp = I->getOperand(PtrOpIdx);
21932
21933 Type *FlatPtr = PointerType::get(I->getContext(), AMDGPUAS::FLAT_ADDRESS);
21934 Value *ASCast = CastInst::CreatePointerCast(PtrOp, FlatPtr, "scratch.ascast",
21935 I->getIterator());
21936 I->setOperand(PtrOpIdx, ASCast);
21937}
21938
21941
21944
21947 if (const auto *ConstVal = dyn_cast<Constant>(AI->getValOperand());
21948