LLVM 18.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 "AMDGPUInstrInfo.h"
17#include "AMDGPUTargetMachine.h"
18#include "GCNSubtarget.h"
21#include "SIRegisterInfo.h"
22#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/Statistic.h"
38#include "llvm/IR/IRBuilder.h"
40#include "llvm/IR/IntrinsicsAMDGPU.h"
41#include "llvm/IR/IntrinsicsR600.h"
44#include "llvm/Support/ModRef.h"
45#include <optional>
46
47using namespace llvm;
48
49#define DEBUG_TYPE "si-lower"
50
51STATISTIC(NumTailCalls, "Number of tail calls");
52
54 "amdgpu-disable-loop-alignment",
55 cl::desc("Do not align and prefetch loops"),
56 cl::init(false));
57
59 "amdgpu-use-divergent-register-indexing",
61 cl::desc("Use indirect register addressing for divergent indexes"),
62 cl::init(false));
63
66 return Info->getMode().FP32Denormals == DenormalMode::getPreserveSign();
67}
68
71 return Info->getMode().FP64FP16Denormals == DenormalMode::getPreserveSign();
72}
73
74static unsigned findFirstFreeSGPR(CCState &CCInfo) {
75 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
76 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
77 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
78 return AMDGPU::SGPR0 + Reg;
79 }
80 }
81 llvm_unreachable("Cannot allocate sgpr");
82}
83
85 const GCNSubtarget &STI)
87 Subtarget(&STI) {
88 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
89 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
90
91 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
92 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
93
94 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
95
96 const SIRegisterInfo *TRI = STI.getRegisterInfo();
97 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
98
99 addRegisterClass(MVT::f64, V64RegClass);
100 addRegisterClass(MVT::v2f32, V64RegClass);
101
102 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
103 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
104
105 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
106 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
107
108 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
109 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
110
111 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
112 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
113
114 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
115 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
116
117 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
118 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
119
120 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
121 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
122
123 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
124 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
125
126 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
127 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
128
129 addRegisterClass(MVT::v9i32, &AMDGPU::SGPR_288RegClass);
130 addRegisterClass(MVT::v9f32, TRI->getVGPRClassForBitWidth(288));
131
132 addRegisterClass(MVT::v10i32, &AMDGPU::SGPR_320RegClass);
133 addRegisterClass(MVT::v10f32, TRI->getVGPRClassForBitWidth(320));
134
135 addRegisterClass(MVT::v11i32, &AMDGPU::SGPR_352RegClass);
136 addRegisterClass(MVT::v11f32, TRI->getVGPRClassForBitWidth(352));
137
138 addRegisterClass(MVT::v12i32, &AMDGPU::SGPR_384RegClass);
139 addRegisterClass(MVT::v12f32, TRI->getVGPRClassForBitWidth(384));
140
141 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
142 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
143
144 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
145 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
146
147 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
148 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
149
150 if (Subtarget->has16BitInsts()) {
151 if (Subtarget->useRealTrue16Insts()) {
152 addRegisterClass(MVT::i16, &AMDGPU::VGPR_16RegClass);
153 addRegisterClass(MVT::f16, &AMDGPU::VGPR_16RegClass);
154 } else {
155 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
156 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
157 }
158
159 // Unless there are also VOP3P operations, not operations are really legal.
160 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
161 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
162 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
163 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
164 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
165 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
166 addRegisterClass(MVT::v16i16, &AMDGPU::SGPR_256RegClass);
167 addRegisterClass(MVT::v16f16, &AMDGPU::SGPR_256RegClass);
168 addRegisterClass(MVT::v32i16, &AMDGPU::SGPR_512RegClass);
169 addRegisterClass(MVT::v32f16, &AMDGPU::SGPR_512RegClass);
170 }
171
172 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
173 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
174
176
177 // The boolean content concept here is too inflexible. Compares only ever
178 // really produce a 1-bit result. Any copy/extend from these will turn into a
179 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
180 // it's what most targets use.
183
184 // We need to custom lower vector stores from local memory
186 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
187 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
188 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
189 MVT::i1, MVT::v32i32},
190 Custom);
191
193 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
194 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
195 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
196 MVT::i1, MVT::v32i32},
197 Custom);
198
199 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
200 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
201 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
202 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
203 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
204 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
205 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
206 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
207 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
208 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
209 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
210 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
211 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
212 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
213 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
214 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
215
216 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
217 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
218 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
219 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
220 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
221 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
222 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
223
224 setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom);
225
229 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
230
231 setOperationAction(ISD::FSQRT, {MVT::f32, MVT::f64}, Custom);
232
234 {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand);
235
237 setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand);
238 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
239
241 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
242 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
243 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32},
244 Expand);
246 {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32,
247 MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v9f32,
248 MVT::v10f32, MVT::v11f32, MVT::v12f32, MVT::v16f32},
249 Expand);
250
252 {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16,
253 MVT::v3i16, MVT::v4i16, MVT::Other},
254 Custom);
255
258 {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand);
259
261
263
265 Expand);
266
267#if 0
269#endif
270
271 // We only support LOAD/STORE and vector manipulation ops for vectors
272 // with > 4 elements.
273 for (MVT VT :
274 {MVT::v8i32, MVT::v8f32, MVT::v9i32, MVT::v9f32, MVT::v10i32,
275 MVT::v10f32, MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32,
276 MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64, MVT::v4i16,
277 MVT::v4f16, MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
278 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, MVT::v8i16,
279 MVT::v8f16, MVT::v16i16, MVT::v16f16, MVT::v16i64, MVT::v16f64,
280 MVT::v32i32, MVT::v32f32, MVT::v32i16, MVT::v32f16}) {
281 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
282 switch (Op) {
283 case ISD::LOAD:
284 case ISD::STORE:
286 case ISD::BITCAST:
287 case ISD::UNDEF:
291 case ISD::IS_FPCLASS:
292 break;
297 break;
298 default:
300 break;
301 }
302 }
303 }
304
306
307 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
308 // is expanded to avoid having two separate loops in case the index is a VGPR.
309
310 // Most operations are naturally 32-bit vector operations. We only support
311 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
312 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
314 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
315
317 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
318
320 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
321
323 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
324 }
325
326 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
328 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
329
331 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
332
334 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
335
337 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
338 }
339
340 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
342 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
343
345 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
346
348 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
349
351 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
352 }
353
354 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
356 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
357
359 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
360
362 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
363
365 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
366 }
367
368 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
370 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
371
373 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
374
376 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
377
379 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
380 }
381
383 {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32},
384 Expand);
385
386 setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16}, Custom);
387
388 // Avoid stack access for these.
389 // TODO: Generalize to more vector types.
391 {MVT::v2i16, MVT::v2f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
392 MVT::v4i16, MVT::v4f16},
393 Custom);
394
395 // Deal with vec3 vector operations when widened to vec4.
397 {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom);
398
399 // Deal with vec5/6/7 vector operations when widened to vec8.
401 {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32,
402 MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32,
403 MVT::v9i32, MVT::v9f32, MVT::v10i32, MVT::v10f32,
404 MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32},
405 Custom);
406
407 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
408 // and output demarshalling
409 setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom);
410
411 // We can't return success/failure, only the old value,
412 // let LLVM add the comparison
414 Expand);
415
416 setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
417
418 setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal);
419
420 // FIXME: This should be narrowed to i32, but that only happens if i64 is
421 // illegal.
422 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
423 setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal);
424
425 // On SI this is s_memtime and s_memrealtime on VI.
428
429 if (Subtarget->has16BitInsts()) {
432 } else {
434 }
435
436 if (Subtarget->hasMadMacF32Insts())
438
439 if (!Subtarget->hasBFI())
440 // fcopysign can be done in a single instruction with BFI.
441 setOperationAction(ISD::FCOPYSIGN, {MVT::f32, MVT::f64}, Expand);
442
443 if (!Subtarget->hasBCNT(32))
445
446 if (!Subtarget->hasBCNT(64))
448
449 if (Subtarget->hasFFBH())
451
452 if (Subtarget->hasFFBL())
454
455 // We only really have 32-bit BFE instructions (and 16-bit on VI).
456 //
457 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
458 // effort to match them now. We want this to be false for i64 cases when the
459 // extraction isn't restricted to the upper or lower half. Ideally we would
460 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
461 // span the midpoint are probably relatively rare, so don't worry about them
462 // for now.
463 if (Subtarget->hasBFE())
465
466 // Clamp modifier on add/sub
467 if (Subtarget->hasIntClamp())
469
470 if (Subtarget->hasAddNoCarry())
471 setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32},
472 Legal);
473
474 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::f32, MVT::f64},
475 Custom);
476
477 // These are really only legal for ieee_mode functions. We should be avoiding
478 // them for functions that don't have ieee_mode enabled, so just say they are
479 // legal.
481 {MVT::f32, MVT::f64}, Legal);
482
483 if (Subtarget->haveRoundOpsF64())
485 Legal);
486 else
488 MVT::f64, Custom);
489
491 setOperationAction({ISD::FLDEXP, ISD::STRICT_FLDEXP}, {MVT::f32, MVT::f64},
492 Legal);
493 setOperationAction(ISD::FFREXP, {MVT::f32, MVT::f64}, Custom);
494
497
498 setOperationAction(ISD::BF16_TO_FP, {MVT::i16, MVT::f32, MVT::f64}, Expand);
499 setOperationAction(ISD::FP_TO_BF16, {MVT::i16, MVT::f32, MVT::f64}, Expand);
500
501 if (Subtarget->has16BitInsts()) {
504 MVT::i16, Legal);
505
506 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
507
509 MVT::i16, Expand);
510
514 ISD::CTPOP},
515 MVT::i16, Promote);
516
518
519 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
520
522 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
524 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
525
527
528 // F16 - Constant Actions.
530
531 // F16 - Load/Store Actions.
533 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
535 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
536
537 // F16 - VOP1 Actions.
540 MVT::f16, Custom);
541
543
546 MVT::f16, Promote);
547
548 // F16 - VOP2 Actions.
553
554 // F16 - VOP3 Actions.
556 if (STI.hasMadF16())
558
559 for (MVT VT :
560 {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
561 MVT::v8f16, MVT::v16i16, MVT::v16f16, MVT::v32i16, MVT::v32f16}) {
562 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
563 switch (Op) {
564 case ISD::LOAD:
565 case ISD::STORE:
567 case ISD::BITCAST:
568 case ISD::UNDEF:
574 case ISD::IS_FPCLASS:
575 break;
578 break;
579 default:
581 break;
582 }
583 }
584 }
585
586 // v_perm_b32 can handle either of these.
587 setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal);
589
590 // XXX - Do these do anything? Vector constants turn into build_vector.
591 setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal);
592
593 setOperationAction(ISD::UNDEF, {MVT::v2i16, MVT::v2f16}, Legal);
594
596 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
598 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
599
601 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
603 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
604
605 setOperationAction(ISD::AND, MVT::v2i16, Promote);
606 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
607 setOperationAction(ISD::OR, MVT::v2i16, Promote);
608 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
609 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
610 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
611
613 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
615 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
616
618 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
620 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
621
623 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
625 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
626
628 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
630 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
631
633 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
635 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
636
637 setOperationAction(ISD::LOAD, MVT::v16i16, Promote);
638 AddPromotedToType(ISD::LOAD, MVT::v16i16, MVT::v8i32);
639 setOperationAction(ISD::LOAD, MVT::v16f16, Promote);
640 AddPromotedToType(ISD::LOAD, MVT::v16f16, MVT::v8i32);
641
643 AddPromotedToType(ISD::STORE, MVT::v16i16, MVT::v8i32);
645 AddPromotedToType(ISD::STORE, MVT::v16f16, MVT::v8i32);
646
647 setOperationAction(ISD::LOAD, MVT::v32i16, Promote);
648 AddPromotedToType(ISD::LOAD, MVT::v32i16, MVT::v16i32);
649 setOperationAction(ISD::LOAD, MVT::v32f16, Promote);
650 AddPromotedToType(ISD::LOAD, MVT::v32f16, MVT::v16i32);
651
653 AddPromotedToType(ISD::STORE, MVT::v32i16, MVT::v16i32);
655 AddPromotedToType(ISD::STORE, MVT::v32f16, MVT::v16i32);
656
658 MVT::v2i32, Expand);
660
662 MVT::v4i32, Expand);
663
665 MVT::v8i32, Expand);
666
667 if (!Subtarget->hasVOP3PInsts())
668 setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16}, Custom);
669
670 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
671 // This isn't really legal, but this avoids the legalizer unrolling it (and
672 // allows matching fneg (fabs x) patterns)
673 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
674
677
679 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
680 Custom);
681
683 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
684 Expand);
685
686 for (MVT Vec16 : {MVT::v8i16, MVT::v8f16, MVT::v16i16, MVT::v16f16,
687 MVT::v32i16, MVT::v32f16}) {
690 Vec16, Custom);
692 }
693 }
694
695 if (Subtarget->hasVOP3PInsts()) {
699 MVT::v2i16, Legal);
700
703 MVT::v2f16, Legal);
704
705 setOperationAction(ISD::EXTRACT_VECTOR_ELT, {MVT::v2i16, MVT::v2f16},
706 Custom);
707
709 {MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::v8i16,
710 MVT::v16f16, MVT::v16i16, MVT::v32f16, MVT::v32i16},
711 Custom);
712
713 for (MVT VT : {MVT::v4i16, MVT::v8i16, MVT::v16i16, MVT::v32i16})
714 // Split vector operations.
719 VT, Custom);
720
721 for (MVT VT : {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16})
722 // Split vector operations.
724 VT, Custom);
725
726 setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, {MVT::v2f16, MVT::v4f16},
727 Custom);
728
729 setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
730 setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16}, Custom);
731
732 if (Subtarget->hasPackedFP32Ops()) {
734 MVT::v2f32, Legal);
736 {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32},
737 Custom);
738 }
739 }
740
742
743 if (Subtarget->has16BitInsts()) {
745 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
747 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
748 } else {
749 // Legalization hack.
750 setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom);
751
753 }
754
756 {MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
757 MVT::v8i16, MVT::v8f16, MVT::v16i16, MVT::v16f16,
758 MVT::v32i16, MVT::v32f16},
759 Custom);
760
762
763 if (Subtarget->hasMad64_32())
765
767 {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
768 MVT::v2i16, MVT::v2f16, MVT::i128},
769 Custom);
770
772 {MVT::v2f16, MVT::v2i16, MVT::v3f16, MVT::v3i16,
773 MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::Other, MVT::f16,
774 MVT::i16, MVT::i8, MVT::i128},
775 Custom);
776
778 {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v3i16,
779 MVT::v3f16, MVT::v4f16, MVT::v4i16, MVT::f16, MVT::i16,
780 MVT::i8, MVT::i128},
781 Custom);
782
785
786 // TODO: Could move this to custom lowering, could benefit from combines on
787 // extract of relevant bits.
789
791
794 ISD::SUB,
796 ISD::FADD,
797 ISD::FSUB,
798 ISD::FDIV,
803 ISD::FMA,
804 ISD::SMIN,
805 ISD::SMAX,
806 ISD::UMIN,
807 ISD::UMAX,
809 ISD::AND,
810 ISD::OR,
811 ISD::XOR,
812 ISD::FSHR,
822
823 if (Subtarget->has16BitInsts() && !Subtarget->hasMed3_16())
825
826 // All memory operations. Some folding on the pointer operand is done to help
827 // matching the constant offsets in the addressing modes.
850
851 // FIXME: In other contexts we pretend this is a per-function property.
853
855}
856
858 return Subtarget;
859}
860
861//===----------------------------------------------------------------------===//
862// TargetLowering queries
863//===----------------------------------------------------------------------===//
864
865// v_mad_mix* support a conversion from f16 to f32.
866//
867// There is only one special case when denormals are enabled we don't currently,
868// where this is OK to use.
870 EVT DestVT, EVT SrcVT) const {
871 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
872 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
873 DestVT.getScalarType() == MVT::f32 &&
874 SrcVT.getScalarType() == MVT::f16 &&
875 // TODO: This probably only requires no input flushing?
877}
878
880 LLT DestTy, LLT SrcTy) const {
881 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
882 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
883 DestTy.getScalarSizeInBits() == 32 &&
884 SrcTy.getScalarSizeInBits() == 16 &&
885 // TODO: This probably only requires no input flushing?
887}
888
890 // SI has some legal vector types, but no legal vector operations. Say no
891 // shuffles are legal in order to prefer scalarizing some vector operations.
892 return false;
893}
894
897 EVT VT) const {
900
901 if (VT.isVector()) {
902 EVT ScalarVT = VT.getScalarType();
903 unsigned Size = ScalarVT.getSizeInBits();
904 if (Size == 16) {
905 if (Subtarget->has16BitInsts()) {
906 if (VT.isInteger())
907 return MVT::v2i16;
908 return (ScalarVT == MVT::bf16 ? MVT::i32 : MVT::v2f16);
909 }
910 return VT.isInteger() ? MVT::i32 : MVT::f32;
911 }
912
913 if (Size < 16)
914 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
915 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
916 }
917
918 if (VT.getSizeInBits() > 32)
919 return MVT::i32;
920
922}
923
926 EVT VT) const {
929
930 if (VT.isVector()) {
931 unsigned NumElts = VT.getVectorNumElements();
932 EVT ScalarVT = VT.getScalarType();
933 unsigned Size = ScalarVT.getSizeInBits();
934
935 // FIXME: Should probably promote 8-bit vectors to i16.
936 if (Size == 16 && Subtarget->has16BitInsts())
937 return (NumElts + 1) / 2;
938
939 if (Size <= 32)
940 return NumElts;
941
942 if (Size > 32)
943 return NumElts * ((Size + 31) / 32);
944 } else if (VT.getSizeInBits() > 32)
945 return (VT.getSizeInBits() + 31) / 32;
946
948}
949
952 EVT VT, EVT &IntermediateVT,
953 unsigned &NumIntermediates, MVT &RegisterVT) const {
954 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
955 unsigned NumElts = VT.getVectorNumElements();
956 EVT ScalarVT = VT.getScalarType();
957 unsigned Size = ScalarVT.getSizeInBits();
958 // FIXME: We should fix the ABI to be the same on targets without 16-bit
959 // support, but unless we can properly handle 3-vectors, it will be still be
960 // inconsistent.
961 if (Size == 16 && Subtarget->has16BitInsts()) {
962 if (ScalarVT == MVT::bf16) {
963 RegisterVT = MVT::i32;
964 IntermediateVT = MVT::v2bf16;
965 } else {
966 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
967 IntermediateVT = RegisterVT;
968 }
969 NumIntermediates = (NumElts + 1) / 2;
970 return NumIntermediates;
971 }
972
973 if (Size == 32) {
974 RegisterVT = ScalarVT.getSimpleVT();
975 IntermediateVT = RegisterVT;
976 NumIntermediates = NumElts;
977 return NumIntermediates;
978 }
979
980 if (Size < 16 && Subtarget->has16BitInsts()) {
981 // FIXME: Should probably form v2i16 pieces
982 RegisterVT = MVT::i16;
983 IntermediateVT = ScalarVT;
984 NumIntermediates = NumElts;
985 return NumIntermediates;
986 }
987
988
989 if (Size != 16 && Size <= 32) {
990 RegisterVT = MVT::i32;
991 IntermediateVT = ScalarVT;
992 NumIntermediates = NumElts;
993 return NumIntermediates;
994 }
995
996 if (Size > 32) {
997 RegisterVT = MVT::i32;
998 IntermediateVT = RegisterVT;
999 NumIntermediates = NumElts * ((Size + 31) / 32);
1000 return NumIntermediates;
1001 }
1002 }
1003
1005 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1006}
1007
1008static EVT memVTFromLoadIntrData(Type *Ty, unsigned MaxNumLanes) {
1009 assert(MaxNumLanes != 0);
1010
1011 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1012 unsigned NumElts = std::min(MaxNumLanes, VT->getNumElements());
1013 return EVT::getVectorVT(Ty->getContext(),
1014 EVT::getEVT(VT->getElementType()),
1015 NumElts);
1016 }
1017
1018 return EVT::getEVT(Ty);
1019}
1020
1021// Peek through TFE struct returns to only use the data size.
1022static EVT memVTFromLoadIntrReturn(Type *Ty, unsigned MaxNumLanes) {
1023 auto *ST = dyn_cast<StructType>(Ty);
1024 if (!ST)
1025 return memVTFromLoadIntrData(Ty, MaxNumLanes);
1026
1027 // TFE intrinsics return an aggregate type.
1028 assert(ST->getNumContainedTypes() == 2 &&
1029 ST->getContainedType(1)->isIntegerTy(32));
1030 return memVTFromLoadIntrData(ST->getContainedType(0), MaxNumLanes);
1031}
1032
1033/// Map address space 7 to MVT::v5i32 because that's its in-memory
1034/// representation. This return value is vector-typed because there is no
1035/// MVT::i160 and it is not clear if one can be added. While this could
1036/// cause issues during codegen, these address space 7 pointers will be
1037/// rewritten away by then. Therefore, we can return MVT::v5i32 in order
1038/// to allow pre-codegen passes that query TargetTransformInfo, often for cost
1039/// modeling, to work.
1041 if (AMDGPUAS::BUFFER_FAT_POINTER == AS && DL.getPointerSizeInBits(AS) == 160)
1042 return MVT::v5i32;
1044}
1045/// Similarly, the in-memory representation of a p7 is {p8, i32}, aka
1046/// v8i32 when padding is added.
1048 if (AMDGPUAS::BUFFER_FAT_POINTER == AS && DL.getPointerSizeInBits(AS) == 160)
1049 return MVT::v8i32;
1051}
1052
1054 const CallInst &CI,
1055 MachineFunction &MF,
1056 unsigned IntrID) const {
1058 if (CI.hasMetadata(LLVMContext::MD_invariant_load))
1060
1061 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1064 (Intrinsic::ID)IntrID);
1065 MemoryEffects ME = Attr.getMemoryEffects();
1066 if (ME.doesNotAccessMemory())
1067 return false;
1068
1069 // TODO: Should images get their own address space?
1070 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1071
1072 if (RsrcIntr->IsImage)
1073 Info.align.reset();
1074
1075 Value *RsrcArg = CI.getArgOperand(RsrcIntr->RsrcArg);
1076 if (auto *RsrcPtrTy = dyn_cast<PointerType>(RsrcArg->getType())) {
1077 if (RsrcPtrTy->getAddressSpace() == AMDGPUAS::BUFFER_RESOURCE)
1078 // We conservatively set the memory operand of a buffer intrinsic to the
1079 // base resource pointer, so that we can access alias information about
1080 // those pointers. Cases like "this points at the same value
1081 // but with a different offset" are handled in
1082 // areMemAccessesTriviallyDisjoint.
1083 Info.ptrVal = RsrcArg;
1084 }
1085
1087 if (ME.onlyReadsMemory()) {
1088 unsigned MaxNumLanes = 4;
1089
1090 if (RsrcIntr->IsImage) {
1093 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1095
1096 if (!BaseOpcode->Gather4) {
1097 // If this isn't a gather, we may have excess loaded elements in the
1098 // IR type. Check the dmask for the real number of elements loaded.
1099 unsigned DMask
1100 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1101 MaxNumLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1102 }
1103 }
1104
1105 Info.memVT = memVTFromLoadIntrReturn(CI.getType(), MaxNumLanes);
1106
1107 // FIXME: What does alignment mean for an image?
1110 } else if (ME.onlyWritesMemory()) {
1112
1113 Type *DataTy = CI.getArgOperand(0)->getType();
1114 if (RsrcIntr->IsImage) {
1115 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1116 unsigned DMaskLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1117 Info.memVT = memVTFromLoadIntrData(DataTy, DMaskLanes);
1118 } else
1119 Info.memVT = EVT::getEVT(DataTy);
1120
1122 } else {
1123 // Atomic
1124 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1126 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1130
1131 // XXX - Should this be volatile without known ordering?
1133
1134 switch (IntrID) {
1135 default:
1136 break;
1137 case Intrinsic::amdgcn_raw_buffer_load_lds:
1138 case Intrinsic::amdgcn_raw_ptr_buffer_load_lds:
1139 case Intrinsic::amdgcn_struct_buffer_load_lds:
1140 case Intrinsic::amdgcn_struct_ptr_buffer_load_lds: {
1141 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1142 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1143 return true;
1144 }
1145 }
1146 }
1147 return true;
1148 }
1149
1150 switch (IntrID) {
1151 case Intrinsic::amdgcn_ds_ordered_add:
1152 case Intrinsic::amdgcn_ds_ordered_swap:
1153 case Intrinsic::amdgcn_ds_fadd:
1154 case Intrinsic::amdgcn_ds_fmin:
1155 case Intrinsic::amdgcn_ds_fmax: {
1157 Info.memVT = MVT::getVT(CI.getType());
1158 Info.ptrVal = CI.getOperand(0);
1159 Info.align.reset();
1161
1162 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1163 if (!Vol->isZero())
1165
1166 return true;
1167 }
1168 case Intrinsic::amdgcn_buffer_atomic_fadd: {
1170 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1171 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1172 Info.align.reset();
1174
1175 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1176 if (!Vol || !Vol->isZero())
1178
1179 return true;
1180 }
1181 case Intrinsic::amdgcn_ds_add_gs_reg_rtn:
1182 case Intrinsic::amdgcn_ds_sub_gs_reg_rtn: {
1184 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1185 Info.ptrVal = nullptr;
1186 Info.fallbackAddressSpace = AMDGPUAS::STREAMOUT_REGISTER;
1188 return true;
1189 }
1190 case Intrinsic::amdgcn_ds_append:
1191 case Intrinsic::amdgcn_ds_consume: {
1193 Info.memVT = MVT::getVT(CI.getType());
1194 Info.ptrVal = CI.getOperand(0);
1195 Info.align.reset();
1197
1198 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1199 if (!Vol->isZero())
1201
1202 return true;
1203 }
1204 case Intrinsic::amdgcn_global_atomic_csub: {
1206 Info.memVT = MVT::getVT(CI.getType());
1207 Info.ptrVal = CI.getOperand(0);
1208 Info.align.reset();
1212 return true;
1213 }
1214 case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1216 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1217
1218 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1219 Info.align.reset();
1222 return true;
1223 }
1224 case Intrinsic::amdgcn_global_atomic_fadd:
1225 case Intrinsic::amdgcn_global_atomic_fmin:
1226 case Intrinsic::amdgcn_global_atomic_fmax:
1227 case Intrinsic::amdgcn_flat_atomic_fadd:
1228 case Intrinsic::amdgcn_flat_atomic_fmin:
1229 case Intrinsic::amdgcn_flat_atomic_fmax:
1230 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1231 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1233 Info.memVT = MVT::getVT(CI.getType());
1234 Info.ptrVal = CI.getOperand(0);
1235 Info.align.reset();
1240 return true;
1241 }
1242 case Intrinsic::amdgcn_ds_gws_init:
1243 case Intrinsic::amdgcn_ds_gws_barrier:
1244 case Intrinsic::amdgcn_ds_gws_sema_v:
1245 case Intrinsic::amdgcn_ds_gws_sema_br:
1246 case Intrinsic::amdgcn_ds_gws_sema_p:
1247 case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1249
1250 const GCNTargetMachine &TM =
1251 static_cast<const GCNTargetMachine &>(getTargetMachine());
1252
1254 Info.ptrVal = MFI->getGWSPSV(TM);
1255
1256 // This is an abstract access, but we need to specify a type and size.
1257 Info.memVT = MVT::i32;
1258 Info.size = 4;
1259 Info.align = Align(4);
1260
1261 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1263 else
1265 return true;
1266 }
1267 case Intrinsic::amdgcn_global_load_lds: {
1269 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1270 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1273 return true;
1274 }
1275 case Intrinsic::amdgcn_ds_bvh_stack_rtn: {
1277
1278 const GCNTargetMachine &TM =
1279 static_cast<const GCNTargetMachine &>(getTargetMachine());
1280
1282 Info.ptrVal = MFI->getGWSPSV(TM);
1283
1284 // This is an abstract access, but we need to specify a type and size.
1285 Info.memVT = MVT::i32;
1286 Info.size = 4;
1287 Info.align = Align(4);
1288
1290 return true;
1291 }
1292 default:
1293 return false;
1294 }
1295}
1296
1299 Type *&AccessTy) const {
1300 switch (II->getIntrinsicID()) {
1301 case Intrinsic::amdgcn_ds_ordered_add:
1302 case Intrinsic::amdgcn_ds_ordered_swap:
1303 case Intrinsic::amdgcn_ds_append:
1304 case Intrinsic::amdgcn_ds_consume:
1305 case Intrinsic::amdgcn_ds_fadd:
1306 case Intrinsic::amdgcn_ds_fmin:
1307 case Intrinsic::amdgcn_ds_fmax:
1308 case Intrinsic::amdgcn_global_atomic_fadd:
1309 case Intrinsic::amdgcn_flat_atomic_fadd:
1310 case Intrinsic::amdgcn_flat_atomic_fmin:
1311 case Intrinsic::amdgcn_flat_atomic_fmax:
1312 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1313 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1314 case Intrinsic::amdgcn_global_atomic_csub: {
1315 Value *Ptr = II->getArgOperand(0);
1316 AccessTy = II->getType();
1317 Ops.push_back(Ptr);
1318 return true;
1319 }
1320 default:
1321 return false;
1322 }
1323}
1324
1325bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM,
1326 unsigned AddrSpace,
1327 uint64_t FlatVariant) const {
1328 if (!Subtarget->hasFlatInstOffsets()) {
1329 // Flat instructions do not have offsets, and only have the register
1330 // address.
1331 return AM.BaseOffs == 0 && AM.Scale == 0;
1332 }
1333
1334 return AM.Scale == 0 &&
1335 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1336 AM.BaseOffs, AddrSpace, FlatVariant));
1337}
1338
1340 if (Subtarget->hasFlatGlobalInsts())
1341 return isLegalFlatAddressingMode(AM, AMDGPUAS::GLOBAL_ADDRESS,
1343
1344 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1345 // Assume the we will use FLAT for all global memory accesses
1346 // on VI.
1347 // FIXME: This assumption is currently wrong. On VI we still use
1348 // MUBUF instructions for the r + i addressing mode. As currently
1349 // implemented, the MUBUF instructions only work on buffer < 4GB.
1350 // It may be possible to support > 4GB buffers with MUBUF instructions,
1351 // by setting the stride value in the resource descriptor which would
1352 // increase the size limit to (stride * 4GB). However, this is risky,
1353 // because it has never been validated.
1354 return isLegalFlatAddressingMode(AM, AMDGPUAS::FLAT_ADDRESS,
1356 }
1357
1358 return isLegalMUBUFAddressingMode(AM);
1359}
1360
1361bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1362 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1363 // additionally can do r + r + i with addr64. 32-bit has more addressing
1364 // mode options. Depending on the resource constant, it can also do
1365 // (i64 r0) + (i32 r1) * (i14 i).
1366 //
1367 // Private arrays end up using a scratch buffer most of the time, so also
1368 // assume those use MUBUF instructions. Scratch loads / stores are currently
1369 // implemented as mubuf instructions with offen bit set, so slightly
1370 // different than the normal addr64.
1371 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1372 return false;
1373
1374 // FIXME: Since we can split immediate into soffset and immediate offset,
1375 // would it make sense to allow any immediate?
1376
1377 switch (AM.Scale) {
1378 case 0: // r + i or just i, depending on HasBaseReg.
1379 return true;
1380 case 1:
1381 return true; // We have r + r or r + i.
1382 case 2:
1383 if (AM.HasBaseReg) {
1384 // Reject 2 * r + r.
1385 return false;
1386 }
1387
1388 // Allow 2 * r as r + r
1389 // Or 2 * r + i is allowed as r + r + i.
1390 return true;
1391 default: // Don't allow n * r
1392 return false;
1393 }
1394}
1395
1397 const AddrMode &AM, Type *Ty,
1398 unsigned AS, Instruction *I) const {
1399 // No global is ever allowed as a base.
1400 if (AM.BaseGV)
1401 return false;
1402
1403 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1404 return isLegalGlobalAddressingMode(AM);
1405
1406 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1409 // If the offset isn't a multiple of 4, it probably isn't going to be
1410 // correctly aligned.
1411 // FIXME: Can we get the real alignment here?
1412 if (AM.BaseOffs % 4 != 0)
1413 return isLegalMUBUFAddressingMode(AM);
1414
1415 // There are no SMRD extloads, so if we have to do a small type access we
1416 // will use a MUBUF load.
1417 // FIXME?: We also need to do this if unaligned, but we don't know the
1418 // alignment here.
1419 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1420 return isLegalGlobalAddressingMode(AM);
1421
1423 // SMRD instructions have an 8-bit, dword offset on SI.
1424 if (!isUInt<8>(AM.BaseOffs / 4))
1425 return false;
1426 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1427 // On CI+, this can also be a 32-bit literal constant offset. If it fits
1428 // in 8-bits, it can use a smaller encoding.
1429 if (!isUInt<32>(AM.BaseOffs / 4))
1430 return false;
1431 } else if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX9) {
1432 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1433 if (!isUInt<20>(AM.BaseOffs))
1434 return false;
1435 } else {
1436 // On GFX9 the offset is signed 21-bit in bytes (but must not be negative
1437 // for S_BUFFER_* instructions).
1438 if (!isInt<21>(AM.BaseOffs))
1439 return false;
1440 }
1441
1442 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1443 return true;
1444
1445 if (AM.Scale == 1 && AM.HasBaseReg)
1446 return true;
1447
1448 return false;
1449 }
1450
1451 if (AS == AMDGPUAS::PRIVATE_ADDRESS)
1452 return Subtarget->enableFlatScratch()
1453 ? isLegalFlatAddressingMode(AM, AMDGPUAS::PRIVATE_ADDRESS,
1455 : isLegalMUBUFAddressingMode(AM);
1456
1457 if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1458 (AS == AMDGPUAS::REGION_ADDRESS && Subtarget->hasGDS())) {
1459 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1460 // field.
1461 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1462 // an 8-bit dword offset but we don't know the alignment here.
1463 if (!isUInt<16>(AM.BaseOffs))
1464 return false;
1465
1466 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1467 return true;
1468
1469 if (AM.Scale == 1 && AM.HasBaseReg)
1470 return true;
1471
1472 return false;
1473 }
1474
1476 // For an unknown address space, this usually means that this is for some
1477 // reason being used for pure arithmetic, and not based on some addressing
1478 // computation. We don't have instructions that compute pointers with any
1479 // addressing modes, so treat them as having no offset like flat
1480 // instructions.
1481 return isLegalFlatAddressingMode(AM, AMDGPUAS::FLAT_ADDRESS,
1483 }
1484
1485 // Assume a user alias of global for unknown address spaces.
1486 return isLegalGlobalAddressingMode(AM);
1487}
1488
1490 const MachineFunction &MF) const {
1492 return (MemVT.getSizeInBits() <= 4 * 32);
1493 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1494 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1495 return (MemVT.getSizeInBits() <= MaxPrivateBits);
1496 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1497 return (MemVT.getSizeInBits() <= 2 * 32);
1498 }
1499 return true;
1500}
1501
1503 unsigned Size, unsigned AddrSpace, Align Alignment,
1504 MachineMemOperand::Flags Flags, unsigned *IsFast) const {
1505 if (IsFast)
1506 *IsFast = 0;
1507
1508 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1509 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1510 // Check if alignment requirements for ds_read/write instructions are
1511 // disabled.
1512 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1513 return false;
1514
1515 Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1516 if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1517 Alignment < RequiredAlignment)
1518 return false;
1519
1520 // Either, the alignment requirements are "enabled", or there is an
1521 // unaligned LDS access related hardware bug though alignment requirements
1522 // are "disabled". In either case, we need to check for proper alignment
1523 // requirements.
1524 //
1525 switch (Size) {
1526 case 64:
1527 // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1528 // address is negative, then the instruction is incorrectly treated as
1529 // out-of-bounds even if base + offsets is in bounds. Split vectorized
1530 // loads here to avoid emitting ds_read2_b32. We may re-combine the
1531 // load later in the SILoadStoreOptimizer.
1532 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1533 return false;
1534
1535 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1536 // can do a 4 byte aligned, 8 byte access in a single operation using
1537 // ds_read2/write2_b32 with adjacent offsets.
1538 RequiredAlignment = Align(4);
1539
1540 if (Subtarget->hasUnalignedDSAccessEnabled()) {
1541 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1542 // ds_write2_b32 depending on the alignment. In either case with either
1543 // alignment there is no faster way of doing this.
1544
1545 // The numbers returned here and below are not additive, it is a 'speed
1546 // rank'. They are just meant to be compared to decide if a certain way
1547 // of lowering an operation is faster than another. For that purpose
1548 // naturally aligned operation gets it bitsize to indicate that "it
1549 // operates with a speed comparable to N-bit wide load". With the full
1550 // alignment ds128 is slower than ds96 for example. If underaligned it
1551 // is comparable to a speed of a single dword access, which would then
1552 // mean 32 < 128 and it is faster to issue a wide load regardless.
1553 // 1 is simply "slow, don't do it". I.e. comparing an aligned load to a
1554 // wider load which will not be aligned anymore the latter is slower.
1555 if (IsFast)
1556 *IsFast = (Alignment >= RequiredAlignment) ? 64
1557 : (Alignment < Align(4)) ? 32
1558 : 1;
1559 return true;
1560 }
1561
1562 break;
1563 case 96:
1564 if (!Subtarget->hasDS96AndDS128())
1565 return false;
1566
1567 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1568 // gfx8 and older.
1569
1570 if (Subtarget->hasUnalignedDSAccessEnabled()) {
1571 // Naturally aligned access is fastest. However, also report it is Fast
1572 // if memory is aligned less than DWORD. A narrow load or store will be
1573 // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1574 // be more of them, so overall we will pay less penalty issuing a single
1575 // instruction.
1576
1577 // See comment on the values above.
1578 if (IsFast)
1579 *IsFast = (Alignment >= RequiredAlignment) ? 96
1580 : (Alignment < Align(4)) ? 32
1581 : 1;
1582 return true;
1583 }
1584
1585 break;
1586 case 128:
1587 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1588 return false;
1589
1590 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1591 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a
1592 // single operation using ds_read2/write2_b64.
1593 RequiredAlignment = Align(8);
1594
1595 if (Subtarget->hasUnalignedDSAccessEnabled()) {
1596 // Naturally aligned access is fastest. However, also report it is Fast
1597 // if memory is aligned less than DWORD. A narrow load or store will be
1598 // be equally slow as a single ds_read_b128/ds_write_b128, but there
1599 // will be more of them, so overall we will pay less penalty issuing a
1600 // single instruction.
1601
1602 // See comment on the values above.
1603 if (IsFast)
1604 *IsFast = (Alignment >= RequiredAlignment) ? 128
1605 : (Alignment < Align(4)) ? 32
1606 : 1;
1607 return true;
1608 }
1609
1610 break;
1611 default:
1612 if (Size > 32)
1613 return false;
1614
1615 break;
1616 }
1617
1618 // See comment on the values above.
1619 // Note that we have a single-dword or sub-dword here, so if underaligned
1620 // it is a slowest possible access, hence returned value is 0.
1621 if (IsFast)
1622 *IsFast = (Alignment >= RequiredAlignment) ? Size : 0;
1623
1624 return Alignment >= RequiredAlignment ||
1625 Subtarget->hasUnalignedDSAccessEnabled();
1626 }
1627
1628 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1629 bool AlignedBy4 = Alignment >= Align(4);
1630 if (IsFast)
1631 *IsFast = AlignedBy4;
1632
1633 return AlignedBy4 ||
1634 Subtarget->enableFlatScratch() ||
1635 Subtarget->hasUnalignedScratchAccess();
1636 }
1637
1638 // FIXME: We have to be conservative here and assume that flat operations
1639 // will access scratch. If we had access to the IR function, then we
1640 // could determine if any private memory was used in the function.
1641 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1642 !Subtarget->hasUnalignedScratchAccess()) {
1643 bool AlignedBy4 = Alignment >= Align(4);
1644 if (IsFast)
1645 *IsFast = AlignedBy4;
1646
1647 return AlignedBy4;
1648 }
1649
1650 // So long as they are correct, wide global memory operations perform better
1651 // than multiple smaller memory ops -- even when misaligned
1652 if (AMDGPU::isExtendedGlobalAddrSpace(AddrSpace)) {
1653 if (IsFast)
1654 *IsFast = Size;
1655
1656 return Alignment >= Align(4) ||
1658 }
1659
1660 // Smaller than dword value must be aligned.
1661 if (Size < 32)
1662 return false;
1663
1664 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1665 // byte-address are ignored, thus forcing Dword alignment.
1666 // This applies to private, global, and constant memory.
1667 if (IsFast)
1668 *IsFast = 1;
1669
1670 return Size >= 32 && Alignment >= Align(4);
1671}
1672
1674 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1675 unsigned *IsFast) const {
1677 Alignment, Flags, IsFast);
1678}
1679
1681 const MemOp &Op, const AttributeList &FuncAttributes) const {
1682 // FIXME: Should account for address space here.
1683
1684 // The default fallback uses the private pointer size as a guess for a type to
1685 // use. Make sure we switch these to 64-bit accesses.
1686
1687 if (Op.size() >= 16 &&
1688 Op.isDstAligned(Align(4))) // XXX: Should only do for global
1689 return MVT::v4i32;
1690
1691 if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1692 return MVT::v2i32;
1693
1694 // Use the default.
1695 return MVT::Other;
1696}
1697
1699 const MemSDNode *MemNode = cast<MemSDNode>(N);
1700 return MemNode->getMemOperand()->getFlags() & MONoClobber;
1701}
1702
1704 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1706}
1707
1709 unsigned DestAS) const {
1710 // Flat -> private/local is a simple truncate.
1711 // Flat -> global is no-op
1712 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1713 return true;
1714
1715 const GCNTargetMachine &TM =
1716 static_cast<const GCNTargetMachine &>(getTargetMachine());
1717 return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1718}
1719
1721 const MemSDNode *MemNode = cast<MemSDNode>(N);
1722
1724}
1725
1728 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1729 VT.getScalarType().bitsLE(MVT::i16))
1732}
1733
1735 Type *Ty) const {
1736 // FIXME: Could be smarter if called for vector constants.
1737 return true;
1738}
1739
1741 unsigned Index) const {
1743 return false;
1744
1745 // TODO: Add more cases that are cheap.
1746 return Index == 0;
1747}
1748
1750 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1751 switch (Op) {
1752 case ISD::LOAD:
1753 case ISD::STORE:
1754
1755 // These operations are done with 32-bit instructions anyway.
1756 case ISD::AND:
1757 case ISD::OR:
1758 case ISD::XOR:
1759 case ISD::SELECT:
1760 // TODO: Extensions?
1761 return true;
1762 default:
1763 return false;
1764 }
1765 }
1766
1767 // SimplifySetCC uses this function to determine whether or not it should
1768 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1769 if (VT == MVT::i1 && Op == ISD::SETCC)
1770 return false;
1771
1773}
1774
1775SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1776 const SDLoc &SL,
1777 SDValue Chain,
1778 uint64_t Offset) const {
1779 const DataLayout &DL = DAG.getDataLayout();
1782
1783 const ArgDescriptor *InputPtrReg;
1784 const TargetRegisterClass *RC;
1785 LLT ArgTy;
1787
1788 std::tie(InputPtrReg, RC, ArgTy) =
1790
1791 // We may not have the kernarg segment argument if we have no kernel
1792 // arguments.
1793 if (!InputPtrReg)
1794 return DAG.getConstant(0, SL, PtrVT);
1795
1797 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1798 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1799
1800 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Offset));
1801}
1802
1803SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1804 const SDLoc &SL) const {
1807 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1808}
1809
1810SDValue SITargetLowering::getLDSKernelId(SelectionDAG &DAG,
1811 const SDLoc &SL) const {
1812
1814 std::optional<uint32_t> KnownSize =
1816 if (KnownSize.has_value())
1817 return DAG.getConstant(*KnownSize, SL, MVT::i32);
1818 return SDValue();
1819}
1820
1821SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1822 const SDLoc &SL, SDValue Val,
1823 bool Signed,
1824 const ISD::InputArg *Arg) const {
1825 // First, if it is a widened vector, narrow it.
1826 if (VT.isVector() &&
1828 EVT NarrowedVT =
1831 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1832 DAG.getConstant(0, SL, MVT::i32));
1833 }
1834
1835 // Then convert the vector elements or scalar value.
1836 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1837 VT.bitsLT(MemVT)) {
1838 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1839 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1840 }
1841
1842 if (MemVT.isFloatingPoint())
1843 Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1844 else if (Signed)
1845 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1846 else
1847 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1848
1849 return Val;
1850}
1851
1852SDValue SITargetLowering::lowerKernargMemParameter(
1853 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1854 uint64_t Offset, Align Alignment, bool Signed,
1855 const ISD::InputArg *Arg) const {
1857
1858 // Try to avoid using an extload by loading earlier than the argument address,
1859 // and extracting the relevant bits. The load should hopefully be merged with
1860 // the previous argument.
1861 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1862 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1863 int64_t AlignDownOffset = alignDown(Offset, 4);
1864 int64_t OffsetDiff = Offset - AlignDownOffset;
1865
1866 EVT IntVT = MemVT.changeTypeToInteger();
1867
1868 // TODO: If we passed in the base kernel offset we could have a better
1869 // alignment than 4, but we don't really need it.
1870 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1871 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1874
1875 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1876 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1877
1878 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1879 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1880 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1881
1882
1883 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1884 }
1885
1886 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1887 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1890
1891 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1892 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1893}
1894
1895SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1896 const SDLoc &SL, SDValue Chain,
1897 const ISD::InputArg &Arg) const {
1899 MachineFrameInfo &MFI = MF.getFrameInfo();
1900
1901 if (Arg.Flags.isByVal()) {
1902 unsigned Size = Arg.Flags.getByValSize();
1903 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1904 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1905 }
1906
1907 unsigned ArgOffset = VA.getLocMemOffset();
1908 unsigned ArgSize = VA.getValVT().getStoreSize();
1909
1910 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1911
1912 // Create load nodes to retrieve arguments from the stack.
1913 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1914 SDValue ArgValue;
1915
1916 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1918 MVT MemVT = VA.getValVT();
1919
1920 switch (VA.getLocInfo()) {
1921 default:
1922 break;
1923 case CCValAssign::BCvt:
1924 MemVT = VA.getLocVT();
1925 break;
1926 case CCValAssign::SExt:
1927 ExtType = ISD::SEXTLOAD;
1928 break;
1929 case CCValAssign::ZExt:
1930 ExtType = ISD::ZEXTLOAD;
1931 break;
1932 case CCValAssign::AExt:
1933 ExtType = ISD::EXTLOAD;
1934 break;
1935 }
1936
1937 ArgValue = DAG.getExtLoad(
1938 ExtType, SL, VA.getLocVT(), Chain, FIN,
1940 MemVT);
1941 return ArgValue;
1942}
1943
1944SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1945 const SIMachineFunctionInfo &MFI,
1946 EVT VT,
1948 const ArgDescriptor *Reg;
1949 const TargetRegisterClass *RC;
1950 LLT Ty;
1951
1952 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1953 if (!Reg) {
1955 // It's possible for a kernarg intrinsic call to appear in a kernel with
1956 // no allocated segment, in which case we do not add the user sgpr
1957 // argument, so just return null.
1958 return DAG.getConstant(0, SDLoc(), VT);
1959 }
1960
1961 // It's undefined behavior if a function marked with the amdgpu-no-*
1962 // attributes uses the corresponding intrinsic.
1963 return DAG.getUNDEF(VT);
1964 }
1965
1966 return loadInputValue(DAG, RC, VT, SDLoc(DAG.getEntryNode()), *Reg);
1967}
1968
1970 CallingConv::ID CallConv,
1971 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1972 FunctionType *FType,
1973 SIMachineFunctionInfo *Info) {
1974 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1975 const ISD::InputArg *Arg = &Ins[I];
1976
1977 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1978 "vector type argument should have been split");
1979
1980 // First check if it's a PS input addr.
1981 if (CallConv == CallingConv::AMDGPU_PS &&
1982 !Arg->Flags.isInReg() && PSInputNum <= 15) {
1983 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1984
1985 // Inconveniently only the first part of the split is marked as isSplit,
1986 // so skip to the end. We only want to increment PSInputNum once for the
1987 // entire split argument.
1988 if (Arg->Flags.isSplit()) {
1989 while (!Arg->Flags.isSplitEnd()) {
1990 assert((!Arg->VT.isVector() ||
1991 Arg->VT.getScalarSizeInBits() == 16) &&
1992 "unexpected vector split in ps argument type");
1993 if (!SkipArg)
1994 Splits.push_back(*Arg);
1995 Arg = &Ins[++I];
1996 }
1997 }
1998
1999 if (SkipArg) {
2000 // We can safely skip PS inputs.
2001 Skipped.set(Arg->getOrigArgIndex());
2002 ++PSInputNum;
2003 continue;
2004 }
2005
2006 Info->markPSInputAllocated(PSInputNum);
2007 if (Arg->Used)
2008 Info->markPSInputEnabled(PSInputNum);
2009
2010 ++PSInputNum;
2011 }
2012
2013 Splits.push_back(*Arg);
2014 }
2015}
2016
2017// Allocate special inputs passed in VGPRs.
2019 MachineFunction &MF,
2020 const SIRegisterInfo &TRI,
2021 SIMachineFunctionInfo &Info) const {
2022 const LLT S32 = LLT::scalar(32);
2024
2025 if (Info.hasWorkItemIDX()) {
2026 Register Reg = AMDGPU::VGPR0;
2027 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2028
2029 CCInfo.AllocateReg(Reg);
2030 unsigned Mask = (Subtarget->hasPackedTID() &&
2031 Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
2032 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2033 }
2034
2035 if (Info.hasWorkItemIDY()) {
2036 assert(Info.hasWorkItemIDX());
2037 if (Subtarget->hasPackedTID()) {
2038 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2039 0x3ff << 10));
2040 } else {
2041 unsigned Reg = AMDGPU::VGPR1;
2042 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2043
2044 CCInfo.AllocateReg(Reg);
2045 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
2046 }
2047 }
2048
2049 if (Info.hasWorkItemIDZ()) {
2050 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
2051 if (Subtarget->hasPackedTID()) {
2052 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2053 0x3ff << 20));
2054 } else {
2055 unsigned Reg = AMDGPU::VGPR2;
2056 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2057
2058 CCInfo.AllocateReg(Reg);
2059 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
2060 }
2061 }
2062}
2063
2064// Try to allocate a VGPR at the end of the argument list, or if no argument
2065// VGPRs are left allocating a stack slot.
2066// If \p Mask is is given it indicates bitfield position in the register.
2067// If \p Arg is given use it with new ]p Mask instead of allocating new.
2068static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
2069 ArgDescriptor Arg = ArgDescriptor()) {
2070 if (Arg.isSet())
2071 return ArgDescriptor::createArg(Arg, Mask);
2072
2073 ArrayRef<MCPhysReg> ArgVGPRs = ArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
2074 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2075 if (RegIdx == ArgVGPRs.size()) {
2076 // Spill to stack required.
2077 int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2078
2079 return ArgDescriptor::createStack(Offset, Mask);
2080 }
2081
2082 unsigned Reg = ArgVGPRs[RegIdx];
2083 Reg = CCInfo.AllocateReg(Reg);
2084 assert(Reg != AMDGPU::NoRegister);
2085
2086 MachineFunction &MF = CCInfo.getMachineFunction();
2087 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2088 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2089 return ArgDescriptor::createRegister(Reg, Mask);
2090}
2091
2093 const TargetRegisterClass *RC,
2094 unsigned NumArgRegs) {
2095 ArrayRef<MCPhysReg> ArgSGPRs = ArrayRef(RC->begin(), 32);
2096 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2097 if (RegIdx == ArgSGPRs.size())
2098 report_fatal_error("ran out of SGPRs for arguments");
2099
2100 unsigned Reg = ArgSGPRs[RegIdx];
2101 Reg = CCInfo.AllocateReg(Reg);
2102 assert(Reg != AMDGPU::NoRegister);
2103
2104 MachineFunction &MF = CCInfo.getMachineFunction();
2105 MF.addLiveIn(Reg, RC);
2107}
2108
2109// If this has a fixed position, we still should allocate the register in the
2110// CCInfo state. Technically we could get away with this for values passed
2111// outside of the normal argument range.
2113 const TargetRegisterClass *RC,
2114 MCRegister Reg) {
2115 Reg = CCInfo.AllocateReg(Reg);
2116 assert(Reg != AMDGPU::NoRegister);
2117 MachineFunction &MF = CCInfo.getMachineFunction();
2118 MF.addLiveIn(Reg, RC);
2119}
2120
2121static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2122 if (Arg) {
2123 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2124 Arg.getRegister());
2125 } else
2126 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2127}
2128
2129static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2130 if (Arg) {
2131 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2132 Arg.getRegister());
2133 } else
2134 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2135}
2136
2137/// Allocate implicit function VGPR arguments at the end of allocated user
2138/// arguments.
2140 CCState &CCInfo, MachineFunction &MF,
2141 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2142 const unsigned Mask = 0x3ff;
2143 ArgDescriptor Arg;
2144
2145 if (Info.hasWorkItemIDX()) {
2146 Arg = allocateVGPR32Input(CCInfo, Mask);
2147 Info.setWorkItemIDX(Arg);
2148 }
2149
2150 if (Info.hasWorkItemIDY()) {
2151 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2152 Info.setWorkItemIDY(Arg);
2153 }
2154
2155 if (Info.hasWorkItemIDZ())
2156 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2157}
2158
2159/// Allocate implicit function VGPR arguments in fixed registers.
2161 CCState &CCInfo, MachineFunction &MF,
2162 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2163 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2164 if (!Reg)
2165 report_fatal_error("failed to allocated VGPR for implicit arguments");
2166
2167 const unsigned Mask = 0x3ff;
2168 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2169 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2170 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2171}
2172
2174 CCState &CCInfo,
2175 MachineFunction &MF,
2176 const SIRegisterInfo &TRI,
2177 SIMachineFunctionInfo &Info) const {
2178 auto &ArgInfo = Info.getArgInfo();
2179 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
2180
2181 // TODO: Unify handling with private memory pointers.
2182 if (UserSGPRInfo.hasDispatchPtr())
2183 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2184
2185 const Module *M = MF.getFunction().getParent();
2186 if (UserSGPRInfo.hasQueuePtr() &&
2188 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2189
2190 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2191 // constant offset from the kernarg segment.
2192 if (Info.hasImplicitArgPtr())
2193 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2194
2195 if (UserSGPRInfo.hasDispatchID())
2196 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2197
2198 // flat_scratch_init is not applicable for non-kernel functions.
2199
2200 if (Info.hasWorkGroupIDX())
2201 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2202
2203 if (Info.hasWorkGroupIDY())
2204 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2205
2206 if (Info.hasWorkGroupIDZ())
2207 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2208
2209 if (Info.hasLDSKernelId())
2210 allocateSGPR32Input(CCInfo, ArgInfo.LDSKernelId);
2211}
2212
2213// Allocate special inputs passed in user SGPRs.
2215 MachineFunction &MF,
2216 const SIRegisterInfo &TRI,
2217 SIMachineFunctionInfo &Info) const {
2218 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
2219 if (UserSGPRInfo.hasImplicitBufferPtr()) {
2220 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2221 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2222 CCInfo.AllocateReg(ImplicitBufferPtrReg);
2223 }
2224
2225 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2226 if (UserSGPRInfo.hasPrivateSegmentBuffer()) {
2227 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2228 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2229 CCInfo.AllocateReg(PrivateSegmentBufferReg);
2230 }
2231
2232 if (UserSGPRInfo.hasDispatchPtr()) {
2233 Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2234 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2235 CCInfo.AllocateReg(DispatchPtrReg);
2236 }
2237
2238 const Module *M = MF.getFunction().getParent();
2239 if (UserSGPRInfo.hasQueuePtr() &&
2241 Register QueuePtrReg = Info.addQueuePtr(TRI);
2242 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2243 CCInfo.AllocateReg(QueuePtrReg);
2244 }
2245
2246 if (UserSGPRInfo.hasKernargSegmentPtr()) {
2248 Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2249 CCInfo.AllocateReg(InputPtrReg);
2250
2251 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2252 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2253 }
2254
2255 if (UserSGPRInfo.hasDispatchID()) {
2256 Register DispatchIDReg = Info.addDispatchID(TRI);
2257 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2258 CCInfo.AllocateReg(DispatchIDReg);
2259 }
2260
2261 if (UserSGPRInfo.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2262 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2263 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2264 CCInfo.AllocateReg(FlatScratchInitReg);
2265 }
2266
2267 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2268 // these from the dispatch pointer.
2269}
2270
2271// Allocate pre-loaded kernel arguemtns. Arguments to be preloading must be
2272// sequential starting from the first argument.
2274 CCState &CCInfo, SmallVectorImpl<CCValAssign> &ArgLocs,
2276 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2277 Function &F = MF.getFunction();
2278 unsigned LastExplicitArgOffset =
2279 MF.getSubtarget<GCNSubtarget>().getExplicitKernelArgOffset();
2280 GCNUserSGPRUsageInfo &SGPRInfo = Info.getUserSGPRInfo();
2281 bool InPreloadSequence = true;
2282 unsigned InIdx = 0;
2283 for (auto &Arg : F.args()) {
2284 if (!InPreloadSequence || !Arg.hasInRegAttr())
2285 break;
2286
2287 int ArgIdx = Arg.getArgNo();
2288 // Don't preload non-original args or parts not in the current preload
2289 // sequence.
2290 if (InIdx < Ins.size() && (!Ins[InIdx].isOrigArg() ||
2291 (int)Ins[InIdx].getOrigArgIndex() != ArgIdx))
2292 break;
2293
2294 for (; InIdx < Ins.size() && Ins[InIdx].isOrigArg() &&
2295 (int)Ins[InIdx].getOrigArgIndex() == ArgIdx;
2296 InIdx++) {
2297 assert(ArgLocs[ArgIdx].isMemLoc());
2298 auto &ArgLoc = ArgLocs[InIdx];
2299 const Align KernelArgBaseAlign = Align(16);
2300 unsigned ArgOffset = ArgLoc.getLocMemOffset();
2301 Align Alignment = commonAlignment(KernelArgBaseAlign, ArgOffset);
2302 unsigned NumAllocSGPRs =
2303 alignTo(ArgLoc.getLocVT().getFixedSizeInBits(), 32) / 32;
2304
2305 // Arg is preloaded into the previous SGPR.
2306 if (ArgLoc.getLocVT().getStoreSize() < 4 && Alignment < 4) {
2307 Info.getArgInfo().PreloadKernArgs[InIdx].Regs.push_back(
2308 Info.getArgInfo().PreloadKernArgs[InIdx - 1].Regs[0]);
2309 continue;
2310 }
2311
2312 unsigned Padding = ArgOffset - LastExplicitArgOffset;
2313 unsigned PaddingSGPRs = alignTo(Padding, 4) / 4;
2314 // Check for free user SGPRs for preloading.
2315 if (PaddingSGPRs + NumAllocSGPRs + 1 /*Synthetic SGPRs*/ >
2316 SGPRInfo.getNumFreeUserSGPRs()) {
2317 InPreloadSequence = false;
2318 break;
2319 }
2320
2321 // Preload this argument.
2322 const TargetRegisterClass *RC =
2323 TRI.getSGPRClassForBitWidth(NumAllocSGPRs * 32);
2324 SmallVectorImpl<MCRegister> *PreloadRegs =
2325 Info.addPreloadedKernArg(TRI, RC, NumAllocSGPRs, InIdx, PaddingSGPRs);
2326
2327 if (PreloadRegs->size() > 1)
2328 RC = &AMDGPU::SGPR_32RegClass;
2329 for (auto &Reg : *PreloadRegs) {
2330 assert(Reg);
2331 MF.addLiveIn(Reg, RC);
2332 CCInfo.AllocateReg(Reg);
2333 }
2334
2335 LastExplicitArgOffset = NumAllocSGPRs * 4 + ArgOffset;
2336 }
2337 }
2338}
2339
2341 const SIRegisterInfo &TRI,
2342 SIMachineFunctionInfo &Info) const {
2343 // Always allocate this last since it is a synthetic preload.
2344 if (Info.hasLDSKernelId()) {
2345 Register Reg = Info.addLDSKernelId();
2346 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2347 CCInfo.AllocateReg(Reg);
2348 }
2349}
2350
2351// Allocate special input registers that are initialized per-wave.
2353 MachineFunction &MF,
2355 CallingConv::ID CallConv,
2356 bool IsShader) const {
2357 bool HasArchitectedSGPRs = Subtarget->hasArchitectedSGPRs();
2358 if (Subtarget->hasUserSGPRInit16Bug() && !IsShader) {
2359 // Note: user SGPRs are handled by the front-end for graphics shaders
2360 // Pad up the used user SGPRs with dead inputs.
2361
2362 // TODO: NumRequiredSystemSGPRs computation should be adjusted appropriately
2363 // before enabling architected SGPRs for workgroup IDs.
2364 assert(!HasArchitectedSGPRs && "Unhandled feature for the subtarget");
2365
2366 unsigned CurrentUserSGPRs = Info.getNumUserSGPRs();
2367 // Note we do not count the PrivateSegmentWaveByteOffset. We do not want to
2368 // rely on it to reach 16 since if we end up having no stack usage, it will
2369 // not really be added.
2370 unsigned NumRequiredSystemSGPRs = Info.hasWorkGroupIDX() +
2371 Info.hasWorkGroupIDY() +
2372 Info.hasWorkGroupIDZ() +
2373 Info.hasWorkGroupInfo();
2374 for (unsigned i = NumRequiredSystemSGPRs + CurrentUserSGPRs; i < 16; ++i) {
2375 Register Reg = Info.addReservedUserSGPR();
2376 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2377 CCInfo.AllocateReg(Reg);
2378 }
2379 }
2380
2381 if (Info.hasWorkGroupIDX()) {
2382 Register Reg = Info.addWorkGroupIDX(HasArchitectedSGPRs);
2383 if (!HasArchitectedSGPRs)
2384 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2385
2386 CCInfo.AllocateReg(Reg);
2387 }
2388
2389 if (Info.hasWorkGroupIDY()) {
2390 Register Reg = Info.addWorkGroupIDY(HasArchitectedSGPRs);
2391 if (!HasArchitectedSGPRs)
2392 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2393
2394 CCInfo.AllocateReg(Reg);
2395 }
2396
2397 if (Info.hasWorkGroupIDZ()) {
2398 Register Reg = Info.addWorkGroupIDZ(HasArchitectedSGPRs);
2399 if (!HasArchitectedSGPRs)
2400 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2401
2402 CCInfo.AllocateReg(Reg);
2403 }
2404
2405 if (Info.hasWorkGroupInfo()) {
2406 Register Reg = Info.addWorkGroupInfo();
2407 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2408 CCInfo.AllocateReg(Reg);
2409 }
2410
2411 if (Info.hasPrivateSegmentWaveByteOffset()) {
2412 // Scratch wave offset passed in system SGPR.
2413 unsigned PrivateSegmentWaveByteOffsetReg;
2414
2415 if (IsShader) {
2416 PrivateSegmentWaveByteOffsetReg =
2417 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2418
2419 // This is true if the scratch wave byte offset doesn't have a fixed
2420 // location.
2421 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2422 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2423 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2424 }
2425 } else
2426 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2427
2428 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2429 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2430 }
2431
2432 assert(!Subtarget->hasUserSGPRInit16Bug() || IsShader ||
2433 Info.getNumPreloadedSGPRs() >= 16);
2434}
2435
2437 MachineFunction &MF,
2438 const SIRegisterInfo &TRI,
2439 SIMachineFunctionInfo &Info) {
2440 // Now that we've figured out where the scratch register inputs are, see if
2441 // should reserve the arguments and use them directly.
2442 MachineFrameInfo &MFI = MF.getFrameInfo();
2443 bool HasStackObjects = MFI.hasStackObjects();
2444 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2445
2446 // Record that we know we have non-spill stack objects so we don't need to
2447 // check all stack objects later.
2448 if (HasStackObjects)
2449 Info.setHasNonSpillStackObjects(true);
2450
2451 // Everything live out of a block is spilled with fast regalloc, so it's
2452 // almost certain that spilling will be required.
2453 if (TM.getOptLevel() == CodeGenOptLevel::None)
2454 HasStackObjects = true;
2455
2456 // For now assume stack access is needed in any callee functions, so we need
2457 // the scratch registers to pass in.
2458 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2459
2460 if (!ST.enableFlatScratch()) {
2461 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2462 // If we have stack objects, we unquestionably need the private buffer
2463 // resource. For the Code Object V2 ABI, this will be the first 4 user
2464 // SGPR inputs. We can reserve those and use them directly.
2465
2466 Register PrivateSegmentBufferReg =
2468 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2469 } else {
2470 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2471 // We tentatively reserve the last registers (skipping the last registers
2472 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2473 // we'll replace these with the ones immediately after those which were
2474 // really allocated. In the prologue copies will be inserted from the
2475 // argument to these reserved registers.
2476
2477 // Without HSA, relocations are used for the scratch pointer and the
2478 // buffer resource setup is always inserted in the prologue. Scratch wave
2479 // offset is still in an input SGPR.
2480 Info.setScratchRSrcReg(ReservedBufferReg);
2481 }
2482 }
2483
2485
2486 // For entry functions we have to set up the stack pointer if we use it,
2487 // whereas non-entry functions get this "for free". This means there is no
2488 // intrinsic advantage to using S32 over S34 in cases where we do not have
2489 // calls but do need a frame pointer (i.e. if we are requested to have one
2490 // because frame pointer elimination is disabled). To keep things simple we
2491 // only ever use S32 as the call ABI stack pointer, and so using it does not
2492 // imply we need a separate frame pointer.
2493 //
2494 // Try to use s32 as the SP, but move it if it would interfere with input
2495 // arguments. This won't work with calls though.
2496 //
2497 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2498 // registers.
2499 if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2500 Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2501 } else {
2503
2504 if (MFI.hasCalls())
2505 report_fatal_error("call in graphics shader with too many input SGPRs");
2506
2507 for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2508 if (!MRI.isLiveIn(Reg)) {
2509 Info.setStackPtrOffsetReg(Reg);
2510 break;
2511 }
2512 }
2513
2514 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2515 report_fatal_error("failed to find register for SP");
2516 }
2517
2518 // hasFP should be accurate for entry functions even before the frame is
2519 // finalized, because it does not rely on the known stack size, only
2520 // properties like whether variable sized objects are present.
2521 if (ST.getFrameLowering()->hasFP(MF)) {
2522 Info.setFrameOffsetReg(AMDGPU::SGPR33);
2523 }
2524}
2525
2528 return !Info->isEntryFunction();
2529}
2530
2532
2533}
2534
2536 MachineBasicBlock *Entry,
2537 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2539
2540 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2541 if (!IStart)
2542 return;
2543
2544 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2545 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2546 MachineBasicBlock::iterator MBBI = Entry->begin();
2547 for (const MCPhysReg *I = IStart; *I; ++I) {
2548 const TargetRegisterClass *RC = nullptr;
2549 if (AMDGPU::SReg_64RegClass.contains(*I))
2550 RC = &AMDGPU::SGPR_64RegClass;
2551 else if (AMDGPU::SReg_32RegClass.contains(*I))
2552 RC = &AMDGPU::SGPR_32RegClass;
2553 else
2554 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2555
2556 Register NewVR = MRI->createVirtualRegister(RC);
2557 // Create copy from CSR to a virtual register.
2558 Entry->addLiveIn(*I);
2559 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2560 .addReg(*I);
2561
2562 // Insert the copy-back instructions right before the terminator.
2563 for (auto *Exit : Exits)
2564 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2565 TII->get(TargetOpcode::COPY), *I)
2566 .addReg(NewVR);
2567 }
2568}
2569
2571 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2572 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2573 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2575
2577 const Function &Fn = MF.getFunction();
2580
2581 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2582 DiagnosticInfoUnsupported NoGraphicsHSA(
2583 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2584 DAG.getContext()->diagnose(NoGraphicsHSA);
2585 return DAG.getEntryNode();
2586 }
2587
2590 BitVector Skipped(Ins.size());
2591 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2592 *DAG.getContext());
2593
2594 bool IsGraphics = AMDGPU::isGraphics(CallConv);
2595 bool IsKernel = AMDGPU::isKernel(CallConv);
2596 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2597
2598 if (IsGraphics) {
2599 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info->getUserSGPRInfo();
2600 assert(!UserSGPRInfo.hasDispatchPtr() &&
2601 !UserSGPRInfo.hasKernargSegmentPtr() && !Info->hasWorkGroupInfo() &&
2602 !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() &&
2603 !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ());
2604 (void)UserSGPRInfo;
2605 if (!Subtarget->enableFlatScratch())
2606 assert(!UserSGPRInfo.hasFlatScratchInit());
2607 if (CallConv != CallingConv::AMDGPU_CS || !Subtarget->hasArchitectedSGPRs())
2608 assert(!Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2609 !Info->hasWorkGroupIDZ());
2610 }
2611
2612 if (CallConv == CallingConv::AMDGPU_PS) {
2613 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2614
2615 // At least one interpolation mode must be enabled or else the GPU will
2616 // hang.
2617 //
2618 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2619 // set PSInputAddr, the user wants to enable some bits after the compilation
2620 // based on run-time states. Since we can't know what the final PSInputEna
2621 // will look like, so we shouldn't do anything here and the user should take
2622 // responsibility for the correct programming.
2623 //
2624 // Otherwise, the following restrictions apply:
2625 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2626 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2627 // enabled too.
2628 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2629 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2630 CCInfo.AllocateReg(AMDGPU::VGPR0);
2631 CCInfo.AllocateReg(AMDGPU::VGPR1);
2632 Info->markPSInputAllocated(0);
2633 Info->markPSInputEnabled(0);
2634 }
2635 if (Subtarget->isAmdPalOS()) {
2636 // For isAmdPalOS, the user does not enable some bits after compilation
2637 // based on run-time states; the register values being generated here are
2638 // the final ones set in hardware. Therefore we need to apply the
2639 // workaround to PSInputAddr and PSInputEnable together. (The case where
2640 // a bit is set in PSInputAddr but not PSInputEnable is where the
2641 // frontend set up an input arg for a particular interpolation mode, but
2642 // nothing uses that input arg. Really we should have an earlier pass
2643 // that removes such an arg.)
2644 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2645 if ((PsInputBits & 0x7F) == 0 ||
2646 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2647 Info->markPSInputEnabled(llvm::countr_zero(Info->getPSInputAddr()));
2648 }
2649 } else if (IsKernel) {
2650 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2651 } else {
2652 Splits.append(Ins.begin(), Ins.end());
2653 }
2654
2655 if (IsKernel)
2656 analyzeFormalArgumentsCompute(CCInfo, Ins);
2657
2658 if (IsEntryFunc) {
2659 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2660 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2661 if (IsKernel && Subtarget->hasKernargPreload() &&
2663 allocatePreloadKernArgSGPRs(CCInfo, ArgLocs, Ins, MF, *TRI, *Info);
2664
2665 allocateLDSKernelId(CCInfo, MF, *TRI, *Info);
2666 } else if (!IsGraphics) {
2667 // For the fixed ABI, pass workitem IDs in the last argument register.
2668 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2669 }
2670
2671 if (!IsKernel) {
2672 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2673 if (!IsGraphics && !Subtarget->enableFlatScratch()) {
2674 CCInfo.AllocateRegBlock(ArrayRef<MCPhysReg>{AMDGPU::SGPR0, AMDGPU::SGPR1,
2675 AMDGPU::SGPR2, AMDGPU::SGPR3},
2676 4);
2677 }
2678 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2679 }
2680
2682
2683 // FIXME: This is the minimum kernel argument alignment. We should improve
2684 // this to the maximum alignment of the arguments.
2685 //
2686 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2687 // kern arg offset.
2688 const Align KernelArgBaseAlign = Align(16);
2689
2690 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2691 const ISD::InputArg &Arg = Ins[i];
2692 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2693 InVals.push_back(DAG.getUNDEF(Arg.VT));
2694 continue;
2695 }
2696
2697 CCValAssign &VA = ArgLocs[ArgIdx++];
2698 MVT VT = VA.getLocVT();
2699
2700 if (IsEntryFunc && VA.isMemLoc()) {
2701 VT = Ins[i].VT;
2702 EVT MemVT = VA.getLocVT();
2703
2704 const uint64_t Offset = VA.getLocMemOffset();
2705 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2706
2707 if (Arg.Flags.isByRef()) {
2708 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2709
2710 const GCNTargetMachine &TM =
2711 static_cast<const GCNTargetMachine &>(getTargetMachine());
2712 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2713 Arg.Flags.getPointerAddrSpace())) {
2716 }
2717
2718 InVals.push_back(Ptr);
2719 continue;
2720 }
2721
2722 SDValue NewArg;
2723 if (Arg.isOrigArg() && Info->getArgInfo().PreloadKernArgs.count(i)) {
2724 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
2725 // In this case the argument is packed into the previous preload SGPR.
2726 int64_t AlignDownOffset = alignDown(Offset, 4);
2727 int64_t OffsetDiff = Offset - AlignDownOffset;
2728 EVT IntVT = MemVT.changeTypeToInteger();
2729
2733 Register Reg =
2734 Info->getArgInfo().PreloadKernArgs.find(i)->getSecond().Regs[0];
2735
2736 assert(Reg);
2737 Register VReg = MRI.getLiveInVirtReg(Reg);
2738 SDValue Copy = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i32);
2739
2740 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, DL, MVT::i32);
2741 SDValue Extract = DAG.getNode(ISD::SRL, DL, MVT::i32, Copy, ShiftAmt);
2742
2743 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, Extract);
2744 ArgVal = DAG.getNode(ISD::BITCAST, DL, MemVT, ArgVal);
2745 NewArg = convertArgType(DAG, VT, MemVT, DL, ArgVal,
2746 Ins[i].Flags.isSExt(), &Ins[i]);
2747
2748 NewArg = DAG.getMergeValues({NewArg, Copy.getValue(1)}, DL);
2749 } else {
2753 const SmallVectorImpl<MCRegister> &PreloadRegs =
2754 Info->getArgInfo().PreloadKernArgs.find(i)->getSecond().Regs;
2755
2756 SDValue Copy;
2757 if (PreloadRegs.size() == 1) {
2758 Register VReg = MRI.getLiveInVirtReg(PreloadRegs[0]);
2759 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
2760 NewArg = DAG.getCopyFromReg(
2761 Chain, DL, VReg,
2763 TRI->getRegSizeInBits(*RC)));
2764
2765 } else {
2766 // If the kernarg alignment does not match the alignment of the SGPR
2767 // tuple RC that can accommodate this argument, it will be built up
2768 // via copies from from the individual SGPRs that the argument was
2769 // preloaded to.
2771 for (auto Reg : PreloadRegs) {
2772 Register VReg = MRI.getLiveInVirtReg(Reg);
2773 Copy = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i32);
2774 Elts.push_back(Copy);
2775 }
2776 NewArg =
2777 DAG.getBuildVector(EVT::getVectorVT(*DAG.getContext(), MVT::i32,
2778 PreloadRegs.size()),
2779 DL, Elts);
2780 }
2781
2782 SDValue CMemVT;
2783 if (VT.isScalarInteger() && VT.bitsLT(NewArg.getSimpleValueType()))
2784 CMemVT = DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewArg);
2785 else
2786 CMemVT = DAG.getBitcast(MemVT, NewArg);
2787 NewArg = convertArgType(DAG, VT, MemVT, DL, CMemVT,
2788 Ins[i].Flags.isSExt(), &Ins[i]);
2789 NewArg = DAG.getMergeValues({NewArg, Chain}, DL);
2790 }
2791 } else {
2792 NewArg =
2793 lowerKernargMemParameter(DAG, VT, MemVT, DL, Chain, Offset,
2794 Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2795 }
2796 Chains.push_back(NewArg.getValue(1));
2797
2798 auto *ParamTy =
2799 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2801 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2802 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2803 // On SI local pointers are just offsets into LDS, so they are always
2804 // less than 16-bits. On CI and newer they could potentially be
2805 // real pointers, so we can't guarantee their size.
2806 NewArg = DAG.getNode(ISD::AssertZext, DL, NewArg.getValueType(), NewArg,
2807 DAG.getValueType(MVT::i16));
2808 }
2809
2810 InVals.push_back(NewArg);
2811 continue;
2812 } else if (!IsEntryFunc && VA.isMemLoc()) {
2813 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2814 InVals.push_back(Val);
2815 if (!Arg.Flags.isByVal())
2816 Chains.push_back(Val.getValue(1));
2817 continue;
2818 }
2819
2820 assert(VA.isRegLoc() && "Parameter must be in a register!");
2821
2822 Register Reg = VA.getLocReg();
2823 const TargetRegisterClass *RC = nullptr;
2824 if (AMDGPU::VGPR_32RegClass.contains(Reg))
2825 RC = &AMDGPU::VGPR_32RegClass;
2826 else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2827 RC = &AMDGPU::SGPR_32RegClass;
2828 else
2829 llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2830 EVT ValVT = VA.getValVT();
2831
2832 Reg = MF.addLiveIn(Reg, RC);
2833 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2834
2835 if (Arg.Flags.isSRet()) {
2836 // The return object should be reasonably addressable.
2837
2838 // FIXME: This helps when the return is a real sret. If it is a
2839 // automatically inserted sret (i.e. CanLowerReturn returns false), an
2840 // extra copy is inserted in SelectionDAGBuilder which obscures this.
2841 unsigned NumBits
2843 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2844 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2845 }
2846
2847 // If this is an 8 or 16-bit value, it is really passed promoted
2848 // to 32 bits. Insert an assert[sz]ext to capture this, then
2849 // truncate to the right size.
2850 switch (VA.getLocInfo()) {
2851 case CCValAssign::Full:
2852 break;
2853 case CCValAssign::BCvt:
2854 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2855 break;
2856 case CCValAssign::SExt:
2857 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2858 DAG.getValueType(ValVT));
2859 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2860 break;
2861 case CCValAssign::ZExt:
2862 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2863 DAG.getValueType(ValVT));
2864 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2865 break;
2866 case CCValAssign::AExt:
2867 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2868 break;
2869 default:
2870 llvm_unreachable("Unknown loc info!");
2871 }
2872
2873 InVals.push_back(Val);
2874 }
2875
2876 // Start adding system SGPRs.
2877 if (IsEntryFunc) {
2878 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2879 } else {
2880 CCInfo.AllocateReg(Info->getScratchRSrcReg());
2881 if (!IsGraphics)
2882 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2883 }
2884
2885 auto &ArgUsageInfo =
2887 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2888
2889 unsigned StackArgSize = CCInfo.getStackSize();
2890 Info->setBytesInStackArgArea(StackArgSize);
2891
2892 return Chains.empty() ? Chain :
2893 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2894}
2895
2896// TODO: If return values can't fit in registers, we should return as many as
2897// possible in registers before passing on stack.
2899 CallingConv::ID CallConv,
2900 MachineFunction &MF, bool IsVarArg,
2902 LLVMContext &Context) const {
2903 // Replacing returns with sret/stack usage doesn't make sense for shaders.
2904 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2905 // for shaders. Vector types should be explicitly handled by CC.
2906 if (AMDGPU::isEntryFunctionCC(CallConv))
2907 return true;
2908
2910 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2911 if (!CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)))
2912 return false;
2913
2914 // We must use the stack if return would require unavailable registers.
2915 unsigned MaxNumVGPRs = Subtarget->getMaxNumVGPRs(MF);
2916 unsigned TotalNumVGPRs = AMDGPU::VGPR_32RegClass.getNumRegs();
2917 for (unsigned i = MaxNumVGPRs; i < TotalNumVGPRs; ++i)
2918 if (CCInfo.isAllocated(AMDGPU::VGPR_32RegClass.getRegister(i)))
2919 return false;
2920
2921 return true;
2922}
2923
2924SDValue
2926 bool isVarArg,
2928 const SmallVectorImpl<SDValue> &OutVals,
2929 const SDLoc &DL, SelectionDAG &DAG) const {
2932
2933 if (AMDGPU::isKernel(CallConv)) {
2934 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2935 OutVals, DL, DAG);
2936 }
2937
2938 bool IsShader = AMDGPU::isShader(CallConv);
2939
2940 Info->setIfReturnsVoid(Outs.empty());
2941 bool IsWaveEnd = Info->returnsVoid() && IsShader;
2942
2943 // CCValAssign - represent the assignment of the return value to a location.
2946
2947 // CCState - Info about the registers and stack slots.
2948 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2949 *DAG.getContext());
2950
2951 // Analyze outgoing return values.
2952 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2953
2954 SDValue Glue;
2956 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2957
2958 // Copy the result values into the output registers.
2959 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2960 ++I, ++RealRVLocIdx) {
2961 CCValAssign &VA = RVLocs[I];
2962 assert(VA.isRegLoc() && "Can only return in registers!");
2963 // TODO: Partially return in registers if return values don't fit.
2964 SDValue Arg = OutVals[RealRVLocIdx];
2965
2966 // Copied from other backends.
2967 switch (VA.getLocInfo()) {
2968 case CCValAssign::Full:
2969 break;
2970 case CCValAssign::BCvt:
2971 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2972 break;
2973 case CCValAssign::SExt:
2974 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2975 break;
2976 case CCValAssign::ZExt:
2977 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2978 break;
2979 case CCValAssign::AExt:
2980 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2981 break;
2982 default:
2983 llvm_unreachable("Unknown loc info!");
2984 }
2985
2986 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Glue);
2987 Glue = Chain.getValue(1);
2988 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2989 }
2990
2991 // FIXME: Does sret work properly?
2992 if (!Info->isEntryFunction()) {
2993 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2994 const MCPhysReg *I =
2995 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2996 if (I) {
2997 for (; *I; ++I) {
2998 if (AMDGPU::SReg_64RegClass.contains(*I))
2999 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3000 else if (AMDGPU::SReg_32RegClass.contains(*I))
3001 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3002 else
3003 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3004 }
3005 }
3006 }
3007
3008 // Update chain and glue.
3009 RetOps[0] = Chain;
3010 if (Glue.getNode())
3011 RetOps.push_back(Glue);
3012
3013 unsigned Opc = AMDGPUISD::ENDPGM;
3014 if (!IsWaveEnd)
3016 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
3017}
3018
3020 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
3021 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3022 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
3023 SDValue ThisVal) const {
3024 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
3025
3026 // Assign locations to each value returned by this call.
3028 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3029 *DAG.getContext());
3030 CCInfo.AnalyzeCallResult(Ins, RetCC);
3031
3032 // Copy all of the result registers out of their specified physreg.
3033 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3034 CCValAssign VA = RVLocs[i];
3035 SDValue Val;
3036
3037 if (VA.isRegLoc()) {
3038 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InGlue);
3039 Chain = Val.getValue(1);
3040 InGlue = Val.getValue(2);
3041 } else if (VA.isMemLoc()) {
3042 report_fatal_error("TODO: return values in memory");
3043 } else
3044 llvm_unreachable("unknown argument location type");
3045
3046 switch (VA.getLocInfo()) {
3047 case CCValAssign::Full:
3048 break;
3049 case CCValAssign::BCvt:
3050 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3051 break;
3052 case CCValAssign::ZExt:
3053 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3054 DAG.getValueType(VA.getValVT()));
3055 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3056 break;
3057 case CCValAssign::SExt:
3058 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3059 DAG.getValueType(VA.getValVT()));
3060 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3061 break;
3062 case CCValAssign::AExt:
3063 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3064 break;
3065 default:
3066 llvm_unreachable("Unknown loc info!");
3067 }
3068
3069 InVals.push_back(Val);
3070 }
3071
3072 return Chain;
3073}
3074
3075// Add code to pass special inputs required depending on used features separate
3076// from the explicit user arguments present in the IR.
3078 CallLoweringInfo &CLI,
3079 CCState &CCInfo,
3080 const SIMachineFunctionInfo &Info,
3081 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
3082 SmallVectorImpl<SDValue> &MemOpChains,
3083 SDValue Chain) const {
3084 // If we don't have a call site, this was a call inserted by
3085 // legalization. These can never use special inputs.
3086 if (!CLI.CB)
3087 return;
3088
3089 SelectionDAG &DAG = CLI.DAG;
3090 const SDLoc &DL = CLI.DL;
3091 const Function &F = DAG.getMachineFunction().getFunction();
3092
3093 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
3094 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
3095
3096 const AMDGPUFunctionArgInfo *CalleeArgInfo
3098 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
3099 auto &ArgUsageInfo =
3101 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
3102 }
3103
3104 // TODO: Unify with private memory register handling. This is complicated by
3105 // the fact that at least in kernels, the input argument is not necessarily
3106 // in the same location as the input.
3107 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
3109 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
3110 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
3111 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
3112 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
3113 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
3114 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
3115 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"},
3116 {AMDGPUFunctionArgInfo::LDS_KERNEL_ID,"amdgpu-no-lds-kernel-id"},
3117 };
3118
3119 for (auto Attr : ImplicitAttrs) {
3120 const ArgDescriptor *OutgoingArg;
3121 const TargetRegisterClass *ArgRC;
3122 LLT ArgTy;
3123
3124 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
3125
3126 // If the callee does not use the attribute value, skip copying the value.
3127 if (CLI.CB->hasFnAttr(Attr.second))
3128 continue;
3129
3130 std::tie(OutgoingArg, ArgRC, ArgTy) =
3131 CalleeArgInfo->getPreloadedValue(InputID);
3132 if (!OutgoingArg)
3133 continue;
3134
3135 const ArgDescriptor *IncomingArg;
3136 const TargetRegisterClass *IncomingArgRC;
3137 LLT Ty;
3138 std::tie(IncomingArg, IncomingArgRC, Ty) =
3139 CallerArgInfo.getPreloadedValue(InputID);
3140 assert(IncomingArgRC == ArgRC);
3141
3142 // All special arguments are ints for now.
3143 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
3144 SDValue InputReg;
3145
3146 if (IncomingArg) {
3147 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
3148 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
3149 // The implicit arg ptr is special because it doesn't have a corresponding
3150 // input for kernels, and is computed from the kernarg segment pointer.
3151 InputReg = getImplicitArgPtr(DAG, DL);
3152 } else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {
3153 std::optional<uint32_t> Id =
3155 if (Id.has_value()) {
3156 InputReg = DAG.getConstant(*Id, DL, ArgVT);
3157 } else {
3158 InputReg = DAG.getUNDEF(ArgVT);
3159 }
3160 } else {
3161 // We may have proven the input wasn't needed, although the ABI is
3162 // requiring it. We just need to allocate the register appropriately.
3163 InputReg = DAG.getUNDEF(ArgVT);
3164 }
3165
3166 if (OutgoingArg->isRegister()) {
3167 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
3168 if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
3169 report_fatal_error("failed to allocate implicit input argument");
3170 } else {
3171 unsigned SpecialArgOffset =
3172 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
3173 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
3174 SpecialArgOffset);
3175 MemOpChains.push_back(ArgStore);
3176 }
3177 }
3178
3179 // Pack workitem IDs into a single register or pass it as is if already
3180 // packed.
3181 const ArgDescriptor *OutgoingArg;
3182 const TargetRegisterClass *ArgRC;
3183 LLT Ty;
3184
3185 std::tie(OutgoingArg, ArgRC, Ty) =
3187 if (!OutgoingArg)
3188 std::tie(OutgoingArg, ArgRC, Ty) =
3190 if (!OutgoingArg)
3191 std::tie(OutgoingArg, ArgRC, Ty) =
3193 if (!OutgoingArg)
3194 return;
3195
3196 const ArgDescriptor *IncomingArgX = std::get<0>(
3198 const ArgDescriptor *IncomingArgY = std::get<0>(
3200 const ArgDescriptor *IncomingArgZ = std::get<0>(
3202
3203 SDValue InputReg;
3204 SDLoc SL;
3205
3206 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
3207 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
3208 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
3209
3210 // If incoming ids are not packed we need to pack them.
3211 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
3212 NeedWorkItemIDX) {
3213 if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
3214 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
3215 } else {
3216 InputReg = DAG.getConstant(0, DL, MVT::i32);
3217 }
3218 }
3219
3220 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
3221 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
3222 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
3223 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
3224 DAG.getShiftAmountConstant(10, MVT::i32, SL));
3225 InputReg = InputReg.getNode() ?
3226 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
3227 }
3228
3229 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
3230 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
3231 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
3232 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
3233 DAG.getShiftAmountConstant(20, MVT::i32, SL));
3234 InputReg = InputReg.getNode() ?
3235 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
3236 }
3237
3238 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
3239 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
3240 // We're in a situation where the outgoing function requires the workitem
3241 // ID, but the calling function does not have it (e.g a graphics function
3242 // calling a C calling convention function). This is illegal, but we need
3243 // to produce something.
3244 InputReg = DAG.getUNDEF(MVT::i32);
3245 } else {
3246 // Workitem ids are already packed, any of present incoming arguments
3247 // will carry all required fields.
3249 IncomingArgX ? *IncomingArgX :
3250 IncomingArgY ? *IncomingArgY :
3251 *IncomingArgZ, ~0u);
3252 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
3253 }
3254 }
3255
3256 if (OutgoingArg->isRegister()) {
3257 if (InputReg)
3258 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
3259
3260 CCInfo.AllocateReg(OutgoingArg->getRegister());
3261 } else {
3262 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
3263 if (InputReg) {
3264 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
3265 SpecialArgOffset);
3266 MemOpChains.push_back(ArgStore);
3267 }
3268 }
3269}
3270
3272 return CC == CallingConv::Fast;
3273}
3274
3275/// Return true if we might ever do TCO for calls with this calling convention.
3277 switch (CC) {
3278 case CallingConv::C:
3280 return true;
3281 default:
3282 return canGuaranteeTCO(CC);
3283 }
3284}
3285
3287 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3289 const SmallVectorImpl<SDValue> &OutVals,
3290 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3291 if (AMDGPU::isChainCC(CalleeCC))
3292 return true;
3293
3294 if (!mayTailCallThisCC(CalleeCC))
3295 return false;
3296
3297 // For a divergent call target, we need to do a waterfall loop over the
3298 // possible callees which precludes us from using a simple jump.
3299 if (Callee->isDivergent())
3300 return false;
3301
3303 const Function &CallerF = MF.getFunction();
3304 CallingConv::ID CallerCC = CallerF.getCallingConv();
3306 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3307
3308 // Kernels aren't callable, and don't have a live in return address so it
3309 // doesn't make sense to do a tail call with entry functions.
3310 if (!CallerPreserved)
3311 return false;
3312
3313 bool CCMatch = CallerCC == CalleeCC;
3314
3316 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3317 return true;
3318 return false;
3319 }
3320
3321 // TODO: Can we handle var args?
3322 if (IsVarArg)
3323 return false;
3324
3325 for (const Argument &Arg : CallerF.args()) {
3326 if (Arg.hasByValAttr())
3327 return false;
3328 }
3329
3330 LLVMContext &Ctx = *DAG.getContext();
3331
3332 // Check that the call results are passed in the same way.
3333 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3334 CCAssignFnForCall(CalleeCC, IsVarArg),
3335 CCAssignFnForCall(CallerCC, IsVarArg)))
3336 return false;
3337
3338 // The callee has to preserve all registers the caller needs to preserve.
3339 if (!CCMatch) {
3340 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3341 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3342 return false;
3343 }
3344
3345 // Nothing more to check if the callee is taking no arguments.
3346 if (Outs.empty())
3347 return true;
3348
3350 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3351
3352 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3353
3354 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3355 // If the stack arguments for this call do not fit into our own save area then
3356 // the call cannot be made tail.
3357 // TODO: Is this really necessary?
3358 if (CCInfo.getStackSize() > FuncInfo->getBytesInStackArgArea())
3359 return false;
3360
3361 const MachineRegisterInfo &MRI = MF.getRegInfo();
3362 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3363}
3364
3366 if (!CI->isTailCall())
3367 return false;
3368
3369 const Function *ParentFn = CI->getParent()->getParent();
3371 return false;
3372 return true;
3373}
3374
3375// The wave scratch offset register is used as the global base pointer.
3377 SmallVectorImpl<SDValue> &InVals) const {
3378 CallingConv::ID CallConv = CLI.CallConv;
3379 bool IsChainCallConv = AMDGPU::isChainCC(CallConv);
3380
3381 SelectionDAG &DAG = CLI.DAG;
3382
3383 TargetLowering::ArgListEntry RequestedExec;
3384 if (IsChainCallConv) {
3385 // The last argument should be the value that we need to put in EXEC.
3386 // Pop it out of CLI.Outs and CLI.OutVals before we do any processing so we
3387 // don't treat it like the rest of the arguments.
3388 RequestedExec = CLI.Args.back();
3389 assert(RequestedExec.Node && "No node for EXEC");
3390
3391 if (!RequestedExec.Ty->isIntegerTy(Subtarget->getWavefrontSize()))
3392 return lowerUnhandledCall(CLI, InVals, "Invalid value for EXEC");
3393
3394 assert(CLI.Outs.back().OrigArgIndex == 2 && "Unexpected last arg");
3395 CLI.Outs.pop_back();
3396 CLI.OutVals.pop_back();
3397
3398 if (RequestedExec.Ty->isIntegerTy(64)) {
3399 assert(CLI.Outs.back().OrigArgIndex == 2 && "Exec wasn't split up");
3400 CLI.Outs.pop_back();
3401 CLI.OutVals.pop_back();
3402 }
3403
3404 assert(CLI.Outs.back().OrigArgIndex != 2 &&
3405 "Haven't popped all the pieces of the EXEC mask");
3406 }
3407
3408 const SDLoc &DL = CLI.DL;
3410 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3412 SDValue Chain = CLI.Chain;
3413 SDValue Callee = CLI.Callee;
3414 bool &IsTailCall = CLI.IsTailCall;
3415 bool IsVarArg = CLI.IsVarArg;
3416 bool IsSibCall = false;
3417 bool IsThisReturn = false;
3419
3420 if (Callee.isUndef() || isNullConstant(Callee)) {
3421 if (!CLI.IsTailCall) {
3422 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3423 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3424 }
3425
3426 return Chain;
3427 }
3428
3429 if (IsVarArg) {
3430 return lowerUnhandledCall(CLI, InVals,
3431 "unsupported call to variadic function ");
3432 }
3433
3434 if (!CLI.CB)
3435 report_fatal_error("unsupported libcall legalization");
3436
3437 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3438 return lowerUnhandledCall(CLI, InVals,
3439 "unsupported required tail call to function ");
3440 }
3441
3442 if (IsTailCall) {
3444 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3445 if (!IsTailCall &&
3446 ((CLI.CB && CLI.CB->isMustTailCall()) || IsChainCallConv)) {
3447 report_fatal_error("failed to perform tail call elimination on a call "
3448 "site marked musttail or on llvm.amdgcn.cs.chain");
3449 }
3450
3451 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3452
3453 // A sibling call is one where we're under the usual C ABI and not planning
3454 // to change that but can still do a tail call:
3455 if (!TailCallOpt && IsTailCall)
3456 IsSibCall = true;
3457
3458 if (IsTailCall)
3459 ++NumTailCalls;
3460 }
3461
3464 SmallVector<SDValue, 8> MemOpChains;
3465
3466 // Analyze operands of the call, assigning locations to each operand.
3468 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3469 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3470
3471 if (CallConv != CallingConv::AMDGPU_Gfx && !AMDGPU::isChainCC(CallConv)) {
3472 // With a fixed ABI, allocate fixed registers before user arguments.
3473 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3474 }
3475
3476 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3477
3478 // Get a count of how many bytes are to be pushed on the stack.
3479 unsigned NumBytes = CCInfo.getStackSize();
3480
3481 if (IsSibCall) {
3482 // Since we're not changing the ABI to make this a tail call, the memory
3483 // operands are already available in the caller's incoming argument space.
3484 NumBytes = 0;
3485 }
3486
3487 // FPDiff is the byte offset of the call's argument area from the callee's.
3488 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3489 // by this amount for a tail call. In a sibling call it must be 0 because the
3490 // caller will deallocate the entire stack and the callee still expects its
3491 // arguments to begin at SP+0. Completely unused for non-tail calls.
3492 int32_t FPDiff = 0;
3493 MachineFrameInfo &MFI = MF.getFrameInfo();
3494
3495 // Adjust the stack pointer for the new arguments...
3496 // These operations are automatically eliminated by the prolog/epilog pass
3497 if (!IsSibCall)
3498 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3499
3500 if (!IsSibCall || IsChainCallConv) {
3501 if (!Subtarget->enableFlatScratch()) {
3502 SmallVector<SDValue, 4> CopyFromChains;
3503
3504 // In the HSA case, this should be an identity copy.
3505 SDValue ScratchRSrcReg
3506 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3507 RegsToPass.emplace_back(IsChainCallConv
3508 ? AMDGPU::SGPR48_SGPR49_SGPR50_SGPR51
3509 : AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3,
3510 ScratchRSrcReg);
3511 CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3512 Chain = DAG.getTokenFactor(DL, CopyFromChains);
3513 }
3514 }
3515
3516 MVT PtrVT = MVT::i32;
3517
3518 // Walk the register/memloc assignments, inserting copies/loads.
3519 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3520 CCValAssign &VA = ArgLocs[i];
3521 SDValue Arg = OutVals[i];
3522
3523 // Promote the value if needed.
3524 switch (VA.getLocInfo()) {
3525 case CCValAssign::Full:
3526 break;
3527 case CCValAssign::BCvt:
3528 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3529 break;
3530 case CCValAssign::ZExt:
3531 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3532 break;
3533 case CCValAssign::SExt:
3534 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3535 break;
3536 case CCValAssign::AExt:
3537 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3538 break;
3539 case CCValAssign::FPExt:
3540 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3541 break;
3542 default:
3543 llvm_unreachable("Unknown loc info!");
3544 }
3545
3546 if (VA.isRegLoc()) {
3547 RegsToPass.push_back(std::pair(VA.getLocReg(), Arg));
3548 } else {
3549 assert(VA.isMemLoc());
3550
3551 SDValue DstAddr;
3552 MachinePointerInfo DstInfo;
3553
3554 unsigned LocMemOffset = VA.getLocMemOffset();
3555 int32_t Offset = LocMemOffset;
3556
3557 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3558 MaybeAlign Alignment;
3559
3560 if (IsTailCall) {
3561 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3562 unsigned OpSize = Flags.isByVal() ?
3563 Flags.getByValSize() : VA.getValVT().getStoreSize();
3564
3565 // FIXME: We can have better than the minimum byval required alignment.
3566 Alignment =
3567 Flags.isByVal()
3568 ? Flags.getNonZeroByValAlign()
3569 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3570
3571 Offset = Offset + FPDiff;
3572 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3573
3574 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3575 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3576
3577 // Make sure any stack arguments overlapping with where we're storing
3578 // are loaded before this eventual operation. Otherwise they'll be
3579 // clobbered.
3580
3581 // FIXME: Why is this really necessary? This seems to just result in a
3582 // lot of code to copy the stack and write them back to the same
3583 // locations, which are supposed to be immutable?
3584 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3585 } else {
3586 // Stores to the argument stack area are relative to the stack pointer.
3587 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3588 MVT::i32);
3589 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3590 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3591 Alignment =
3592 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3593 }
3594
3595 if (Outs[i].Flags.isByVal()) {
3596 SDValue SizeNode =
3597 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3598 SDValue Cpy =
3599 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3600 Outs[i].Flags.getNonZeroByValAlign(),
3601 /*isVol = */ false, /*AlwaysInline = */ true,
3602 /*isTailCall = */ false, DstInfo,
3604
3605 MemOpChains.push_back(Cpy);
3606 } else {
3607 SDValue Store =
3608 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3609 MemOpChains.push_back(Store);
3610 }
3611 }
3612 }
3613
3614 if (!MemOpChains.empty())
3615 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3616
3617 // Build a sequence of copy-to-reg nodes chained together with token chain
3618 // and flag operands which copy the outgoing args into the appropriate regs.
3619 SDValue InGlue;
3620 for (auto &RegToPass : RegsToPass) {
3621 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3622 RegToPass.second, InGlue);
3623 InGlue = Chain.getValue(1);
3624 }
3625
3626
3627 // We don't usually want to end the call-sequence here because we would tidy
3628 // the frame up *after* the call, however in the ABI-changing tail-call case
3629 // we've carefully laid out the parameters so that when sp is reset they'll be
3630 // in the correct location.
3631 if (IsTailCall && !IsSibCall) {
3632 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, DL);
3633 InGlue = Chain.getValue(1);
3634 }
3635
3636 std::vector<SDValue> Ops;
3637 Ops.push_back(Chain);
3638 Ops.push_back(Callee);
3639 // Add a redundant copy of the callee global which will not be legalized, as
3640 // we need direct access to the callee later.
3641 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3642 const GlobalValue *GV = GSD->getGlobal();
3643 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3644 } else {
3645 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3646 }
3647
3648 if (IsTailCall) {
3649 // Each tail call may have to adjust the stack by a different amount, so
3650 // this information must travel along with the operation for eventual
3651 // consumption by emitEpilogue.
3652 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3653 }
3654
3655 if (IsChainCallConv)
3656 Ops.push_back(RequestedExec.Node);
3657
3658 // Add argument registers to the end of the list so that they are known live
3659 // into the call.
3660 for (auto &RegToPass : RegsToPass) {
3661 Ops.push_back(DAG.getRegister(RegToPass.first,
3662 RegToPass.second.getValueType()));
3663 }
3664
3665 // Add a register mask operand representing the call-preserved registers.
3666 auto *TRI = static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
3667 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3668 assert(Mask && "Missing call preserved mask for calling convention");
3669 Ops.push_back(DAG.getRegisterMask(Mask));
3670
3671 if (InGlue.getNode())
3672 Ops.push_back(InGlue);
3673
3674 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3675
3676 // If we're doing a tall call, use a TC_RETURN here rather than an
3677 // actual call instruction.
3678 if (IsTailCall) {
3679 MFI.setHasTailCall();
3680 unsigned OPC = AMDGPUISD::TC_RETURN;
3681 switch (CallConv) {
3684 break;
3688 break;
3689 }
3690
3691 return DAG.getNode(OPC, DL, NodeTys, Ops);
3692 }
3693
3694 // Returns a chain and a flag for retval copy to use.
3695 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3696 Chain = Call.getValue(0);
3697 InGlue = Call.getValue(1);
3698
3699 uint64_t CalleePopBytes = NumBytes;
3700 Chain = DAG.getCALLSEQ_END(Chain, 0, CalleePopBytes, InGlue, DL);
3701 if (!Ins.empty())
3702 InGlue = Chain.getValue(1);
3703
3704 // Handle result values, copying them out of physregs into vregs that we
3705 // return.
3706 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
3707 InVals, IsThisReturn,
3708 IsThisReturn ? OutVals[0] : SDValue());
3709}
3710
3711// This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3712// except for applying the wave size scale to the increment amount.
3714 SDValue Op, SelectionDAG &DAG) const {
3715 const MachineFunction &MF = DAG.getMachineFunction();
3717
3718 SDLoc dl(Op);
3719 EVT VT = Op.getValueType();
3720 SDValue Tmp1 = Op;
3721 SDValue Tmp2 = Op.getValue(1);
3722 SDValue Tmp3 = Op.getOperand(2);
3723 SDValue Chain = Tmp1.getOperand(0);
3724
3725 Register SPReg = Info->getStackPtrOffsetReg();
3726
3727 // Chain the dynamic stack allocation so that it doesn't modify the stack
3728 // pointer when other instructions are using the stack.
3729 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3730
3731 SDValue Size = Tmp2.getOperand(1);
3732 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3733 Chain = SP.getValue(1);
3734 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3735 const TargetFrameLowering *TFL = Subtarget->getFrameLowering();
3736 unsigned Opc =
3739
3740 SDValue ScaledSize = DAG.getNode(
3741 ISD::SHL, dl, VT, Size,
3742 DAG.getConstant(Subtarget->getWavefrontSizeLog2(), dl, MVT::i32));
3743
3744 Align StackAlign = TFL->getStackAlign();
3745 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3746 if (Alignment && *Alignment > StackAlign) {
3747 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3748 DAG.getConstant(-(uint64_t)Alignment->value()
3749 << Subtarget->getWavefrontSizeLog2(),
3750 dl, VT));
3751 }
3752
3753 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
3754 Tmp2 = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
3755
3756 return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3757}
3758
3760 SelectionDAG &DAG) const {
3761 // We only handle constant sizes here to allow non-entry block, static sized
3762 // allocas. A truly dynamic value is more difficult to support because we
3763 // don't know if the size value is uniform or not. If the size isn't uniform,
3764 // we would need to do a wave reduction to get the maximum size to know how
3765 // much to increment the uniform stack pointer.
3766 SDValue Size = Op.getOperand(1);
3767 if (isa<ConstantSDNode>(Size))
3768 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3769
3771}
3772
3774 if (Op.getValueType() != MVT::i32)
3775 return Op; // Defer to cannot select error.
3776
3778 SDLoc SL(Op);
3779
3780 SDValue CopyFromSP = DAG.getCopyFromReg(Op->getOperand(0), SL, SP, MVT::i32);
3781
3782 // Convert from wave uniform to swizzled vector address. This should protect
3783 // from any edge cases where the stacksave result isn't directly used with
3784 // stackrestore.
3785 SDValue VectorAddress =
3786 DAG.getNode(AMDGPUISD::WAVE_ADDRESS, SL, MVT::i32, CopyFromSP);
3787 return DAG.getMergeValues({VectorAddress, CopyFromSP.getValue(1)}, SL);
3788}
3789
3791 SelectionDAG &DAG) const {
3792 SDLoc SL(Op);
3793 assert(Op.getValueType() == MVT::i32);
3794
3795 uint32_t BothRoundHwReg =
3797 SDValue GetRoundBothImm = DAG.getTargetConstant(BothRoundHwReg, SL, MVT::i32);
3798
3799 SDValue IntrinID =
3800 DAG.getTargetConstant(Intrinsic::amdgcn_s_getreg, SL, MVT::i32);
3801 SDValue GetReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, Op->getVTList(),
3802 Op.getOperand(0), IntrinID, GetRoundBothImm);
3803
3804 // There are two rounding modes, one for f32 and one for f64/f16. We only
3805 // report in the standard value range if both are the same.
3806 //
3807 // The raw values also differ from the expected FLT_ROUNDS values. Nearest
3808 // ties away from zero is not supported, and the other values are rotated by
3809 // 1.
3810 //
3811 // If the two rounding modes are not the same, report a target defined value.
3812
3813 // Mode register rounding mode fields:
3814 //
3815 // [1:0] Single-precision round mode.
3816 // [3:2] Double/Half-precision round mode.
3817 //
3818 // 0=nearest even; 1= +infinity; 2= -infinity, 3= toward zero.
3819 //
3820 // Hardware Spec
3821 // Toward-0 3 0
3822 // Nearest Even 0 1
3823 // +Inf 1 2
3824 // -Inf 2 3
3825 // NearestAway0 N/A 4
3826 //
3827 // We have to handle 16 permutations of a 4-bit value, so we create a 64-bit
3828 // table we can index by the raw hardware mode.
3829 //
3830 // (trunc (FltRoundConversionTable >> MODE.fp_round)) & 0xf
3831
3832 SDValue BitTable =
3834
3835 SDValue Two = DAG.getConstant(2, SL, MVT::i32);
3836 SDValue RoundModeTimesNumBits =
3837 DAG.getNode(ISD::SHL, SL, MVT::i32, GetReg, Two);
3838
3839 // TODO: We could possibly avoid a 64-bit shift and use a simpler table if we
3840 // knew only one mode was demanded.
3841 SDValue TableValue =
3842 DAG.getNode(ISD::SRL, SL, MVT::i64, BitTable, RoundModeTimesNumBits);
3843 SDValue TruncTable = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, TableValue);
3844
3845 SDValue EntryMask = DAG.getConstant(0xf, SL, MVT::i32);
3846 SDValue TableEntry =
3847 DAG.getNode(ISD::AND, SL, MVT::i32, TruncTable, EntryMask);
3848
3849 // There's a gap in the 4-bit encoded table and actual enum values, so offset
3850 // if it's an extended value.
3851 SDValue Four = DAG.getConstant(4, SL, MVT::i32);
3852 SDValue IsStandardValue =
3853 DAG.getSetCC(SL, MVT::i1, TableEntry, Four, ISD::SETULT);
3854 SDValue EnumOffset = DAG.getNode(ISD::ADD, SL, MVT::i32, TableEntry, Four);
3855 SDValue Result = DAG.getNode(ISD::SELECT, SL, MVT::i32, IsStandardValue,
3856 TableEntry, EnumOffset);
3857
3858 return DAG.getMergeValues({Result, GetReg.getValue(1)}, SL);
3859}
3860
3862 const MachineFunction &MF) const {
3864 .Case("m0", AMDGPU::M0)
3865 .Case("exec", AMDGPU::EXEC)
3866 .Case("exec_lo", AMDGPU::EXEC_LO)
3867 .Case("exec_hi", AMDGPU::EXEC_HI)
3868 .Case("flat_scratch", AMDGPU::FLAT_SCR)
3869 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3870 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3871 .Default(Register());
3872
3873 if (Reg == AMDGPU::NoRegister) {
3874 report_fatal_error(Twine("invalid register name \""
3875 + StringRef(RegName) + "\"."));
3876
3877 }
3878
3879 if (!Subtarget->hasFlatScrRegister() &&
3880 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3881 report_fatal_error(Twine("invalid register \""
3882 + StringRef(RegName) + "\" for subtarget."));
3883 }
3884
3885 switch (Reg) {
3886 case AMDGPU::M0:
3887 case AMDGPU::EXEC_LO:
3888 case AMDGPU::EXEC_HI:
3889 case AMDGPU::FLAT_SCR_LO:
3890 case AMDGPU::FLAT_SCR_HI:
3891 if (VT.getSizeInBits() == 32)
3892 return Reg;
3893 break;
3894 case AMDGPU::EXEC:
3895 case AMDGPU::FLAT_SCR:
3896 if (VT.getSizeInBits() == 64)
3897 return Reg;
3898 break;
3899 default:
3900 llvm_unreachable("missing register type checking");
3901 }
3902
3903 report_fatal_error(Twine("invalid type for register \""
3904 + StringRef(RegName) + "\"."));
3905}
3906
3907// If kill is not the last instruction, split the block so kill is always a
3908// proper terminator.
3911 MachineBasicBlock *BB) const {
3912 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3914 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3915 return SplitBB;
3916}
3917
3918// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3919// \p MI will be the only instruction in the loop body block. Otherwise, it will
3920// be the first instruction in the remainder block.
3921//
3922/// \returns { LoopBody, Remainder }
3923static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3927
3928 // To insert the loop we need to split the block. Move everything after this
3929 // point to a new block, and insert a new empty block between the two.
3931 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3933 ++MBBI;
3934
3935 MF->insert(MBBI, LoopBB);
3936 MF->insert(MBBI, RemainderBB);
3937
3938 LoopBB->addSuccessor(LoopBB);
3939 LoopBB->addSuccessor(RemainderBB);
3940
3941 // Move the rest of the block into a new block.
3942 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3943
3944 if (InstInLoop) {
3945 auto Next = std::next(I);
3946
3947 // Move instruction to loop body.
3948 LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3949
3950 // Move the rest of the block.
3951 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3952 } else {
3953 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3954 }
3955
3956 MBB.addSuccessor(LoopBB);
3957
3958 return std::pair(LoopBB, RemainderBB);
3959}
3960
3961/// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3963 MachineBasicBlock *MBB = MI.getParent();
3965 auto I = MI.getIterator();
3966 auto E = std::next(I);
3967
3968 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3969 .addImm(0);
3970
3971 MIBundleBuilder Bundler(*MBB, I, E);
3972 finalizeBundle(*MBB, Bundler.begin());
3973}
3974
3977 MachineBasicBlock *BB) const {
3978 const DebugLoc &DL = MI.getDebugLoc();
3979
3981
3982 MachineBasicBlock *LoopBB;
3983 MachineBasicBlock *RemainderBB;
3985
3986 // Apparently kill flags are only valid if the def is in the same block?
3987 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3988 Src->setIsKill(false);
3989
3990 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3991
3992 MachineBasicBlock::iterator I = LoopBB->end();
3993
3994 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3996
3997 // Clear TRAP_STS.MEM_VIOL
3998 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3999 .addImm(0)
4000 .addImm(EncodedReg);
4001
4003
4004 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4005
4006 // Load and check TRAP_STS.MEM_VIOL
4007 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
4008 .addImm(EncodedReg);
4009
4010 // FIXME: Do we need to use an isel pseudo that may clobber scc?
4011 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4012 .addReg(Reg, RegState::Kill)
4013 .addImm(0);
4014 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4015 .addMBB(LoopBB);
4016
4017 return RemainderBB;
4018}
4019
4020// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
4021// wavefront. If the value is uniform and just happens to be in a VGPR, this
4022// will only do one iteration. In the worst case, this will loop 64 times.
4023//
4024// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
4027 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
4028 const DebugLoc &DL, const MachineOperand &Idx,
4029 unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
4030 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
4031 Register &SGPRIdxReg) {
4032
4033 MachineFunction *MF = OrigBB.getParent();
4034 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4035 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4037
4038 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4039 Register PhiExec = MRI.createVirtualRegister(BoolRC);
4040 Register NewExec = MRI.createVirtualRegister(BoolRC);
4041 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4042 Register CondReg = MRI.createVirtualRegister(BoolRC);
4043
4044 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
4045 .addReg(InitReg)
4046 .addMBB(&OrigBB)
4047 .addReg(ResultReg)
4048 .addMBB(&LoopBB);
4049
4050 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
4051 .addReg(InitSaveExecReg)
4052 .addMBB(&OrigBB)
4053 .addReg(NewExec)
4054 .addMBB(&LoopBB);
4055
4056 // Read the next variant <- also loop target.
4057 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
4058 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
4059
4060 // Compare the just read M0 value to all possible Idx values.
4061 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
4062 .addReg(CurrentIdxReg)
4063 .addReg(Idx.getReg(), 0, Idx.getSubReg());
4064
4065 // Update EXEC, save the original EXEC value to VCC.
4066 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
4067 : AMDGPU::S_AND_SAVEEXEC_B64),
4068 NewExec)
4069 .addReg(CondReg, RegState::Kill);
4070
4071 MRI.setSimpleHint(NewExec, CondReg);
4072
4073 if (UseGPRIdxMode) {
4074 if (Offset == 0) {
4075 SGPRIdxReg = CurrentIdxReg;
4076 } else {
4077 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4078 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
4079 .addReg(CurrentIdxReg, RegState::Kill)
4080 .addImm(Offset);
4081 }
4082 } else {
4083 // Move index from VCC into M0
4084 if (Offset == 0) {
4085 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4086 .addReg(CurrentIdxReg, RegState::Kill);
4087 } else {
4088 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
4089 .addReg(CurrentIdxReg, RegState::Kill)
4090 .addImm(Offset);
4091 }
4092 }
4093
4094 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
4095 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4096 MachineInstr *InsertPt =
4097 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
4098 : AMDGPU::S_XOR_B64_term), Exec)
4099 .addReg(Exec)
4100 .addReg(NewExec);
4101
4102 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
4103 // s_cbranch_scc0?
4104
4105 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
4106 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
4107 .addMBB(&LoopBB);
4108
4109 return InsertPt->getIterator();
4110}
4111
4112// This has slightly sub-optimal regalloc when the source vector is killed by
4113// the read. The register allocator does not understand that the kill is
4114// per-workitem, so is kept alive for the whole loop so we end up not re-using a
4115// subregister from it, using 1 more VGPR than necessary. This was saved when
4116// this was expanded after register allocation.
4119 unsigned InitResultReg, unsigned PhiReg, int Offset,
4120 bool UseGPRIdxMode, Register &SGPRIdxReg) {
4122 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4123 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4125 const DebugLoc &DL = MI.getDebugLoc();
4127
4128 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4129 Register DstReg = MI.getOperand(0).getReg();
4130 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
4131 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
4132 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4133 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
4134
4135 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
4136
4137 // Save the EXEC mask
4138 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
4139 .addReg(Exec);
4140
4141 MachineBasicBlock *LoopBB;
4142 MachineBasicBlock *RemainderBB;
4143 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
4144
4145 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
4146
4147 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
4148 InitResultReg, DstReg, PhiReg, TmpExec,
4149 Offset, UseGPRIdxMode, SGPRIdxReg);
4150
4151 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
4153 ++MBBI;
4154 MF->insert(MBBI, LandingPad);
4155 LoopBB->removeSuccessor(RemainderBB);
4156 LandingPad->addSuccessor(RemainderBB);
4157 LoopBB->addSuccessor(LandingPad);
4158 MachineBasicBlock::iterator First = LandingPad->begin();
4159 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
4160 .addReg(SaveExec);
4161
4162 return InsPt;
4163}
4164
4165// Returns subreg index, offset
4166static std::pair<unsigned, int>
4168 const TargetRegisterClass *SuperRC,
4169 unsigned VecReg,
4170 int Offset) {
4171 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
4172
4173 // Skip out of bounds offsets, or else we would end up using an undefined
4174 // register.
4175 if (Offset >= NumElts || Offset < 0)
4176 return std::pair(AMDGPU::sub0, Offset);
4177
4178 return std::pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
4179}
4180
4183 int Offset) {
4184 MachineBasicBlock *MBB = MI.getParent();
4185 const DebugLoc &DL = MI.getDebugLoc();
4187
4188 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
4189
4190 assert(Idx->getReg() != AMDGPU::NoRegister);
4191
4192 if (Offset == 0) {
4193 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
4194 } else {
4195 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
4196 .add(*Idx)
4197 .addImm(Offset);
4198 }
4199}
4200
4203 int Offset) {
4204 MachineBasicBlock *MBB = MI.getParent();
4205 const DebugLoc &DL = MI.getDebugLoc();
4207
4208 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
4209
4210 if (Offset == 0)
4211 return Idx->getReg();
4212
4213 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4214 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
4215 .add(*Idx)
4216 .addImm(Offset);
4217 return Tmp;
4218}
4219
4222 const GCNSubtarget &ST) {
4223 const SIInstrInfo *TII = ST.getInstrInfo();
4224 const SIRegisterInfo &TRI = TII->getRegisterInfo();
4227
4228 Register Dst = MI.getOperand(0).getReg();
4229 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
4230 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
4231 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
4232
4233 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
4234 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
4235
4236 unsigned SubReg;
4237 std::tie(SubReg, Offset)
4238 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
4239
4240 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
4241
4242 // Check for a SGPR index.
4243 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
4245 const DebugLoc &DL = MI.getDebugLoc();
4246
4247 if (UseGPRIdxMode) {
4248 // TODO: Look at the uses to avoid the copy. This may require rescheduling
4249 // to avoid interfering with other uses, so probably requires a new
4250 // optimization pass.
4252
4253 const MCInstrDesc &GPRIDXDesc =
4254 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
4255 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
4256 .addReg(SrcReg)
4257 .addReg(Idx)
4258 .addImm(SubReg);
4259 } else {
4261
4262 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
4263 .addReg(SrcReg, 0, SubReg)
4264 .addReg(SrcReg, RegState::Implicit);
4265 }
4266
4267 MI.eraseFromParent();
4268
4269 return &MBB;
4270 }
4271
4272 // Control flow needs to be inserted if indexing with a VGPR.
4273 const DebugLoc &DL = MI.getDebugLoc();
4275
4276 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4277 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4278
4279 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
4280
4281 Register SGPRIdxReg;
4282 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
4283 UseGPRIdxMode, SGPRIdxReg);
4284
4285 MachineBasicBlock *LoopBB = InsPt->getParent();
4286
4287 if (UseGPRIdxMode) {
4288 const MCInstrDesc &GPRIDXDesc =
4289 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
4290
4291 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4292 .addReg(SrcReg)
4293 .addReg(SGPRIdxReg)
4294 .addImm(SubReg);
4295 } else {
4296 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
4297 .addReg(SrcReg, 0, SubReg)
4298 .addReg(SrcReg, RegState::Implicit);
4299 }
4300
4301 MI.eraseFromParent();
4302
4303 return LoopBB;
4304}
4305
4308 const GCNSubtarget &ST) {
4309 const SIInstrInfo *TII = ST.getInstrInfo();
4310 const SIRegisterInfo &TRI = TII->getRegisterInfo();
4313
4314 Register Dst = MI.getOperand(0).getReg();
4315 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);