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